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
c66a48cecfff1273dfa46a539fd1d334ab0da38e
0
pex-gl/pex-renderer,pex-gl/pex-renderer
const isPOT = require('is-power-of-two') const nextPOT = require('next-power-of-two') const log = require('debug')('gltf-build') const assert = require('assert') const aabb = require('pex-geom/aabb') const vec3 = require('pex-math/vec3') const createBox = require('primitive-box') const edges = require('geom-edges') var WebGLConstants = { ELEMENT_ARRAY_BUFFER: 34963, // 0x8893 ARRAY_BUFFER: 34962, // 0x8892 BYTE: 5120, // 0x1400 UNSIGNED_BYTE: 5121, // 0x1401 SHORT: 5122, // 0x1402 UNSIGNED_SHORT: 5123, // 0x1403 UNSIGNED_INT: 5125, FLOAT: 5126, // 0x1406 TRIANGLES: 4, // 0x0004 SAMPLER_2D: 35678, // 0x8B5E FLOAT_VEC2: 35664, // 0x8B50 FLOAT_VEC3: 35665, // 0x8B51 FLOAT_VEC4: 35666, // 0x8B52 FLOAT_MAT4: 35676 // 0x8B5C } const AttributeSizeMap = { SCALAR: 1, VEC2: 2, VEC3: 3, VEC4: 4, MAT4: 16 } const AttributeNameMap = { POSITION: 'positions', NORMAL: 'normals', TANGENT: 'tangents', TEXCOORD_0: 'texCoords', TEXCOORD_1: 'texCoords1', TEXCOORD_2: 'texCoords2', JOINTS_0: 'joints', WEIGHTS_0: 'weights', COLOR_0: 'vertexColors' } function handleBufferView (bufferView, bufferData, ctx, renderer) { if (bufferView.byteOffset === undefined) bufferView.byteOffset = 0 bufferView._data = bufferData.slice( bufferView.byteOffset, bufferView.byteOffset + bufferView.byteLength ) // console.log('handleBufferView', bufferView) if (bufferView.target === WebGLConstants.ELEMENT_ARRAY_BUFFER) { bufferView._indexBuffer = ctx.indexBuffer(bufferView._data) } else if (bufferView.target === WebGLConstants.ARRAY_BUFFER) { bufferView._vertexBuffer = ctx.vertexBuffer(bufferView._data) } } function handleAccessor (accessor, bufferView, ctx, renderer) { const size = AttributeSizeMap[accessor.type] if (accessor.byteOffset === undefined) accessor.byteOffset = 0 accessor._bufferView = bufferView if (bufferView._indexBuffer) { accessor._buffer = bufferView._indexBuffer // return } if (bufferView._vertexBuffer) { accessor._buffer = bufferView._vertexBuffer // return } // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessor-element-size // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays#Typed_array_views // https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/Constants#Data_types if (accessor.componentType === WebGLConstants.BYTE) { const data = new Int8Array(bufferView._data.slice( accessor.byteOffset, accessor.byteOffset + accessor.count * size * 1 )) accessor._data = data } else if (accessor.componentType === WebGLConstants.UNSIGNED_BYTE) { const data = new Uint8Array(bufferView._data.slice( accessor.byteOffset, accessor.byteOffset + accessor.count * size * 1 )) accessor._data = data } else if (accessor.componentType === WebGLConstants.SHORT) { const data = new Int16Array(bufferView._data.slice( accessor.byteOffset, accessor.byteOffset + accessor.count * size * 2 )) accessor._data = data } else if (accessor.componentType === WebGLConstants.UNSIGNED_SHORT) { const data = new Uint16Array(bufferView._data.slice( accessor.byteOffset, accessor.byteOffset + accessor.count * size * 2 )) accessor._data = data } else if (accessor.componentType === WebGLConstants.UNSIGNED_INT) { const data = new Uint32Array(bufferView._data.slice( accessor.byteOffset, accessor.byteOffset + accessor.count * size * 4 )) accessor._data = data } else if (accessor.componentType === WebGLConstants.FLOAT) { const data = new Float32Array(bufferView._data.slice( accessor.byteOffset, accessor.byteOffset + accessor.count * size * 4 )) accessor._data = data } else if (accessor.componentType === WebGLConstants.FLOAT_VEC2) { const data = new Float32Array(bufferView._data.slice( accessor.byteOffset, accessor.byteOffset + accessor.count * size * 4 )) accessor._data = data } else if (accessor.componentType === WebGLConstants.FLOAT_VEC3) { const data = new Float32Array(bufferView._data.slice( accessor.byteOffset, accessor.byteOffset + accessor.count * size * 4 )) accessor._data = data } else if (accessor.componentType === WebGLConstants.FLOAT_VEC4) { const data = new Float32Array(bufferView._data.slice( accessor.byteOffset, accessor.byteOffset + accessor.count * size * 4 )) accessor._data = data } else { // TODO log('uncaught', accessor) } } // TODO: add texture cache so we don't load the same texture twice // TODO: make it sync as the data is loaded already function loadTexture (materialTexture, gltf, encoding, ctx, renderer) { let texture = gltf.textures[materialTexture.index] let image = gltf.images[texture.source] let sampler = gltf.samplers ? gltf.samplers[texture.sampler] : { minFilter: ctx.Filter.Linear, magFilter: ctx.Filter.Linear } sampler.minFilter = ctx.Filter.LinearMipmapLinear // set defaults as per GLTF 2.0 spec if (!sampler.wrapS) sampler.wrapS = ctx.Wrap.Repeat if (!sampler.wrapT) sampler.wrapT = ctx.Wrap.Repeat if (texture._tex) { return texture._tex } let img = image._img if (!isPOT(img.width) || !isPOT(img.height)) { // FIXME: this is WebGL1 limitation if (sampler.wrapS !== ctx.Wrap.Clamp || sampler.wrapT !== ctx.Wrap.Clamp || (sampler.minFilter !== ctx.Filter.Nearest && sampler.minFilter !== ctx.Filter.Linear)) { const nw = nextPOT(img.width) const nh = nextPOT(img.height) log(`Warning: NPOT Repeat Wrap mode and mipmapping is not supported for NPOT Textures. Resizing... ${img.width}x${img.height} -> ${nw}x${nh}`) var canvas2d = document.createElement('canvas') canvas2d.width = nw canvas2d.height = nh var ctx2d = canvas2d.getContext('2d') ctx2d.drawImage(img, 0, 0, canvas2d.width, canvas2d.height) img = canvas2d } } var tex = texture._tex = ctx.texture2D({ data: img, width: img.width, height: img.height, encoding: encoding || ctx.Encoding.SRGB, pixelFormat: ctx.PixelFormat.RGBA8, wrapS: sampler.wrapS, wrapT: sampler.wrapT, min: sampler.minFilter, mag: sampler.magFilter, mipmap: true, aniso: 16, flipY: false // this is confusing as }) if (sampler.minFilter !== ctx.Filter.Nearest && sampler.minFilter !== ctx.Filter.Linear) { ctx.update(tex, { mipmap: true }) } return tex } function handleMaterial (material, gltf, ctx, renderer) { const materialCmp = renderer.material({ baseColor: [1, 1, 1, 1.0], roughness: 1.0, metallic: 1.0, castShadows: true, receiveShadows: true, cullFaceEnabled: !material.doubleSided }) if (material.alphaMode === 'BLEND') { // TODO: support alpha cutout materialCmp.set({ depthWrite: false, blend: true, blendSrcRGBFactor: ctx.BlendFactor.SrcAlpha, blendSrcAlphaFactor: ctx.BlendFactor.One, blendDstRGBFactor: ctx.BlendFactor.OneMinusSrcAlpha, blendDstAlphaFactor: ctx.BlendFactor.One }) } if (material.alphaMode === 'MASK') { materialCmp.set({ alphaTest: material.alphaCutoff || 0.5 }) } const pbrMetallicRoughness = material.pbrMetallicRoughness if (pbrMetallicRoughness) { log('pbrMetallicRoughness') materialCmp.set({ baseColor: [1, 1, 1, 1], roughness: 1, metallic: 1 }) log('material.pbrMatallicRoughness', pbrMetallicRoughness, materialCmp) if (pbrMetallicRoughness.baseColorFactor !== undefined) { materialCmp.set({ baseColor: pbrMetallicRoughness.baseColorFactor }) } if (pbrMetallicRoughness.baseColorTexture) { let tex = loadTexture(pbrMetallicRoughness.baseColorTexture, gltf, ctx.Encoding.SRGB, ctx, renderer) log('baseColorTexture', tex) materialCmp.set({ baseColorMap: tex }) } if (pbrMetallicRoughness.metallicFactor !== undefined) { materialCmp.set({ metallic: pbrMetallicRoughness.metallicFactor }) } if (pbrMetallicRoughness.roughnessFactor !== undefined) { materialCmp.set({ roughness: pbrMetallicRoughness.roughnessFactor }) } if (pbrMetallicRoughness.metallicRoughnessTexture) { let tex = loadTexture(pbrMetallicRoughness.metallicRoughnessTexture, gltf, ctx.Encoding.Linear, ctx, renderer) materialCmp.set({ metallicRoughnessMap: tex }) } } const pbrSpecularGlossiness = material.extensions ? material.extensions.KHR_materials_pbrSpecularGlossiness : null if (pbrSpecularGlossiness) { materialCmp.set({ diffuse: [1, 1, 1, 1], specular: [1, 1, 1], glossiness: 1 }) log('material.pbrSpecularGlossiness', pbrSpecularGlossiness, materialCmp) if (pbrSpecularGlossiness.diffuseFactor !== undefined) { materialCmp.set({ diffuse: pbrSpecularGlossiness.diffuseFactor }) } if (pbrSpecularGlossiness.specularFactor !== undefined) { materialCmp.set({ specular: pbrSpecularGlossiness.specularFactor }) } if (pbrSpecularGlossiness.glossinessFactor !== undefined) { materialCmp.set({ glossiness: pbrSpecularGlossiness.glossinessFactor }) } if (pbrSpecularGlossiness.diffuseTexture) { let tex = loadTexture(pbrSpecularGlossiness.diffuseTexture, gltf, ctx.Encoding.SRGB, ctx, renderer) materialCmp.set({ diffuseMap: tex }) } if (pbrSpecularGlossiness.specularGlossinessTexture) { let tex = loadTexture(pbrSpecularGlossiness.specularGlossinessTexture, gltf, ctx.Encoding.SRGB, ctx, renderer) materialCmp.set({ specularGlossinessMap: tex }) } if (pbrSpecularGlossiness.diffuseFactor !== undefined) { materialCmp.set({ diffuse: pbrSpecularGlossiness.diffuseFactor }) } else { materialCmp.set({ diffuse: [1, 1, 1, 1] }) } if (pbrSpecularGlossiness.glossinessFactor !== undefined) { materialCmp.set({ glossiness: pbrSpecularGlossiness.glossinessFactor }) } else { materialCmp.set({ glossiness: 1 }) } if (pbrSpecularGlossiness.specularFactor !== undefined) { materialCmp.set({ specular: pbrSpecularGlossiness.specularFactor.slice(0, 3) }) } else { materialCmp.set({ specular: [1, 1, 1] }) } } if (material.normalTexture) { let tex = loadTexture(material.normalTexture, gltf, ctx.Encoding.Linear, ctx, renderer) materialCmp.set({ normalMap: tex }) } if (material.emissiveFactor) { materialCmp.set({ emissiveColor: [ material.emissiveFactor[0], material.emissiveFactor[1], material.emissiveFactor[2], 1 ]}) } if (material.occlusionTexture) { let tex = loadTexture(material.occlusionTexture, gltf, ctx.Encoding.Linear, ctx, renderer) materialCmp.set({ occlusionMap: tex }) } if (material.emissiveTexture) { // TODO: double check sRGB var tex = loadTexture(material.emissiveTexture, gltf, ctx.Encoding.SRGB, ctx, renderer) materialCmp.set({ emissiveColorMap: tex }) } if (material.extensions && material.extensions.KHR_materials_unlit) { materialCmp.set({ roughness: null, metallic: null }) } return materialCmp } function handleMesh (mesh, gltf, ctx, renderer) { return mesh.primitives.map((primitive) => { const attributes = Object.keys(primitive.attributes).reduce((attributes, name) => { const accessor = gltf.accessors[primitive.attributes[name]] // TODO: add stride support (requires update to pex-render/geometry if (accessor._buffer) { const attributeName = AttributeNameMap[name] assert(attributeName, `GLTF: Unknown attribute '${name}'`) attributes[attributeName] = { buffer: accessor._buffer, offset: accessor.byteOffset, type: accessor.componentType, stride: accessor._bufferView.stride } } else { const attributeName = AttributeNameMap[name] assert(attributeName, `GLTF: Unknown attribute '${name}'`) attributes[attributeName] = accessor._data } return attributes }, {}) log('handleMesh.attributes', attributes) const positionAccessor = gltf.accessors[primitive.attributes.POSITION] const indicesAccessor = gltf.accessors[primitive.indices] log('handleMesh.positionAccessor', positionAccessor) log('handleMesh.indicesAccessor', indicesAccessor) const geometryCmp = renderer.geometry(attributes) geometryCmp.set({ bounds: [positionAccessor.min, positionAccessor.max] }) if (indicesAccessor) { if (indicesAccessor._buffer) { log('indicesAccessor._buffer', indicesAccessor) geometryCmp.set({ indices: { buffer: indicesAccessor._buffer, offset: indicesAccessor.byteOffset, type: indicesAccessor.componentType, count: indicesAccessor.count } }) } else { // TODO: does it ever happen? geometryCmp.set({ indices: indicesAccessor._data }) } } else { geometryCmp.set({ count: positionAccessor.buffer.length / 3 }) } let materialCmp = null if (primitive.material !== undefined) { const material = gltf.materials[primitive.material] materialCmp = handleMaterial(material, gltf, ctx, renderer) } else { materialCmp = renderer.material({}) } // materialCmp = renderer.material({ // roughness: 0.1, // metallic: 0, // baseColor: [1, 0.2, 0.2, 1], // castShadows: true, // receiveShadows: true // }) let components = [ geometryCmp, materialCmp ] log('components', components) if (primitive.targets) { let targets = primitive.targets.map((target) => { return gltf.accessors[target.POSITION]._data }) let morphCmp = renderer.morph({ // TODO the rest ? targets: targets, weights: mesh.weights }) components.push(morphCmp) } return components }) } function handleNode (node, gltf, i, ctx, renderer) { const transform = { position: node.translation || [0, 0, 0], rotation: node.rotation || [0, 0, 0, 1], scale: node.scale || [1, 1, 1] } if (node.matrix) transform.matrix = node.matrix const transformCmp = renderer.transform(transform) node.entity = renderer.add(renderer.entity([ transformCmp ])) node.entity.name = node.name || ('node_' + i) let skinCmp = null if (node.skin !== undefined) { const skin = gltf.skins[node.skin] const data = gltf.accessors[skin.inverseBindMatrices]._data let inverseBindMatrices = [] for (let i = 0; i < data.length; i += 16) { inverseBindMatrices.push(data.slice(i, i + 16)) } skinCmp = renderer.skin({ inverseBindMatrices: inverseBindMatrices }) } if (node.mesh !== undefined) { const primitives = handleMesh(gltf.meshes[node.mesh], gltf, ctx, renderer) if (primitives.length === 1) { primitives[0].forEach((component) => { node.entity.addComponent(component) }) if (skinCmp) node.entity.addComponent(skinCmp) return node.entity } else { // create sub modes for each primitive const primitiveNodes = primitives.map((components, j) => { const subMesh = renderer.add(renderer.entity(components)) subMesh.name = `node_${i}_${j}` subMesh.transform.set({ parent: node.entity.transform }) // TODO: should skin component be shared? if (skinCmp) subMesh.addComponent(skinCmp) return subMesh }) const nodes = [node.entity].concat(primitiveNodes) return nodes } } return node.entity } function buildHierarchy (nodes, gltf) { nodes.forEach((node, index) => { let parent = nodes[index] if (!parent || !parent.entity) return // TEMP: for debuggin only, child should always exist let parentTransform = parent.entity.transform if (node.children) { node.children.forEach((childIndex) => { let child = nodes[childIndex] if (!child || !child.entity) return // TEMP: for debuggin only, child should always exist let childTransform = child.entity.transform childTransform.set({ parent: parentTransform }) }) } }) nodes.forEach((node) => { if (node.skin !== undefined) { const skin = gltf.skins[node.skin] const joints = skin.joints.map((i) => { return nodes[i].entity }) if (gltf.meshes[node.mesh].primitives.length === 1) { node.entity.getComponent('Skin').set({ joints: joints }) } else { node.entity.transform.children.forEach((child) => { // FIXME: currently we share the same Skin component // so this code is redundant after first child child.entity.getComponent('Skin').set({ joints: joints }) }) } } }) } function handleAnimation (animation, gltf, ctx, renderer) { const channels = animation.channels.map((channel) => { const sampler = animation.samplers[channel.sampler] const input = gltf.accessors[sampler.input] const output = gltf.accessors[sampler.output] const target = gltf.nodes[channel.target.node].entity const outputData = [] const od = output._data let offset = AttributeSizeMap[output.type] if (channel.target.path === 'weights') { offset = target.getComponent('Morph').weights.length } for (let i = 0; i < od.length; i += offset) { if (offset === 1) { outputData.push([od[i]]) } if (offset === 2) { outputData.push([od[i], od[i + 1]]) } if (offset === 3) { outputData.push([od[i], od[i + 1], od[i + 2]]) } if (offset === 4) { outputData.push([od[i], od[i + 1], od[i + 2], od[i + 3]]) } } return { input: input._data, output: outputData, interpolation: sampler.interpolation, target: target, path: channel.target.path } }) const animationCmp = renderer.animation({ channels: channels, autoplay: true, loop: true }) return animationCmp } function build (gltf, ctx, renderer) { log('build', gltf) gltf.bufferViews.map((bufferView, i) => { handleBufferView(bufferView, gltf.buffers[bufferView.buffer]._data, ctx, renderer) }) gltf.accessors.map((accessor) => { handleAccessor(accessor, gltf.bufferViews[accessor.bufferView], ctx, renderer) }) const scene = { root: null, entities: null } scene.root = renderer.add(renderer.entity()) scene.root.name = 'sceneRoot' scene.entities = gltf.nodes.reduce((entities, node, i) => { const result = handleNode(node, gltf, i, ctx, renderer) if (result.length) { result.forEach((primitive) => entities.push(primitive)) } else { entities.push(result) } return entities }, []) buildHierarchy(gltf.nodes, gltf) scene.entities.forEach((e) => { if (e.transform.parent === renderer.root.transform) { log('attaching to scene root', e) e.transform.set({ parent: scene.root.transform }) } }) // prune non geometry nodes (cameras, lights, etc) from the hierarchy scene.entities.forEach((e) => { if (e.getComponent('Geometry')) { e.used = true while (e.transform.parent) { e = e.transform.parent.entity e.used = true } } }) if (gltf.animations) { gltf.animations.map((animation) => { const animationComponent = handleAnimation(animation, gltf, ctx, renderer) scene.root.addComponent(animationComponent) }) } if (gltf.skins) { gltf.skins.forEach((skin) => { skin.joints.forEach((jointIndex) => { let e = scene.entities[jointIndex] e.used = true while (e.transform.parent) { e = e.transform.parent.entity e.used = true } }) }) } log('entities pruned', scene.entities) renderer.update() // refresh scene hierarchy const sceneBounds = scene.root.transform.worldBounds const sceneSize = aabb.size(scene.root.transform.worldBounds) const sceneCenter = aabb.center(scene.root.transform.worldBounds) const sceneScale = 1 / (Math.max(sceneSize[0], Math.max(sceneSize[1], sceneSize[2])) || 1) if (!aabb.isEmpty(sceneBounds)) { scene.root.transform.set({ position: vec3.scale([-sceneCenter[0], -sceneBounds[0][1], -sceneCenter[2]], sceneScale), scale: [sceneScale, sceneScale, sceneScale] }) } renderer.update() // refresh scene hierarchy scene.entities.push(scene.root) // function printEntity (e, level, s) { // s = s || '' // level = ' ' + (level || '') // var g = e.getComponent('Geometry') // s += level + (e.name || 'child') + ' ' + aabbToString(e.transform.worldBounds) + ' ' + aabbToString(e.transform.bounds) + ' ' + (g ? aabbToString(g.bounds) : '') + '\n' // if (e.transform) { // e.transform.children.forEach((c) => { // s = printEntity(c.entity, level, s) // }) // } // return s // } var box = createBox(1) box.cells = edges(box.cells) box.primitive = ctx.Primitive.Lines const showBoundingBoxes = false if (showBoundingBoxes) { const bboxes = scene.entities.map((e) => { var size = aabb.size(e.transform.worldBounds) var center = aabb.center(e.transform.worldBounds) const bbox = renderer.add(renderer.entity([ renderer.transform({ scale: size, position: center }), renderer.geometry(box), renderer.material({ baseColor: [1, 0, 0, 1] }) ])) bbox.name = e.name + '_bbox' return bbox }).filter((e) => e) scene.entities = scene.entities.concat(bboxes) } return scene } module.exports = build
examples/gltf/gltf-build.js
const isPOT = require('is-power-of-two') const nextPOT = require('next-power-of-two') const log = require('debug')('gltf-build') const assert = require('assert') const aabb = require('pex-geom/aabb') const vec3 = require('pex-math/vec3') const createBox = require('primitive-box') const edges = require('geom-edges') var WebGLConstants = { ELEMENT_ARRAY_BUFFER: 34963, // 0x8893 ARRAY_BUFFER: 34962, // 0x8892 BYTE: 5120, // 0x1400 UNSIGNED_BYTE: 5121, // 0x1401 SHORT: 5122, // 0x1402 UNSIGNED_SHORT: 5123, // 0x1403 UNSIGNED_INT: 5125, FLOAT: 5126, // 0x1406 TRIANGLES: 4, // 0x0004 SAMPLER_2D: 35678, // 0x8B5E FLOAT_VEC2: 35664, // 0x8B50 FLOAT_VEC3: 35665, // 0x8B51 FLOAT_VEC4: 35666, // 0x8B52 FLOAT_MAT4: 35676 // 0x8B5C } const AttributeSizeMap = { SCALAR: 1, VEC2: 2, VEC3: 3, VEC4: 4, MAT4: 16 } const AttributeNameMap = { POSITION: 'positions', NORMAL: 'normals', TANGENT: 'tangents', TEXCOORD_0: 'texCoords', TEXCOORD_1: 'texCoords1', TEXCOORD_2: 'texCoords2', JOINTS_0: 'joints', WEIGHTS_0: 'weights', COLOR_0: 'vertexColors' } function handleBufferView (bufferView, bufferData, ctx, renderer) { if (bufferView.byteOffset === undefined) bufferView.byteOffset = 0 bufferView._data = bufferData.slice( bufferView.byteOffset, bufferView.byteOffset + bufferView.byteLength ) // console.log('handleBufferView', bufferView) if (bufferView.target === WebGLConstants.ELEMENT_ARRAY_BUFFER) { bufferView._indexBuffer = ctx.indexBuffer(bufferView._data) } else if (bufferView.target === WebGLConstants.ARRAY_BUFFER) { bufferView._vertexBuffer = ctx.vertexBuffer(bufferView._data) } } function handleAccessor (accessor, bufferView, ctx, renderer) { const size = AttributeSizeMap[accessor.type] if (accessor.byteOffset === undefined) accessor.byteOffset = 0 accessor._bufferView = bufferView if (bufferView._indexBuffer) { accessor._buffer = bufferView._indexBuffer // return } if (bufferView._vertexBuffer) { accessor._buffer = bufferView._vertexBuffer // return } // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessor-element-size // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays#Typed_array_views // https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/Constants#Data_types if (accessor.componentType === WebGLConstants.BYTE) { const data = new Int8Array(bufferView._data.slice( accessor.byteOffset, accessor.byteOffset + accessor.count * size * 1 )) accessor._data = data } else if (accessor.componentType === WebGLConstants.UNSIGNED_BYTE) { const data = new Uint8Array(bufferView._data.slice( accessor.byteOffset, accessor.byteOffset + accessor.count * size * 1 )) accessor._data = data } else if (accessor.componentType === WebGLConstants.SHORT) { const data = new Int16Array(bufferView._data.slice( accessor.byteOffset, accessor.byteOffset + accessor.count * size * 2 )) accessor._data = data } else if (accessor.componentType === WebGLConstants.UNSIGNED_SHORT) { const data = new Uint16Array(bufferView._data.slice( accessor.byteOffset, accessor.byteOffset + accessor.count * size * 2 )) accessor._data = data } else if (accessor.componentType === WebGLConstants.UNSIGNED_INT) { const data = new Uint32Array(bufferView._data.slice( accessor.byteOffset, accessor.byteOffset + accessor.count * size * 4 )) accessor._data = data } else if (accessor.componentType === WebGLConstants.FLOAT) { const data = new Float32Array(bufferView._data.slice( accessor.byteOffset, accessor.byteOffset + accessor.count * size * 4 )) accessor._data = data } else if (accessor.componentType === WebGLConstants.FLOAT_VEC2) { const data = new Float32Array(bufferView._data.slice( accessor.byteOffset, accessor.byteOffset + accessor.count * size * 4 )) accessor._data = data } else if (accessor.componentType === WebGLConstants.FLOAT_VEC3) { const data = new Float32Array(bufferView._data.slice( accessor.byteOffset, accessor.byteOffset + accessor.count * size * 4 )) accessor._data = data } else if (accessor.componentType === WebGLConstants.FLOAT_VEC4) { const data = new Float32Array(bufferView._data.slice( accessor.byteOffset, accessor.byteOffset + accessor.count * size * 4 )) accessor._data = data } else { // TODO log('uncaught', accessor) } } // TODO: add texture cache so we don't load the same texture twice // TODO: make it sync as the data is loaded already function loadTexture (materialTexture, gltf, encoding, ctx, renderer) { let texture = gltf.textures[materialTexture.index] let image = gltf.images[texture.source] let sampler = gltf.samplers ? gltf.samplers[texture.sampler] : { minFilter: ctx.Filter.Linear, magFilter: ctx.Filter.Linear } sampler.minFilter = ctx.Filter.LinearMipmapLinear // set defaults as per GLTF 2.0 spec if (!sampler.wrapS) sampler.wrapS = ctx.Wrap.Repeat if (!sampler.wrapT) sampler.wrapT = ctx.Wrap.Repeat if (texture._tex) { return texture._tex } let img = image._img if (!isPOT(img.width) || !isPOT(img.height)) { // FIXME: this is WebGL1 limitation if (sampler.wrapS !== ctx.Wrap.Clamp || sampler.wrapT !== ctx.Wrap.Clamp || (sampler.minFilter !== ctx.Filter.Nearest && sampler.minFilter !== ctx.Filter.Linear)) { const nw = nextPOT(img.width) const nh = nextPOT(img.height) log(`Warning: NPOT Repeat Wrap mode and mipmapping is not supported for NPOT Textures. Resizing... ${img.width}x${img.height} -> ${nw}x${nh}`) var canvas2d = document.createElement('canvas') canvas2d.width = nw canvas2d.height = nh var ctx2d = canvas2d.getContext('2d') ctx2d.drawImage(img, 0, 0, canvas2d.width, canvas2d.height) img = canvas2d } } var tex = texture._tex = ctx.texture2D({ data: img, width: img.width, height: img.height, encoding: encoding || ctx.Encoding.SRGB, pixelFormat: ctx.PixelFormat.RGBA8, wrapS: sampler.wrapS, wrapT: sampler.wrapT, min: sampler.minFilter, mag: sampler.magFilter, mipmap: true, aniso: 16, flipY: false // this is confusing as }) if (sampler.minFilter !== ctx.Filter.Nearest && sampler.minFilter !== ctx.Filter.Linear) { ctx.update(tex, { mipmap: true }) } return tex } function handleMaterial (material, gltf, ctx, renderer) { const materialCmp = renderer.material({ baseColor: [1, 1, 1, 1.0], roughness: 1.0, metallic: 1.0, castShadows: true, receiveShadows: true, cullFaceEnabled: !material.doubleSided }) if (material.alphaMode === 'BLEND') { // TODO: support alpha cutout materialCmp.set({ depthWrite: false, blend: true, blendSrcRGBFactor: ctx.BlendFactor.SrcAlpha, blendSrcAlphaFactor: ctx.BlendFactor.One, blendDstRGBFactor: ctx.BlendFactor.OneMinusSrcAlpha, blendDstAlphaFactor: ctx.BlendFactor.One }) } if (material.alphaMode === 'MASK') { materialCmp.set({ alphaTest: material.alphaCutoff || 0.5 }) } const pbrMetallicRoughness = material.pbrMetallicRoughness if (pbrMetallicRoughness) { log('pbrMetallicRoughness') materialCmp.set({ baseColor: [1, 1, 1, 1], roughness: 1, metallic: 1 }) log('material.pbrMatallicRoughness', pbrMetallicRoughness, materialCmp) if (pbrMetallicRoughness.baseColorFactor !== undefined) { materialCmp.set({ baseColor: pbrMetallicRoughness.baseColorFactor }) } if (pbrMetallicRoughness.baseColorTexture) { let tex = loadTexture(pbrMetallicRoughness.baseColorTexture, gltf, ctx.Encoding.SRGB, ctx, renderer) log('baseColorTexture', tex) materialCmp.set({ baseColorMap: tex }) } if (pbrMetallicRoughness.metallicFactor !== undefined) { materialCmp.set({ metallic: pbrMetallicRoughness.metallicFactor }) } if (pbrMetallicRoughness.roughnessFactor !== undefined) { materialCmp.set({ roughness: pbrMetallicRoughness.roughnessFactor }) } if (pbrMetallicRoughness.metallicRoughnessTexture) { let tex = loadTexture(pbrMetallicRoughness.metallicRoughnessTexture, gltf, ctx.Encoding.Linear, ctx, renderer) materialCmp.set({ metallicRoughnessMap: tex }) } } const pbrSpecularGlossiness = material.extensions ? material.extensions.KHR_materials_pbrSpecularGlossiness : null if (pbrSpecularGlossiness) { materialCmp.set({ diffuse: [1, 1, 1, 1], specular: [1, 1, 1], glossiness: 1 }) log('material.pbrSpecularGlossiness', pbrSpecularGlossiness, materialCmp) if (pbrSpecularGlossiness.diffuseFactor !== undefined) { materialCmp.set({ diffuse: pbrSpecularGlossiness.diffuseFactor }) } if (pbrSpecularGlossiness.specularFactor !== undefined) { materialCmp.set({ specular: pbrSpecularGlossiness.specularFactor }) } if (pbrSpecularGlossiness.glossinessFactor !== undefined) { materialCmp.set({ glossiness: pbrSpecularGlossiness.glossinessFactor }) } if (pbrSpecularGlossiness.diffuseTexture) { let tex = loadTexture(pbrSpecularGlossiness.diffuseTexture, gltf, ctx.Encoding.SRGB, ctx, renderer) materialCmp.set({ diffuseMap: tex }) } if (pbrSpecularGlossiness.specularGlossinessTexture) { let tex = loadTexture(pbrSpecularGlossiness.specularGlossinessTexture, gltf, ctx.Encoding.SRGB, ctx, renderer) materialCmp.set({ specularGlossinessMap: tex }) } if (pbrSpecularGlossiness.diffuseFactor !== undefined) { materialCmp.set({ diffuse: pbrSpecularGlossiness.diffuseFactor }) } else { materialCmp.set({ diffuse: [1, 1, 1, 1] }) } if (pbrSpecularGlossiness.glossinessFactor !== undefined) { materialCmp.set({ glossiness: pbrSpecularGlossiness.glossinessFactor }) } else { materialCmp.set({ glossiness: 1 }) } if (pbrSpecularGlossiness.specularFactor !== undefined) { materialCmp.set({ specular: pbrSpecularGlossiness.specularFactor.slice(0, 3) }) } else { materialCmp.set({ specular: [1, 1, 1] }) } } if (material.normalTexture) { let tex = loadTexture(material.normalTexture, gltf, ctx.Encoding.Linear, ctx, renderer) materialCmp.set({ normalMap: tex }) } if (material.emissiveFactor) { materialCmp.set({ emissiveColor: [ material.emissiveFactor[0], material.emissiveFactor[1], material.emissiveFactor[2], 1 ]}) } if (material.occlusionTexture) { let tex = loadTexture(material.occlusionTexture, gltf, ctx.Encoding.Linear, ctx, renderer) materialCmp.set({ occlusionMap: tex }) } if (material.emissiveTexture) { // TODO: double check sRGB var tex = loadTexture(material.emissiveTexture, gltf, ctx.Encoding.SRGB, ctx, renderer) materialCmp.set({ emissiveColorMap: tex }) } return materialCmp } function handleMesh (mesh, gltf, ctx, renderer) { return mesh.primitives.map((primitive) => { const attributes = Object.keys(primitive.attributes).reduce((attributes, name) => { const accessor = gltf.accessors[primitive.attributes[name]] // TODO: add stride support (requires update to pex-render/geometry if (accessor._buffer) { const attributeName = AttributeNameMap[name] assert(attributeName, `GLTF: Unknown attribute '${name}'`) attributes[attributeName] = { buffer: accessor._buffer, offset: accessor.byteOffset, type: accessor.componentType, stride: accessor._bufferView.stride } } else { const attributeName = AttributeNameMap[name] assert(attributeName, `GLTF: Unknown attribute '${name}'`) attributes[attributeName] = accessor._data } return attributes }, {}) log('handleMesh.attributes', attributes) const positionAccessor = gltf.accessors[primitive.attributes.POSITION] const indicesAccessor = gltf.accessors[primitive.indices] log('handleMesh.positionAccessor', positionAccessor) log('handleMesh.indicesAccessor', indicesAccessor) const geometryCmp = renderer.geometry(attributes) geometryCmp.set({ bounds: [positionAccessor.min, positionAccessor.max] }) if (indicesAccessor) { if (indicesAccessor._buffer) { log('indicesAccessor._buffer', indicesAccessor) geometryCmp.set({ indices: { buffer: indicesAccessor._buffer, offset: indicesAccessor.byteOffset, type: indicesAccessor.componentType, count: indicesAccessor.count } }) } else { // TODO: does it ever happen? geometryCmp.set({ indices: indicesAccessor._data }) } } else { geometryCmp.set({ count: positionAccessor.buffer.length / 3 }) } let materialCmp = null if (primitive.material !== undefined) { const material = gltf.materials[primitive.material] materialCmp = handleMaterial(material, gltf, ctx, renderer) } else { materialCmp = renderer.material({}) } // materialCmp = renderer.material({ // roughness: 0.1, // metallic: 0, // baseColor: [1, 0.2, 0.2, 1], // castShadows: true, // receiveShadows: true // }) let components = [ geometryCmp, materialCmp ] log('components', components) if (primitive.targets) { let targets = primitive.targets.map((target) => { return gltf.accessors[target.POSITION]._data }) let morphCmp = renderer.morph({ // TODO the rest ? targets: targets, weights: mesh.weights }) components.push(morphCmp) } return components }) } function handleNode (node, gltf, i, ctx, renderer) { const transform = { position: node.translation || [0, 0, 0], rotation: node.rotation || [0, 0, 0, 1], scale: node.scale || [1, 1, 1] } if (node.matrix) transform.matrix = node.matrix const transformCmp = renderer.transform(transform) node.entity = renderer.add(renderer.entity([ transformCmp ])) node.entity.name = node.name || ('node_' + i) let skinCmp = null if (node.skin !== undefined) { const skin = gltf.skins[node.skin] const data = gltf.accessors[skin.inverseBindMatrices]._data let inverseBindMatrices = [] for (let i = 0; i < data.length; i += 16) { inverseBindMatrices.push(data.slice(i, i + 16)) } skinCmp = renderer.skin({ inverseBindMatrices: inverseBindMatrices }) } if (node.mesh !== undefined) { const primitives = handleMesh(gltf.meshes[node.mesh], gltf, ctx, renderer) if (primitives.length === 1) { primitives[0].forEach((component) => { node.entity.addComponent(component) }) if (skinCmp) node.entity.addComponent(skinCmp) return node.entity } else { // create sub modes for each primitive const primitiveNodes = primitives.map((components, j) => { const subMesh = renderer.add(renderer.entity(components)) subMesh.name = `node_${i}_${j}` subMesh.transform.set({ parent: node.entity.transform }) // TODO: should skin component be shared? if (skinCmp) subMesh.addComponent(skinCmp) return subMesh }) const nodes = [node.entity].concat(primitiveNodes) return nodes } } return node.entity } function buildHierarchy (nodes, gltf) { nodes.forEach((node, index) => { let parent = nodes[index] if (!parent || !parent.entity) return // TEMP: for debuggin only, child should always exist let parentTransform = parent.entity.transform if (node.children) { node.children.forEach((childIndex) => { let child = nodes[childIndex] if (!child || !child.entity) return // TEMP: for debuggin only, child should always exist let childTransform = child.entity.transform childTransform.set({ parent: parentTransform }) }) } }) nodes.forEach((node) => { if (node.skin !== undefined) { const skin = gltf.skins[node.skin] const joints = skin.joints.map((i) => { return nodes[i].entity }) if (gltf.meshes[node.mesh].primitives.length === 1) { node.entity.getComponent('Skin').set({ joints: joints }) } else { node.entity.transform.children.forEach((child) => { // FIXME: currently we share the same Skin component // so this code is redundant after first child child.entity.getComponent('Skin').set({ joints: joints }) }) } } }) } function handleAnimation (animation, gltf, ctx, renderer) { const channels = animation.channels.map((channel) => { const sampler = animation.samplers[channel.sampler] const input = gltf.accessors[sampler.input] const output = gltf.accessors[sampler.output] const target = gltf.nodes[channel.target.node].entity const outputData = [] const od = output._data let offset = AttributeSizeMap[output.type] if (channel.target.path === 'weights') { offset = target.getComponent('Morph').weights.length } for (let i = 0; i < od.length; i += offset) { if (offset === 1) { outputData.push([od[i]]) } if (offset === 2) { outputData.push([od[i], od[i + 1]]) } if (offset === 3) { outputData.push([od[i], od[i + 1], od[i + 2]]) } if (offset === 4) { outputData.push([od[i], od[i + 1], od[i + 2], od[i + 3]]) } } return { input: input._data, output: outputData, interpolation: sampler.interpolation, target: target, path: channel.target.path } }) const animationCmp = renderer.animation({ channels: channels, autoplay: true, loop: true }) return animationCmp } function build (gltf, ctx, renderer) { log('build', gltf) gltf.bufferViews.map((bufferView, i) => { handleBufferView(bufferView, gltf.buffers[bufferView.buffer]._data, ctx, renderer) }) gltf.accessors.map((accessor) => { handleAccessor(accessor, gltf.bufferViews[accessor.bufferView], ctx, renderer) }) const scene = { root: null, entities: null } scene.root = renderer.add(renderer.entity()) scene.root.name = 'sceneRoot' scene.entities = gltf.nodes.reduce((entities, node, i) => { const result = handleNode(node, gltf, i, ctx, renderer) if (result.length) { result.forEach((primitive) => entities.push(primitive)) } else { entities.push(result) } return entities }, []) buildHierarchy(gltf.nodes, gltf) scene.entities.forEach((e) => { if (e.transform.parent === renderer.root.transform) { log('attaching to scene root', e) e.transform.set({ parent: scene.root.transform }) } }) // prune non geometry nodes (cameras, lights, etc) from the hierarchy scene.entities.forEach((e) => { if (e.getComponent('Geometry')) { e.used = true while (e.transform.parent) { e = e.transform.parent.entity e.used = true } } }) if (gltf.animations) { gltf.animations.map((animation) => { const animationComponent = handleAnimation(animation, gltf, ctx, renderer) scene.root.addComponent(animationComponent) }) } if (gltf.skins) { gltf.skins.forEach((skin) => { skin.joints.forEach((jointIndex) => { let e = scene.entities[jointIndex] e.used = true while (e.transform.parent) { e = e.transform.parent.entity e.used = true } }) }) } log('entities pruned', scene.entities) renderer.update() // refresh scene hierarchy const sceneBounds = scene.root.transform.worldBounds const sceneSize = aabb.size(scene.root.transform.worldBounds) const sceneCenter = aabb.center(scene.root.transform.worldBounds) const sceneScale = 1 / (Math.max(sceneSize[0], Math.max(sceneSize[1], sceneSize[2])) || 1) if (!aabb.isEmpty(sceneBounds)) { scene.root.transform.set({ position: vec3.scale([-sceneCenter[0], -sceneBounds[0][1], -sceneCenter[2]], sceneScale), scale: [sceneScale, sceneScale, sceneScale] }) } renderer.update() // refresh scene hierarchy scene.entities.push(scene.root) // function printEntity (e, level, s) { // s = s || '' // level = ' ' + (level || '') // var g = e.getComponent('Geometry') // s += level + (e.name || 'child') + ' ' + aabbToString(e.transform.worldBounds) + ' ' + aabbToString(e.transform.bounds) + ' ' + (g ? aabbToString(g.bounds) : '') + '\n' // if (e.transform) { // e.transform.children.forEach((c) => { // s = printEntity(c.entity, level, s) // }) // } // return s // } var box = createBox(1) box.cells = edges(box.cells) box.primitive = ctx.Primitive.Lines const showBoundingBoxes = false if (showBoundingBoxes) { const bboxes = scene.entities.map((e) => { var size = aabb.size(e.transform.worldBounds) var center = aabb.center(e.transform.worldBounds) const bbox = renderer.add(renderer.entity([ renderer.transform({ scale: size, position: center }), renderer.geometry(box), renderer.material({ baseColor: [1, 0, 0, 1] }) ])) bbox.name = e.name + '_bbox' return bbox }).filter((e) => e) scene.entities = scene.entities.concat(bboxes) } return scene } module.exports = build
Add support for KHR_materials_unlit extensions (set roughness/metallic to null)
examples/gltf/gltf-build.js
Add support for KHR_materials_unlit extensions (set roughness/metallic to null)
<ide><path>xamples/gltf/gltf-build.js <ide> // TODO: double check sRGB <ide> var tex = loadTexture(material.emissiveTexture, gltf, ctx.Encoding.SRGB, ctx, renderer) <ide> materialCmp.set({ emissiveColorMap: tex }) <add> } <add> <add> if (material.extensions && material.extensions.KHR_materials_unlit) { <add> materialCmp.set({ <add> roughness: null, <add> metallic: null <add> }) <ide> } <ide> <ide> return materialCmp
Java
lgpl-2.1
error: pathspec 'test/org/pentaho/di/repository/RepositoryImportExporterApiTest.java' did not match any file(s) known to git
b7bef41f9102aa51b912a3254a9921a3164ef893
1
juanmjacobs/kettle,cwarden/kettle,cwarden/kettle,juanmjacobs/kettle,juanmjacobs/kettle,cwarden/kettle
package org.pentaho.di.repository; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import junit.framework.TestCase; import org.pentaho.di.core.ProgressMonitorListener; public class RepositoryImportExporterApiTest extends TestCase { /** * Validate the the repository export api hasn't changed from what we use in example files. * * @see RepositoryExporter#exportAllObjects(ProgressMonitorListener, String, RepositoryDirectoryInterface, String) */ public void testExportApi() throws Exception { Class<RepositoryExporter> exporter = RepositoryExporter.class; // Make sure we the expected constructor that takes a repository Constructor<RepositoryExporter> c = exporter.getConstructor(Repository.class); assertNotNull(c); // Make sure we have the correct signature for exporting objects // RepositoryExporter.exportAllObjects(ProgressMonitorListener, String, RepositoryDirectoryInterface, String) Class<?> param1 = ProgressMonitorListener.class; Class<?> param2 = String.class; Class<?> param3 = RepositoryDirectoryInterface.class; Class<?> param4 = String.class; Method m = exporter.getMethod("exportAllObjects", param1, param2, param3, param4); //$NON-NLS-1$ assertNotNull(m); } /** * Validate the the repository import api hasn't changed from what we use in example files. * * @see RepositoryImporter#importAll(RepositoryImportFeedbackInterface, String, String[], RepositoryDirectoryInterface, boolean, boolean, String) */ public void testImportApi() throws Exception { Class<RepositoryImporter> importer = RepositoryImporter.class; // Make sure we the expected constructor that takes a repository Constructor<RepositoryImporter> c = importer.getConstructor(Repository.class); assertNotNull(c); // Make sure we have the correct signature for importing objects // RepositoryImporter.importAll(RepositoryImportFeedbackInterface, String, String[], RepositoryDirectoryInterface, boolean, boolean, String) Class<?> param1 = RepositoryImportFeedbackInterface.class; Class<?> param2 = String.class; Class<?> param3 = String[].class; Class<?> param4 = RepositoryDirectoryInterface.class; Class<?> param5 = boolean.class; Class<?> param6 = boolean.class; Class<?> param7 = String.class; Method m = importer.getMethod("importAll", param1, param2, param3, param4, param5, param6, param7); //$NON-NLS-1$ } }
test/org/pentaho/di/repository/RepositoryImportExporterApiTest.java
[PDI-26] Created unit tests to ensure the repository import/export api we expect to exist exists. git-svn-id: 51b39fcfd0d3a6ea7caa15377cad4af13b9d2664@14745 5fb7f6ec-07c1-534a-b4ca-9155e429e800
test/org/pentaho/di/repository/RepositoryImportExporterApiTest.java
[PDI-26] Created unit tests to ensure the repository import/export api we expect to exist exists.
<ide><path>est/org/pentaho/di/repository/RepositoryImportExporterApiTest.java <add>package org.pentaho.di.repository; <add> <add>import java.lang.reflect.Constructor; <add>import java.lang.reflect.Method; <add> <add>import junit.framework.TestCase; <add> <add>import org.pentaho.di.core.ProgressMonitorListener; <add> <add>public class RepositoryImportExporterApiTest extends TestCase { <add> <add> /** <add> * Validate the the repository export api hasn't changed from what we use in example files. <add> * <add> * @see RepositoryExporter#exportAllObjects(ProgressMonitorListener, String, RepositoryDirectoryInterface, String) <add> */ <add> public void testExportApi() throws Exception { <add> Class<RepositoryExporter> exporter = RepositoryExporter.class; <add> <add> // Make sure we the expected constructor that takes a repository <add> Constructor<RepositoryExporter> c = exporter.getConstructor(Repository.class); <add> assertNotNull(c); <add> <add> // Make sure we have the correct signature for exporting objects <add> // RepositoryExporter.exportAllObjects(ProgressMonitorListener, String, RepositoryDirectoryInterface, String) <add> Class<?> param1 = ProgressMonitorListener.class; <add> Class<?> param2 = String.class; <add> Class<?> param3 = RepositoryDirectoryInterface.class; <add> Class<?> param4 = String.class; <add> Method m = exporter.getMethod("exportAllObjects", param1, param2, param3, param4); //$NON-NLS-1$ <add> assertNotNull(m); <add> } <add> <add> <add> /** <add> * Validate the the repository import api hasn't changed from what we use in example files. <add> * <add> * @see RepositoryImporter#importAll(RepositoryImportFeedbackInterface, String, String[], RepositoryDirectoryInterface, boolean, boolean, String) <add> */ <add> public void testImportApi() throws Exception { <add> Class<RepositoryImporter> importer = RepositoryImporter.class; <add> <add> // Make sure we the expected constructor that takes a repository <add> Constructor<RepositoryImporter> c = importer.getConstructor(Repository.class); <add> assertNotNull(c); <add> <add> // Make sure we have the correct signature for importing objects <add> // RepositoryImporter.importAll(RepositoryImportFeedbackInterface, String, String[], RepositoryDirectoryInterface, boolean, boolean, String) <add> Class<?> param1 = RepositoryImportFeedbackInterface.class; <add> Class<?> param2 = String.class; <add> Class<?> param3 = String[].class; <add> Class<?> param4 = RepositoryDirectoryInterface.class; <add> Class<?> param5 = boolean.class; <add> Class<?> param6 = boolean.class; <add> Class<?> param7 = String.class; <add> Method m = importer.getMethod("importAll", param1, param2, param3, param4, param5, param6, param7); //$NON-NLS-1$ <add> } <add>}
Java
apache-2.0
cf4e17e2992d8f964007965b357f24c06cdf4bbf
0
amiryesh/incubator-trafficcontrol,weifensh/incubator-trafficcontrol,jheitz200/traffic_control,zhilhuan/incubator-trafficcontrol,weifensh/traffic_control,rscrimojr/incubator-trafficcontrol,PSUdaemon/traffic_control,hbeatty/incubator-trafficcontrol,alficles/incubator-trafficcontrol,serDrem/incubator-trafficcontrol,mitchell852/traffic_control,zhilhuan/incubator-trafficcontrol,jeffmart/incubator-trafficcontrol,naamashoresh/incubator-trafficcontrol,weifensh/incubator-trafficcontrol,dewrich/traffic_control,orifinkelman/incubator-trafficcontrol,smalenfant/traffic_control,jheitz200/traffic_control,jheitz200/traffic_control,dewrich/traffic_control,robert-butts/traffic_control,mtorluemke/traffic_control,serDrem/incubator-trafficcontrol,robert-butts/traffic_control,dewrich/traffic_control,smalenfant/traffic_control,alficles/incubator-trafficcontrol,rscrimojr/incubator-trafficcontrol,elsloo/traffic_control,PSUdaemon/traffic_control,serDrem/incubator-trafficcontrol,weifensh/traffic_control,PSUdaemon/traffic_control,mdb/incubator-trafficcontrol,PSUdaemon/traffic_control,robert-butts/traffic_control,dangogh/traffic_control,jeffmart/incubator-trafficcontrol,mdb/incubator-trafficcontrol,zhilhuan/incubator-trafficcontrol,robert-butts/traffic_control,knutsel/traffic_control-1,jeffmart/incubator-trafficcontrol,hbeatty/incubator-trafficcontrol,elsloo/traffic_control,mtorluemke/traffic_control,serDrem/incubator-trafficcontrol,alficles/incubator-trafficcontrol,elsloo/traffic_control,hbeatty/incubator-trafficcontrol,dangogh/traffic_control,weifensh/traffic_control,mitchell852/traffic_control,alficles/incubator-trafficcontrol,PSUdaemon/traffic_control,alficles/incubator-trafficcontrol,alficles/incubator-trafficcontrol,PSUdaemon/traffic_control,elsloo/traffic_control,naamashoresh/incubator-trafficcontrol,dangogh/traffic_control,amiryesh/incubator-trafficcontrol,jheitz200/traffic_control,jeffmart/incubator-trafficcontrol,jeffmart/incubator-trafficcontrol,mdb/incubator-trafficcontrol,mdb/incubator-trafficcontrol,mtorluemke/traffic_control,dewrich/traffic_control,orifinkelman/incubator-trafficcontrol,jeffmart/incubator-trafficcontrol,weifensh/incubator-trafficcontrol,amiryesh/incubator-trafficcontrol,weifensh/traffic_control,mtorluemke/traffic_control,mtorluemke/traffic_control,serDrem/incubator-trafficcontrol,zhilhuan/incubator-trafficcontrol,elsloo/traffic_control,rscrimojr/incubator-trafficcontrol,knutsel/traffic_control-1,knutsel/traffic_control-1,robert-butts/traffic_control,weifensh/incubator-trafficcontrol,dewrich/traffic_control,serDrem/incubator-trafficcontrol,weifensh/incubator-trafficcontrol,mtorluemke/traffic_control,amiryesh/incubator-trafficcontrol,knutsel/traffic_control-1,zhilhuan/incubator-trafficcontrol,hbeatty/incubator-trafficcontrol,rscrimojr/incubator-trafficcontrol,mdb/incubator-trafficcontrol,mitchell852/traffic_control,jheitz200/traffic_control,elsloo/traffic_control,robert-butts/traffic_control,knutsel/traffic_control-1,hbeatty/incubator-trafficcontrol,amiryesh/incubator-trafficcontrol,naamashoresh/incubator-trafficcontrol,mdb/incubator-trafficcontrol,naamashoresh/incubator-trafficcontrol,naamashoresh/incubator-trafficcontrol,knutsel/traffic_control-1,serDrem/incubator-trafficcontrol,weifensh/incubator-trafficcontrol,naamashoresh/incubator-trafficcontrol,orifinkelman/incubator-trafficcontrol,jeffmart/incubator-trafficcontrol,robert-butts/traffic_control,smalenfant/traffic_control,alficles/incubator-trafficcontrol,serDrem/incubator-trafficcontrol,smalenfant/traffic_control,dangogh/traffic_control,robert-butts/traffic_control,hbeatty/incubator-trafficcontrol,weifensh/traffic_control,mitchell852/traffic_control,naamashoresh/incubator-trafficcontrol,weifensh/traffic_control,mitchell852/traffic_control,amiryesh/incubator-trafficcontrol,dewrich/traffic_control,robert-butts/traffic_control,smalenfant/traffic_control,mitchell852/traffic_control,smalenfant/traffic_control,alficles/incubator-trafficcontrol,jheitz200/traffic_control,elsloo/traffic_control,orifinkelman/incubator-trafficcontrol,robert-butts/traffic_control,mdb/incubator-trafficcontrol,alficles/incubator-trafficcontrol,PSUdaemon/traffic_control,zhilhuan/incubator-trafficcontrol,amiryesh/incubator-trafficcontrol,mitchell852/traffic_control,rscrimojr/incubator-trafficcontrol,mitchell852/traffic_control,dewrich/traffic_control,knutsel/traffic_control-1,PSUdaemon/traffic_control,weifensh/traffic_control,jheitz200/traffic_control,mdb/incubator-trafficcontrol,hbeatty/incubator-trafficcontrol,knutsel/traffic_control-1,smalenfant/traffic_control,knutsel/traffic_control-1,smalenfant/traffic_control,amiryesh/incubator-trafficcontrol,orifinkelman/incubator-trafficcontrol,weifensh/traffic_control,orifinkelman/incubator-trafficcontrol,dewrich/traffic_control,weifensh/traffic_control,weifensh/incubator-trafficcontrol,jeffmart/incubator-trafficcontrol,mdb/incubator-trafficcontrol,serDrem/incubator-trafficcontrol,mitchell852/traffic_control,zhilhuan/incubator-trafficcontrol,naamashoresh/incubator-trafficcontrol,dangogh/traffic_control,naamashoresh/incubator-trafficcontrol,zhilhuan/incubator-trafficcontrol,orifinkelman/incubator-trafficcontrol,knutsel/traffic_control-1,mtorluemke/traffic_control,dangogh/traffic_control,alficles/incubator-trafficcontrol,amiryesh/incubator-trafficcontrol,jheitz200/traffic_control,PSUdaemon/traffic_control,hbeatty/incubator-trafficcontrol,smalenfant/traffic_control,naamashoresh/incubator-trafficcontrol,jeffmart/incubator-trafficcontrol,jeffmart/incubator-trafficcontrol,dewrich/traffic_control,weifensh/traffic_control,rscrimojr/incubator-trafficcontrol,weifensh/incubator-trafficcontrol,weifensh/incubator-trafficcontrol,zhilhuan/incubator-trafficcontrol,mtorluemke/traffic_control,mdb/incubator-trafficcontrol,orifinkelman/incubator-trafficcontrol,dangogh/traffic_control,hbeatty/incubator-trafficcontrol,jheitz200/traffic_control,amiryesh/incubator-trafficcontrol,weifensh/incubator-trafficcontrol,elsloo/traffic_control,rscrimojr/incubator-trafficcontrol,rscrimojr/incubator-trafficcontrol,dangogh/traffic_control,serDrem/incubator-trafficcontrol,hbeatty/incubator-trafficcontrol,dangogh/traffic_control,elsloo/traffic_control,jheitz200/traffic_control,rscrimojr/incubator-trafficcontrol,zhilhuan/incubator-trafficcontrol,mtorluemke/traffic_control,dangogh/traffic_control,dewrich/traffic_control,orifinkelman/incubator-trafficcontrol,smalenfant/traffic_control,elsloo/traffic_control,rscrimojr/incubator-trafficcontrol,orifinkelman/incubator-trafficcontrol,mtorluemke/traffic_control,mitchell852/traffic_control,PSUdaemon/traffic_control
/* * Copyright 2015 Comcast Cable Communications Management, 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 com.comcast.cdn.traffic_control.traffic_monitor.health; import java.io.Serializable; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import org.apache.log4j.Logger; import org.apache.wicket.ajax.json.JSONException; import org.apache.wicket.ajax.json.JSONObject; import com.comcast.cdn.traffic_control.traffic_monitor.config.ConfigHandler; public class Event extends JSONObject implements Serializable { private static final Logger EVENT_LOGGER = Logger.getLogger("com.comcast.cdn.traffic_control.traffic_monitor.event"); private static final Logger LOGGER = Logger.getLogger(Event.class); private static final long serialVersionUID = 1L; static List<JSONObject> rollingLog = new LinkedList<JSONObject>(); static int logIndex = 0; public static Event logStateChange(final String hostname, final boolean isAvailable, final String message) { final long currentTimeMillis = System.currentTimeMillis(); final String timeString = String.format("%d.%03d", currentTimeMillis / 1000, currentTimeMillis % 1000); EVENT_LOGGER.info(String.format("%s host=\"%s\", available=%s, msg=\"%s\"", timeString , hostname, String.valueOf(isAvailable), message)); synchronized (rollingLog) { final Event ret = new Event(hostname, isAvailable, message); rollingLog.add(0, ret); while(rollingLog.size() > ConfigHandler.getConfig().getEventLogCount()) { rollingLog.remove(rollingLog.size()-1); } return ret; } } public static List<JSONObject> getEventLog() { synchronized (rollingLog) { return new ArrayList<JSONObject>(rollingLog); } } public Event(final String hostname, final boolean isAvailable, final String error) { try { this.put("hostname", hostname); this.put("time", System.currentTimeMillis()); this.put("index", logIndex++); this.put("isAvailable", isAvailable); this.put("description", error); } catch (JSONException e) { LOGGER.warn(e,e); } } }
traffic_monitor/src/main/java/com/comcast/cdn/traffic_control/traffic_monitor/health/Event.java
/* * Copyright 2015 Comcast Cable Communications Management, 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 com.comcast.cdn.traffic_control.traffic_monitor.health; import java.io.Serializable; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import org.apache.log4j.Logger; import org.apache.wicket.ajax.json.JSONException; import org.apache.wicket.ajax.json.JSONObject; import com.comcast.cdn.traffic_control.traffic_monitor.config.ConfigHandler; public class Event extends JSONObject implements Serializable { private static final Logger EVENT_LOGGER = Logger.getLogger("com.comcast.cdn.traffic_control.traffic_monitor.event"); private static final Logger LOGGER = Logger.getLogger(Event.class); private static final long serialVersionUID = 1L; static List<JSONObject> rollingLog = new LinkedList<JSONObject>(); static int logIndex = 0; public static Event logStateChange(final String hostname, final boolean isAvailable, final String message) { final long currentTimeMillis = System.currentTimeMillis(); final String timeString = String.format("%d.%03d", currentTimeMillis / 1000, currentTimeMillis % 1000); EVENT_LOGGER.info(String.format("%s logStateChange: %s, isAvailable=%s, %s", timeString , hostname, String.valueOf(isAvailable), message)); synchronized (rollingLog) { final Event ret = new Event(hostname, isAvailable, message); rollingLog.add(0, ret); while(rollingLog.size() > ConfigHandler.getConfig().getEventLogCount()) { rollingLog.remove(rollingLog.size()-1); } return ret; } } public static List<JSONObject> getEventLog() { synchronized (rollingLog) { return new ArrayList<JSONObject>(rollingLog); } } public Event(final String hostname, final boolean isAvailable, final String error) { try { this.put("hostname", hostname); this.put("time", System.currentTimeMillis()); this.put("index", logIndex++); this.put("isAvailable", isAvailable); this.put("description", error); } catch (JSONException e) { LOGGER.warn(e,e); } } }
Change format of Traffic Monitor event entries to be key value pairs, more like Traffic Router access event log
traffic_monitor/src/main/java/com/comcast/cdn/traffic_control/traffic_monitor/health/Event.java
Change format of Traffic Monitor event entries to be key value pairs, more like Traffic Router access event log
<ide><path>raffic_monitor/src/main/java/com/comcast/cdn/traffic_control/traffic_monitor/health/Event.java <ide> final long currentTimeMillis = System.currentTimeMillis(); <ide> final String timeString = String.format("%d.%03d", currentTimeMillis / 1000, currentTimeMillis % 1000); <ide> <del> EVENT_LOGGER.info(String.format("%s logStateChange: %s, isAvailable=%s, %s", timeString , hostname, String.valueOf(isAvailable), message)); <add> EVENT_LOGGER.info(String.format("%s host=\"%s\", available=%s, msg=\"%s\"", timeString , hostname, String.valueOf(isAvailable), message)); <ide> <ide> synchronized (rollingLog) { <ide> final Event ret = new Event(hostname, isAvailable, message);
Java
lgpl-2.1
5d4a983e99a84ee8d09f07db9732236c30d42969
0
LiuKeHua/vrjuggler,LiuKeHua/vrjuggler,MichaelMcDonnell/vrjuggler,LiuKeHua/vrjuggler,LiuKeHua/vrjuggler,MichaelMcDonnell/vrjuggler,godbyk/vrjuggler-upstream-old,godbyk/vrjuggler-upstream-old,LiuKeHua/vrjuggler,vrjuggler/vrjuggler,LiuKeHua/vrjuggler,MichaelMcDonnell/vrjuggler,vancegroup-mirrors/vrjuggler,LiuKeHua/vrjuggler,vancegroup-mirrors/vrjuggler,vancegroup-mirrors/vrjuggler,MichaelMcDonnell/vrjuggler,vrjuggler/vrjuggler,godbyk/vrjuggler-upstream-old,vancegroup-mirrors/vrjuggler,vancegroup-mirrors/vrjuggler,MichaelMcDonnell/vrjuggler,MichaelMcDonnell/vrjuggler,vrjuggler/vrjuggler,MichaelMcDonnell/vrjuggler,LiuKeHua/vrjuggler,godbyk/vrjuggler-upstream-old,vrjuggler/vrjuggler,vrjuggler/vrjuggler,vancegroup-mirrors/vrjuggler,godbyk/vrjuggler-upstream-old,vrjuggler/vrjuggler,vrjuggler/vrjuggler,vrjuggler/vrjuggler,MichaelMcDonnell/vrjuggler,godbyk/vrjuggler-upstream-old
/*************** <auto-copyright.pl BEGIN do not edit this line> ************** * * VR Juggler is (C) Copyright 1998-2006 by Iowa State University * * Original Authors: * Allen Bierbaum, Christopher Just, * Patrick Hartling, Kevin Meinert, * Carolina Cruz-Neira, Albert Baker * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * *************** <auto-copyright.pl END do not edit this line> ***************/ package org.vrjuggler.tweek; import java.io.File; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Vector; import javax.swing.UIManager; import javax.swing.tree.DefaultMutableTreeNode; import com.birosoft.liquid.LiquidLookAndFeel; import com.incors.plaf.kunststoff.KunststoffLookAndFeel; import com.incors.plaf.kunststoff.mini.KunststoffMiniLookAndFeel; import com.jgoodies.looks.windows.WindowsLookAndFeel; import com.jgoodies.looks.plastic.PlasticLookAndFeel; import com.jgoodies.looks.plastic.Plastic3DLookAndFeel; import com.jgoodies.looks.plastic.PlasticXPLookAndFeel; import org.vrjuggler.tweek.beans.*; import org.vrjuggler.tweek.beans.loader.BeanInstantiationException; import org.vrjuggler.tweek.event.FileActionGenerator; import org.vrjuggler.tweek.event.FileActionListener; import org.vrjuggler.tweek.event.UndoActionGenerator; import org.vrjuggler.tweek.event.UndoActionListener; import org.vrjuggler.tweek.gui.TweekFrame; import org.vrjuggler.tweek.services.*; import org.vrjuggler.tweek.text.MessageDocument; import org.vrjuggler.tweek.net.corba.*; /** * The singleton entry point into the Tweek Java GUI. */ public class TweekCore implements BeanInstantiationListener { // ======================================================================== // Public methods. // ======================================================================== public static TweekCore instance () { if ( m_instance == null ) { m_instance = new TweekCore(); } return m_instance; } public void init(String[] args) throws Exception { // Register the internal static beans registerStaticBeans(); // This needs to be the first step to ensure that all the basic services // and viewers get loaded. EnvironmentServiceProxy env_service = new EnvironmentServiceProxy(); String default_path = env_service.getenv("TWEEK_BASE_DIR") + File.separator + env_service.getenv("TWEEK_DATA_DIR") + File.separator + "beans"; mBeanDirs.add(default_path); // Add in a user-specific Bean search path. try { GlobalPreferencesService service = new GlobalPreferencesServiceProxy(); String dir_name = service.getPrefsDir() + File.separator + "beans"; File bean_dir = new File(dir_name); if ( bean_dir.exists() && ! bean_dir.isDirectory() ) { System.err.println("WARNING: " + dir_name + " exists, but not as a directory!"); } // If the directory does not exist, create it to prevent a warning // from being printed later. else if ( ! bean_dir.exists() ) { bean_dir.mkdir(); } mBeanDirs.add(dir_name); } catch(RuntimeException ex) { System.err.println("WARNING: Failed to add user-specific directory " + "to the default Bean search path"); System.err.println(ex.getMessage()); } // As a side effect, the following may add more paths to mBeanDirs. String[] new_args = parseTweekArgs(args); // Explicitly load the global preferences now. The // GlobalPreferencesService class does not load them automatically. This // must happen after the command line arguments have been parsed so that // the user can specify an alternate preferences file. try { GlobalPreferencesService global_prefs = new GlobalPreferencesServiceProxy(); global_prefs.load(); // Set the look and feel now so that any GUI components that are // instantiated hereafter will have the correct look and feel. // XXX: If there are GUI components loaded statically (see above), // they will need to be updated. setLookAndFeel(global_prefs); } catch(java.io.IOException ex) { // This exception should never be thrown because failure to // register to GlobalPreferences Service Bean is a fatal error. } // Register the command-line arguments with the Environment Service (if // it is available). try { EnvironmentService service = new EnvironmentServiceProxy(); service.setCommandLineArgs(new_args); } catch(RuntimeException e) { // Use System.err here because the GUI has not been displayed yet. System.err.println("WARNING: Failed to register command-line arguments"); } // We need our TweekFrame instance before any dynamically discovered // Beans are loaded (or instantiated) because TweekFrame needs to know // about Bean instantiations. Furthermore, any given Bean may register // information (directly or indirectly) with TweekFrame in its // constructor, so TweekFrame needs to exist first. m_gui = new TweekFrame(messageDocument); // Loop over all the known Bean directories to search for and load any // Beans that are found. This must occur after the global preferences // have been loaded so that the user can enable or disable lazy Panel // Bean instantiation. Iterator i = mBeanDirs.iterator(); while ( i.hasNext() ) { String path = (String) i.next(); try { findAndLoadBeans(path); } catch (BeanPathException e) { System.out.println("WARNING: Invalid path " + path); } } // Now we need to register the TweekFrame instance as a listener for // BeanFocusChangeEvents. List viewer_beans = BeanRegistry.instance().getBeansOfType( ViewerBean.class.getName() ); for ( Iterator itr = viewer_beans.iterator(); itr.hasNext(); ) { BeanModelViewer v = ((ViewerBean)itr.next()).getViewer(); v.addBeanFocusChangeListener(m_gui); } m_gui.initGUI(); // Now select the default bean if necessary if (defaultBean != null) { messageDocument.printStatusnl("Trying to focus default bean: " + defaultBean); TweekBean bean = BeanRegistry.instance().getBean(defaultBean); // Valid the bean registered under the default bean's name if (bean == null) { messageDocument.printWarningnl("WARNING: Default Bean doesn't exist"); } else if (! (bean instanceof PanelBean)) { messageDocument.printWarningnl("WARNING: Default Bean is not a Panel Bean"); } else { ViewerBean viewer = m_gui.getBeanViewer(); if (viewer != null) { viewer.getViewer().focusBean((PanelBean)bean); } } } } /** * Registers the beans that are internal to Tweek that are required to exist * before the bean loading can begin. */ public static void registerStaticBeans() { BeanRegistry registry = BeanRegistry.instance(); // environment service registry.registerBean( new EnvironmentServiceImpl( new BeanAttributes( "Environment" ) ) ); // global preferences service try { registry.registerBean( new GlobalPreferencesServiceImpl( new BeanAttributes( "GlobalPreferences" ) ) ); } catch(java.io.IOException ex) { System.err.println("FATAL ERROR: Could not register " + "GlobalPreferences Service Bean!"); System.err.println(ex.getMessage()); System.exit(1); } } /** * Called by the BeanInstantiationCommunicator singleton whenever a new bean * is instantiated. */ public void beanInstantiated (BeanInstantiationEvent evt) { // If the bean created is a viewer bean, initialize it with tweek TweekBean bean = evt.getTweekBean(); if ( bean instanceof ViewerBean ) { BeanModelViewer viewer = ((ViewerBean)bean).getViewer(); viewer.setModel(panelTreeModel); viewer.initGUI(); } } /** * Look for TweekBeans in standard locations and register them in the * registry. * * @param path the path in which to search for TweekBeans */ public void findAndLoadBeans( String path ) throws BeanPathException { // Get the beans in the given path and add them to the dependency manager XMLBeanFinder finder = new XMLBeanFinder(mValidateXML); loadBeans(finder.find(path)); } public void loadBeans(List beans) { // Just to be safe... if ( null == beans ) { return; } mDepManager = BeanDependencyManager.instance(); for ( Iterator itr = beans.iterator(); itr.hasNext(); ) { TweekBean bean = (TweekBean)itr.next(); mDepManager.add(bean); } // Instantiate the beans pending in the dependency manager while (mDepManager.hasBeansPending()) { TweekBean bean = (TweekBean)mDepManager.pop(); if (bean == null) { // There are more beans pending, but they all have unsatisfied // dependencies so we can instantiate them ... break; } // Try to instantiate the Bean. try { boolean lazy_inst = true; // This service is loaded statically, so we do not have to worry // about finding the Bean first. try { GlobalPreferencesService prefs = new GlobalPreferencesServiceProxy(); lazy_inst = prefs.getLazyPanelBeanInstantiation(); } catch(java.io.IOException ioEx) { } // If the current Bean is not a Panel Bean or the user has disabled // lazy Panel Bean instantiation, we can instantiate the Bean. if ( ! (bean instanceof org.vrjuggler.tweek.beans.PanelBean) || ! lazy_inst ) { bean.instantiate(); } BeanRegistry.instance().registerBean(bean); } catch(BeanInstantiationException e) { messageDocument.printWarningnl("WARNING: Failed to instantiate Bean '" + bean.getName() + "': " + e.getMessage()); } catch(RuntimeException ex) { ex.printStackTrace(); } } } public BeanTreeModel getPanelTreeModel() { return panelTreeModel; } /** * Gets the name of the panel bean to select/instantiate by default when * Tweek is started. * * @return the name of the default bean; null if there is no default */ public String getDefaultBean() { return defaultBean; } /** * Gets the message document used for displaying run-time informational * messages in the Tweek Java GUI. * * @since 0.92.2 */ public MessageDocument getMessageDocument() { return messageDocument; } /** * Registers all the objects interested in file action events with the * given file action generator. * * @param gen the file action generator associated with a Tweek * Bean that implements the FileLoader interface. * * @see org.vrjuggler.tweek.beans.FileLoader * * @since 0.92.3 */ public void registerFileActionGenerator(FileActionGenerator gen) { gen.addFileActionListener(m_gui); } /** * Un-registers all the objects interested in file action events with the * given file action generator. * * @param gen the file action generator associated with a Tweek * Bean that implements the FileLoader interface. * * @see org.vrjuggler.tweek.beans.FileLoader * * @since 0.92.3 */ public void unregisterFileActionGenerator(FileActionGenerator gen) { gen.removeFileActionListener(m_gui); } /** * Returns all the FileActionListener objects known to the Tweek Java GUI. * * @since 0.92.3 */ public FileActionListener[] getFileActionListeners() { return new FileActionListener[]{m_gui}; } /** * Registers all the objects interested in undo action events with the * given undo action generator. * * @param gen the undo action generator associated with a Tweek * Bean that implements the UndoHandler interface. * * @see org.vrjuggler.tweek.beans.UndoHandler * * @since 0.92.4 */ public void registerUndoActionGenerator(UndoActionGenerator gen) { gen.addUndoActionListener(m_gui); } /** * Un-registers all the objects interested in undo action events with the * given undo action generator. * * @param gen the undo action generator associated with a Tweek * Bean that implements the UndoHandler interface. * * @see org.vrjuggler.tweek.beans.UndoHandler * * @since 0.92.4 */ public void unregisterUndoActionGenerator(UndoActionGenerator gen) { gen.removeUndoActionListener(m_gui); } /** * Returns all the UndoActionListener objects known to the Tweek Java GUI. * * @since 0.92.4 */ public UndoActionListener[] getUndoActionListeners() { return new UndoActionListener[]{m_gui}; } /** * Default constructor. */ protected TweekCore() { BeanInstantiationCommunicator.instance().addBeanInstantiationListener( this ); } /** * Looks through the given array of arguments for any that are specific to * the Tweek Java GUI. Those that are recognized are removed and handled * here. Unrecognized options are left in the array. The remaining * arguments are returned to the caller in a new array. * * Post condition: Any Tweek-specific arguments are removed and a new * array without those arguments is returned. */ protected String[] parseTweekArgs (String[] args) { Vector save_args = new Vector(); for ( int i = 0; i < args.length; i++ ) { if ( args[i].startsWith("--beanpath=") ) { int start = args[i].indexOf('=') + 1; String path = args[i].substring(start); mBeanDirs.add(path); } else if ( args[i].startsWith("--prefs=") ) { int start = args[i].indexOf('=') + 1; String path = args[i].substring(start); GlobalPreferencesService prefs = (GlobalPreferencesService) BeanRegistry.instance().getBean("GlobalPreferences"); prefs.setFileName(path); } else if ( args[i].startsWith("--defaultbean=") ) { int start = args[i].indexOf('=') + 1; // Replace instances of non-breaking space characters with ASCII // space characters. defaultBean = args[i].substring(start).replace('\u00A0', ' '); } else if ( args[i].startsWith("--validate") ) { mValidateXML = true; } else if ( args[i].startsWith("--help") || args[i].startsWith("-h") ) { printUsage(); System.exit(0); } else { save_args.add(args[i]); } } String[] new_args = null; if ( save_args.size() > 0 ) { new_args = new String[save_args.size()]; for ( int i = 0; i < save_args.size(); i++ ) { new_args[i] = (String) save_args.elementAt(i); } } return new_args; } /** * Prints the usage information for running the Tweek Java GUI. */ protected void printUsage() { System.out.println("--help, -h"); System.out.println(" Prints this usage information"); System.out.println("--beanpath=<path>"); System.out.println(" Specifiy one or more additional directories where Beans may be found"); System.out.println(" When using a list of directories, use the platform-specific path separator"); System.out.println("--defaultbean=<Panel Bean name>"); System.out.println(" Name a Panel Bean to load automatically at startup"); System.out.println("--prefs=<file>"); System.out.println(" Name a specific preferences file to load instead of <home-dir>/.tweekrc"); System.out.println("--validate"); System.out.println(" Enable validation of XML Bean list documents"); } // ======================================================================== // Protected data members. // ======================================================================== protected static TweekCore m_instance = null; // ======================================================================== // Private methods. // ======================================================================== /** * Sets the look and feel for the GUI. This assumes that the GUI will be * based on Swing and that Swing is available. */ private void setLookAndFeel(GlobalPreferencesService prefs) { // Install extra look and feels. UIManager.installLookAndFeel("Kunststoff", KunststoffLookAndFeel.class.getName()); KunststoffLookAndFeel.setIsInstalled(true); UIManager.installLookAndFeel("Kunststoff Mini", KunststoffMiniLookAndFeel.class.getName()); KunststoffMiniLookAndFeel.setIsInstalled(true); // These install themselves with the UI Manager automatically. new LiquidLookAndFeel(); new net.sourceforge.mlf.metouia.MetouiaLookAndFeel(); UIManager.installLookAndFeel("JGoodies Windows", WindowsLookAndFeel.class.getName()); UIManager.installLookAndFeel("JGoodies Plastic", PlasticLookAndFeel.class.getName()); UIManager.installLookAndFeel("JGoodies Plastic 3D", Plastic3DLookAndFeel.class.getName()); UIManager.installLookAndFeel("JGoodies Plastic XP", PlasticXPLookAndFeel.class.getName()); try { UIManager.setLookAndFeel(prefs.getLookAndFeel()); } catch (Exception e) { messageDocument.printWarningnl("Failed to set look and feel to " + prefs.getLookAndFeel()); } } // ======================================================================== // Private data members. // ======================================================================== /** * The name of the panel bean to select by default when Tweek is started. */ private String defaultBean = null; /** * The bean dependency manager used to load beans in a stable order. */ private BeanDependencyManager mDepManager; private boolean mValidateXML = false; private List mBeanDirs = new ArrayList(); private MessageDocument messageDocument = new MessageDocument(); private TweekFrame m_gui = null; private BeanTreeModel panelTreeModel = new BeanTreeModel(new DefaultMutableTreeNode()); }
modules/tweek/java/org/vrjuggler/tweek/TweekCore.java
/*************** <auto-copyright.pl BEGIN do not edit this line> ************** * * VR Juggler is (C) Copyright 1998-2006 by Iowa State University * * Original Authors: * Allen Bierbaum, Christopher Just, * Patrick Hartling, Kevin Meinert, * Carolina Cruz-Neira, Albert Baker * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * *************** <auto-copyright.pl END do not edit this line> ***************/ package org.vrjuggler.tweek; import java.io.File; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Vector; import javax.swing.UIManager; import javax.swing.tree.DefaultMutableTreeNode; import com.birosoft.liquid.LiquidLookAndFeel; import com.incors.plaf.kunststoff.KunststoffLookAndFeel; import com.incors.plaf.kunststoff.mini.KunststoffMiniLookAndFeel; import com.jgoodies.looks.windows.WindowsLookAndFeel; import com.jgoodies.looks.plastic.PlasticLookAndFeel; import com.jgoodies.looks.plastic.Plastic3DLookAndFeel; import com.jgoodies.looks.plastic.PlasticXPLookAndFeel; import org.vrjuggler.tweek.beans.*; import org.vrjuggler.tweek.beans.loader.BeanInstantiationException; import org.vrjuggler.tweek.event.FileActionGenerator; import org.vrjuggler.tweek.event.FileActionListener; import org.vrjuggler.tweek.event.UndoActionGenerator; import org.vrjuggler.tweek.event.UndoActionListener; import org.vrjuggler.tweek.gui.TweekFrame; import org.vrjuggler.tweek.services.*; import org.vrjuggler.tweek.text.MessageDocument; import org.vrjuggler.tweek.net.corba.*; /** * The singleton entry point into the Tweek Java GUI. */ public class TweekCore implements BeanInstantiationListener { // ======================================================================== // Public methods. // ======================================================================== public static TweekCore instance () { if ( m_instance == null ) { m_instance = new TweekCore(); } return m_instance; } public void init(String[] args) throws Exception { // Register the internal static beans registerStaticBeans(); // This needs to be the first step to ensure that all the basic services // and viewers get loaded. EnvironmentServiceProxy env_service = new EnvironmentServiceProxy(); String default_path = env_service.getenv("TWEEK_BASE_DIR") + File.separator + env_service.getenv("TWEEK_DATA_DIR") + File.separator + "beans"; mBeanDirs.add(default_path); // Add in a user-specific Bean search path. try { GlobalPreferencesService service = new GlobalPreferencesServiceProxy(); String dir_name = service.getPrefsDir() + File.separator + "beans"; File bean_dir = new File(dir_name); if ( bean_dir.exists() && ! bean_dir.isDirectory() ) { System.err.println("WARNING: " + dir_name + " exists, but not as a directory!"); } // If the directory does not exist, create it to prevent a warning // from being printed later. else if ( ! bean_dir.exists() ) { bean_dir.mkdir(); } mBeanDirs.add(dir_name); } catch(RuntimeException ex) { System.err.println("WARNING: Failed to add user-specific directory " + "to the default Bean search path"); System.err.println(ex.getMessage()); } // As a side effect, the following may add more paths to mBeanDirs. String[] new_args = parseTweekArgs(args); // Explicitly load the global preferences now. The // GlobalPreferencesService class does not load them automatically. This // must happen after the command line arguments have been parsed so that // the user can specify an alternate preferences file. try { GlobalPreferencesService global_prefs = new GlobalPreferencesServiceProxy(); global_prefs.load(); // Set the look and feel now so that any GUI components that are // instantiated hereafter will have the correct look and feel. // XXX: If there are GUI components loaded statically (see above), // they will need to be updated. setLookAndFeel(global_prefs); } catch(java.io.IOException ex) { // This exception should never be thrown because failure to // register to GlobalPreferences Service Bean is a fatal error. } // Register the command-line arguments with the Environment Service (if // it is available). try { EnvironmentService service = new EnvironmentServiceProxy(); service.setCommandLineArgs(new_args); } catch(RuntimeException e) { // Use System.err here because the GUI has not been displayed yet. System.err.println("WARNING: Failed to register command-line arguments"); } // We need our TweekFrame instance before any dynamically discovered // Beans are loaded (or instantiated) because TweekFrame needs to know // about Bean instantiations. Furthermore, any given Bean may register // information (directly or indirectly) with TweekFrame in its // constructor, so TweekFrame needs to exist first. m_gui = new TweekFrame(messageDocument); // Loop over all the known Bean directories to search for and load any // Beans that are found. This must occur after the global preferences // have been loaded so that the user can enable or disable lazy Panel // Bean instantiation. Iterator i = mBeanDirs.iterator(); while ( i.hasNext() ) { String path = (String) i.next(); try { findAndLoadBeans(path); } catch (BeanPathException e) { System.out.println("WARNING: Invalid path " + path); } } // Now we need to register the TweekFrame instance as a listener for // BeanFocusChangeEvents. List viewer_beans = BeanRegistry.instance().getBeansOfType( ViewerBean.class.getName() ); for ( Iterator itr = viewer_beans.iterator(); itr.hasNext(); ) { BeanModelViewer v = ((ViewerBean)itr.next()).getViewer(); v.addBeanFocusChangeListener(m_gui); } m_gui.initGUI(); // Now select the default bean if necessary if (defaultBean != null) { messageDocument.printStatusnl("Trying to focus default bean: " + defaultBean); TweekBean bean = BeanRegistry.instance().getBean(defaultBean); // Valid the bean registered under the default bean's name if (bean == null) { messageDocument.printWarningnl("WARNING: Default Bean doesn't exist"); } else if (! (bean instanceof PanelBean)) { messageDocument.printWarningnl("WARNING: Default Bean is not a Panel Bean"); } else { ViewerBean viewer = m_gui.getBeanViewer(); if (viewer != null) { viewer.getViewer().focusBean((PanelBean)bean); } } } } /** * Registers the beans that are internal to Tweek that are required to exist * before the bean loading can begin. */ public static void registerStaticBeans() { BeanRegistry registry = BeanRegistry.instance(); // environment service registry.registerBean( new EnvironmentServiceImpl( new BeanAttributes( "Environment" ) ) ); // global preferences service try { registry.registerBean( new GlobalPreferencesServiceImpl( new BeanAttributes( "GlobalPreferences" ) ) ); } catch(java.io.IOException ex) { System.err.println("FATAL ERROR: Could not register " + "GlobalPreferences Service Bean!"); System.err.println(ex.getMessage()); System.exit(1); } } /** * Called by the BeanInstantiationCommunicator singleton whenever a new bean * is instantiated. */ public void beanInstantiated (BeanInstantiationEvent evt) { // If the bean created is a viewer bean, initialize it with tweek TweekBean bean = evt.getTweekBean(); if ( bean instanceof ViewerBean ) { BeanModelViewer viewer = ((ViewerBean)bean).getViewer(); viewer.setModel(panelTreeModel); viewer.initGUI(); } } /** * Look for TweekBeans in standard locations and register them in the * registry. * * @param path the path in which to search for TweekBeans */ public void findAndLoadBeans( String path ) throws BeanPathException { // Get the beans in the given path and add them to the dependency manager XMLBeanFinder finder = new XMLBeanFinder(mValidateXML); loadBeans(finder.find(path)); } public void loadBeans(List beans) { // Just to be safe... if ( null == beans ) { return; } mDepManager = BeanDependencyManager.instance(); for ( Iterator itr = beans.iterator(); itr.hasNext(); ) { TweekBean bean = (TweekBean)itr.next(); mDepManager.add(bean); } // Instantiate the beans pending in the dependency manager while (mDepManager.hasBeansPending()) { TweekBean bean = (TweekBean)mDepManager.pop(); if (bean == null) { // There are more beans pending, but they all have unsatisfied // dependencies so we can instantiate them ... break; } // Try to instantiate the Bean. try { boolean lazy_inst = true; // This service is loaded statically, so we do not have to worry // about finding the Bean first. try { GlobalPreferencesService prefs = new GlobalPreferencesServiceProxy(); lazy_inst = prefs.getLazyPanelBeanInstantiation(); } catch(java.io.IOException ioEx) { } // If the current Bean is not a Panel Bean or the user has disabled // lazy Panel Bean instantiation, we can instantiate the Bean. if ( ! (bean instanceof org.vrjuggler.tweek.beans.PanelBean) || ! lazy_inst ) { bean.instantiate(); } BeanRegistry.instance().registerBean(bean); } catch(BeanInstantiationException e) { messageDocument.printWarningnl("WARNING: Failed to instantiate Bean '" + bean.getName() + "': " + e.getMessage()); } catch(RuntimeException ex) { ex.printStackTrace(); } } } public BeanTreeModel getPanelTreeModel() { return panelTreeModel; } /** * Gets the name of the panel bean to select/instantiate by default when * Tweek is started. * * @return the name of the default bean; null if there is no default */ public String getDefaultBean() { return defaultBean; } /** * Gets the message document used for displaying run-time informational * messages in the Tweek Java GUI. * * @since 0.92.2 */ public MessageDocument getMessageDocument() { return messageDocument; } /** * Registers all the objects interested in file action events with the * given file action generator. * * @param gen the file action generator associated with a Tweek * Bean that implements the FileLoader interface. * * @see org.vrjuggler.tweek.beans.FileLoader * * @since 0.92.3 */ public void registerFileActionGenerator(FileActionGenerator gen) { gen.addFileActionListener(m_gui); } /** * Un-registers all the objects interested in file action events with the * given file action generator. * * @param gen the file action generator associated with a Tweek * Bean that implements the FileLoader interface. * * @see org.vrjuggler.tweek.beans.FileLoader * * @since 0.92.3 */ public void unregisterFileActionGenerator(FileActionGenerator gen) { gen.removeFileActionListener(m_gui); } /** * Returns all the FileActionListener objects known to the Tweek Java GUI. * * @since 0.92.3 */ public FileActionListener[] getFileActionListeners() { return new FileActionListener[]{m_gui}; } /** * Registers all the objects interested in undo action events with the * given undo action generator. * * @param gen the undo action generator associated with a Tweek * Bean that implements the UndoHandler interface. * * @see org.vrjuggler.tweek.beans.UndoHandler * * @since 0.92.4 */ public void registerUndoActionGenerator(UndoActionGenerator gen) { gen.addUndoActionListener(m_gui); } /** * Un-registers all the objects interested in undo action events with the * given undo action generator. * * @param gen the undo action generator associated with a Tweek * Bean that implements the UndoHandler interface. * * @see org.vrjuggler.tweek.beans.UndoHandler * * @since 0.92.4 */ public void unregisterUndoActionGenerator(UndoActionGenerator gen) { gen.removeUndoActionListener(m_gui); } /** * Returns all the UndoActionListener objects known to the Tweek Java GUI. * * @since 0.92.4 */ public UndoActionListener[] getUndoActionListeners() { return new UndoActionListener[]{m_gui}; } /** * Default constructor. */ protected TweekCore() { BeanInstantiationCommunicator.instance().addBeanInstantiationListener( this ); } /** * Looks through the given array of arguments for any that are specific to * the Tweek Java GUI. Those that are recognized are removed and handled * here. Unrecognized options are left in the array. The remaining * arguments are returned to the caller in a new array. * * Post condition: Any Tweek-specific arguments are removed and a new * array without those arguments is returned. */ protected String[] parseTweekArgs (String[] args) { Vector save_args = new Vector(); for ( int i = 0; i < args.length; i++ ) { if ( args[i].startsWith("--beanpath=") ) { int start = args[i].indexOf('=') + 1; String path = args[i].substring(start); mBeanDirs.add(path); } else if ( args[i].startsWith("--prefs=") ) { int start = args[i].indexOf('=') + 1; String path = args[i].substring(start); GlobalPreferencesService prefs = (GlobalPreferencesService) BeanRegistry.instance().getBean("GlobalPreferences"); prefs.setFileName(path); } else if ( args[i].startsWith("--defaultbean=") ) { int start = args[i].indexOf('=') + 1; // Replace instances of non-breaking space characters with ASCII // space characters. defaultBean = args[i].substring(start).replace('\u00A0', ' '); } else if ( args[i].startsWith("--validate") ) { mValidateXML = true; } else if ( args[i].startsWith("--help") || args[i].startsWith("-h") ) { printUsage(); System.exit(0); } else { save_args.add(args[i]); } } String[] new_args = null; if ( save_args.size() > 0 ) { new_args = new String[save_args.size()]; for ( int i = 0; i < save_args.size(); i++ ) { new_args[i] = (String) save_args.elementAt(i); } } return new_args; } /** * Prints the usage information for running the Tweek Java GUI. */ protected void printUsage() { System.out.println("--help, -h"); System.out.println(" Prints this usage information"); System.out.println("--beanpath=<path>"); System.out.println(" Specifiy one or more additional directories where Beans may be found"); System.out.println(" When using a list of directories, use the platform-specific path separator"); System.out.println("--defaultbean=<Panel Bean name>"); System.out.println(" Name a Panel Bean to load automatically at startup"); System.out.println("--prefs=<file>"); System.out.println(" Name a specific preferences file to load instead of <home-dir>/.tweekrc"); System.out.println("--validate"); System.out.println(" Enable validation of XML Bean list documents"); } // ======================================================================== // Protected data members. // ======================================================================== protected static TweekCore m_instance = null; // ======================================================================== // Private methods. // ======================================================================== /** * Sets the look and feel for the GUI. This assumes that the GUI will be * based on Swing and that Swing is available. */ private void setLookAndFeel(GlobalPreferencesService prefs) { // Install extra look and feels. UIManager.installLookAndFeel("Kunststoff", KunststoffLookAndFeel.class.getName()); KunststoffLookAndFeel.setIsInstalled(true); UIManager.installLookAndFeel("Kunststoff Mini", KunststoffMiniLookAndFeel.class.getName()); KunststoffMiniLookAndFeel.setIsInstalled(true); // These install themselves with the UI Manager automatically. new LiquidLookAndFeel(); new net.sourceforge.mlf.metouia.MetouiaLookAndFeel(); UIManager.installLookAndFeel("JGoodies Windows", WindowsLookAndFeel.class.getName()); UIManager.installLookAndFeel("JGoodies Plastic", PlasticLookAndFeel.class.getName()); UIManager.installLookAndFeel("JGoodies Plastic 3D", Plastic3DLookAndFeel.class.getName()); UIManager.installLookAndFeel("JGoodies Plastic XP", PlasticXPLookAndFeel.class.getName()); try { UIManager.setLookAndFeel(prefs.getLookAndFeel()); } catch (Exception e) { messageDocument.printWarningnl("Failed to set look and feel to " + prefs.getLookAndFeel()); } } // ======================================================================== // Private data members. // ======================================================================== /** * The name of the panel bean to select by default when Tweek is started. */ private String defaultBean = null; /** * The bean dependency manager used to load beans in a stable order. */ private BeanDependencyManager mDepManager; private boolean mValidateXML = false; private List mBeanDirs = new ArrayList(); private MessageDocument messageDocument = new MessageDocument(); private TweekFrame m_gui = null; private BeanTreeModel panelTreeModel = new BeanTreeModel(new DefaultMutableTreeNode()); }
Style fixes. No functional changes. git-svn-id: a341ccba1312b2efdbe34f40faf90581f48aa49f@19165 08b38cba-cd3b-11de-854e-f91c5b6e4272
modules/tweek/java/org/vrjuggler/tweek/TweekCore.java
Style fixes. No functional changes.
<ide><path>odules/tweek/java/org/vrjuggler/tweek/TweekCore.java <ide> // and viewers get loaded. <ide> EnvironmentServiceProxy env_service = new EnvironmentServiceProxy(); <ide> String default_path = env_service.getenv("TWEEK_BASE_DIR") + <del> File.separator + env_service.getenv("TWEEK_DATA_DIR") + <add> File.separator + <add> env_service.getenv("TWEEK_DATA_DIR") + <ide> File.separator + "beans"; <ide> mBeanDirs.add(default_path); <del> <ide> <ide> // Add in a user-specific Bean search path. <ide> try
JavaScript
bsd-3-clause
19bf5af565998d90291b43ada340ef1dda779655
0
redaktor/deliteful
define([ "dojo/_base/kernel", "..", "dojo/_base/array", // dojo.every "dojo/_base/lang", // dojo.isArray "dojo/_base/window" // dojo.global ], function(dojo, dijit){ // module: // dijit/_editor/range // summary: // W3C range API dijit.range={}; dijit.range.getIndex = function(/*DomNode*/node, /*DomNode*/parent){ // dojo.profile.start("dijit.range.getIndex"); var ret = [], retR = []; var stop = parent; var onode = node; var pnode, n; while(node != stop){ var i = 0; pnode = node.parentNode; while((n = pnode.childNodes[i++])){ if(n === node){ --i; break; } } //if(i>=pnode.childNodes.length){ //dojo.debug("Error finding index of a node in dijit.range.getIndex"); //} ret.unshift(i); retR.unshift(i - pnode.childNodes.length); node = pnode; } //normalized() can not be called so often to prevent //invalidating selection/range, so we have to detect //here that any text nodes in a row if(ret.length > 0 && onode.nodeType == 3){ n = onode.previousSibling; while(n && n.nodeType == 3){ ret[ret.length - 1]--; n = n.previousSibling; } n = onode.nextSibling; while(n && n.nodeType == 3){ retR[retR.length - 1]++; n = n.nextSibling; } } // dojo.profile.end("dijit.range.getIndex"); return {o: ret, r:retR}; }; dijit.range.getNode = function(/*Array*/index, /*DomNode*/parent){ if(!dojo.isArray(index) || index.length == 0){ return parent; } var node = parent; // if(!node)debugger dojo.every(index, function(i){ if(i >= 0 && i < node.childNodes.length){ node = node.childNodes[i]; }else{ node = null; //console.debug('Error: can not find node with index',index,'under parent node',parent ); return false; //terminate dojo.every } return true; //carry on the every loop }); return node; }; dijit.range.getCommonAncestor = function(n1, n2, root){ root = root || n1.ownerDocument.body; var getAncestors = function(n){ var as = []; while(n){ as.unshift(n); if(n !== root){ n = n.parentNode; }else{ break; } } return as; }; var n1as = getAncestors(n1); var n2as = getAncestors(n2); var m = Math.min(n1as.length, n2as.length); var com = n1as[0]; //at least, one element should be in the array: the root (BODY by default) for(var i = 1; i < m; i++){ if(n1as[i] === n2as[i]){ com = n1as[i] }else{ break; } } return com; }; dijit.range.getAncestor = function(/*DomNode*/node, /*RegEx?*/regex, /*DomNode?*/root){ root = root || node.ownerDocument.body; while(node && node !== root){ var name = node.nodeName.toUpperCase(); if(regex.test(name)){ return node; } node = node.parentNode; } return null; }; dijit.range.BlockTagNames = /^(?:P|DIV|H1|H2|H3|H4|H5|H6|ADDRESS|PRE|OL|UL|LI|DT|DE)$/; dijit.range.getBlockAncestor = function(/*DomNode*/node, /*RegEx?*/regex, /*DomNode?*/root){ root = root || node.ownerDocument.body; regex = regex || dijit.range.BlockTagNames; var block = null, blockContainer; while(node && node !== root){ var name = node.nodeName.toUpperCase(); if(!block && regex.test(name)){ block = node; } if(!blockContainer && (/^(?:BODY|TD|TH|CAPTION)$/).test(name)){ blockContainer = node; } node = node.parentNode; } return {blockNode:block, blockContainer:blockContainer || node.ownerDocument.body}; }; dijit.range.atBeginningOfContainer = function(/*DomNode*/container, /*DomNode*/node, /*Int*/offset){ var atBeginning = false; var offsetAtBeginning = (offset == 0); if(!offsetAtBeginning && node.nodeType == 3){ //if this is a text node, check whether the left part is all space if(/^[\s\xA0]+$/.test(node.nodeValue.substr(0, offset))){ offsetAtBeginning = true; } } if(offsetAtBeginning){ var cnode = node; atBeginning = true; while(cnode && cnode !== container){ if(cnode.previousSibling){ atBeginning = false; break; } cnode = cnode.parentNode; } } return atBeginning; }; dijit.range.atEndOfContainer = function(/*DomNode*/container, /*DomNode*/node, /*Int*/offset){ var atEnd = false; var offsetAtEnd = (offset == (node.length || node.childNodes.length)); if(!offsetAtEnd && node.nodeType == 3){ //if this is a text node, check whether the right part is all space if(/^[\s\xA0]+$/.test(node.nodeValue.substr(offset))){ offsetAtEnd = true; } } if(offsetAtEnd){ var cnode = node; atEnd = true; while(cnode && cnode !== container){ if(cnode.nextSibling){ atEnd = false; break; } cnode = cnode.parentNode; } } return atEnd; }; dijit.range.adjacentNoneTextNode = function(startnode, next){ var node = startnode; var len = (0 - startnode.length) || 0; var prop = next ? 'nextSibling' : 'previousSibling'; while(node){ if(node.nodeType != 3){ break; } len += node.length node = node[prop]; } return [node,len]; }; dijit.range._w3c = Boolean(window['getSelection']); dijit.range.create = function(/*Window?*/win){ if(dijit.range._w3c){ return (win || dojo.global).document.createRange(); }else{//IE return new dijit.range.W3CRange; } }; dijit.range.getSelection = function(/*Window*/win, /*Boolean?*/ignoreUpdate){ if(dijit.range._w3c){ return win.getSelection(); }else{//IE var s = new dijit.range.ie.selection(win); if(!ignoreUpdate){ s._getCurrentSelection(); } return s; } }; if(!dijit.range._w3c){ dijit.range.ie = { cachedSelection: {}, selection: function(win){ this._ranges = []; this.addRange = function(r, /*boolean*/internal){ this._ranges.push(r); if(!internal){ r._select(); } this.rangeCount = this._ranges.length; }; this.removeAllRanges = function(){ //don't detach, the range may be used later // for(var i=0;i<this._ranges.length;i++){ // this._ranges[i].detach(); // } this._ranges = []; this.rangeCount = 0; }; var _initCurrentRange = function(){ var r = win.document.selection.createRange(); var type = win.document.selection.type.toUpperCase(); if(type == "CONTROL"){ //TODO: multiple range selection(?) return new dijit.range.W3CRange(dijit.range.ie.decomposeControlRange(r)); }else{ return new dijit.range.W3CRange(dijit.range.ie.decomposeTextRange(r)); } }; this.getRangeAt = function(i){ return this._ranges[i]; }; this._getCurrentSelection = function(){ this.removeAllRanges(); var r = _initCurrentRange(); if(r){ this.addRange(r, true); this.isCollapsed = r.collapsed; }else{ this.isCollapsed = true; } }; }, decomposeControlRange: function(range){ var firstnode = range.item(0), lastnode = range.item(range.length - 1); var startContainer = firstnode.parentNode, endContainer = lastnode.parentNode; var startOffset = dijit.range.getIndex(firstnode, startContainer).o[0]; var endOffset = dijit.range.getIndex(lastnode, endContainer).o[0] + 1; return [startContainer, startOffset,endContainer, endOffset]; }, getEndPoint: function(range, end){ var atmrange = range.duplicate(); atmrange.collapse(!end); var cmpstr = 'EndTo' + (end ? 'End' : 'Start'); var parentNode = atmrange.parentElement(); var startnode, startOffset, lastNode; if(parentNode.childNodes.length > 0){ dojo.every(parentNode.childNodes, function(node, i){ var calOffset; if(node.nodeType != 3){ atmrange.moveToElementText(node); if(atmrange.compareEndPoints(cmpstr, range) > 0){ //startnode = node.previousSibling; if(lastNode && lastNode.nodeType == 3){ //where shall we put the start? in the text node or after? startnode = lastNode; calOffset = true; }else{ startnode = parentNode; startOffset = i; return false; } }else{ if(i == parentNode.childNodes.length - 1){ startnode = parentNode; startOffset = parentNode.childNodes.length; return false; } } }else{ if(i == parentNode.childNodes.length - 1){//at the end of this node startnode = node; calOffset = true; } } // try{ if(calOffset && startnode){ var prevnode = dijit.range.adjacentNoneTextNode(startnode)[0]; if(prevnode){ startnode = prevnode.nextSibling; }else{ startnode = parentNode.firstChild; //firstChild must be a text node } var prevnodeobj = dijit.range.adjacentNoneTextNode(startnode); prevnode = prevnodeobj[0]; var lenoffset = prevnodeobj[1]; if(prevnode){ atmrange.moveToElementText(prevnode); atmrange.collapse(false); }else{ atmrange.moveToElementText(parentNode); } atmrange.setEndPoint(cmpstr, range); startOffset = atmrange.text.length - lenoffset; return false; } // }catch(e){ debugger } lastNode = node; return true; }); }else{ startnode = parentNode; startOffset = 0; } //if at the end of startnode and we are dealing with start container, then //move the startnode to nextSibling if it is a text node //TODO: do this for end container? if(!end && startnode.nodeType == 1 && startOffset == startnode.childNodes.length){ var nextnode = startnode.nextSibling; if(nextnode && nextnode.nodeType == 3){ startnode = nextnode; startOffset = 0; } } return [startnode, startOffset]; }, setEndPoint: function(range, container, offset){ //text node var atmrange = range.duplicate(), node, len; if(container.nodeType != 3){ //normal node if(offset > 0){ node = container.childNodes[offset - 1]; if(node){ if(node.nodeType == 3){ container = node; offset = node.length; //pass through }else{ if(node.nextSibling && node.nextSibling.nodeType == 3){ container = node.nextSibling; offset = 0; //pass through }else{ atmrange.moveToElementText(node.nextSibling ? node : container); var parent = node.parentNode; var tempNode = parent.insertBefore(node.ownerDocument.createTextNode(' '), node.nextSibling); atmrange.collapse(false); parent.removeChild(tempNode); } } } }else{ atmrange.moveToElementText(container); atmrange.collapse(true); } } if(container.nodeType == 3){ var prevnodeobj = dijit.range.adjacentNoneTextNode(container); var prevnode = prevnodeobj[0]; len = prevnodeobj[1]; if(prevnode){ atmrange.moveToElementText(prevnode); atmrange.collapse(false); //if contentEditable is not inherit, the above collapse won't make the end point //in the correctly position: it always has a -1 offset, so compensate it if(prevnode.contentEditable != 'inherit'){ len++; } }else{ atmrange.moveToElementText(container.parentNode); atmrange.collapse(true); } offset += len; if(offset > 0){ if(atmrange.move('character', offset) != offset){ console.error('Error when moving!'); } } } return atmrange; }, decomposeTextRange: function(range){ var tmpary = dijit.range.ie.getEndPoint(range); var startContainer = tmpary[0], startOffset = tmpary[1]; var endContainer = tmpary[0], endOffset = tmpary[1]; if(range.htmlText.length){ if(range.htmlText == range.text){ //in the same text node endOffset = startOffset + range.text.length; }else{ tmpary = dijit.range.ie.getEndPoint(range, true); endContainer = tmpary[0],endOffset = tmpary[1]; // if(startContainer.tagName == "BODY"){ // startContainer = startContainer.firstChild; // } } } return [startContainer, startOffset, endContainer, endOffset]; }, setRange: function(range, startContainer, startOffset, endContainer, endOffset, collapsed){ var start = dijit.range.ie.setEndPoint(range, startContainer, startOffset); range.setEndPoint('StartToStart', start); if(!collapsed){ var end = dijit.range.ie.setEndPoint(range, endContainer, endOffset); } range.setEndPoint('EndToEnd', end || start); return range; } }; dojo.declare("dijit.range.W3CRange",null, { constructor: function(){ if(arguments.length>0){ this.setStart(arguments[0][0],arguments[0][1]); this.setEnd(arguments[0][2],arguments[0][3]); }else{ this.commonAncestorContainer = null; this.startContainer = null; this.startOffset = 0; this.endContainer = null; this.endOffset = 0; this.collapsed = true; } }, _updateInternal: function(){ if(this.startContainer !== this.endContainer){ this.commonAncestorContainer = dijit.range.getCommonAncestor(this.startContainer, this.endContainer); }else{ this.commonAncestorContainer = this.startContainer; } this.collapsed = (this.startContainer === this.endContainer) && (this.startOffset == this.endOffset); }, setStart: function(node, offset){ offset=parseInt(offset); if(this.startContainer === node && this.startOffset == offset){ return; } delete this._cachedBookmark; this.startContainer = node; this.startOffset = offset; if(!this.endContainer){ this.setEnd(node, offset); }else{ this._updateInternal(); } }, setEnd: function(node, offset){ offset=parseInt(offset); if(this.endContainer === node && this.endOffset == offset){ return; } delete this._cachedBookmark; this.endContainer = node; this.endOffset = offset; if(!this.startContainer){ this.setStart(node, offset); }else{ this._updateInternal(); } }, setStartAfter: function(node, offset){ this._setPoint('setStart', node, offset, 1); }, setStartBefore: function(node, offset){ this._setPoint('setStart', node, offset, 0); }, setEndAfter: function(node, offset){ this._setPoint('setEnd', node, offset, 1); }, setEndBefore: function(node, offset){ this._setPoint('setEnd', node, offset, 0); }, _setPoint: function(what, node, offset, ext){ var index = dijit.range.getIndex(node, node.parentNode).o; this[what](node.parentNode, index.pop()+ext); }, _getIERange: function(){ var r = (this._body || this.endContainer.ownerDocument.body).createTextRange(); dijit.range.ie.setRange(r, this.startContainer, this.startOffset, this.endContainer, this.endOffset, this.collapsed); return r; }, getBookmark: function(body){ this._getIERange(); return this._cachedBookmark; }, _select: function(){ var r = this._getIERange(); r.select(); }, deleteContents: function(){ var r = this._getIERange(); r.pasteHTML(''); this.endContainer = this.startContainer; this.endOffset = this.startOffset; this.collapsed = true; }, cloneRange: function(){ var r = new dijit.range.W3CRange([this.startContainer,this.startOffset, this.endContainer,this.endOffset]); r._body = this._body; return r; }, detach: function(){ this._body = null; this.commonAncestorContainer = null; this.startContainer = null; this.startOffset = 0; this.endContainer = null; this.endOffset = 0; this.collapsed = true; } }); } //if(!dijit.range._w3c) return dijit.range; });
_editor/range.js
define([ "dojo/_base/kernel", "..", "dojo/_base/array", // dojo.every "dojo/_base/lang", // dojo.isArray "dojo/_base/window" // dojo.global ], function(dojo, dijit){ // module: // dijit/_editor/range // summary: // W3C range API dijit.range={}; dijit.range.getIndex = function(/*DomNode*/node, /*DomNode*/parent){ // dojo.profile.start("dijit.range.getIndex"); var ret = [], retR = []; var stop = parent; var onode = node; var pnode, n; while(node != stop){ var i = 0; pnode = node.parentNode; while((n = pnode.childNodes[i++])){ if(n === node){ --i; break; } } //if(i>=pnode.childNodes.length){ //dojo.debug("Error finding index of a node in dijit.range.getIndex"); //} ret.unshift(i); retR.unshift(i - pnode.childNodes.length); node = pnode; } //normalized() can not be called so often to prevent //invalidating selection/range, so we have to detect //here that any text nodes in a row if(ret.length > 0 && onode.nodeType == 3){ n = onode.previousSibling; while(n && n.nodeType == 3){ ret[ret.length - 1]--; n = n.previousSibling; } n = onode.nextSibling; while(n && n.nodeType == 3){ retR[retR.length - 1]++; n = n.nextSibling; } } // dojo.profile.end("dijit.range.getIndex"); return {o: ret, r:retR}; }; dijit.range.getNode = function(/*Array*/index, /*DomNode*/parent){ if(!dojo.isArray(index) || index.length == 0){ return parent; } var node = parent; // if(!node)debugger dojo.every(index, function(i){ if(i >= 0 && i < node.childNodes.length){ node = node.childNodes[i]; }else{ node = null; //console.debug('Error: can not find node with index',index,'under parent node',parent ); return false; //terminate dojo.every } return true; //carry on the every loop }); return node; }; dijit.range.getCommonAncestor = function(n1, n2, root){ root = root || n1.ownerDocument.body; var getAncestors = function(n){ var as = []; while(n){ as.unshift(n); if(n !== root){ n = n.parentNode; }else{ break; } } return as; }; var n1as = getAncestors(n1); var n2as = getAncestors(n2); var m = Math.min(n1as.length, n2as.length); var com = n1as[0]; //at least, one element should be in the array: the root (BODY by default) for(var i = 1; i < m; i++){ if(n1as[i] === n2as[i]){ com = n1as[i] }else{ break; } } return com; }; dijit.range.getAncestor = function(/*DomNode*/node, /*RegEx?*/regex, /*DomNode?*/root){ root = root || node.ownerDocument.body; while(node && node !== root){ var name = node.nodeName.toUpperCase(); if(regex.test(name)){ return node; } node = node.parentNode; } return null; }; dijit.range.BlockTagNames = /^(?:P|DIV|H1|H2|H3|H4|H5|H6|ADDRESS|PRE|OL|UL|LI|DT|DE)$/; dijit.range.getBlockAncestor = function(/*DomNode*/node, /*RegEx?*/regex, /*DomNode?*/root){ root = root || node.ownerDocument.body; regex = regex || dijit.range.BlockTagNames; var block = null, blockContainer; while(node && node !== root){ var name = node.nodeName.toUpperCase(); if(!block && regex.test(name)){ block = node; } if(!blockContainer && (/^(?:BODY|TD|TH|CAPTION)$/).test(name)){ blockContainer = node; } node = node.parentNode; } return {blockNode:block, blockContainer:blockContainer || node.ownerDocument.body}; }; dijit.range.atBeginningOfContainer = function(/*DomNode*/container, /*DomNode*/node, /*Int*/offset){ var atBeginning = false; var offsetAtBeginning = (offset == 0); if(!offsetAtBeginning && node.nodeType == 3){ //if this is a text node, check whether the left part is all space if(/^[\s\xA0]+$/.test(node.nodeValue.substr(0, offset))){ offsetAtBeginning = true; } } if(offsetAtBeginning){ var cnode = node; atBeginning = true; while(cnode && cnode !== container){ if(cnode.previousSibling){ atBeginning = false; break; } cnode = cnode.parentNode; } } return atBeginning; }; dijit.range.atEndOfContainer = function(/*DomNode*/container, /*DomNode*/node, /*Int*/offset){ var atEnd = false; var offsetAtEnd = (offset == (node.length || node.childNodes.length)); if(!offsetAtEnd && node.nodeType == 3){ //if this is a text node, check whether the right part is all space if(/^[\s\xA0]+$/.test(node.nodeValue.substr(offset))){ offsetAtEnd = true; } } if(offsetAtEnd){ var cnode = node; atEnd = true; while(cnode && cnode !== container){ if(cnode.nextSibling){ atEnd = false; break; } cnode = cnode.parentNode; } } return atEnd; }; dijit.range.adjacentNoneTextNode = function(startnode, next){ var node = startnode; var len = (0 - startnode.length) || 0; var prop = next ? 'nextSibling' : 'previousSibling'; while(node){ if(node.nodeType != 3){ break; } len += node.length node = node[prop]; } return [node,len]; }; dijit.range._w3c = Boolean(window['getSelection']); dijit.range.create = function(/*Window?*/win){ if(dijit.range._w3c){ return (win || dojo.global).document.createRange(); }else{//IE return new dijit.range.W3CRange; } }; dijit.range.getSelection = function(/*Window*/win, /*Boolean?*/ignoreUpdate){ if(dijit.range._w3c){ return win.getSelection(); }else{//IE var s = new dijit.range.ie.selection(win); if(!ignoreUpdate){ s._getCurrentSelection(); } return s; } }; if(!dijit.range._w3c){ dijit.range.ie = { cachedSelection: {}, selection: function(win){ this._ranges = []; this.addRange = function(r, /*boolean*/internal){ this._ranges.push(r); if(!internal){ r._select(); } this.rangeCount = this._ranges.length; }; this.removeAllRanges = function(){ //don't detach, the range may be used later // for(var i=0;i<this._ranges.length;i++){ // this._ranges[i].detach(); // } this._ranges = []; this.rangeCount = 0; }; var _initCurrentRange = function(){ var r = win.document.selection.createRange(); var type = win.document.selection.type.toUpperCase(); if(type == "CONTROL"){ //TODO: multiple range selection(?) return new dijit.range.W3CRange(dijit.range.ie.decomposeControlRange(r)); }else{ return new dijit.range.W3CRange(dijit.range.ie.decomposeTextRange(r)); } }; this.getRangeAt = function(i){ return this._ranges[i]; }; this._getCurrentSelection = function(){ this.removeAllRanges(); var r = _initCurrentRange(); if(r){ this.addRange(r, true); this.isCollapsed = r.collapsed; }else{ this.isCollapsed = true; } }; }, decomposeControlRange: function(range){ var firstnode = range.item(0), lastnode = range.item(range.length - 1); var startContainer = firstnode.parentNode, endContainer = lastnode.parentNode; var startOffset = dijit.range.getIndex(firstnode, startContainer).o; var endOffset = dijit.range.getIndex(lastnode, endContainer).o + 1; return [startContainer, startOffset,endContainer, endOffset]; }, getEndPoint: function(range, end){ var atmrange = range.duplicate(); atmrange.collapse(!end); var cmpstr = 'EndTo' + (end ? 'End' : 'Start'); var parentNode = atmrange.parentElement(); var startnode, startOffset, lastNode; if(parentNode.childNodes.length > 0){ dojo.every(parentNode.childNodes, function(node, i){ var calOffset; if(node.nodeType != 3){ atmrange.moveToElementText(node); if(atmrange.compareEndPoints(cmpstr, range) > 0){ //startnode = node.previousSibling; if(lastNode && lastNode.nodeType == 3){ //where shall we put the start? in the text node or after? startnode = lastNode; calOffset = true; }else{ startnode = parentNode; startOffset = i; return false; } }else{ if(i == parentNode.childNodes.length - 1){ startnode = parentNode; startOffset = parentNode.childNodes.length; return false; } } }else{ if(i == parentNode.childNodes.length - 1){//at the end of this node startnode = node; calOffset = true; } } // try{ if(calOffset && startnode){ var prevnode = dijit.range.adjacentNoneTextNode(startnode)[0]; if(prevnode){ startnode = prevnode.nextSibling; }else{ startnode = parentNode.firstChild; //firstChild must be a text node } var prevnodeobj = dijit.range.adjacentNoneTextNode(startnode); prevnode = prevnodeobj[0]; var lenoffset = prevnodeobj[1]; if(prevnode){ atmrange.moveToElementText(prevnode); atmrange.collapse(false); }else{ atmrange.moveToElementText(parentNode); } atmrange.setEndPoint(cmpstr, range); startOffset = atmrange.text.length - lenoffset; return false; } // }catch(e){ debugger } lastNode = node; return true; }); }else{ startnode = parentNode; startOffset = 0; } //if at the end of startnode and we are dealing with start container, then //move the startnode to nextSibling if it is a text node //TODO: do this for end container? if(!end && startnode.nodeType == 1 && startOffset == startnode.childNodes.length){ var nextnode = startnode.nextSibling; if(nextnode && nextnode.nodeType == 3){ startnode = nextnode; startOffset = 0; } } return [startnode, startOffset]; }, setEndPoint: function(range, container, offset){ //text node var atmrange = range.duplicate(), node, len; if(container.nodeType != 3){ //normal node if(offset > 0){ node = container.childNodes[offset - 1]; if(node){ if(node.nodeType == 3){ container = node; offset = node.length; //pass through }else{ if(node.nextSibling && node.nextSibling.nodeType == 3){ container = node.nextSibling; offset = 0; //pass through }else{ atmrange.moveToElementText(node.nextSibling ? node : container); var parent = node.parentNode; var tempNode = parent.insertBefore(node.ownerDocument.createTextNode(' '), node.nextSibling); atmrange.collapse(false); parent.removeChild(tempNode); } } } }else{ atmrange.moveToElementText(container); atmrange.collapse(true); } } if(container.nodeType == 3){ var prevnodeobj = dijit.range.adjacentNoneTextNode(container); var prevnode = prevnodeobj[0]; len = prevnodeobj[1]; if(prevnode){ atmrange.moveToElementText(prevnode); atmrange.collapse(false); //if contentEditable is not inherit, the above collapse won't make the end point //in the correctly position: it always has a -1 offset, so compensate it if(prevnode.contentEditable != 'inherit'){ len++; } }else{ atmrange.moveToElementText(container.parentNode); atmrange.collapse(true); } offset += len; if(offset > 0){ if(atmrange.move('character', offset) != offset){ console.error('Error when moving!'); } } } return atmrange; }, decomposeTextRange: function(range){ var tmpary = dijit.range.ie.getEndPoint(range); var startContainer = tmpary[0], startOffset = tmpary[1]; var endContainer = tmpary[0], endOffset = tmpary[1]; if(range.htmlText.length){ if(range.htmlText == range.text){ //in the same text node endOffset = startOffset + range.text.length; }else{ tmpary = dijit.range.ie.getEndPoint(range, true); endContainer = tmpary[0],endOffset = tmpary[1]; // if(startContainer.tagName == "BODY"){ // startContainer = startContainer.firstChild; // } } } return [startContainer, startOffset, endContainer, endOffset]; }, setRange: function(range, startContainer, startOffset, endContainer, endOffset, collapsed){ var start = dijit.range.ie.setEndPoint(range, startContainer, startOffset); range.setEndPoint('StartToStart', start); if(!collapsed){ var end = dijit.range.ie.setEndPoint(range, endContainer, endOffset); } range.setEndPoint('EndToEnd', end || start); return range; } }; dojo.declare("dijit.range.W3CRange",null, { constructor: function(){ if(arguments.length>0){ this.setStart(arguments[0][0],arguments[0][1]); this.setEnd(arguments[0][2],arguments[0][3]); }else{ this.commonAncestorContainer = null; this.startContainer = null; this.startOffset = 0; this.endContainer = null; this.endOffset = 0; this.collapsed = true; } }, _updateInternal: function(){ if(this.startContainer !== this.endContainer){ this.commonAncestorContainer = dijit.range.getCommonAncestor(this.startContainer, this.endContainer); }else{ this.commonAncestorContainer = this.startContainer; } this.collapsed = (this.startContainer === this.endContainer) && (this.startOffset == this.endOffset); }, setStart: function(node, offset){ offset=parseInt(offset); if(this.startContainer === node && this.startOffset == offset){ return; } delete this._cachedBookmark; this.startContainer = node; this.startOffset = offset; if(!this.endContainer){ this.setEnd(node, offset); }else{ this._updateInternal(); } }, setEnd: function(node, offset){ offset=parseInt(offset); if(this.endContainer === node && this.endOffset == offset){ return; } delete this._cachedBookmark; this.endContainer = node; this.endOffset = offset; if(!this.startContainer){ this.setStart(node, offset); }else{ this._updateInternal(); } }, setStartAfter: function(node, offset){ this._setPoint('setStart', node, offset, 1); }, setStartBefore: function(node, offset){ this._setPoint('setStart', node, offset, 0); }, setEndAfter: function(node, offset){ this._setPoint('setEnd', node, offset, 1); }, setEndBefore: function(node, offset){ this._setPoint('setEnd', node, offset, 0); }, _setPoint: function(what, node, offset, ext){ var index = dijit.range.getIndex(node, node.parentNode).o; this[what](node.parentNode, index.pop()+ext); }, _getIERange: function(){ var r = (this._body || this.endContainer.ownerDocument.body).createTextRange(); dijit.range.ie.setRange(r, this.startContainer, this.startOffset, this.endContainer, this.endOffset, this.collapsed); return r; }, getBookmark: function(body){ this._getIERange(); return this._cachedBookmark; }, _select: function(){ var r = this._getIERange(); r.select(); }, deleteContents: function(){ var r = this._getIERange(); r.pasteHTML(''); this.endContainer = this.startContainer; this.endOffset = this.startOffset; this.collapsed = true; }, cloneRange: function(){ var r = new dijit.range.W3CRange([this.startContainer,this.startOffset, this.endContainer,this.endOffset]); r._body = this._body; return r; }, detach: function(){ this._body = null; this.commonAncestorContainer = null; this.startContainer = null; this.startOffset = 0; this.endContainer = null; this.endOffset = 0; this.collapsed = true; } }); } //if(!dijit.range._w3c) return dijit.range; });
refs #8490: fixed a typo (getIndex returns a list, not a integer) git-svn-id: 674a2d6b1e32e53f607eb824547723f32280967e@25801 560b804f-0ae3-0310-86f3-f6aa0a117693
_editor/range.js
refs #8490: fixed a typo (getIndex returns a list, not a integer)
<ide><path>editor/range.js <ide> decomposeControlRange: function(range){ <ide> var firstnode = range.item(0), lastnode = range.item(range.length - 1); <ide> var startContainer = firstnode.parentNode, endContainer = lastnode.parentNode; <del> var startOffset = dijit.range.getIndex(firstnode, startContainer).o; <del> var endOffset = dijit.range.getIndex(lastnode, endContainer).o + 1; <add> var startOffset = dijit.range.getIndex(firstnode, startContainer).o[0]; <add> var endOffset = dijit.range.getIndex(lastnode, endContainer).o[0] + 1; <ide> return [startContainer, startOffset,endContainer, endOffset]; <ide> }, <ide> getEndPoint: function(range, end){
Java
apache-2.0
1de7b1a70c2a326d1a4fb5ca959ef3d74dd0818e
0
hanst/elasticsearch,wuranbo/elasticsearch,AleksKochev/elasticsearch,janmejay/elasticsearch,NBSW/elasticsearch,Clairebi/ElasticsearchClone,truemped/elasticsearch,sposam/elasticsearch,huypx1292/elasticsearch,feiqitian/elasticsearch,uboness/elasticsearch,vvcephei/elasticsearch,uboness/elasticsearch,koxa29/elasticsearch,linglaiyao1314/elasticsearch,dylan8902/elasticsearch,mkis-/elasticsearch,pablocastro/elasticsearch,brandonkearby/elasticsearch,Siddartha07/elasticsearch,karthikjaps/elasticsearch,artnowo/elasticsearch,ivansun1010/elasticsearch,Rygbee/elasticsearch,Uiho/elasticsearch,infusionsoft/elasticsearch,vorce/es-metrics,C-Bish/elasticsearch,mrorii/elasticsearch,Helen-Zhao/elasticsearch,knight1128/elasticsearch,liweinan0423/elasticsearch,nellicus/elasticsearch,apepper/elasticsearch,karthikjaps/elasticsearch,pozhidaevak/elasticsearch,tsohil/elasticsearch,pozhidaevak/elasticsearch,heng4fun/elasticsearch,pablocastro/elasticsearch,vroyer/elasticassandra,vroyer/elassandra,naveenhooda2000/elasticsearch,mnylen/elasticsearch,Shekharrajak/elasticsearch,infusionsoft/elasticsearch,mortonsykes/elasticsearch,rmuir/elasticsearch,JackyMai/elasticsearch,aparo/elasticsearch,Microsoft/elasticsearch,libosu/elasticsearch,mohsinh/elasticsearch,clintongormley/elasticsearch,PhaedrusTheGreek/elasticsearch,njlawton/elasticsearch,mohit/elasticsearch,himanshuag/elasticsearch,KimTaehee/elasticsearch,rhoml/elasticsearch,kcompher/elasticsearch,vvcephei/elasticsearch,kunallimaye/elasticsearch,AshishThakur/elasticsearch,i-am-Nathan/elasticsearch,micpalmia/elasticsearch,combinatorist/elasticsearch,karthikjaps/elasticsearch,GlenRSmith/elasticsearch,raishiv/elasticsearch,fred84/elasticsearch,LewayneNaidoo/elasticsearch,jw0201/elastic,AndreKR/elasticsearch,markharwood/elasticsearch,lightslife/elasticsearch,gfyoung/elasticsearch,ouyangkongtong/elasticsearch,tebriel/elasticsearch,lchennup/elasticsearch,hafkensite/elasticsearch,sjohnr/elasticsearch,phani546/elasticsearch,dpursehouse/elasticsearch,hirdesh2008/elasticsearch,sc0ttkclark/elasticsearch,wbowling/elasticsearch,alexkuk/elasticsearch,marcuswr/elasticsearch-dateline,springning/elasticsearch,yanjunh/elasticsearch,codebunt/elasticsearch,tkssharma/elasticsearch,elasticdog/elasticsearch,zeroctu/elasticsearch,mkis-/elasticsearch,gfyoung/elasticsearch,wangtuo/elasticsearch,Clairebi/ElasticsearchClone,kcompher/elasticsearch,alexshadow007/elasticsearch,kevinkluge/elasticsearch,ricardocerq/elasticsearch,dylan8902/elasticsearch,overcome/elasticsearch,wangyuxue/elasticsearch,awislowski/elasticsearch,kimimj/elasticsearch,dataduke/elasticsearch,shreejay/elasticsearch,SergVro/elasticsearch,himanshuag/elasticsearch,palecur/elasticsearch,janmejay/elasticsearch,avikurapati/elasticsearch,raishiv/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,zkidkid/elasticsearch,elancom/elasticsearch,andrestc/elasticsearch,AndreKR/elasticsearch,fekaputra/elasticsearch,kevinkluge/elasticsearch,lzo/elasticsearch-1,tebriel/elasticsearch,martinstuga/elasticsearch,wuranbo/elasticsearch,HarishAtGitHub/elasticsearch,wimvds/elasticsearch,beiske/elasticsearch,codebunt/elasticsearch,mjhennig/elasticsearch,obourgain/elasticsearch,masaruh/elasticsearch,kimimj/elasticsearch,coding0011/elasticsearch,masterweb121/elasticsearch,btiernay/elasticsearch,clintongormley/elasticsearch,MaineC/elasticsearch,knight1128/elasticsearch,strapdata/elassandra,hechunwen/elasticsearch,areek/elasticsearch,StefanGor/elasticsearch,NBSW/elasticsearch,jimczi/elasticsearch,palecur/elasticsearch,nezirus/elasticsearch,rmuir/elasticsearch,PhaedrusTheGreek/elasticsearch,mjason3/elasticsearch,djschny/elasticsearch,nomoa/elasticsearch,franklanganke/elasticsearch,C-Bish/elasticsearch,sauravmondallive/elasticsearch,huypx1292/elasticsearch,jango2015/elasticsearch,xingguang2013/elasticsearch,davidvgalbraith/elasticsearch,kenshin233/elasticsearch,petmit/elasticsearch,naveenhooda2000/elasticsearch,YosuaMichael/elasticsearch,Kakakakakku/elasticsearch,kevinkluge/elasticsearch,fred84/elasticsearch,schonfeld/elasticsearch,s1monw/elasticsearch,sdauletau/elasticsearch,mnylen/elasticsearch,robin13/elasticsearch,jbertouch/elasticsearch,sc0ttkclark/elasticsearch,alexbrasetvik/elasticsearch,drewr/elasticsearch,andrestc/elasticsearch,drewr/elasticsearch,ImpressTV/elasticsearch,kalimatas/elasticsearch,kunallimaye/elasticsearch,hanst/elasticsearch,janmejay/elasticsearch,mohsinh/elasticsearch,zeroctu/elasticsearch,masterweb121/elasticsearch,wangtuo/elasticsearch,alexbrasetvik/elasticsearch,mnylen/elasticsearch,ESamir/elasticsearch,Flipkart/elasticsearch,vrkansagara/elasticsearch,socialrank/elasticsearch,ThalaivaStars/OrgRepo1,tsohil/elasticsearch,nknize/elasticsearch,mjhennig/elasticsearch,spiegela/elasticsearch,pritishppai/elasticsearch,ricardocerq/elasticsearch,jw0201/elastic,salyh/elasticsearch,Siddartha07/elasticsearch,ivansun1010/elasticsearch,obourgain/elasticsearch,Microsoft/elasticsearch,bawse/elasticsearch,mbrukman/elasticsearch,gingerwizard/elasticsearch,queirozfcom/elasticsearch,Shepard1212/elasticsearch,Microsoft/elasticsearch,Shekharrajak/elasticsearch,lchennup/elasticsearch,awislowski/elasticsearch,F0lha/elasticsearch,obourgain/elasticsearch,achow/elasticsearch,SergVro/elasticsearch,xpandan/elasticsearch,thecocce/elasticsearch,truemped/elasticsearch,janmejay/elasticsearch,YosuaMichael/elasticsearch,cwurm/elasticsearch,kimchy/elasticsearch,StefanGor/elasticsearch,awislowski/elasticsearch,wayeast/elasticsearch,AndreKR/elasticsearch,ulkas/elasticsearch,mikemccand/elasticsearch,ESamir/elasticsearch,polyfractal/elasticsearch,ImpressTV/elasticsearch,StefanGor/elasticsearch,yanjunh/elasticsearch,rhoml/elasticsearch,linglaiyao1314/elasticsearch,liweinan0423/elasticsearch,franklanganke/elasticsearch,HarishAtGitHub/elasticsearch,fforbeck/elasticsearch,kimchy/elasticsearch,lmtwga/elasticsearch,mkis-/elasticsearch,winstonewert/elasticsearch,janmejay/elasticsearch,ivansun1010/elasticsearch,kevinkluge/elasticsearch,javachengwc/elasticsearch,javachengwc/elasticsearch,GlenRSmith/elasticsearch,wangtuo/elasticsearch,dataduke/elasticsearch,phani546/elasticsearch,raishiv/elasticsearch,strapdata/elassandra-test,sneivandt/elasticsearch,kkirsche/elasticsearch,andrestc/elasticsearch,sreeramjayan/elasticsearch,onegambler/elasticsearch,abibell/elasticsearch,javachengwc/elasticsearch,iacdingping/elasticsearch,polyfractal/elasticsearch,cnfire/elasticsearch-1,sdauletau/elasticsearch,yanjunh/elasticsearch,schonfeld/elasticsearch,chrismwendt/elasticsearch,rmuir/elasticsearch,trangvh/elasticsearch,abhijitiitr/es,iamjakob/elasticsearch,pritishppai/elasticsearch,lchennup/elasticsearch,schonfeld/elasticsearch,weipinghe/elasticsearch,sarwarbhuiyan/elasticsearch,alexkuk/elasticsearch,vvcephei/elasticsearch,ajhalani/elasticsearch,Clairebi/ElasticsearchClone,schonfeld/elasticsearch,gingerwizard/elasticsearch,MichaelLiZhou/elasticsearch,JervyShi/elasticsearch,elasticdog/elasticsearch,fernandozhu/elasticsearch,obourgain/elasticsearch,wimvds/elasticsearch,jbertouch/elasticsearch,wuranbo/elasticsearch,MichaelLiZhou/elasticsearch,khiraiwa/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,jango2015/elasticsearch,rento19962/elasticsearch,dantuffery/elasticsearch,davidvgalbraith/elasticsearch,hafkensite/elasticsearch,dongjoon-hyun/elasticsearch,Liziyao/elasticsearch,Widen/elasticsearch,codebunt/elasticsearch,Collaborne/elasticsearch,Flipkart/elasticsearch,Ansh90/elasticsearch,Shekharrajak/elasticsearch,markwalkom/elasticsearch,salyh/elasticsearch,nrkkalyan/elasticsearch,petabytedata/elasticsearch,jaynblue/elasticsearch,loconsolutions/elasticsearch,micpalmia/elasticsearch,maddin2016/elasticsearch,szroland/elasticsearch,rhoml/elasticsearch,mmaracic/elasticsearch,ESamir/elasticsearch,yuy168/elasticsearch,KimTaehee/elasticsearch,nezirus/elasticsearch,mute/elasticsearch,nellicus/elasticsearch,artnowo/elasticsearch,tkssharma/elasticsearch,mrorii/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,a2lin/elasticsearch,lzo/elasticsearch-1,Liziyao/elasticsearch,alexbrasetvik/elasticsearch,umeshdangat/elasticsearch,sneivandt/elasticsearch,wittyameta/elasticsearch,Rygbee/elasticsearch,jaynblue/elasticsearch,markwalkom/elasticsearch,kenshin233/elasticsearch,elasticdog/elasticsearch,JervyShi/elasticsearch,TonyChai24/ESSource,likaiwalkman/elasticsearch,zeroctu/elasticsearch,feiqitian/elasticsearch,vroyer/elasticassandra,khiraiwa/elasticsearch,mmaracic/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,himanshuag/elasticsearch,loconsolutions/elasticsearch,kunallimaye/elasticsearch,sposam/elasticsearch,apepper/elasticsearch,yongminxia/elasticsearch,Charlesdong/elasticsearch,jsgao0/elasticsearch,gingerwizard/elasticsearch,achow/elasticsearch,aglne/elasticsearch,slavau/elasticsearch,caengcjd/elasticsearch,fooljohnny/elasticsearch,tkssharma/elasticsearch,ThiagoGarciaAlves/elasticsearch,fekaputra/elasticsearch,aparo/elasticsearch,amaliujia/elasticsearch,AleksKochev/elasticsearch,markharwood/elasticsearch,ckclark/elasticsearch,andrejserafim/elasticsearch,opendatasoft/elasticsearch,Kakakakakku/elasticsearch,golubev/elasticsearch,hydro2k/elasticsearch,kubum/elasticsearch,winstonewert/elasticsearch,fubuki/elasticsearch,skearns64/elasticsearch,Fsero/elasticsearch,kenshin233/elasticsearch,sauravmondallive/elasticsearch,JSCooke/elasticsearch,drewr/elasticsearch,markllama/elasticsearch,caengcjd/elasticsearch,tahaemin/elasticsearch,jango2015/elasticsearch,easonC/elasticsearch,SergVro/elasticsearch,raishiv/elasticsearch,girirajsharma/elasticsearch,peschlowp/elasticsearch,onegambler/elasticsearch,mute/elasticsearch,kingaj/elasticsearch,jpountz/elasticsearch,Chhunlong/elasticsearch,ThiagoGarciaAlves/elasticsearch,petmit/elasticsearch,njlawton/elasticsearch,vrkansagara/elasticsearch,markllama/elasticsearch,hafkensite/elasticsearch,hydro2k/elasticsearch,tkssharma/elasticsearch,AshishThakur/elasticsearch,weipinghe/elasticsearch,ZTE-PaaS/elasticsearch,humandb/elasticsearch,clintongormley/elasticsearch,mkis-/elasticsearch,kunallimaye/elasticsearch,fekaputra/elasticsearch,polyfractal/elasticsearch,mjhennig/elasticsearch,martinstuga/elasticsearch,iacdingping/elasticsearch,kcompher/elasticsearch,MetSystem/elasticsearch,jsgao0/elasticsearch,ZTE-PaaS/elasticsearch,Siddartha07/elasticsearch,vingupta3/elasticsearch,jprante/elasticsearch,tebriel/elasticsearch,schonfeld/elasticsearch,adrianbk/elasticsearch,dylan8902/elasticsearch,umeshdangat/elasticsearch,shreejay/elasticsearch,i-am-Nathan/elasticsearch,iantruslove/elasticsearch,huanzhong/elasticsearch,dataduke/elasticsearch,drewr/elasticsearch,kingaj/elasticsearch,kimchy/elasticsearch,VukDukic/elasticsearch,smflorentino/elasticsearch,Ansh90/elasticsearch,Clairebi/ElasticsearchClone,lightslife/elasticsearch,apepper/elasticsearch,LeoYao/elasticsearch,mrorii/elasticsearch,kalburgimanjunath/elasticsearch,phani546/elasticsearch,jimhooker2002/elasticsearch,sdauletau/elasticsearch,elasticdog/elasticsearch,Rygbee/elasticsearch,sjohnr/elasticsearch,Charlesdong/elasticsearch,kkirsche/elasticsearch,Collaborne/elasticsearch,ouyangkongtong/elasticsearch,Collaborne/elasticsearch,mbrukman/elasticsearch,liweinan0423/elasticsearch,robin13/elasticsearch,jchampion/elasticsearch,F0lha/elasticsearch,MichaelLiZhou/elasticsearch,HarishAtGitHub/elasticsearch,dongjoon-hyun/elasticsearch,scorpionvicky/elasticsearch,fred84/elasticsearch,javachengwc/elasticsearch,thecocce/elasticsearch,ckclark/elasticsearch,jw0201/elastic,Liziyao/elasticsearch,knight1128/elasticsearch,easonC/elasticsearch,nezirus/elasticsearch,golubev/elasticsearch,mgalushka/elasticsearch,zhaocloud/elasticsearch,sarwarbhuiyan/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,likaiwalkman/elasticsearch,xuzha/elasticsearch,JervyShi/elasticsearch,btiernay/elasticsearch,linglaiyao1314/elasticsearch,Widen/elasticsearch,glefloch/elasticsearch,tebriel/elasticsearch,spiegela/elasticsearch,TonyChai24/ESSource,jsgao0/elasticsearch,hanswang/elasticsearch,infusionsoft/elasticsearch,AleksKochev/elasticsearch,kubum/elasticsearch,humandb/elasticsearch,kubum/elasticsearch,jaynblue/elasticsearch,qwerty4030/elasticsearch,raishiv/elasticsearch,sposam/elasticsearch,mbrukman/elasticsearch,milodky/elasticsearch,StefanGor/elasticsearch,areek/elasticsearch,strapdata/elassandra,markllama/elasticsearch,KimTaehee/elasticsearch,alexkuk/elasticsearch,peschlowp/elasticsearch,fernandozhu/elasticsearch,hechunwen/elasticsearch,lydonchandra/elasticsearch,YosuaMichael/elasticsearch,ivansun1010/elasticsearch,lightslife/elasticsearch,mnylen/elasticsearch,franklanganke/elasticsearch,AleksKochev/elasticsearch,ydsakyclguozi/elasticsearch,nazarewk/elasticsearch,fubuki/elasticsearch,huypx1292/elasticsearch,EasonYi/elasticsearch,LeoYao/elasticsearch,Shepard1212/elasticsearch,jeteve/elasticsearch,queirozfcom/elasticsearch,Stacey-Gammon/elasticsearch,SergVro/elasticsearch,huanzhong/elasticsearch,rento19962/elasticsearch,franklanganke/elasticsearch,masaruh/elasticsearch,knight1128/elasticsearch,strapdata/elassandra5-rc,wenpos/elasticsearch,khiraiwa/elasticsearch,bestwpw/elasticsearch,smflorentino/elasticsearch,fforbeck/elasticsearch,pablocastro/elasticsearch,strapdata/elassandra-test,kcompher/elasticsearch,hanst/elasticsearch,kingaj/elasticsearch,franklanganke/elasticsearch,lmtwga/elasticsearch,trangvh/elasticsearch,tsohil/elasticsearch,Rygbee/elasticsearch,fernandozhu/elasticsearch,achow/elasticsearch,aglne/elasticsearch,yynil/elasticsearch,mm0/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,humandb/elasticsearch,iamjakob/elasticsearch,huanzhong/elasticsearch,palecur/elasticsearch,sauravmondallive/elasticsearch,shreejay/elasticsearch,camilojd/elasticsearch,drewr/elasticsearch,Flipkart/elasticsearch,kkirsche/elasticsearch,Brijeshrpatel9/elasticsearch,jsgao0/elasticsearch,onegambler/elasticsearch,hafkensite/elasticsearch,liweinan0423/elasticsearch,Ansh90/elasticsearch,myelin/elasticsearch,xpandan/elasticsearch,beiske/elasticsearch,ouyangkongtong/elasticsearch,Liziyao/elasticsearch,lydonchandra/elasticsearch,wenpos/elasticsearch,polyfractal/elasticsearch,TonyChai24/ESSource,fred84/elasticsearch,vvcephei/elasticsearch,i-am-Nathan/elasticsearch,dongjoon-hyun/elasticsearch,likaiwalkman/elasticsearch,lydonchandra/elasticsearch,mohsinh/elasticsearch,lzo/elasticsearch-1,anti-social/elasticsearch,pablocastro/elasticsearch,mohsinh/elasticsearch,winstonewert/elasticsearch,mute/elasticsearch,zhaocloud/elasticsearch,uschindler/elasticsearch,kalburgimanjunath/elasticsearch,bestwpw/elasticsearch,brwe/elasticsearch,slavau/elasticsearch,fubuki/elasticsearch,mgalushka/elasticsearch,springning/elasticsearch,pranavraman/elasticsearch,kingaj/elasticsearch,rhoml/elasticsearch,rajanm/elasticsearch,wangyuxue/elasticsearch,SergVro/elasticsearch,kubum/elasticsearch,pranavraman/elasticsearch,jimczi/elasticsearch,wangyuxue/elasticsearch,micpalmia/elasticsearch,shreejay/elasticsearch,koxa29/elasticsearch,tahaemin/elasticsearch,koxa29/elasticsearch,KimTaehee/elasticsearch,socialrank/elasticsearch,onegambler/elasticsearch,lzo/elasticsearch-1,jimhooker2002/elasticsearch,pritishppai/elasticsearch,YosuaMichael/elasticsearch,rento19962/elasticsearch,sauravmondallive/elasticsearch,iacdingping/elasticsearch,umeshdangat/elasticsearch,18098924759/elasticsearch,MetSystem/elasticsearch,tsohil/elasticsearch,wuranbo/elasticsearch,cnfire/elasticsearch-1,bawse/elasticsearch,btiernay/elasticsearch,njlawton/elasticsearch,hirdesh2008/elasticsearch,tebriel/elasticsearch,iantruslove/elasticsearch,bawse/elasticsearch,dantuffery/elasticsearch,rlugojr/elasticsearch,adrianbk/elasticsearch,Asimov4/elasticsearch,JSCooke/elasticsearch,btiernay/elasticsearch,amit-shar/elasticsearch,IanvsPoplicola/elasticsearch,andrewvc/elasticsearch,socialrank/elasticsearch,franklanganke/elasticsearch,abhijitiitr/es,kalimatas/elasticsearch,jchampion/elasticsearch,himanshuag/elasticsearch,fekaputra/elasticsearch,vietlq/elasticsearch,milodky/elasticsearch,abhijitiitr/es,F0lha/elasticsearch,kevinkluge/elasticsearch,szroland/elasticsearch,markharwood/elasticsearch,gfyoung/elasticsearch,chirilo/elasticsearch,overcome/elasticsearch,mbrukman/elasticsearch,ImpressTV/elasticsearch,mjhennig/elasticsearch,caengcjd/elasticsearch,mcku/elasticsearch,HonzaKral/elasticsearch,chirilo/elasticsearch,phani546/elasticsearch,ricardocerq/elasticsearch,heng4fun/elasticsearch,mortonsykes/elasticsearch,linglaiyao1314/elasticsearch,socialrank/elasticsearch,javachengwc/elasticsearch,zeroctu/elasticsearch,kalburgimanjunath/elasticsearch,kkirsche/elasticsearch,jchampion/elasticsearch,sreeramjayan/elasticsearch,ydsakyclguozi/elasticsearch,tsohil/elasticsearch,MetSystem/elasticsearch,truemped/elasticsearch,cnfire/elasticsearch-1,rmuir/elasticsearch,tkssharma/elasticsearch,ouyangkongtong/elasticsearch,HonzaKral/elasticsearch,jw0201/elastic,xuzha/elasticsearch,himanshuag/elasticsearch,spiegela/elasticsearch,mortonsykes/elasticsearch,vietlq/elasticsearch,btiernay/elasticsearch,Chhunlong/elasticsearch,nrkkalyan/elasticsearch,alexksikes/elasticsearch,petmit/elasticsearch,mapr/elasticsearch,girirajsharma/elasticsearch,heng4fun/elasticsearch,pozhidaevak/elasticsearch,scottsom/elasticsearch,feiqitian/elasticsearch,ulkas/elasticsearch,loconsolutions/elasticsearch,lmtwga/elasticsearch,queirozfcom/elasticsearch,chirilo/elasticsearch,ricardocerq/elasticsearch,markllama/elasticsearch,kubum/elasticsearch,F0lha/elasticsearch,markwalkom/elasticsearch,VukDukic/elasticsearch,nilabhsagar/elasticsearch,truemped/elasticsearch,18098924759/elasticsearch,Shepard1212/elasticsearch,anti-social/elasticsearch,lks21c/elasticsearch,andrejserafim/elasticsearch,easonC/elasticsearch,milodky/elasticsearch,EasonYi/elasticsearch,MichaelLiZhou/elasticsearch,xingguang2013/elasticsearch,jeteve/elasticsearch,nellicus/elasticsearch,skearns64/elasticsearch,vvcephei/elasticsearch,amaliujia/elasticsearch,loconsolutions/elasticsearch,iacdingping/elasticsearch,phani546/elasticsearch,s1monw/elasticsearch,janmejay/elasticsearch,xingguang2013/elasticsearch,kunallimaye/elasticsearch,weipinghe/elasticsearch,strapdata/elassandra-test,awislowski/elasticsearch,phani546/elasticsearch,mm0/elasticsearch,Asimov4/elasticsearch,dataduke/elasticsearch,kunallimaye/elasticsearch,Liziyao/elasticsearch,queirozfcom/elasticsearch,skearns64/elasticsearch,PhaedrusTheGreek/elasticsearch,JSCooke/elasticsearch,petabytedata/elasticsearch,mohit/elasticsearch,mapr/elasticsearch,yuy168/elasticsearch,lmtwga/elasticsearch,rajanm/elasticsearch,Ansh90/elasticsearch,PhaedrusTheGreek/elasticsearch,nazarewk/elasticsearch,weipinghe/elasticsearch,nrkkalyan/elasticsearch,avikurapati/elasticsearch,LewayneNaidoo/elasticsearch,qwerty4030/elasticsearch,overcome/elasticsearch,amit-shar/elasticsearch,HarishAtGitHub/elasticsearch,jango2015/elasticsearch,brwe/elasticsearch,khiraiwa/elasticsearch,opendatasoft/elasticsearch,PhaedrusTheGreek/elasticsearch,milodky/elasticsearch,mgalushka/elasticsearch,iacdingping/elasticsearch,coding0011/elasticsearch,strapdata/elassandra-test,sreeramjayan/elasticsearch,winstonewert/elasticsearch,jpountz/elasticsearch,PhaedrusTheGreek/elasticsearch,mmaracic/elasticsearch,xingguang2013/elasticsearch,diendt/elasticsearch,khiraiwa/elasticsearch,djschny/elasticsearch,NBSW/elasticsearch,sdauletau/elasticsearch,Collaborne/elasticsearch,wbowling/elasticsearch,wimvds/elasticsearch,lydonchandra/elasticsearch,ESamir/elasticsearch,henakamaMSFT/elasticsearch,andrejserafim/elasticsearch,lchennup/elasticsearch,abibell/elasticsearch,uschindler/elasticsearch,petabytedata/elasticsearch,jango2015/elasticsearch,Liziyao/elasticsearch,aglne/elasticsearch,djschny/elasticsearch,jimhooker2002/elasticsearch,nknize/elasticsearch,tcucchietti/elasticsearch,gmarz/elasticsearch,iantruslove/elasticsearch,knight1128/elasticsearch,szroland/elasticsearch,robin13/elasticsearch,AshishThakur/elasticsearch,luiseduardohdbackup/elasticsearch,kaneshin/elasticsearch,jw0201/elastic,iantruslove/elasticsearch,JackyMai/elasticsearch,camilojd/elasticsearch,vroyer/elasticassandra,luiseduardohdbackup/elasticsearch,EasonYi/elasticsearch,mgalushka/elasticsearch,linglaiyao1314/elasticsearch,nellicus/elasticsearch,xpandan/elasticsearch,sdauletau/elasticsearch,combinatorist/elasticsearch,camilojd/elasticsearch,fooljohnny/elasticsearch,sjohnr/elasticsearch,strapdata/elassandra,nknize/elasticsearch,Helen-Zhao/elasticsearch,TonyChai24/ESSource,MisterAndersen/elasticsearch,scottsom/elasticsearch,abhijitiitr/es,mbrukman/elasticsearch,codebunt/elasticsearch,adrianbk/elasticsearch,sneivandt/elasticsearch,lzo/elasticsearch-1,infusionsoft/elasticsearch,Kakakakakku/elasticsearch,lmenezes/elasticsearch,mjason3/elasticsearch,wbowling/elasticsearch,henakamaMSFT/elasticsearch,socialrank/elasticsearch,vrkansagara/elasticsearch,jeteve/elasticsearch,xingguang2013/elasticsearch,kalimatas/elasticsearch,ThiagoGarciaAlves/elasticsearch,mm0/elasticsearch,weipinghe/elasticsearch,beiske/elasticsearch,rlugojr/elasticsearch,naveenhooda2000/elasticsearch,uschindler/elasticsearch,alexshadow007/elasticsearch,alexshadow007/elasticsearch,amit-shar/elasticsearch,fernandozhu/elasticsearch,NBSW/elasticsearch,peschlowp/elasticsearch,hirdesh2008/elasticsearch,szroland/elasticsearch,adrianbk/elasticsearch,fred84/elasticsearch,hafkensite/elasticsearch,masaruh/elasticsearch,abhijitiitr/es,masterweb121/elasticsearch,strapdata/elassandra5-rc,kenshin233/elasticsearch,humandb/elasticsearch,zkidkid/elasticsearch,mkis-/elasticsearch,yuy168/elasticsearch,mnylen/elasticsearch,MjAbuz/elasticsearch,VukDukic/elasticsearch,tsohil/elasticsearch,rmuir/elasticsearch,xuzha/elasticsearch,lydonchandra/elasticsearch,nazarewk/elasticsearch,lmtwga/elasticsearch,hirdesh2008/elasticsearch,marcuswr/elasticsearch-dateline,bestwpw/elasticsearch,Helen-Zhao/elasticsearch,karthikjaps/elasticsearch,lmtwga/elasticsearch,LeoYao/elasticsearch,mrorii/elasticsearch,djschny/elasticsearch,masterweb121/elasticsearch,brwe/elasticsearch,henakamaMSFT/elasticsearch,zeroctu/elasticsearch,diendt/elasticsearch,gmarz/elasticsearch,jaynblue/elasticsearch,nellicus/elasticsearch,andrestc/elasticsearch,njlawton/elasticsearch,Charlesdong/elasticsearch,xpandan/elasticsearch,StefanGor/elasticsearch,alexbrasetvik/elasticsearch,Stacey-Gammon/elasticsearch,a2lin/elasticsearch,pablocastro/elasticsearch,Helen-Zhao/elasticsearch,fooljohnny/elasticsearch,mapr/elasticsearch,lzo/elasticsearch-1,snikch/elasticsearch,caengcjd/elasticsearch,mute/elasticsearch,sc0ttkclark/elasticsearch,nrkkalyan/elasticsearch,abibell/elasticsearch,artnowo/elasticsearch,humandb/elasticsearch,rento19962/elasticsearch,sarwarbhuiyan/elasticsearch,masterweb121/elasticsearch,18098924759/elasticsearch,sauravmondallive/elasticsearch,jeteve/elasticsearch,zhaocloud/elasticsearch,tcucchietti/elasticsearch,vingupta3/elasticsearch,martinstuga/elasticsearch,masaruh/elasticsearch,milodky/elasticsearch,yongminxia/elasticsearch,pablocastro/elasticsearch,MisterAndersen/elasticsearch,sarwarbhuiyan/elasticsearch,lightslife/elasticsearch,zhiqinghuang/elasticsearch,huypx1292/elasticsearch,achow/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,NBSW/elasticsearch,Uiho/elasticsearch,wayeast/elasticsearch,18098924759/elasticsearch,mohit/elasticsearch,yynil/elasticsearch,girirajsharma/elasticsearch,sposam/elasticsearch,ydsakyclguozi/elasticsearch,clintongormley/elasticsearch,Brijeshrpatel9/elasticsearch,nazarewk/elasticsearch,sauravmondallive/elasticsearch,alexksikes/elasticsearch,MjAbuz/elasticsearch,AleksKochev/elasticsearch,strapdata/elassandra5-rc,mjason3/elasticsearch,MaineC/elasticsearch,kalburgimanjunath/elasticsearch,ESamir/elasticsearch,gingerwizard/elasticsearch,zhiqinghuang/elasticsearch,scottsom/elasticsearch,dataduke/elasticsearch,sreeramjayan/elasticsearch,umeshdangat/elasticsearch,Uiho/elasticsearch,pranavraman/elasticsearch,milodky/elasticsearch,hanswang/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,LeoYao/elasticsearch,chirilo/elasticsearch,vrkansagara/elasticsearch,Microsoft/elasticsearch,apepper/elasticsearch,snikch/elasticsearch,likaiwalkman/elasticsearch,alexbrasetvik/elasticsearch,skearns64/elasticsearch,ckclark/elasticsearch,hydro2k/elasticsearch,scottsom/elasticsearch,jeteve/elasticsearch,trangvh/elasticsearch,springning/elasticsearch,infusionsoft/elasticsearch,geidies/elasticsearch,mikemccand/elasticsearch,humandb/elasticsearch,hechunwen/elasticsearch,wayeast/elasticsearch,yongminxia/elasticsearch,markharwood/elasticsearch,IanvsPoplicola/elasticsearch,vorce/es-metrics,zeroctu/elasticsearch,truemped/elasticsearch,tkssharma/elasticsearch,kaneshin/elasticsearch,yongminxia/elasticsearch,sarwarbhuiyan/elasticsearch,KimTaehee/elasticsearch,Charlesdong/elasticsearch,jsgao0/elasticsearch,LewayneNaidoo/elasticsearch,ouyangkongtong/elasticsearch,liweinan0423/elasticsearch,wimvds/elasticsearch,Uiho/elasticsearch,MetSystem/elasticsearch,qwerty4030/elasticsearch,kalimatas/elasticsearch,GlenRSmith/elasticsearch,acchen97/elasticsearch,strapdata/elassandra5-rc,kalburgimanjunath/elasticsearch,markllama/elasticsearch,elancom/elasticsearch,socialrank/elasticsearch,vingupta3/elasticsearch,mgalushka/elasticsearch,mohsinh/elasticsearch,ulkas/elasticsearch,drewr/elasticsearch,combinatorist/elasticsearch,dantuffery/elasticsearch,VukDukic/elasticsearch,Flipkart/elasticsearch,amit-shar/elasticsearch,chirilo/elasticsearch,HonzaKral/elasticsearch,njlawton/elasticsearch,rlugojr/elasticsearch,episerver/elasticsearch,JSCooke/elasticsearch,thecocce/elasticsearch,glefloch/elasticsearch,opendatasoft/elasticsearch,jchampion/elasticsearch,mjason3/elasticsearch,episerver/elasticsearch,artnowo/elasticsearch,spiegela/elasticsearch,trangvh/elasticsearch,elancom/elasticsearch,uschindler/elasticsearch,jsgao0/elasticsearch,AndreKR/elasticsearch,hanst/elasticsearch,tkssharma/elasticsearch,jpountz/elasticsearch,uboness/elasticsearch,GlenRSmith/elasticsearch,overcome/elasticsearch,Shekharrajak/elasticsearch,ydsakyclguozi/elasticsearch,girirajsharma/elasticsearch,glefloch/elasticsearch,overcome/elasticsearch,lightslife/elasticsearch,likaiwalkman/elasticsearch,cnfire/elasticsearch-1,episerver/elasticsearch,fekaputra/elasticsearch,mute/elasticsearch,avikurapati/elasticsearch,anti-social/elasticsearch,andrejserafim/elasticsearch,sdauletau/elasticsearch,PhaedrusTheGreek/elasticsearch,loconsolutions/elasticsearch,Shepard1212/elasticsearch,sscarduzio/elasticsearch,martinstuga/elasticsearch,lchennup/elasticsearch,amaliujia/elasticsearch,peschlowp/elasticsearch,ImpressTV/elasticsearch,kcompher/elasticsearch,sscarduzio/elasticsearch,vietlq/elasticsearch,mcku/elasticsearch,vietlq/elasticsearch,C-Bish/elasticsearch,Widen/elasticsearch,i-am-Nathan/elasticsearch,alexksikes/elasticsearch,hanswang/elasticsearch,avikurapati/elasticsearch,gfyoung/elasticsearch,caengcjd/elasticsearch,LeoYao/elasticsearch,Charlesdong/elasticsearch,vietlq/elasticsearch,cnfire/elasticsearch-1,nezirus/elasticsearch,chirilo/elasticsearch,nazarewk/elasticsearch,vietlq/elasticsearch,vingupta3/elasticsearch,GlenRSmith/elasticsearch,Widen/elasticsearch,mmaracic/elasticsearch,mbrukman/elasticsearch,wangtuo/elasticsearch,vingupta3/elasticsearch,xingguang2013/elasticsearch,maddin2016/elasticsearch,zkidkid/elasticsearch,yuy168/elasticsearch,acchen97/elasticsearch,yynil/elasticsearch,areek/elasticsearch,salyh/elasticsearch,lmtwga/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,aparo/elasticsearch,mcku/elasticsearch,springning/elasticsearch,rajanm/elasticsearch,dpursehouse/elasticsearch,nilabhsagar/elasticsearch,springning/elasticsearch,bestwpw/elasticsearch,wenpos/elasticsearch,mgalushka/elasticsearch,gmarz/elasticsearch,huypx1292/elasticsearch,sc0ttkclark/elasticsearch,lightslife/elasticsearch,18098924759/elasticsearch,mortonsykes/elasticsearch,lks21c/elasticsearch,obourgain/elasticsearch,mjason3/elasticsearch,ouyangkongtong/elasticsearch,diendt/elasticsearch,maddin2016/elasticsearch,wittyameta/elasticsearch,snikch/elasticsearch,koxa29/elasticsearch,slavau/elasticsearch,EasonYi/elasticsearch,coding0011/elasticsearch,ulkas/elasticsearch,acchen97/elasticsearch,sneivandt/elasticsearch,YosuaMichael/elasticsearch,hanst/elasticsearch,s1monw/elasticsearch,i-am-Nathan/elasticsearch,IanvsPoplicola/elasticsearch,luiseduardohdbackup/elasticsearch,dylan8902/elasticsearch,acchen97/elasticsearch,fubuki/elasticsearch,nrkkalyan/elasticsearch,MjAbuz/elasticsearch,YosuaMichael/elasticsearch,MjAbuz/elasticsearch,s1monw/elasticsearch,anti-social/elasticsearch,luiseduardohdbackup/elasticsearch,dylan8902/elasticsearch,Uiho/elasticsearch,ckclark/elasticsearch,cnfire/elasticsearch-1,fernandozhu/elasticsearch,IanvsPoplicola/elasticsearch,sarwarbhuiyan/elasticsearch,wayeast/elasticsearch,TonyChai24/ESSource,jbertouch/elasticsearch,NBSW/elasticsearch,MetSystem/elasticsearch,masterweb121/elasticsearch,Chhunlong/elasticsearch,coding0011/elasticsearch,elancom/elasticsearch,thecocce/elasticsearch,Stacey-Gammon/elasticsearch,alexkuk/elasticsearch,mjhennig/elasticsearch,clintongormley/elasticsearch,palecur/elasticsearch,luiseduardohdbackup/elasticsearch,kimimj/elasticsearch,wittyameta/elasticsearch,jeteve/elasticsearch,lchennup/elasticsearch,MjAbuz/elasticsearch,smflorentino/elasticsearch,Rygbee/elasticsearch,opendatasoft/elasticsearch,markwalkom/elasticsearch,bestwpw/elasticsearch,JSCooke/elasticsearch,wayeast/elasticsearch,onegambler/elasticsearch,LeoYao/elasticsearch,andrejserafim/elasticsearch,tcucchietti/elasticsearch,kcompher/elasticsearch,wbowling/elasticsearch,AndreKR/elasticsearch,YosuaMichael/elasticsearch,boliza/elasticsearch,jbertouch/elasticsearch,Asimov4/elasticsearch,xingguang2013/elasticsearch,caengcjd/elasticsearch,polyfractal/elasticsearch,hirdesh2008/elasticsearch,winstonewert/elasticsearch,jaynblue/elasticsearch,yuy168/elasticsearch,Shepard1212/elasticsearch,strapdata/elassandra-test,Kakakakakku/elasticsearch,codebunt/elasticsearch,Ansh90/elasticsearch,wittyameta/elasticsearch,libosu/elasticsearch,sc0ttkclark/elasticsearch,ckclark/elasticsearch,zeroctu/elasticsearch,fooljohnny/elasticsearch,episerver/elasticsearch,Fsero/elasticsearch,tahaemin/elasticsearch,pranavraman/elasticsearch,thecocce/elasticsearch,jchampion/elasticsearch,gingerwizard/elasticsearch,Siddartha07/elasticsearch,zhaocloud/elasticsearch,ThiagoGarciaAlves/elasticsearch,zhiqinghuang/elasticsearch,Brijeshrpatel9/elasticsearch,zkidkid/elasticsearch,ThalaivaStars/OrgRepo1,Stacey-Gammon/elasticsearch,JackyMai/elasticsearch,KimTaehee/elasticsearch,huanzhong/elasticsearch,nknize/elasticsearch,rajanm/elasticsearch,episerver/elasticsearch,weipinghe/elasticsearch,jbertouch/elasticsearch,jpountz/elasticsearch,huypx1292/elasticsearch,yanjunh/elasticsearch,clintongormley/elasticsearch,masaruh/elasticsearch,salyh/elasticsearch,btiernay/elasticsearch,petabytedata/elasticsearch,mcku/elasticsearch,boliza/elasticsearch,boliza/elasticsearch,Chhunlong/elasticsearch,amaliujia/elasticsearch,scorpionvicky/elasticsearch,chrismwendt/elasticsearch,easonC/elasticsearch,luiseduardohdbackup/elasticsearch,dpursehouse/elasticsearch,alexksikes/elasticsearch,a2lin/elasticsearch,kkirsche/elasticsearch,sjohnr/elasticsearch,Flipkart/elasticsearch,kkirsche/elasticsearch,sc0ttkclark/elasticsearch,myelin/elasticsearch,smflorentino/elasticsearch,areek/elasticsearch,ThiagoGarciaAlves/elasticsearch,mmaracic/elasticsearch,Kakakakakku/elasticsearch,cwurm/elasticsearch,rlugojr/elasticsearch,nomoa/elasticsearch,ydsakyclguozi/elasticsearch,kalburgimanjunath/elasticsearch,petabytedata/elasticsearch,vroyer/elassandra,gmarz/elasticsearch,luiseduardohdbackup/elasticsearch,uboness/elasticsearch,cwurm/elasticsearch,abibell/elasticsearch,Ansh90/elasticsearch,yynil/elasticsearch,yuy168/elasticsearch,dylan8902/elasticsearch,mm0/elasticsearch,VukDukic/elasticsearch,anti-social/elasticsearch,salyh/elasticsearch,ThalaivaStars/OrgRepo1,beiske/elasticsearch,jprante/elasticsearch,alexshadow007/elasticsearch,jango2015/elasticsearch,slavau/elasticsearch,MaineC/elasticsearch,Clairebi/ElasticsearchClone,ivansun1010/elasticsearch,mrorii/elasticsearch,iacdingping/elasticsearch,elancom/elasticsearch,mapr/elasticsearch,scottsom/elasticsearch,xuzha/elasticsearch,Helen-Zhao/elasticsearch,s1monw/elasticsearch,apepper/elasticsearch,bawse/elasticsearch,pranavraman/elasticsearch,likaiwalkman/elasticsearch,KimTaehee/elasticsearch,hanswang/elasticsearch,davidvgalbraith/elasticsearch,artnowo/elasticsearch,achow/elasticsearch,Shekharrajak/elasticsearch,nomoa/elasticsearch,mikemccand/elasticsearch,dylan8902/elasticsearch,loconsolutions/elasticsearch,xuzha/elasticsearch,nknize/elasticsearch,pritishppai/elasticsearch,rajanm/elasticsearch,MjAbuz/elasticsearch,Widen/elasticsearch,schonfeld/elasticsearch,NBSW/elasticsearch,vorce/es-metrics,Uiho/elasticsearch,Clairebi/ElasticsearchClone,MichaelLiZhou/elasticsearch,JervyShi/elasticsearch,hafkensite/elasticsearch,huanzhong/elasticsearch,rlugojr/elasticsearch,ImpressTV/elasticsearch,djschny/elasticsearch,rajanm/elasticsearch,hechunwen/elasticsearch,mmaracic/elasticsearch,amaliujia/elasticsearch,strapdata/elassandra,18098924759/elasticsearch,lchennup/elasticsearch,vrkansagara/elasticsearch,rento19962/elasticsearch,JervyShi/elasticsearch,a2lin/elasticsearch,beiske/elasticsearch,slavau/elasticsearch,slavau/elasticsearch,aglne/elasticsearch,MichaelLiZhou/elasticsearch,djschny/elasticsearch,geidies/elasticsearch,rento19962/elasticsearch,bestwpw/elasticsearch,pozhidaevak/elasticsearch,pritishppai/elasticsearch,scorpionvicky/elasticsearch,franklanganke/elasticsearch,alexkuk/elasticsearch,nrkkalyan/elasticsearch,lydonchandra/elasticsearch,MisterAndersen/elasticsearch,lydonchandra/elasticsearch,wimvds/elasticsearch,EasonYi/elasticsearch,javachengwc/elasticsearch,vingupta3/elasticsearch,ckclark/elasticsearch,btiernay/elasticsearch,lks21c/elasticsearch,tebriel/elasticsearch,MisterAndersen/elasticsearch,onegambler/elasticsearch,aglne/elasticsearch,kingaj/elasticsearch,achow/elasticsearch,koxa29/elasticsearch,wayeast/elasticsearch,fubuki/elasticsearch,rhoml/elasticsearch,mute/elasticsearch,hanst/elasticsearch,ajhalani/elasticsearch,kcompher/elasticsearch,davidvgalbraith/elasticsearch,mikemccand/elasticsearch,trangvh/elasticsearch,sposam/elasticsearch,slavau/elasticsearch,mohit/elasticsearch,yongminxia/elasticsearch,JackyMai/elasticsearch,jimhooker2002/elasticsearch,mbrukman/elasticsearch,amaliujia/elasticsearch,kimimj/elasticsearch,nellicus/elasticsearch,vrkansagara/elasticsearch,Collaborne/elasticsearch,andrestc/elasticsearch,rmuir/elasticsearch,wbowling/elasticsearch,kubum/elasticsearch,acchen97/elasticsearch,fforbeck/elasticsearch,Brijeshrpatel9/elasticsearch,karthikjaps/elasticsearch,mohit/elasticsearch,golubev/elasticsearch,andrejserafim/elasticsearch,peschlowp/elasticsearch,TonyChai24/ESSource,pozhidaevak/elasticsearch,dpursehouse/elasticsearch,nezirus/elasticsearch,ZTE-PaaS/elasticsearch,zhaocloud/elasticsearch,snikch/elasticsearch,lks21c/elasticsearch,rento19962/elasticsearch,zhiqinghuang/elasticsearch,zhaocloud/elasticsearch,queirozfcom/elasticsearch,geidies/elasticsearch,chrismwendt/elasticsearch,F0lha/elasticsearch,kubum/elasticsearch,linglaiyao1314/elasticsearch,jimczi/elasticsearch,LewayneNaidoo/elasticsearch,linglaiyao1314/elasticsearch,caengcjd/elasticsearch,myelin/elasticsearch,18098924759/elasticsearch,mm0/elasticsearch,HarishAtGitHub/elasticsearch,naveenhooda2000/elasticsearch,sdauletau/elasticsearch,areek/elasticsearch,diendt/elasticsearch,fekaputra/elasticsearch,tahaemin/elasticsearch,jchampion/elasticsearch,jprante/elasticsearch,marcuswr/elasticsearch-dateline,mortonsykes/elasticsearch,petmit/elasticsearch,jimczi/elasticsearch,Collaborne/elasticsearch,strapdata/elassandra5-rc,wuranbo/elasticsearch,chrismwendt/elasticsearch,mnylen/elasticsearch,davidvgalbraith/elasticsearch,pritishppai/elasticsearch,xpandan/elasticsearch,amit-shar/elasticsearch,C-Bish/elasticsearch,koxa29/elasticsearch,zhiqinghuang/elasticsearch,TonyChai24/ESSource,petmit/elasticsearch,kaneshin/elasticsearch,iamjakob/elasticsearch,iamjakob/elasticsearch,kingaj/elasticsearch,aparo/elasticsearch,vorce/es-metrics,infusionsoft/elasticsearch,kevinkluge/elasticsearch,naveenhooda2000/elasticsearch,ulkas/elasticsearch,achow/elasticsearch,hanswang/elasticsearch,polyfractal/elasticsearch,ZTE-PaaS/elasticsearch,apepper/elasticsearch,tsohil/elasticsearch,skearns64/elasticsearch,Ansh90/elasticsearch,weipinghe/elasticsearch,hydro2k/elasticsearch,Stacey-Gammon/elasticsearch,henakamaMSFT/elasticsearch,geidies/elasticsearch,abibell/elasticsearch,Siddartha07/elasticsearch,kalimatas/elasticsearch,AndreKR/elasticsearch,maddin2016/elasticsearch,himanshuag/elasticsearch,sreeramjayan/elasticsearch,jw0201/elastic,elancom/elasticsearch,umeshdangat/elasticsearch,pablocastro/elasticsearch,gmarz/elasticsearch,bawse/elasticsearch,LeoYao/elasticsearch,andrewvc/elasticsearch,smflorentino/elasticsearch,abibell/elasticsearch,scorpionvicky/elasticsearch,mcku/elasticsearch,hechunwen/elasticsearch,golubev/elasticsearch,himanshuag/elasticsearch,palecur/elasticsearch,qwerty4030/elasticsearch,Siddartha07/elasticsearch,iantruslove/elasticsearch,Charlesdong/elasticsearch,Microsoft/elasticsearch,wimvds/elasticsearch,wittyameta/elasticsearch,brandonkearby/elasticsearch,girirajsharma/elasticsearch,HarishAtGitHub/elasticsearch,henakamaMSFT/elasticsearch,micpalmia/elasticsearch,Charlesdong/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,mm0/elasticsearch,sjohnr/elasticsearch,infusionsoft/elasticsearch,mnylen/elasticsearch,myelin/elasticsearch,acchen97/elasticsearch,springning/elasticsearch,spiegela/elasticsearch,hechunwen/elasticsearch,Chhunlong/elasticsearch,JackyMai/elasticsearch,nomoa/elasticsearch,awislowski/elasticsearch,Chhunlong/elasticsearch,lmenezes/elasticsearch,knight1128/elasticsearch,EasonYi/elasticsearch,hafkensite/elasticsearch,strapdata/elassandra-test,ajhalani/elasticsearch,F0lha/elasticsearch,Liziyao/elasticsearch,Fsero/elasticsearch,hanswang/elasticsearch,MetSystem/elasticsearch,kenshin233/elasticsearch,camilojd/elasticsearch,petabytedata/elasticsearch,wbowling/elasticsearch,fubuki/elasticsearch,drewr/elasticsearch,Shekharrajak/elasticsearch,ckclark/elasticsearch,fforbeck/elasticsearch,kaneshin/elasticsearch,camilojd/elasticsearch,LewayneNaidoo/elasticsearch,kenshin233/elasticsearch,adrianbk/elasticsearch,adrianbk/elasticsearch,mapr/elasticsearch,ajhalani/elasticsearch,humandb/elasticsearch,truemped/elasticsearch,knight1128/elasticsearch,ajhalani/elasticsearch,marcuswr/elasticsearch-dateline,davidvgalbraith/elasticsearch,elancom/elasticsearch,kimimj/elasticsearch,snikch/elasticsearch,hanswang/elasticsearch,feiqitian/elasticsearch,vingupta3/elasticsearch,jeteve/elasticsearch,robin13/elasticsearch,yynil/elasticsearch,andrewvc/elasticsearch,jimhooker2002/elasticsearch,jimczi/elasticsearch,nilabhsagar/elasticsearch,yanjunh/elasticsearch,andrestc/elasticsearch,kalburgimanjunath/elasticsearch,Kakakakakku/elasticsearch,ydsakyclguozi/elasticsearch,onegambler/elasticsearch,AshishThakur/elasticsearch,markwalkom/elasticsearch,wimvds/elasticsearch,fekaputra/elasticsearch,mapr/elasticsearch,pranavraman/elasticsearch,Uiho/elasticsearch,kaneshin/elasticsearch,markllama/elasticsearch,geidies/elasticsearch,kimimj/elasticsearch,tahaemin/elasticsearch,mm0/elasticsearch,mute/elasticsearch,dantuffery/elasticsearch,MisterAndersen/elasticsearch,camilojd/elasticsearch,jprante/elasticsearch,jaynblue/elasticsearch,JervyShi/elasticsearch,a2lin/elasticsearch,vroyer/elassandra,alexkuk/elasticsearch,Asimov4/elasticsearch,mgalushka/elasticsearch,pritishppai/elasticsearch,nomoa/elasticsearch,combinatorist/elasticsearch,strapdata/elassandra-test,aparo/elasticsearch,combinatorist/elasticsearch,dongjoon-hyun/elasticsearch,nrkkalyan/elasticsearch,andrestc/elasticsearch,Fsero/elasticsearch,martinstuga/elasticsearch,EasonYi/elasticsearch,cwurm/elasticsearch,mikemccand/elasticsearch,beiske/elasticsearch,xuzha/elasticsearch,Flipkart/elasticsearch,AshishThakur/elasticsearch,nilabhsagar/elasticsearch,hydro2k/elasticsearch,dantuffery/elasticsearch,easonC/elasticsearch,ZTE-PaaS/elasticsearch,sreeramjayan/elasticsearch,Brijeshrpatel9/elasticsearch,opendatasoft/elasticsearch,bestwpw/elasticsearch,skearns64/elasticsearch,ESamir/elasticsearch,avikurapati/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,amit-shar/elasticsearch,alexshadow007/elasticsearch,jpountz/elasticsearch,acchen97/elasticsearch,libosu/elasticsearch,huanzhong/elasticsearch,hirdesh2008/elasticsearch,C-Bish/elasticsearch,libosu/elasticsearch,myelin/elasticsearch,Widen/elasticsearch,iamjakob/elasticsearch,kimimj/elasticsearch,abibell/elasticsearch,SergVro/elasticsearch,nilabhsagar/elasticsearch,gfyoung/elasticsearch,vvcephei/elasticsearch,karthikjaps/elasticsearch,brandonkearby/elasticsearch,iamjakob/elasticsearch,iacdingping/elasticsearch,MjAbuz/elasticsearch,Fsero/elasticsearch,adrianbk/elasticsearch,mcku/elasticsearch,szroland/elasticsearch,Widen/elasticsearch,pranavraman/elasticsearch,kenshin233/elasticsearch,truemped/elasticsearch,jimhooker2002/elasticsearch,hirdesh2008/elasticsearch,wenpos/elasticsearch,springning/elasticsearch,micpalmia/elasticsearch,kingaj/elasticsearch,kevinkluge/elasticsearch,dataduke/elasticsearch,hydro2k/elasticsearch,alexbrasetvik/elasticsearch,diendt/elasticsearch,coding0011/elasticsearch,vorce/es-metrics,mkis-/elasticsearch,sscarduzio/elasticsearch,yynil/elasticsearch,Brijeshrpatel9/elasticsearch,boliza/elasticsearch,codebunt/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,iamjakob/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,robin13/elasticsearch,likaiwalkman/elasticsearch,fforbeck/elasticsearch,alexksikes/elasticsearch,markllama/elasticsearch,hydro2k/elasticsearch,wenpos/elasticsearch,golubev/elasticsearch,ulkas/elasticsearch,feiqitian/elasticsearch,smflorentino/elasticsearch,brandonkearby/elasticsearch,queirozfcom/elasticsearch,Rygbee/elasticsearch,nellicus/elasticsearch,yuy168/elasticsearch,maddin2016/elasticsearch,mjhennig/elasticsearch,chrismwendt/elasticsearch,djschny/elasticsearch,areek/elasticsearch,cwurm/elasticsearch,brwe/elasticsearch,geidies/elasticsearch,feiqitian/elasticsearch,HarishAtGitHub/elasticsearch,ivansun1010/elasticsearch,mcku/elasticsearch,beiske/elasticsearch,diendt/elasticsearch,dataduke/elasticsearch,easonC/elasticsearch,elasticdog/elasticsearch,jprante/elasticsearch,ricardocerq/elasticsearch,mjhennig/elasticsearch,ouyangkongtong/elasticsearch,brwe/elasticsearch,sc0ttkclark/elasticsearch,yongminxia/elasticsearch,ThalaivaStars/OrgRepo1,lzo/elasticsearch-1,Asimov4/elasticsearch,zhiqinghuang/elasticsearch,sscarduzio/elasticsearch,opendatasoft/elasticsearch,strapdata/elassandra,wangtuo/elasticsearch,jango2015/elasticsearch,tahaemin/elasticsearch,tcucchietti/elasticsearch,markharwood/elasticsearch,xpandan/elasticsearch,AshishThakur/elasticsearch,overcome/elasticsearch,sarwarbhuiyan/elasticsearch,heng4fun/elasticsearch,vietlq/elasticsearch,wittyameta/elasticsearch,glefloch/elasticsearch,yongminxia/elasticsearch,schonfeld/elasticsearch,wbowling/elasticsearch,sposam/elasticsearch,kunallimaye/elasticsearch,ThalaivaStars/OrgRepo1,SaiprasadKrishnamurthy/elasticsearch,scorpionvicky/elasticsearch,aparo/elasticsearch,thecocce/elasticsearch,wittyameta/elasticsearch,anti-social/elasticsearch,kaneshin/elasticsearch,karthikjaps/elasticsearch,libosu/elasticsearch,amit-shar/elasticsearch,fooljohnny/elasticsearch,markwalkom/elasticsearch,sposam/elasticsearch,IanvsPoplicola/elasticsearch,mrorii/elasticsearch,martinstuga/elasticsearch,Rygbee/elasticsearch,glefloch/elasticsearch,sneivandt/elasticsearch,szroland/elasticsearch,jpountz/elasticsearch,Siddartha07/elasticsearch,gingerwizard/elasticsearch,Fsero/elasticsearch,lks21c/elasticsearch,masterweb121/elasticsearch,Chhunlong/elasticsearch,heng4fun/elasticsearch,iantruslove/elasticsearch,tcucchietti/elasticsearch,rhoml/elasticsearch,marcuswr/elasticsearch-dateline,boliza/elasticsearch,MaineC/elasticsearch,Fsero/elasticsearch,queirozfcom/elasticsearch,aglne/elasticsearch,Shekharrajak/elasticsearch,snikch/elasticsearch,golubev/elasticsearch,gingerwizard/elasticsearch,HonzaKral/elasticsearch,tahaemin/elasticsearch,fooljohnny/elasticsearch,zkidkid/elasticsearch,ImpressTV/elasticsearch,jimhooker2002/elasticsearch,lightslife/elasticsearch,girirajsharma/elasticsearch,jbertouch/elasticsearch,areek/elasticsearch,shreejay/elasticsearch,ulkas/elasticsearch,MichaelLiZhou/elasticsearch,wayeast/elasticsearch,ThiagoGarciaAlves/elasticsearch,dongjoon-hyun/elasticsearch,socialrank/elasticsearch,MetSystem/elasticsearch,qwerty4030/elasticsearch,cnfire/elasticsearch-1,Asimov4/elasticsearch,ThalaivaStars/OrgRepo1,MaineC/elasticsearch,khiraiwa/elasticsearch,iantruslove/elasticsearch,apepper/elasticsearch,zhiqinghuang/elasticsearch,dpursehouse/elasticsearch,libosu/elasticsearch,uschindler/elasticsearch,ImpressTV/elasticsearch,petabytedata/elasticsearch,markharwood/elasticsearch,sscarduzio/elasticsearch,Brijeshrpatel9/elasticsearch,brandonkearby/elasticsearch,Collaborne/elasticsearch,huanzhong/elasticsearch,sjohnr/elasticsearch
/* * Licensed to ElasticSearch and Shay Banon 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.support.replication; import org.elasticsearch.ElasticSearchException; import org.elasticsearch.ElasticSearchIllegalStateException; import org.elasticsearch.ExceptionsHelper; import org.elasticsearch.action.*; import org.elasticsearch.action.support.TransportAction; import org.elasticsearch.action.support.TransportActions; import org.elasticsearch.cluster.ClusterChangedEvent; import org.elasticsearch.cluster.ClusterService; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.TimeoutClusterStateListener; import org.elasticsearch.cluster.action.shard.ShardStateAction; import org.elasticsearch.cluster.block.ClusterBlockException; import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.cluster.routing.ShardIterator; import org.elasticsearch.cluster.routing.ShardRouting; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.io.stream.Streamable; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.util.concurrent.AbstractRunnable; import org.elasticsearch.index.engine.DocumentAlreadyExistsException; import org.elasticsearch.index.engine.VersionConflictEngineException; import org.elasticsearch.indices.IndicesService; import org.elasticsearch.node.NodeClosedException; import org.elasticsearch.rest.RestStatus; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.transport.*; import java.io.IOException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import static org.elasticsearch.ExceptionsHelper.detailedMessage; /** */ public abstract class TransportShardReplicationOperationAction<Request extends ShardReplicationOperationRequest, ReplicaRequest extends ActionRequest, Response extends ActionResponse> extends TransportAction<Request, Response> { protected final TransportService transportService; protected final ClusterService clusterService; protected final IndicesService indicesService; protected final ShardStateAction shardStateAction; protected final ReplicationType defaultReplicationType; protected final WriteConsistencyLevel defaultWriteConsistencyLevel; protected final TransportRequestOptions transportOptions; final String transportAction; final String transportReplicaAction; final String executor; final boolean checkWriteConsistency; protected TransportShardReplicationOperationAction(Settings settings, TransportService transportService, ClusterService clusterService, IndicesService indicesService, ThreadPool threadPool, ShardStateAction shardStateAction) { super(settings, threadPool); this.transportService = transportService; this.clusterService = clusterService; this.indicesService = indicesService; this.shardStateAction = shardStateAction; this.transportAction = transportAction(); this.transportReplicaAction = transportReplicaAction(); this.executor = executor(); this.checkWriteConsistency = checkWriteConsistency(); transportService.registerHandler(transportAction, new OperationTransportHandler()); transportService.registerHandler(transportReplicaAction, new ReplicaOperationTransportHandler()); this.transportOptions = transportOptions(); this.defaultReplicationType = ReplicationType.fromString(settings.get("action.replication_type", "sync")); this.defaultWriteConsistencyLevel = WriteConsistencyLevel.fromString(settings.get("action.write_consistency", "quorum")); } @Override protected void doExecute(Request request, ActionListener<Response> listener) { new AsyncShardOperationAction(request, listener).start(); } protected abstract Request newRequestInstance(); protected abstract ReplicaRequest newReplicaRequestInstance(); protected abstract Response newResponseInstance(); protected abstract String transportAction(); protected abstract String executor(); protected abstract PrimaryResponse<Response, ReplicaRequest> shardOperationOnPrimary(ClusterState clusterState, PrimaryOperationRequest shardRequest); protected abstract void shardOperationOnReplica(ReplicaOperationRequest shardRequest); /** * Called once replica operations have been dispatched on the */ protected void postPrimaryOperation(Request request, PrimaryResponse<Response, ReplicaRequest> response) { } protected abstract ShardIterator shards(ClusterState clusterState, Request request) throws ElasticSearchException; protected abstract boolean checkWriteConsistency(); protected abstract ClusterBlockException checkGlobalBlock(ClusterState state, Request request); protected abstract ClusterBlockException checkRequestBlock(ClusterState state, Request request); /** * Resolves the request, by default, simply setting the concrete index (if its aliased one). If the resolve * means a different execution, then return false here to indicate not to continue and execute this request. */ protected boolean resolveRequest(ClusterState state, Request request, ActionListener<Response> listener) { request.index(state.metaData().concreteIndex(request.index())); return true; } protected TransportRequestOptions transportOptions() { return TransportRequestOptions.EMPTY; } /** * Should the operations be performed on the replicas as well. Defaults to <tt>false</tt> meaning operations * will be executed on the replica. */ protected boolean ignoreReplicas() { return false; } private String transportReplicaAction() { return transportAction() + "/replica"; } protected boolean retryPrimaryException(Throwable e) { return TransportActions.isShardNotAvailableException(e); } /** * Should an exception be ignored when the operation is performed on the replica. */ boolean ignoreReplicaException(Throwable e) { if (TransportActions.isShardNotAvailableException(e)) { return true; } Throwable cause = ExceptionsHelper.unwrapCause(e); if (cause instanceof ConnectTransportException) { return true; } // on version conflict or document missing, it means // that a news change has crept into the replica, and its fine if (cause instanceof VersionConflictEngineException) { return true; } // same here if (cause instanceof DocumentAlreadyExistsException) { return true; } return false; } class OperationTransportHandler extends BaseTransportRequestHandler<Request> { @Override public Request newInstance() { return newRequestInstance(); } @Override public String executor() { return ThreadPool.Names.SAME; } @Override public void messageReceived(final Request request, final TransportChannel channel) throws Exception { // no need to have a threaded listener since we just send back a response request.listenerThreaded(false); // if we have a local operation, execute it on a thread since we don't spawn request.operationThreaded(true); execute(request, new ActionListener<Response>() { @Override public void onResponse(Response result) { try { channel.sendResponse(result); } catch (Throwable e) { onFailure(e); } } @Override public void onFailure(Throwable e) { try { channel.sendResponse(e); } catch (Throwable e1) { logger.warn("Failed to send response for " + transportAction, e1); } } }); } } class ReplicaOperationTransportHandler extends BaseTransportRequestHandler<ReplicaOperationRequest> { @Override public ReplicaOperationRequest newInstance() { return new ReplicaOperationRequest(); } @Override public String executor() { return executor; } @Override public void messageReceived(final ReplicaOperationRequest request, final TransportChannel channel) throws Exception { shardOperationOnReplica(request); channel.sendResponse(TransportResponse.Empty.INSTANCE); } } protected class PrimaryOperationRequest implements Streamable { public int shardId; public Request request; public PrimaryOperationRequest() { } public PrimaryOperationRequest(int shardId, Request request) { this.shardId = shardId; this.request = request; } @Override public void readFrom(StreamInput in) throws IOException { shardId = in.readVInt(); request = newRequestInstance(); request.readFrom(in); } @Override public void writeTo(StreamOutput out) throws IOException { out.writeVInt(shardId); request.writeTo(out); } } protected class ReplicaOperationRequest extends TransportRequest { public int shardId; public ReplicaRequest request; public ReplicaOperationRequest() { } public ReplicaOperationRequest(int shardId, ReplicaRequest request) { super(request); this.shardId = shardId; this.request = request; } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); shardId = in.readVInt(); request = newReplicaRequestInstance(); request.readFrom(in); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeVInt(shardId); request.writeTo(out); } } protected class AsyncShardOperationAction { private final ActionListener<Response> listener; private final Request request; private ClusterState clusterState; private ShardIterator shardIt; private final AtomicBoolean primaryOperationStarted = new AtomicBoolean(); private final ReplicationType replicationType; AsyncShardOperationAction(Request request, ActionListener<Response> listener) { this.request = request; this.listener = listener; if (request.replicationType() != ReplicationType.DEFAULT) { replicationType = request.replicationType(); } else { replicationType = defaultReplicationType; } } public void start() { start(false); } /** * Returns <tt>true</tt> if the action starting to be performed on the primary (or is done). */ public boolean start(final boolean fromClusterEvent) throws ElasticSearchException { this.clusterState = clusterService.state(); try { ClusterBlockException blockException = checkGlobalBlock(clusterState, request); if (blockException != null) { if (blockException.retryable()) { logger.debug("Cluster is blocked ({}), scheduling a retry", blockException.getMessage()); retry(fromClusterEvent, blockException); return false; } else { throw blockException; } } // check if we need to execute, and if not, return if (!resolveRequest(clusterState, request, listener)) { return true; } blockException = checkRequestBlock(clusterState, request); if (blockException != null) { if (blockException.retryable()) { logger.debug("Cluster is blocked ({}), scheduling a retry", blockException.getMessage()); retry(fromClusterEvent, blockException); return false; } else { throw blockException; } } shardIt = shards(clusterState, request); } catch (Throwable e) { listener.onFailure(e); return true; } // no shardIt, might be in the case between index gateway recovery and shardIt initialization if (shardIt.size() == 0) { logger.debug("No shard instances known for index [{}]. Scheduling a retry", shardIt.shardId()); retry(fromClusterEvent, null); return false; } boolean foundPrimary = false; ShardRouting shardX; while ((shardX = shardIt.nextOrNull()) != null) { final ShardRouting shard = shardX; // we only deal with primary shardIt here... if (!shard.primary()) { continue; } if (!shard.active() || !clusterState.nodes().nodeExists(shard.currentNodeId())) { logger.debug("primary shard [{}] is not yet active or we do not know the node it is assigned to [{}]. Scheduling a retry.", shard.shardId(), shard.currentNodeId()); retry(fromClusterEvent, null); return false; } // check here for consistency if (checkWriteConsistency) { WriteConsistencyLevel consistencyLevel = defaultWriteConsistencyLevel; if (request.consistencyLevel() != WriteConsistencyLevel.DEFAULT) { consistencyLevel = request.consistencyLevel(); } int requiredNumber = 1; if (consistencyLevel == WriteConsistencyLevel.QUORUM && shardIt.size() > 2) { // only for more than 2 in the number of shardIt it makes sense, otherwise its 1 shard with 1 replica, quorum is 1 (which is what it is initialized to) requiredNumber = (shardIt.size() / 2) + 1; } else if (consistencyLevel == WriteConsistencyLevel.ALL) { requiredNumber = shardIt.size(); } if (shardIt.sizeActive() < requiredNumber) { logger.debug("Not enough active copies of shard [{}] to meet write consistency of [{}] (have {}, needed {}). Scheduling a retry.", shard.shardId(), consistencyLevel, shardIt.sizeActive(), requiredNumber); retry(fromClusterEvent, null); return false; } } if (!primaryOperationStarted.compareAndSet(false, true)) { return true; } foundPrimary = true; if (shard.currentNodeId().equals(clusterState.nodes().localNodeId())) { try { if (request.operationThreaded()) { request.beforeLocalFork(); threadPool.executor(executor).execute(new Runnable() { @Override public void run() { try { performOnPrimary(shard.id(), fromClusterEvent, shard, clusterState); } catch (Throwable t) { listener.onFailure(t); } } }); } else { performOnPrimary(shard.id(), fromClusterEvent, shard, clusterState); } } catch (Throwable t) { listener.onFailure(t); } } else { DiscoveryNode node = clusterState.nodes().get(shard.currentNodeId()); transportService.sendRequest(node, transportAction, request, transportOptions, new BaseTransportResponseHandler<Response>() { @Override public Response newInstance() { return newResponseInstance(); } @Override public String executor() { return ThreadPool.Names.SAME; } @Override public void handleResponse(Response response) { listener.onResponse(response); } @Override public void handleException(TransportException exp) { // if we got disconnected from the node, or the node / shard is not in the right state (being closed) if (exp.unwrapCause() instanceof ConnectTransportException || exp.unwrapCause() instanceof NodeClosedException || retryPrimaryException(exp)) { primaryOperationStarted.set(false); // we already marked it as started when we executed it (removed the listener) so pass false // to re-add to the cluster listener logger.debug("received an error from node the primary was assigned to ({}). Scheduling a retry", exp.getMessage()); retry(false, null); } else { listener.onFailure(exp); } } }); } break; } // we won't find a primary if there are no shards in the shard iterator, retry... if (!foundPrimary) { logger.debug("Couldn't find a eligible primary shard. Scheduling for retry."); retry(fromClusterEvent, null); return false; } return true; } void retry(boolean fromClusterEvent, @Nullable final Throwable failure) { if (!fromClusterEvent) { // make it threaded operation so we fork on the discovery listener thread request.beforeLocalFork(); request.operationThreaded(true); clusterService.add(request.timeout(), new TimeoutClusterStateListener() { @Override public void postAdded() { logger.debug("Listener to cluster state added. Trying to index again."); if (start(true)) { // if we managed to start and perform the operation on the primary, we can remove this listener clusterService.remove(this); } } @Override public void onClose() { clusterService.remove(this); listener.onFailure(new NodeClosedException(clusterService.localNode())); } @Override public void clusterChanged(ClusterChangedEvent event) { logger.debug("Cluster changed (version {}). Trying to index again.", event.state().version()); if (start(true)) { // if we managed to start and perform the operation on the primary, we can remove this listener clusterService.remove(this); } } @Override public void onTimeout(TimeValue timeValue) { // just to be on the safe side, see if we can start it now? if (start(true)) { clusterService.remove(this); return; } clusterService.remove(this); Throwable listenerFailure = failure; if (listenerFailure == null) { if (shardIt == null) { listenerFailure = new UnavailableShardsException(null, "no available shards: Timeout waiting for [" + timeValue + "], request: " + request.toString()); } else { listenerFailure = new UnavailableShardsException(shardIt.shardId(), "[" + shardIt.size() + "] shardIt, [" + shardIt.sizeActive() + "] active : Timeout waiting for [" + timeValue + "], request: " + request.toString()); } } listener.onFailure(listenerFailure); } }); } else { logger.debug("Retry scheduling ignored as it as we already have a listener in place."); } } void performOnPrimary(int primaryShardId, boolean fromDiscoveryListener, final ShardRouting shard, ClusterState clusterState) { try { PrimaryResponse<Response, ReplicaRequest> response = shardOperationOnPrimary(clusterState, new PrimaryOperationRequest(primaryShardId, request)); performReplicas(response); } catch (Throwable e) { // shard has not been allocated yet, retry it here if (retryPrimaryException(e)) { primaryOperationStarted.set(false); logger.debug("Had an error while performing operation on primary ({}). Scheduling a retry.", e.getMessage()); retry(fromDiscoveryListener, null); return; } if (e instanceof ElasticSearchException && ((ElasticSearchException) e).status() == RestStatus.CONFLICT) { if (logger.isTraceEnabled()) { logger.trace(shard.shortSummary() + ": Failed to execute [" + request + "]", e); } } else { if (logger.isDebugEnabled()) { logger.debug(shard.shortSummary() + ": Failed to execute [" + request + "]", e); } } listener.onFailure(e); } } void performReplicas(final PrimaryResponse<Response, ReplicaRequest> response) { if (ignoreReplicas()) { postPrimaryOperation(request, response); listener.onResponse(response.response()); return; } ShardRouting shard; // we double check on the state, if it got changed we need to make sure we take the latest one cause // maybe a replica shard started its recovery process and we need to apply it there... // we also need to make sure if the new state has a new primary shard (that we indexed to before) started // and assigned to another node (while the indexing happened). In that case, we want to apply it on the // new primary shard as well... ClusterState newState = clusterService.state(); ShardRouting newPrimaryShard = null; if (clusterState != newState) { shardIt.reset(); ShardRouting originalPrimaryShard = null; while ((shard = shardIt.nextOrNull()) != null) { if (shard.primary()) { originalPrimaryShard = shard; break; } } if (originalPrimaryShard == null || !originalPrimaryShard.active()) { throw new ElasticSearchIllegalStateException("unexpected state, failed to find primary shard on an index operation that succeeded"); } clusterState = newState; shardIt = shards(newState, request); while ((shard = shardIt.nextOrNull()) != null) { if (shard.primary()) { if (originalPrimaryShard.currentNodeId().equals(shard.currentNodeId())) { newPrimaryShard = null; } else { newPrimaryShard = shard; } break; } } } // initialize the counter int replicaCounter = shardIt.assignedReplicasIncludingRelocating(); if (newPrimaryShard != null) { replicaCounter++; } if (replicaCounter == 0) { postPrimaryOperation(request, response); listener.onResponse(response.response()); return; } if (replicationType == ReplicationType.ASYNC) { postPrimaryOperation(request, response); // async replication, notify the listener listener.onResponse(response.response()); // now, trick the counter so it won't decrease to 0 and notify the listeners replicaCounter = Integer.MIN_VALUE; } // we add one to the replica count to do the postPrimaryOperation replicaCounter++; AtomicInteger counter = new AtomicInteger(replicaCounter); if (newPrimaryShard != null) { performOnReplica(response, counter, newPrimaryShard, newPrimaryShard.currentNodeId()); } shardIt.reset(); // reset the iterator while ((shard = shardIt.nextOrNull()) != null) { // if its unassigned, nothing to do here... if (shard.unassigned()) { continue; } // if the shard is primary and relocating, add one to the counter since we perform it on the replica as well // (and we already did it on the primary) boolean doOnlyOnRelocating = false; if (shard.primary()) { if (shard.relocating()) { doOnlyOnRelocating = true; } else { continue; } } // we index on a replica that is initializing as well since we might not have got the event // yet that it was started. We will get an exception IllegalShardState exception if its not started // and that's fine, we will ignore it if (!doOnlyOnRelocating) { performOnReplica(response, counter, shard, shard.currentNodeId()); } if (shard.relocating()) { performOnReplica(response, counter, shard, shard.relocatingNodeId()); } } // now do the postPrimary operation, and check if the listener needs to be invoked postPrimaryOperation(request, response); // we also invoke here in case replicas finish before postPrimaryAction does if (counter.decrementAndGet() == 0) { listener.onResponse(response.response()); } } void performOnReplica(final PrimaryResponse<Response, ReplicaRequest> response, final AtomicInteger counter, final ShardRouting shard, String nodeId) { // if we don't have that node, it means that it might have failed and will be created again, in // this case, we don't have to do the operation, and just let it failover if (!clusterState.nodes().nodeExists(nodeId)) { if (counter.decrementAndGet() == 0) { listener.onResponse(response.response()); } return; } final ReplicaOperationRequest shardRequest = new ReplicaOperationRequest(shardIt.shardId().id(), response.replicaRequest()); if (!nodeId.equals(clusterState.nodes().localNodeId())) { DiscoveryNode node = clusterState.nodes().get(nodeId); transportService.sendRequest(node, transportReplicaAction, shardRequest, transportOptions, new EmptyTransportResponseHandler(ThreadPool.Names.SAME) { @Override public void handleResponse(TransportResponse.Empty vResponse) { finishIfPossible(); } @Override public void handleException(TransportException exp) { if (!ignoreReplicaException(exp.unwrapCause())) { logger.warn("Failed to perform " + transportAction + " on replica " + shardIt.shardId(), exp); shardStateAction.shardFailed(shard, "Failed to perform [" + transportAction + "] on replica, message [" + detailedMessage(exp) + "]"); } finishIfPossible(); } private void finishIfPossible() { if (counter.decrementAndGet() == 0) { listener.onResponse(response.response()); } } }); } else { if (request.operationThreaded()) { request.beforeLocalFork(); try { threadPool.executor(executor).execute(new AbstractRunnable() { @Override public void run() { try { shardOperationOnReplica(shardRequest); } catch (Throwable e) { if (!ignoreReplicaException(e)) { logger.warn("Failed to perform " + transportAction + " on replica " + shardIt.shardId(), e); shardStateAction.shardFailed(shard, "Failed to perform [" + transportAction + "] on replica, message [" + detailedMessage(e) + "]"); } } if (counter.decrementAndGet() == 0) { listener.onResponse(response.response()); } } // we must never reject on because of thread pool capacity on replicas @Override public boolean isForceExecution() { return true; } }); } catch (Throwable e) { if (!ignoreReplicaException(e)) { logger.warn("Failed to perform " + transportAction + " on replica " + shardIt.shardId(), e); shardStateAction.shardFailed(shard, "Failed to perform [" + transportAction + "] on replica, message [" + detailedMessage(e) + "]"); } // we want to decrement the counter here, in teh failure handling, cause we got rejected // from executing on the thread pool if (counter.decrementAndGet() == 0) { listener.onResponse(response.response()); } } } else { try { shardOperationOnReplica(shardRequest); } catch (Throwable e) { if (!ignoreReplicaException(e)) { logger.warn("Failed to perform " + transportAction + " on replica" + shardIt.shardId(), e); shardStateAction.shardFailed(shard, "Failed to perform [" + transportAction + "] on replica, message [" + detailedMessage(e) + "]"); } } if (counter.decrementAndGet() == 0) { listener.onResponse(response.response()); } } } } } public static class PrimaryResponse<Response, ReplicaRequest> { private final ReplicaRequest replicaRequest; private final Response response; private final Object payload; public PrimaryResponse(ReplicaRequest replicaRequest, Response response, Object payload) { this.replicaRequest = replicaRequest; this.response = response; this.payload = payload; } public ReplicaRequest replicaRequest() { return this.replicaRequest; } public Response response() { return response; } public Object payload() { return payload; } } }
src/main/java/org/elasticsearch/action/support/replication/TransportShardReplicationOperationAction.java
/* * Licensed to ElasticSearch and Shay Banon 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.support.replication; import org.elasticsearch.ElasticSearchException; import org.elasticsearch.ElasticSearchIllegalStateException; import org.elasticsearch.ExceptionsHelper; import org.elasticsearch.action.*; import org.elasticsearch.action.support.TransportAction; import org.elasticsearch.action.support.TransportActions; import org.elasticsearch.cluster.ClusterChangedEvent; import org.elasticsearch.cluster.ClusterService; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.TimeoutClusterStateListener; import org.elasticsearch.cluster.action.shard.ShardStateAction; import org.elasticsearch.cluster.block.ClusterBlockException; import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.cluster.routing.ShardIterator; import org.elasticsearch.cluster.routing.ShardRouting; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.io.stream.Streamable; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.util.concurrent.AbstractRunnable; import org.elasticsearch.index.engine.DocumentAlreadyExistsException; import org.elasticsearch.index.engine.VersionConflictEngineException; import org.elasticsearch.indices.IndicesService; import org.elasticsearch.node.NodeClosedException; import org.elasticsearch.rest.RestStatus; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.transport.*; import java.io.IOException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import static org.elasticsearch.ExceptionsHelper.detailedMessage; /** */ public abstract class TransportShardReplicationOperationAction<Request extends ShardReplicationOperationRequest, ReplicaRequest extends ActionRequest, Response extends ActionResponse> extends TransportAction<Request, Response> { protected final TransportService transportService; protected final ClusterService clusterService; protected final IndicesService indicesService; protected final ShardStateAction shardStateAction; protected final ReplicationType defaultReplicationType; protected final WriteConsistencyLevel defaultWriteConsistencyLevel; protected final TransportRequestOptions transportOptions; final String transportAction; final String transportReplicaAction; final String executor; final boolean checkWriteConsistency; protected TransportShardReplicationOperationAction(Settings settings, TransportService transportService, ClusterService clusterService, IndicesService indicesService, ThreadPool threadPool, ShardStateAction shardStateAction) { super(settings, threadPool); this.transportService = transportService; this.clusterService = clusterService; this.indicesService = indicesService; this.shardStateAction = shardStateAction; this.transportAction = transportAction(); this.transportReplicaAction = transportReplicaAction(); this.executor = executor(); this.checkWriteConsistency = checkWriteConsistency(); transportService.registerHandler(transportAction, new OperationTransportHandler()); transportService.registerHandler(transportReplicaAction, new ReplicaOperationTransportHandler()); this.transportOptions = transportOptions(); this.defaultReplicationType = ReplicationType.fromString(settings.get("action.replication_type", "sync")); this.defaultWriteConsistencyLevel = WriteConsistencyLevel.fromString(settings.get("action.write_consistency", "quorum")); } @Override protected void doExecute(Request request, ActionListener<Response> listener) { new AsyncShardOperationAction(request, listener).start(); } protected abstract Request newRequestInstance(); protected abstract ReplicaRequest newReplicaRequestInstance(); protected abstract Response newResponseInstance(); protected abstract String transportAction(); protected abstract String executor(); protected abstract PrimaryResponse<Response, ReplicaRequest> shardOperationOnPrimary(ClusterState clusterState, PrimaryOperationRequest shardRequest); protected abstract void shardOperationOnReplica(ReplicaOperationRequest shardRequest); /** * Called once replica operations have been dispatched on the */ protected void postPrimaryOperation(Request request, PrimaryResponse<Response, ReplicaRequest> response) { } protected abstract ShardIterator shards(ClusterState clusterState, Request request) throws ElasticSearchException; protected abstract boolean checkWriteConsistency(); protected abstract ClusterBlockException checkGlobalBlock(ClusterState state, Request request); protected abstract ClusterBlockException checkRequestBlock(ClusterState state, Request request); /** * Resolves the request, by default, simply setting the concrete index (if its aliased one). If the resolve * means a different execution, then return false here to indicate not to continue and execute this request. */ protected boolean resolveRequest(ClusterState state, Request request, ActionListener<Response> listener) { request.index(state.metaData().concreteIndex(request.index())); return true; } protected TransportRequestOptions transportOptions() { return TransportRequestOptions.EMPTY; } /** * Should the operations be performed on the replicas as well. Defaults to <tt>false</tt> meaning operations * will be executed on the replica. */ protected boolean ignoreReplicas() { return false; } private String transportReplicaAction() { return transportAction() + "/replica"; } protected boolean retryPrimaryException(Throwable e) { return TransportActions.isShardNotAvailableException(e); } /** * Should an exception be ignored when the operation is performed on the replica. */ boolean ignoreReplicaException(Throwable e) { if (TransportActions.isShardNotAvailableException(e)) { return true; } Throwable cause = ExceptionsHelper.unwrapCause(e); if (cause instanceof ConnectTransportException) { return true; } // on version conflict or document missing, it means // that a news change has crept into the replica, and its fine if (cause instanceof VersionConflictEngineException) { return true; } // same here if (cause instanceof DocumentAlreadyExistsException) { return true; } return false; } class OperationTransportHandler extends BaseTransportRequestHandler<Request> { @Override public Request newInstance() { return newRequestInstance(); } @Override public String executor() { return ThreadPool.Names.SAME; } @Override public void messageReceived(final Request request, final TransportChannel channel) throws Exception { // no need to have a threaded listener since we just send back a response request.listenerThreaded(false); // if we have a local operation, execute it on a thread since we don't spawn request.operationThreaded(true); execute(request, new ActionListener<Response>() { @Override public void onResponse(Response result) { try { channel.sendResponse(result); } catch (Throwable e) { onFailure(e); } } @Override public void onFailure(Throwable e) { try { channel.sendResponse(e); } catch (Throwable e1) { logger.warn("Failed to send response for " + transportAction, e1); } } }); } } class ReplicaOperationTransportHandler extends BaseTransportRequestHandler<ReplicaOperationRequest> { @Override public ReplicaOperationRequest newInstance() { return new ReplicaOperationRequest(); } @Override public String executor() { return executor; } @Override public void messageReceived(final ReplicaOperationRequest request, final TransportChannel channel) throws Exception { shardOperationOnReplica(request); channel.sendResponse(TransportResponse.Empty.INSTANCE); } } protected class PrimaryOperationRequest implements Streamable { public int shardId; public Request request; public PrimaryOperationRequest() { } public PrimaryOperationRequest(int shardId, Request request) { this.shardId = shardId; this.request = request; } @Override public void readFrom(StreamInput in) throws IOException { shardId = in.readVInt(); request = newRequestInstance(); request.readFrom(in); } @Override public void writeTo(StreamOutput out) throws IOException { out.writeVInt(shardId); request.writeTo(out); } } protected class ReplicaOperationRequest extends TransportRequest { public int shardId; public ReplicaRequest request; public ReplicaOperationRequest() { } public ReplicaOperationRequest(int shardId, ReplicaRequest request) { super(request); this.shardId = shardId; this.request = request; } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); shardId = in.readVInt(); request = newReplicaRequestInstance(); request.readFrom(in); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeVInt(shardId); request.writeTo(out); } } protected class AsyncShardOperationAction { private final ActionListener<Response> listener; private final Request request; private ClusterState clusterState; private ShardIterator shardIt; private final AtomicBoolean primaryOperationStarted = new AtomicBoolean(); private final ReplicationType replicationType; AsyncShardOperationAction(Request request, ActionListener<Response> listener) { this.request = request; this.listener = listener; if (request.replicationType() != ReplicationType.DEFAULT) { replicationType = request.replicationType(); } else { replicationType = defaultReplicationType; } } public void start() { start(false); } /** * Returns <tt>true</tt> if the action starting to be performed on the primary (or is done). */ public boolean start(final boolean fromClusterEvent) throws ElasticSearchException { this.clusterState = clusterService.state(); try { ClusterBlockException blockException = checkGlobalBlock(clusterState, request); if (blockException != null) { if (blockException.retryable()) { logger.debug("Cluster is blocked ({}), scheduling a retry", blockException.getMessage()); retry(fromClusterEvent, blockException); return false; } else { throw blockException; } } // check if we need to execute, and if not, return if (!resolveRequest(clusterState, request, listener)) { return true; } blockException = checkRequestBlock(clusterState, request); if (blockException != null) { if (blockException.retryable()) { logger.debug("Cluster is blocked ({}), scheduling a retry", blockException.getMessage()); retry(fromClusterEvent, blockException); return false; } else { throw blockException; } } shardIt = shards(clusterState, request); } catch (Throwable e) { listener.onFailure(e); return true; } // no shardIt, might be in the case between index gateway recovery and shardIt initialization if (shardIt.size() == 0) { logger.debug("No shard instances known for index [{}]. Scheduling a retry", shardIt.shardId()); retry(fromClusterEvent, null); return false; } boolean foundPrimary = false; ShardRouting shardX; while ((shardX = shardIt.nextOrNull()) != null) { final ShardRouting shard = shardX; // we only deal with primary shardIt here... if (!shard.primary()) { continue; } if (!shard.active() || !clusterState.nodes().nodeExists(shard.currentNodeId())) { logger.debug("primary shard [{}] is not yet active or we do not know the node it is assigned to [{}]. Scheduling a retry.", shard.shardId(), shard.currentNodeId()); retry(fromClusterEvent, null); return false; } // check here for consistency if (checkWriteConsistency) { WriteConsistencyLevel consistencyLevel = defaultWriteConsistencyLevel; if (request.consistencyLevel() != WriteConsistencyLevel.DEFAULT) { consistencyLevel = request.consistencyLevel(); } int requiredNumber = 1; if (consistencyLevel == WriteConsistencyLevel.QUORUM && shardIt.size() > 2) { // only for more than 2 in the number of shardIt it makes sense, otherwise its 1 shard with 1 replica, quorum is 1 (which is what it is initialized to) requiredNumber = (shardIt.size() / 2) + 1; } else if (consistencyLevel == WriteConsistencyLevel.ALL) { requiredNumber = shardIt.size(); } if (shardIt.sizeActive() < requiredNumber) { logger.debug("Not enough active copies of shard [{}] to meet write consistency of [{}] (have {}, needed {}). Scheduling a retry.", shard.shardId(), consistencyLevel, shardIt.sizeActive(), requiredNumber); retry(fromClusterEvent, null); return false; } } if (!primaryOperationStarted.compareAndSet(false, true)) { return true; } foundPrimary = true; if (shard.currentNodeId().equals(clusterState.nodes().localNodeId())) { try { if (request.operationThreaded()) { request.beforeLocalFork(); threadPool.executor(executor).execute(new Runnable() { @Override public void run() { try { performOnPrimary(shard.id(), fromClusterEvent, shard, clusterState); } catch (Throwable t) { listener.onFailure(t); } } }); } else { performOnPrimary(shard.id(), fromClusterEvent, shard, clusterState); } } catch (Throwable t) { listener.onFailure(t); } } else { DiscoveryNode node = clusterState.nodes().get(shard.currentNodeId()); transportService.sendRequest(node, transportAction, request, transportOptions, new BaseTransportResponseHandler<Response>() { @Override public Response newInstance() { return newResponseInstance(); } @Override public String executor() { return ThreadPool.Names.SAME; } @Override public void handleResponse(Response response) { listener.onResponse(response); } @Override public void handleException(TransportException exp) { // if we got disconnected from the node, or the node / shard is not in the right state (being closed) if (exp.unwrapCause() instanceof ConnectTransportException || exp.unwrapCause() instanceof NodeClosedException || retryPrimaryException(exp)) { primaryOperationStarted.set(false); // we already marked it as started when we executed it (removed the listener) so pass false // to re-add to the cluster listener logger.debug("received an error from node the primary was assigned to ({}). Scheduling a retry", exp.getMessage()); retry(false, null); } else { listener.onFailure(exp); } } }); } break; } // we won't find a primary if there are no shards in the shard iterator, retry... if (!foundPrimary) { logger.debug("Couldn't find a eligible primary shard. Scheduling for retry."); retry(fromClusterEvent, null); return false; } return true; } void retry(boolean fromClusterEvent, @Nullable final Throwable failure) { if (!fromClusterEvent) { // make it threaded operation so we fork on the discovery listener thread request.beforeLocalFork(); request.operationThreaded(true); clusterService.add(request.timeout(), new TimeoutClusterStateListener() { @Override public void postAdded() { logger.debug("ShardRepOp: listener to cluster state added. Trying again"); if (start(true)) { // if we managed to start and perform the operation on the primary, we can remove this listener clusterService.remove(this); } } @Override public void onClose() { clusterService.remove(this); listener.onFailure(new NodeClosedException(clusterService.localNode())); } @Override public void clusterChanged(ClusterChangedEvent event) { logger.debug("ShardRepOp: cluster changed (version {}). Trying again", event.state().version()); if (start(true)) { // if we managed to start and perform the operation on the primary, we can remove this listener clusterService.remove(this); } } @Override public void onTimeout(TimeValue timeValue) { // just to be on the safe side, see if we can start it now? if (start(true)) { clusterService.remove(this); return; } clusterService.remove(this); Throwable listenerFailure = failure; if (listenerFailure == null) { if (shardIt == null) { listenerFailure = new UnavailableShardsException(null, "no available shards: Timeout waiting for [" + timeValue + "], request: " + request.toString()); } else { listenerFailure = new UnavailableShardsException(shardIt.shardId(), "[" + shardIt.size() + "] shardIt, [" + shardIt.sizeActive() + "] active : Timeout waiting for [" + timeValue + "], request: " + request.toString()); } } listener.onFailure(listenerFailure); } }); } else { logger.debug("ShardRepOp: retry scheduling ignored as it was executed from an active cluster state listener"); } } void performOnPrimary(int primaryShardId, boolean fromDiscoveryListener, final ShardRouting shard, ClusterState clusterState) { try { PrimaryResponse<Response, ReplicaRequest> response = shardOperationOnPrimary(clusterState, new PrimaryOperationRequest(primaryShardId, request)); performReplicas(response); } catch (Throwable e) { // shard has not been allocated yet, retry it here if (retryPrimaryException(e)) { primaryOperationStarted.set(false); logger.debug("Had an error while performing operation on primary ({}). Scheduling a retry.", e.getMessage()); retry(fromDiscoveryListener, null); return; } if (e instanceof ElasticSearchException && ((ElasticSearchException) e).status() == RestStatus.CONFLICT) { if (logger.isTraceEnabled()) { logger.trace(shard.shortSummary() + ": Failed to execute [" + request + "]", e); } } else { if (logger.isDebugEnabled()) { logger.debug(shard.shortSummary() + ": Failed to execute [" + request + "]", e); } } listener.onFailure(e); } } void performReplicas(final PrimaryResponse<Response, ReplicaRequest> response) { if (ignoreReplicas()) { postPrimaryOperation(request, response); listener.onResponse(response.response()); return; } ShardRouting shard; // we double check on the state, if it got changed we need to make sure we take the latest one cause // maybe a replica shard started its recovery process and we need to apply it there... // we also need to make sure if the new state has a new primary shard (that we indexed to before) started // and assigned to another node (while the indexing happened). In that case, we want to apply it on the // new primary shard as well... ClusterState newState = clusterService.state(); ShardRouting newPrimaryShard = null; if (clusterState != newState) { shardIt.reset(); ShardRouting originalPrimaryShard = null; while ((shard = shardIt.nextOrNull()) != null) { if (shard.primary()) { originalPrimaryShard = shard; break; } } if (originalPrimaryShard == null || !originalPrimaryShard.active()) { throw new ElasticSearchIllegalStateException("unexpected state, failed to find primary shard on an index operation that succeeded"); } clusterState = newState; shardIt = shards(newState, request); while ((shard = shardIt.nextOrNull()) != null) { if (shard.primary()) { if (originalPrimaryShard.currentNodeId().equals(shard.currentNodeId())) { newPrimaryShard = null; } else { newPrimaryShard = shard; } break; } } } // initialize the counter int replicaCounter = shardIt.assignedReplicasIncludingRelocating(); if (newPrimaryShard != null) { replicaCounter++; } if (replicaCounter == 0) { postPrimaryOperation(request, response); listener.onResponse(response.response()); return; } if (replicationType == ReplicationType.ASYNC) { postPrimaryOperation(request, response); // async replication, notify the listener listener.onResponse(response.response()); // now, trick the counter so it won't decrease to 0 and notify the listeners replicaCounter = Integer.MIN_VALUE; } // we add one to the replica count to do the postPrimaryOperation replicaCounter++; AtomicInteger counter = new AtomicInteger(replicaCounter); if (newPrimaryShard != null) { performOnReplica(response, counter, newPrimaryShard, newPrimaryShard.currentNodeId()); } shardIt.reset(); // reset the iterator while ((shard = shardIt.nextOrNull()) != null) { // if its unassigned, nothing to do here... if (shard.unassigned()) { continue; } // if the shard is primary and relocating, add one to the counter since we perform it on the replica as well // (and we already did it on the primary) boolean doOnlyOnRelocating = false; if (shard.primary()) { if (shard.relocating()) { doOnlyOnRelocating = true; } else { continue; } } // we index on a replica that is initializing as well since we might not have got the event // yet that it was started. We will get an exception IllegalShardState exception if its not started // and that's fine, we will ignore it if (!doOnlyOnRelocating) { performOnReplica(response, counter, shard, shard.currentNodeId()); } if (shard.relocating()) { performOnReplica(response, counter, shard, shard.relocatingNodeId()); } } // now do the postPrimary operation, and check if the listener needs to be invoked postPrimaryOperation(request, response); // we also invoke here in case replicas finish before postPrimaryAction does if (counter.decrementAndGet() == 0) { listener.onResponse(response.response()); } } void performOnReplica(final PrimaryResponse<Response, ReplicaRequest> response, final AtomicInteger counter, final ShardRouting shard, String nodeId) { // if we don't have that node, it means that it might have failed and will be created again, in // this case, we don't have to do the operation, and just let it failover if (!clusterState.nodes().nodeExists(nodeId)) { if (counter.decrementAndGet() == 0) { listener.onResponse(response.response()); } return; } final ReplicaOperationRequest shardRequest = new ReplicaOperationRequest(shardIt.shardId().id(), response.replicaRequest()); if (!nodeId.equals(clusterState.nodes().localNodeId())) { DiscoveryNode node = clusterState.nodes().get(nodeId); transportService.sendRequest(node, transportReplicaAction, shardRequest, transportOptions, new EmptyTransportResponseHandler(ThreadPool.Names.SAME) { @Override public void handleResponse(TransportResponse.Empty vResponse) { finishIfPossible(); } @Override public void handleException(TransportException exp) { if (!ignoreReplicaException(exp.unwrapCause())) { logger.warn("Failed to perform " + transportAction + " on replica " + shardIt.shardId(), exp); shardStateAction.shardFailed(shard, "Failed to perform [" + transportAction + "] on replica, message [" + detailedMessage(exp) + "]"); } finishIfPossible(); } private void finishIfPossible() { if (counter.decrementAndGet() == 0) { listener.onResponse(response.response()); } } }); } else { if (request.operationThreaded()) { request.beforeLocalFork(); try { threadPool.executor(executor).execute(new AbstractRunnable() { @Override public void run() { try { shardOperationOnReplica(shardRequest); } catch (Throwable e) { if (!ignoreReplicaException(e)) { logger.warn("Failed to perform " + transportAction + " on replica " + shardIt.shardId(), e); shardStateAction.shardFailed(shard, "Failed to perform [" + transportAction + "] on replica, message [" + detailedMessage(e) + "]"); } } if (counter.decrementAndGet() == 0) { listener.onResponse(response.response()); } } // we must never reject on because of thread pool capacity on replicas @Override public boolean isForceExecution() { return true; } }); } catch (Throwable e) { if (!ignoreReplicaException(e)) { logger.warn("Failed to perform " + transportAction + " on replica " + shardIt.shardId(), e); shardStateAction.shardFailed(shard, "Failed to perform [" + transportAction + "] on replica, message [" + detailedMessage(e) + "]"); } // we want to decrement the counter here, in teh failure handling, cause we got rejected // from executing on the thread pool if (counter.decrementAndGet() == 0) { listener.onResponse(response.response()); } } } else { try { shardOperationOnReplica(shardRequest); } catch (Throwable e) { if (!ignoreReplicaException(e)) { logger.warn("Failed to perform " + transportAction + " on replica" + shardIt.shardId(), e); shardStateAction.shardFailed(shard, "Failed to perform [" + transportAction + "] on replica, message [" + detailedMessage(e) + "]"); } } if (counter.decrementAndGet() == 0) { listener.onResponse(response.response()); } } } } } public static class PrimaryResponse<Response, ReplicaRequest> { private final ReplicaRequest replicaRequest; private final Response response; private final Object payload; public PrimaryResponse(ReplicaRequest replicaRequest, Response response, Object payload) { this.replicaRequest = replicaRequest; this.response = response; this.payload = payload; } public ReplicaRequest replicaRequest() { return this.replicaRequest; } public Response response() { return response; } public Object payload() { return payload; } } }
Minor cleanup to logging messages.
src/main/java/org/elasticsearch/action/support/replication/TransportShardReplicationOperationAction.java
Minor cleanup to logging messages.
<ide><path>rc/main/java/org/elasticsearch/action/support/replication/TransportShardReplicationOperationAction.java <ide> clusterService.add(request.timeout(), new TimeoutClusterStateListener() { <ide> @Override <ide> public void postAdded() { <del> logger.debug("ShardRepOp: listener to cluster state added. Trying again"); <add> logger.debug("Listener to cluster state added. Trying to index again."); <ide> if (start(true)) { <ide> // if we managed to start and perform the operation on the primary, we can remove this listener <ide> clusterService.remove(this); <ide> <ide> @Override <ide> public void clusterChanged(ClusterChangedEvent event) { <del> logger.debug("ShardRepOp: cluster changed (version {}). Trying again", event.state().version()); <add> logger.debug("Cluster changed (version {}). Trying to index again.", event.state().version()); <ide> if (start(true)) { <ide> // if we managed to start and perform the operation on the primary, we can remove this listener <ide> clusterService.remove(this); <ide> } <ide> }); <ide> } else { <del> logger.debug("ShardRepOp: retry scheduling ignored as it was executed from an active cluster state listener"); <add> logger.debug("Retry scheduling ignored as it as we already have a listener in place."); <ide> } <ide> } <ide>
Java
apache-2.0
3c1fcf0e4c0f675b8f0f3719d7606a058b614ead
0
LPTK/intellij-scala,triggerNZ/intellij-scala,triggerNZ/intellij-scala,JetBrains/intellij-scala-historical,JetBrains/intellij-scala-historical,SergeevPavel/intellij-scala,SergeevPavel/intellij-scala,LPTK/intellij-scala,SergeevPavel/intellij-scala,triggerNZ/intellij-scala,LPTK/intellij-scala,JetBrains/intellij-scala-historical,consulo/consulo-scala
package org.jetbrains.jps.incremental.scala.model; import com.intellij.openapi.util.io.FileUtil; import com.intellij.util.xmlb.XmlSerializerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.jps.model.ex.JpsElementBase; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * @author Pavel Fatin */ public class FacetSettingsImpl extends JpsElementBase<FacetSettingsImpl> implements FacetSettings { private State myState; public FacetSettingsImpl(State state) { myState = state; } public LibraryLevel getCompilerLibraryLevel() { return myState.compilerLibraryLevel; } public String getCompilerLibraryName() { return myState.compilerLibraryName; } public boolean isFscEnabled() { return myState.fsc; } public String[] getCompilerOptions() { List<String> list = new ArrayList<String>(); if (!myState.warnings) { list.add("-nowarn"); } if (myState.deprecationWarnings) { list.add("-deprecation"); } if (myState.uncheckedWarnings) { list.add("-unchecked"); } if (myState.optimiseBytecode) { list.add("-optimise"); } if (myState.explainTypeErrors) { list.add("-explaintypes"); } if (myState.continuations) { list.add("-P:continuations:enable"); } switch (myState.debuggingInfoLevel) { case None: list.add("-g:none"); break; case Source: list.add("-g:source"); break; case Line: list.add("-g:line"); break; case Vars: list.add("-g:vars"); break; case Notc: list.add("-g:notc"); } for (String pluginPath : myState.pluginPaths) { list.add("-Xplugin:" + FileUtil.toCanonicalPath(pluginPath)); } String optionsString = myState.compilerOptions.trim(); if (!optionsString.isEmpty()) { String[] options = optionsString.split("\\s+"); list.addAll(Arrays.asList(options)); } return list.toArray(new String[list.size()]); } @NotNull @Override public FacetSettingsImpl createCopy() { return new FacetSettingsImpl(XmlSerializerUtil.createCopy(myState)); } @Override public void applyChanges(@NotNull FacetSettingsImpl facetSettings) { // do nothing } public static class State { public LibraryLevel compilerLibraryLevel; public String compilerLibraryName; public boolean fsc; public boolean warnings = true; public boolean deprecationWarnings; public boolean uncheckedWarnings; public boolean optimiseBytecode; public boolean explainTypeErrors; public boolean continuations; public DebuggingInfoLevel debuggingInfoLevel = DebuggingInfoLevel.Vars; public String compilerOptions = ""; public String[] pluginPaths = new String[] {}; } }
jps-plugin/src/org/jetbrains/jps/incremental/scala/model/FacetSettingsImpl.java
package org.jetbrains.jps.incremental.scala.model; import com.intellij.openapi.util.io.FileUtil; import com.intellij.util.xmlb.XmlSerializerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.jps.model.ex.JpsElementBase; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * @author Pavel Fatin */ public class FacetSettingsImpl extends JpsElementBase<FacetSettingsImpl> implements FacetSettings { private State myState; public FacetSettingsImpl(State state) { myState = state; } public LibraryLevel getCompilerLibraryLevel() { return myState.compilerLibraryLevel; } public String getCompilerLibraryName() { return myState.compilerLibraryName; } public boolean isFscEnabled() { return myState.fsc; } public String[] getCompilerOptions() { List<String> list = new ArrayList<String>(); if (myState.warnings) { list.add("-nowarn"); } if (myState.deprecationWarnings) { list.add("-deprecation"); } if (myState.uncheckedWarnings) { list.add("-unchecked"); } if (myState.optimiseBytecode) { list.add("-optimise"); } if (myState.explainTypeErrors) { list.add("-explaintypes"); } if (myState.continuations) { list.add("-P:continuations:enable"); } switch (myState.debuggingInfoLevel) { case None: list.add("-g:none"); break; case Source: list.add("-g:source"); break; case Line: list.add("-g:line"); break; case Vars: list.add("-g:vars"); break; case Notc: list.add("-g:notc"); } for (String pluginPath : myState.pluginPaths) { list.add("-Xplugin:" + FileUtil.toCanonicalPath(pluginPath)); } String optionsString = myState.compilerOptions.trim(); if (!optionsString.isEmpty()) { String[] options = optionsString.split("\\s+"); list.addAll(Arrays.asList(options)); } return list.toArray(new String[list.size()]); } @NotNull @Override public FacetSettingsImpl createCopy() { return new FacetSettingsImpl(XmlSerializerUtil.createCopy(myState)); } @Override public void applyChanges(@NotNull FacetSettingsImpl facetSettings) { // do nothing } public static class State { public LibraryLevel compilerLibraryLevel; public String compilerLibraryName; public boolean fsc; public boolean warnings = true; public boolean deprecationWarnings; public boolean uncheckedWarnings; public boolean optimiseBytecode; public boolean explainTypeErrors; public boolean continuations; public DebuggingInfoLevel debuggingInfoLevel = DebuggingInfoLevel.Vars; public String compilerOptions = ""; public String[] pluginPaths = new String[] {}; } }
JPS: proper "-nowarn" option handling
jps-plugin/src/org/jetbrains/jps/incremental/scala/model/FacetSettingsImpl.java
JPS: proper "-nowarn" option handling
<ide><path>ps-plugin/src/org/jetbrains/jps/incremental/scala/model/FacetSettingsImpl.java <ide> public String[] getCompilerOptions() { <ide> List<String> list = new ArrayList<String>(); <ide> <del> if (myState.warnings) { <add> if (!myState.warnings) { <ide> list.add("-nowarn"); <ide> } <ide>
Java
mit
94e88808b4357f06a763d7914493d0a620b3c4cf
0
deki/jira-plugin,warden/jira-plugin,kuldazbraslav/jira-plugin,kuldazbraslav/jira-plugin,escoem/jira-plugin,escoem/jira-plugin,deki/jira-plugin,warden/jira-plugin
/* * The MIT License * * Copyright (c) 2015 schristou88 * * 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 hudson.plugins.jira; import hudson.model.User; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; import java.util.Collections; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertThat; /** * @author schristou88 */ public class MailResolverTest extends JenkinsRule { @Rule public JenkinsRule r = new JenkinsRule(); @BeforeClass public static void setUp() throws Exception { System.setProperty("hudson.plugins.jira.JiraMailAddressResolver.disabled", "true"); } @Test public void disableEmailResolver() { User user = User.get("bob", true, Collections.emptyMap()); assertThat(JiraMailAddressResolver.resolve(user), is(nullValue())); } }
src/test/java/hudson/plugins/jira/MailResolverTest.java
/* * The MIT License * * Copyright (c) 2015 schristou88 * * 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 hudson.plugins.jira; import hudson.model.User; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; import java.util.Collections; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertThat; /** * @author schristou88 */ public class MailResolverTest extends JenkinsRule { @Rule public JenkinsRule r = new JenkinsRule(); @BeforeClass public static void setUp() throws Exception { System.setProperty(JiraMailAddressResolver.class.getName() + ".DISABLE", "true"); } @Test public void disableEmailResolver() { User user = User.get("bob", true, Collections.emptyMap()); assertThat(JiraMailAddressResolver.resolve(user), is(nullValue())); } }
Use full class name to protect against class rename/move.
src/test/java/hudson/plugins/jira/MailResolverTest.java
Use full class name to protect against class rename/move.
<ide><path>rc/test/java/hudson/plugins/jira/MailResolverTest.java <ide> <ide> @BeforeClass <ide> public static void setUp() throws Exception { <del> System.setProperty(JiraMailAddressResolver.class.getName() + ".DISABLE", "true"); <add> System.setProperty("hudson.plugins.jira.JiraMailAddressResolver.disabled", "true"); <ide> } <ide> <ide> @Test
Java
apache-2.0
a62e98f966d269baa14ba361e77d52b72134319b
0
keycloak/keycloak,reneploetz/keycloak,jpkrohling/keycloak,mhajas/keycloak,srose/keycloak,reneploetz/keycloak,mhajas/keycloak,stianst/keycloak,abstractj/keycloak,jpkrohling/keycloak,mhajas/keycloak,reneploetz/keycloak,stianst/keycloak,srose/keycloak,abstractj/keycloak,abstractj/keycloak,jpkrohling/keycloak,srose/keycloak,keycloak/keycloak,reneploetz/keycloak,stianst/keycloak,srose/keycloak,jpkrohling/keycloak,mhajas/keycloak,jpkrohling/keycloak,stianst/keycloak,srose/keycloak,stianst/keycloak,abstractj/keycloak,keycloak/keycloak,reneploetz/keycloak,abstractj/keycloak,keycloak/keycloak,mhajas/keycloak,keycloak/keycloak
/* * Copyright 2022 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * 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.keycloak.models.map.user; import org.jboss.logging.Logger; import org.keycloak.authorization.AuthorizationProvider; import org.keycloak.authorization.model.Resource; import org.keycloak.authorization.store.ResourceStore; import org.keycloak.common.util.Time; import org.keycloak.common.util.reflections.Types; import org.keycloak.component.ComponentModel; import org.keycloak.credential.CredentialAuthentication; import org.keycloak.credential.CredentialInput; import org.keycloak.credential.CredentialProvider; import org.keycloak.credential.CredentialProviderFactory; import org.keycloak.models.ClientModel; import org.keycloak.models.ClientScopeModel; import org.keycloak.models.CredentialValidationOutput; import org.keycloak.models.FederatedIdentityModel; import org.keycloak.models.GroupModel; import org.keycloak.models.IdentityProviderModel; import org.keycloak.models.KeycloakSession; import org.keycloak.models.ModelDuplicateException; import org.keycloak.models.ModelException; import org.keycloak.models.ProtocolMapperModel; import org.keycloak.models.RealmModel; import org.keycloak.models.RequiredActionProviderModel; import org.keycloak.models.RoleModel; import org.keycloak.models.SubjectCredentialManager; import org.keycloak.models.UserConsentModel; import org.keycloak.models.UserModel; import org.keycloak.models.UserModel.SearchableFields; import org.keycloak.models.UserProvider; import org.keycloak.models.map.common.TimeAdapter; import org.keycloak.models.map.credential.MapUserCredentialManager; import org.keycloak.models.map.storage.MapKeycloakTransactionWithAuth; import org.keycloak.models.map.storage.MapKeycloakTransaction; import org.keycloak.models.map.storage.MapStorage; import org.keycloak.models.map.storage.ModelCriteriaBuilder.Operator; import org.keycloak.models.map.storage.criteria.DefaultModelCriteria; import org.keycloak.models.utils.KeycloakModelUtils; import java.util.Collection; import java.util.EnumMap; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.keycloak.common.util.StackUtil.getShortStackTrace; import static org.keycloak.models.UserModel.EMAIL; import static org.keycloak.models.UserModel.EMAIL_VERIFIED; import static org.keycloak.models.UserModel.FIRST_NAME; import static org.keycloak.models.UserModel.LAST_NAME; import static org.keycloak.models.UserModel.USERNAME; import static org.keycloak.models.map.common.AbstractMapProviderFactory.MapProviderObjectType.USER_AFTER_REMOVE; import static org.keycloak.models.map.common.AbstractMapProviderFactory.MapProviderObjectType.USER_BEFORE_REMOVE; import static org.keycloak.models.map.storage.QueryParameters.Order.ASCENDING; import static org.keycloak.models.map.storage.QueryParameters.withCriteria; import static org.keycloak.models.map.storage.criteria.DefaultModelCriteria.criteria; import static org.keycloak.models.map.user.MapUserProviderFactory.REALM_ATTR_USERNAME_CASE_SENSITIVE; import static org.keycloak.models.map.user.MapUserProviderFactory.REALM_ATTR_USERNAME_CASE_SENSITIVE_DEFAULT; public class MapUserProvider implements UserProvider.Streams { private static final Logger LOG = Logger.getLogger(MapUserProvider.class); private final KeycloakSession session; final MapKeycloakTransaction<MapUserEntity, UserModel> tx; public MapUserProvider(KeycloakSession session, MapStorage<MapUserEntity, UserModel> store) { this.session = session; this.tx = store.createTransaction(session); session.getTransactionManager().enlist(tx); } private Boolean getUsernameCaseSensitiveAttribute(RealmModel realm) { return realm.getAttribute(REALM_ATTR_USERNAME_CASE_SENSITIVE, REALM_ATTR_USERNAME_CASE_SENSITIVE_DEFAULT); } private Function<MapUserEntity, UserModel> entityToAdapterFunc(RealmModel realm) { // Clone entity before returning back, to avoid giving away a reference to the live object to the caller return origEntity -> new MapUserAdapter(session, realm, origEntity) { @Override public boolean checkEmailUniqueness(RealmModel realm, String email) { return getUserByEmail(realm, email) != null; } @Override public boolean checkUsernameUniqueness(RealmModel realm, String username) { return getUserByUsername(realm, username) != null; } @Override public SubjectCredentialManager credentialManager() { return new MapUserCredentialManager(session, realm, this, entity); } }; } private Predicate<MapUserEntity> entityRealmFilter(RealmModel realm) { if (realm == null || realm.getId() == null) { return c -> false; } String realmId = realm.getId(); return entity -> entity.getRealmId() == null || Objects.equals(realmId, entity.getRealmId()); } private ModelException userDoesntExistException() { return new ModelException("Specified user doesn't exist."); } private Optional<MapUserEntity> getEntityById(RealmModel realm, String id) { try { MapUserEntity mapUserEntity = tx.read(id); if (mapUserEntity != null && entityRealmFilter(realm).test(mapUserEntity)) { return Optional.of(mapUserEntity); } return Optional.empty(); } catch (IllegalArgumentException ex) { return Optional.empty(); } } private MapUserEntity getEntityByIdOrThrow(RealmModel realm, String id) { return getEntityById(realm, id) .orElseThrow(this::userDoesntExistException); } @Override public void addFederatedIdentity(RealmModel realm, UserModel user, FederatedIdentityModel socialLink) { if (user == null || user.getId() == null) { return; } LOG.tracef("addFederatedIdentity(%s, %s, %s)%s", realm, user.getId(), socialLink.getIdentityProvider(), getShortStackTrace()); getEntityById(realm, user.getId()) .ifPresent(userEntity -> userEntity.addFederatedIdentity(MapUserFederatedIdentityEntity.fromModel(socialLink))); } @Override public boolean removeFederatedIdentity(RealmModel realm, UserModel user, String socialProvider) { LOG.tracef("removeFederatedIdentity(%s, %s, %s)%s", realm, user.getId(), socialProvider, getShortStackTrace()); Optional<MapUserEntity> entityById = getEntityById(realm, user.getId()); if (!entityById.isPresent()) return false; Boolean result = entityById.get().removeFederatedIdentity(socialProvider); return result == null ? true : result; // TODO: make removeFederatedIdentity return Boolean so the caller can correctly handle "I don't know" null answer } @Override public void preRemove(RealmModel realm, IdentityProviderModel provider) { String socialProvider = provider.getAlias(); LOG.tracef("preRemove[RealmModel realm, IdentityProviderModel provider](%s, %s)%s", realm, socialProvider, getShortStackTrace()); DefaultModelCriteria<UserModel> mcb = criteria(); mcb = mcb.compare(SearchableFields.REALM_ID, Operator.EQ, realm.getId()) .compare(SearchableFields.IDP_AND_USER, Operator.EQ, socialProvider); tx.read(withCriteria(mcb)) .forEach(userEntity -> userEntity.removeFederatedIdentity(socialProvider)); } @Override public void updateFederatedIdentity(RealmModel realm, UserModel federatedUser, FederatedIdentityModel federatedIdentityModel) { LOG.tracef("updateFederatedIdentity(%s, %s, %s)%s", realm, federatedUser.getId(), federatedIdentityModel.getIdentityProvider(), getShortStackTrace()); getEntityById(realm, federatedUser.getId()) .flatMap(u -> u.getFederatedIdentity(federatedIdentityModel.getIdentityProvider())) .ifPresent(fi -> { fi.setUserId(federatedIdentityModel.getUserId()); fi.setUserName(federatedIdentityModel.getUserName()); fi.setToken(federatedIdentityModel.getToken()); }); } @Override public Stream<FederatedIdentityModel> getFederatedIdentitiesStream(RealmModel realm, UserModel user) { LOG.tracef("getFederatedIdentitiesStream(%s, %s)%s", realm, user.getId(), getShortStackTrace()); return getEntityById(realm, user.getId()) .map(MapUserEntity::getFederatedIdentities) .map(Collection::stream) .orElseGet(Stream::empty) .map(MapUserFederatedIdentityEntity::toModel); } @Override public FederatedIdentityModel getFederatedIdentity(RealmModel realm, UserModel user, String socialProvider) { LOG.tracef("getFederatedIdentity(%s, %s, %s)%s", realm, user.getId(), socialProvider, getShortStackTrace()); return getEntityById(realm, user.getId()) .flatMap(userEntity -> userEntity.getFederatedIdentity(socialProvider)) .map(MapUserFederatedIdentityEntity::toModel) .orElse(null); } @Override public UserModel getUserByFederatedIdentity(RealmModel realm, FederatedIdentityModel socialLink) { LOG.tracef("getUserByFederatedIdentity(%s, %s)%s", realm, socialLink, getShortStackTrace()); DefaultModelCriteria<UserModel> mcb = criteria(); mcb = mcb.compare(SearchableFields.REALM_ID, Operator.EQ, realm.getId()) .compare(SearchableFields.IDP_AND_USER, Operator.EQ, socialLink.getIdentityProvider(), socialLink.getUserId()); return tx.read(withCriteria(mcb)) .collect(Collectors.collectingAndThen( Collectors.toList(), list -> { if (list.isEmpty()) { return null; } else if (list.size() != 1) { throw new IllegalStateException("More results found for identityProvider=" + socialLink.getIdentityProvider() + ", userId=" + socialLink.getUserId() + ", results=" + list); } return entityToAdapterFunc(realm).apply(list.get(0)); })); } @Override public void addConsent(RealmModel realm, String userId, UserConsentModel consent) { LOG.tracef("addConsent(%s, %s, %s)%s", realm, userId, consent, getShortStackTrace()); getEntityByIdOrThrow(realm, userId) .addUserConsent(MapUserConsentEntity.fromModel(consent)); } @Override public UserConsentModel getConsentByClient(RealmModel realm, String userId, String clientInternalId) { LOG.tracef("getConsentByClient(%s, %s, %s)%s", realm, userId, clientInternalId, getShortStackTrace()); return getEntityById(realm, userId) .flatMap(userEntity -> userEntity.getUserConsent(clientInternalId)) .map(consent -> MapUserConsentEntity.toModel(realm, consent)) .orElse(null); } @Override public Stream<UserConsentModel> getConsentsStream(RealmModel realm, String userId) { LOG.tracef("getConsentByClientStream(%s, %s)%s", realm, userId, getShortStackTrace()); return getEntityById(realm, userId) .map(MapUserEntity::getUserConsents) .map(Collection::stream) .orElseGet(Stream::empty) .map(consent -> MapUserConsentEntity.toModel(realm, consent)); } @Override public void updateConsent(RealmModel realm, String userId, UserConsentModel consent) { LOG.tracef("updateConsent(%s, %s, %s)%s", realm, userId, consent, getShortStackTrace()); MapUserEntity user = getEntityByIdOrThrow(realm, userId); MapUserConsentEntity userConsentEntity = user.getUserConsent(consent.getClient().getId()) .orElseThrow(() -> new ModelException("Consent not found for client [" + consent.getClient().getId() + "] and user [" + userId + "]")); userConsentEntity.setGrantedClientScopesIds( consent.getGrantedClientScopes().stream() .map(ClientScopeModel::getId) .collect(Collectors.toSet()) ); userConsentEntity.setLastUpdatedDate(Time.currentTimeMillis()); } @Override public boolean revokeConsentForClient(RealmModel realm, String userId, String clientInternalId) { LOG.tracef("revokeConsentForClient(%s, %s, %s)%s", realm, userId, clientInternalId, getShortStackTrace()); Optional<MapUserEntity> entityById = getEntityById(realm, userId); if (!entityById.isPresent()) return false; Boolean result = entityById.get().removeUserConsent(clientInternalId); return result == null ? true : result; // TODO: make revokeConsentForClient return Boolean so the caller can correctly handle "I don't know" null answer } @Override public void setNotBeforeForUser(RealmModel realm, UserModel user, int notBefore) { LOG.tracef("setNotBeforeForUser(%s, %s, %d)%s", realm, user.getId(), notBefore, getShortStackTrace()); getEntityByIdOrThrow(realm, user.getId()).setNotBefore(TimeAdapter.fromIntegerWithTimeInSecondsToLongWithTimeAsInSeconds(notBefore)); } @Override public int getNotBeforeOfUser(RealmModel realm, UserModel user) { LOG.tracef("getNotBeforeOfUser(%s, %s)%s", realm, user.getId(), getShortStackTrace()); Long notBefore = getEntityById(realm, user.getId()) .orElseThrow(this::userDoesntExistException) .getNotBefore(); return notBefore == null ? 0 : TimeAdapter.fromLongWithTimeInSecondsToIntegerWithTimeInSeconds(notBefore); } @Override public UserModel getServiceAccount(ClientModel client) { LOG.tracef("getServiceAccount(%s)%s", client.getId(), getShortStackTrace()); DefaultModelCriteria<UserModel> mcb = criteria(); mcb = mcb.compare(SearchableFields.REALM_ID, Operator.EQ, client.getRealm().getId()) .compare(SearchableFields.SERVICE_ACCOUNT_CLIENT, Operator.EQ, client.getId()); return tx.read(withCriteria(mcb)) .collect(Collectors.collectingAndThen( Collectors.toList(), list -> { if (list.isEmpty()) { return null; } else if (list.size() != 1) { throw new IllegalStateException("More service account linked users found for client=" + client.getClientId() + ", results=" + list); } return entityToAdapterFunc(client.getRealm()).apply(list.get(0)); } )); } @Override public UserModel addUser(RealmModel realm, String id, String username, boolean addDefaultRoles, boolean addDefaultRequiredActions) { LOG.tracef("addUser(%s, %s, %s, %s, %s)%s", realm, id, username, addDefaultRoles, addDefaultRequiredActions, getShortStackTrace()); DefaultModelCriteria<UserModel> mcb = criteria(); mcb = mcb.compare(SearchableFields.REALM_ID, Operator.EQ, realm.getId()) .compare(getUsernameCaseSensitiveAttribute(realm) ? SearchableFields.USERNAME : SearchableFields.USERNAME_CASE_INSENSITIVE, Operator.EQ, username); if (tx.getCount(withCriteria(mcb)) > 0) { throw new ModelDuplicateException("User with username '" + username + "' in realm " + realm.getName() + " already exists" ); } if (id != null && tx.read(id) != null) { throw new ModelDuplicateException("User exists: " + id); } MapUserEntity entity = new MapUserEntityImpl(); entity.setId(id); entity.setRealmId(realm.getId()); entity.setEmailConstraint(KeycloakModelUtils.generateId()); entity.setUsername(username); entity.setCreatedTimestamp(Time.currentTimeMillis()); entity = tx.create(entity); final UserModel userModel = entityToAdapterFunc(realm).apply(entity); if (addDefaultRoles) { userModel.grantRole(realm.getDefaultRole()); // No need to check if user has group as it's new user realm.getDefaultGroupsStream().forEach(userModel::joinGroup); } if (addDefaultRequiredActions){ realm.getRequiredActionProvidersStream() .filter(RequiredActionProviderModel::isEnabled) .filter(RequiredActionProviderModel::isDefaultAction) .map(RequiredActionProviderModel::getAlias) .forEach(userModel::addRequiredAction); } return userModel; } @Override public void preRemove(RealmModel realm) { LOG.tracef("preRemove[RealmModel](%s)%s", realm, getShortStackTrace()); DefaultModelCriteria<UserModel> mcb = criteria(); mcb = mcb.compare(SearchableFields.REALM_ID, Operator.EQ, realm.getId()); tx.delete(withCriteria(mcb)); } @Override public void removeImportedUsers(RealmModel realm, String storageProviderId) { LOG.tracef("removeImportedUsers(%s, %s)%s", realm, storageProviderId, getShortStackTrace()); DefaultModelCriteria<UserModel> mcb = criteria(); mcb = mcb.compare(SearchableFields.REALM_ID, Operator.EQ, realm.getId()) .compare(SearchableFields.FEDERATION_LINK, Operator.EQ, storageProviderId); tx.delete(withCriteria(mcb)); } @Override public void unlinkUsers(RealmModel realm, String storageProviderId) { LOG.tracef("unlinkUsers(%s, %s)%s", realm, storageProviderId, getShortStackTrace()); DefaultModelCriteria<UserModel> mcb = criteria(); mcb = mcb.compare(SearchableFields.REALM_ID, Operator.EQ, realm.getId()) .compare(SearchableFields.FEDERATION_LINK, Operator.EQ, storageProviderId); try (Stream<MapUserEntity> s = tx.read(withCriteria(mcb))) { s.forEach(userEntity -> userEntity.setFederationLink(null)); } } @Override public void preRemove(RealmModel realm, RoleModel role) { String roleId = role.getId(); LOG.tracef("preRemove[RoleModel](%s, %s)%s", realm, roleId, getShortStackTrace()); DefaultModelCriteria<UserModel> mcb = criteria(); mcb = mcb.compare(SearchableFields.REALM_ID, Operator.EQ, realm.getId()) .compare(SearchableFields.ASSIGNED_ROLE, Operator.EQ, roleId); try (Stream<MapUserEntity> s = tx.read(withCriteria(mcb))) { s.forEach(userEntity -> userEntity.removeRolesMembership(roleId)); } } @Override public void preRemove(RealmModel realm, GroupModel group) { String groupId = group.getId(); LOG.tracef("preRemove[GroupModel](%s, %s)%s", realm, groupId, getShortStackTrace()); DefaultModelCriteria<UserModel> mcb = criteria(); mcb = mcb.compare(SearchableFields.REALM_ID, Operator.EQ, realm.getId()) .compare(SearchableFields.ASSIGNED_GROUP, Operator.EQ, groupId); try (Stream<MapUserEntity> s = tx.read(withCriteria(mcb))) { s.forEach(userEntity -> userEntity.removeGroupsMembership(groupId)); } } @Override public void preRemove(RealmModel realm, ClientModel client) { String clientId = client.getId(); LOG.tracef("preRemove[ClientModel](%s, %s)%s", realm, clientId, getShortStackTrace()); DefaultModelCriteria<UserModel> mcb = criteria(); mcb = mcb.compare(SearchableFields.REALM_ID, Operator.EQ, realm.getId()) .compare(SearchableFields.CONSENT_FOR_CLIENT, Operator.EQ, clientId); try (Stream<MapUserEntity> s = tx.read(withCriteria(mcb))) { s.forEach(userEntity -> userEntity.removeUserConsent(clientId)); } } @Override public void preRemove(ProtocolMapperModel protocolMapper) { // No-op } @Override public void preRemove(ClientScopeModel clientScope) { String clientScopeId = clientScope.getId(); LOG.tracef("preRemove[ClientScopeModel](%s)%s", clientScopeId, getShortStackTrace()); DefaultModelCriteria<UserModel> mcb = criteria(); mcb = mcb.compare(SearchableFields.REALM_ID, Operator.EQ, clientScope.getRealm().getId()) .compare(SearchableFields.CONSENT_WITH_CLIENT_SCOPE, Operator.EQ, clientScopeId); try (Stream<MapUserEntity> s = tx.read(withCriteria(mcb))) { s.map(MapUserEntity::getUserConsents) .filter(Objects::nonNull) .flatMap(Collection::stream) .forEach(consent -> consent.removeGrantedClientScopesId(clientScopeId)); } } @Override public void preRemove(RealmModel realm, ComponentModel component) { } @Override public void grantToAllUsers(RealmModel realm, RoleModel role) { String roleId = role.getId(); LOG.tracef("grantToAllUsers(%s, %s)%s", realm, roleId, getShortStackTrace()); DefaultModelCriteria<UserModel> mcb = criteria(); mcb = mcb.compare(SearchableFields.REALM_ID, Operator.EQ, realm.getId()); try (Stream<MapUserEntity> s = tx.read(withCriteria(mcb))) { s.forEach(entity -> entity.addRolesMembership(roleId)); } } @Override public UserModel getUserById(RealmModel realm, String id) { LOG.tracef("getUserById(%s, %s)%s", realm, id, getShortStackTrace()); return getEntityById(realm, id).map(entityToAdapterFunc(realm)).orElse(null); } @Override public UserModel getUserByUsername(RealmModel realm, String username) { if (username == null) return null; LOG.tracef("getUserByUsername(%s, %s)%s", realm, username, getShortStackTrace()); DefaultModelCriteria<UserModel> mcb = criteria(); mcb = mcb.compare(SearchableFields.REALM_ID, Operator.EQ, realm.getId()) .compare(getUsernameCaseSensitiveAttribute(realm) ? SearchableFields.USERNAME : SearchableFields.USERNAME_CASE_INSENSITIVE, Operator.EQ, username); // there is orderBy used to always return the same user in case multiple users are returned from the store try (Stream<MapUserEntity> s = tx.read(withCriteria(mcb).orderBy(SearchableFields.USERNAME, ASCENDING))) { List<MapUserEntity> users = s.collect(Collectors.toList()); if (users.isEmpty()) return null; if (users.size() != 1) { throw new ModelDuplicateException(String.format("There are colliding usernames for users with usernames and ids: %s", users.stream().collect(Collectors.toMap(MapUserEntity::getUsername, MapUserEntity::getId)))); } return entityToAdapterFunc(realm).apply(users.get(0)); } } @Override public UserModel getUserByEmail(RealmModel realm, String email) { LOG.tracef("getUserByEmail(%s, %s)%s", realm, email, getShortStackTrace()); DefaultModelCriteria<UserModel> mcb = criteria(); mcb = mcb.compare(SearchableFields.REALM_ID, Operator.EQ, realm.getId()) .compare(SearchableFields.EMAIL, Operator.EQ, email); List<MapUserEntity> usersWithEmail = tx.read(withCriteria(mcb)).collect(Collectors.toList()); if (usersWithEmail.isEmpty()) return null; if (usersWithEmail.size() > 1) { // Realm settings have been changed from allowing duplicate emails to not allowing them // but duplicates haven't been removed. throw new ModelDuplicateException("Multiple users with email '" + email + "' exist in Keycloak."); } MapUserEntity userEntity = usersWithEmail.get(0); if (!realm.isDuplicateEmailsAllowed()) { if (userEntity.getEmail() != null && !userEntity.getEmail().equals(userEntity.getEmailConstraint())) { // Realm settings have been changed from allowing duplicate emails to not allowing them. // We need to update the email constraint to reflect this change in the user entities. userEntity.setEmailConstraint(userEntity.getEmail()); } } return entityToAdapterFunc(realm).apply(userEntity); } @Override public int getUsersCount(RealmModel realm, boolean includeServiceAccount) { LOG.tracef("getUsersCount(%s, %s)%s", realm, includeServiceAccount, getShortStackTrace()); DefaultModelCriteria<UserModel> mcb = criteria(); mcb = mcb.compare(SearchableFields.REALM_ID, Operator.EQ, realm.getId()); if (! includeServiceAccount) { mcb = mcb.compare(SearchableFields.SERVICE_ACCOUNT_CLIENT, Operator.NOT_EXISTS); } return (int) tx.getCount(withCriteria(mcb)); } @Override public Stream<UserModel> searchForUserStream(RealmModel realm, String search, Integer firstResult, Integer maxResults) { LOG.tracef("searchForUserStream(%s, %s, %d, %d)%s", realm, search, firstResult, maxResults, getShortStackTrace()); Map<String, String> attributes = new HashMap<>(); attributes.put(UserModel.SEARCH, search); attributes.put(UserModel.INCLUDE_SERVICE_ACCOUNT, Boolean.FALSE.toString()); return searchForUserStream(realm, attributes, firstResult, maxResults); } @Override public Stream<UserModel> searchForUserStream(RealmModel realm, Map<String, String> attributes, Integer firstResult, Integer maxResults) { LOG.tracef("searchForUserStream(%s, %s, %d, %d)%s", realm, attributes, firstResult, maxResults, getShortStackTrace()); final DefaultModelCriteria<UserModel> mcb = criteria(); DefaultModelCriteria<UserModel> criteria = mcb.compare(SearchableFields.REALM_ID, Operator.EQ, realm.getId()); final boolean exactSearch = Boolean.parseBoolean(attributes.getOrDefault(UserModel.EXACT, Boolean.FALSE.toString())); for (Map.Entry<String, String> entry : attributes.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); if (value == null) { continue; } value = value.trim(); final String searchedString = exactSearch ? value : ("%" + value + "%"); switch (key) { case UserModel.SEARCH: DefaultModelCriteria<UserModel> searchCriteria = null; for (String stringToSearch : value.split("\\s+")) { if (searchCriteria == null) { searchCriteria = addSearchToModelCriteria(realm, stringToSearch, mcb); } else { searchCriteria = mcb.and(searchCriteria, addSearchToModelCriteria(realm, stringToSearch, mcb)); } } criteria = mcb.and(criteria, searchCriteria); break; case USERNAME: criteria = getUsernameCaseSensitiveAttribute(realm) ? criteria.compare(SearchableFields.USERNAME, Operator.LIKE, searchedString) : criteria.compare(SearchableFields.USERNAME_CASE_INSENSITIVE, Operator.ILIKE, searchedString); break; case FIRST_NAME: criteria = criteria.compare(SearchableFields.FIRST_NAME, Operator.ILIKE, searchedString); break; case LAST_NAME: criteria = criteria.compare(SearchableFields.LAST_NAME, Operator.ILIKE, searchedString); break; case EMAIL: criteria = criteria.compare(SearchableFields.EMAIL, Operator.ILIKE, searchedString); break; case EMAIL_VERIFIED: { boolean booleanValue = Boolean.parseBoolean(value); criteria = criteria.compare(SearchableFields.EMAIL_VERIFIED, Operator.EQ, booleanValue); break; } case UserModel.ENABLED: { boolean booleanValue = Boolean.parseBoolean(value); criteria = criteria.compare(SearchableFields.ENABLED, Operator.EQ, booleanValue); break; } case UserModel.IDP_ALIAS: { if (!attributes.containsKey(UserModel.IDP_USER_ID)) { criteria = criteria.compare(SearchableFields.IDP_AND_USER, Operator.EQ, value); } break; } case UserModel.IDP_USER_ID: { criteria = criteria.compare(SearchableFields.IDP_AND_USER, Operator.EQ, attributes.get(UserModel.IDP_ALIAS), value); break; } case UserModel.INCLUDE_SERVICE_ACCOUNT: { if (!attributes.containsKey(UserModel.INCLUDE_SERVICE_ACCOUNT) || !Boolean.parseBoolean(attributes.get(UserModel.INCLUDE_SERVICE_ACCOUNT))) { criteria = criteria.compare(SearchableFields.SERVICE_ACCOUNT_CLIENT, Operator.NOT_EXISTS); } break; } case UserModel.EXACT: break; default: criteria = criteria.compare(SearchableFields.ATTRIBUTE, Operator.EQ, key, value); break; } } // Only return those results that the current user is authorized to view, // i.e. there is an intersection of groups with view permission of the current // user (passed in via UserModel.GROUPS attribute), the groups for the returned // users, and the respective group resource available from the authorization provider @SuppressWarnings("unchecked") Set<String> userGroups = (Set<String>) session.getAttribute(UserModel.GROUPS); if (userGroups != null) { if (userGroups.isEmpty()) { return Stream.empty(); } final ResourceStore resourceStore = session.getProvider(AuthorizationProvider.class).getStoreFactory().getResourceStore(); HashSet<String> authorizedGroups = new HashSet<>(userGroups); authorizedGroups.removeIf(id -> { Map<Resource.FilterOption, String[]> values = new EnumMap<>(Resource.FilterOption.class); values.put(Resource.FilterOption.EXACT_NAME, new String[] {"group.resource." + id}); return resourceStore.find(realm, null, values, 0, 1).isEmpty(); }); criteria = criteria.compare(SearchableFields.ASSIGNED_GROUP, Operator.IN, authorizedGroups); } return tx.read(withCriteria(criteria).pagination(firstResult, maxResults, SearchableFields.USERNAME)) .map(entityToAdapterFunc(realm)) .filter(Objects::nonNull); } @Override public Stream<UserModel> getGroupMembersStream(RealmModel realm, GroupModel group, Integer firstResult, Integer maxResults) { LOG.tracef("getGroupMembersStream(%s, %s, %d, %d)%s", realm, group.getId(), firstResult, maxResults, getShortStackTrace()); DefaultModelCriteria<UserModel> mcb = criteria(); mcb = mcb.compare(SearchableFields.REALM_ID, Operator.EQ, realm.getId()) .compare(SearchableFields.ASSIGNED_GROUP, Operator.EQ, group.getId()); return tx.read(withCriteria(mcb).pagination(firstResult, maxResults, SearchableFields.USERNAME)) .map(entityToAdapterFunc(realm)); } @Override public Stream<UserModel> searchForUserByUserAttributeStream(RealmModel realm, String attrName, String attrValue) { LOG.tracef("searchForUserByUserAttributeStream(%s, %s, %s)%s", realm, attrName, attrValue, getShortStackTrace()); DefaultModelCriteria<UserModel> mcb = criteria(); mcb = mcb.compare(SearchableFields.REALM_ID, Operator.EQ, realm.getId()) .compare(SearchableFields.ATTRIBUTE, Operator.EQ, attrName, attrValue); return tx.read(withCriteria(mcb).orderBy(SearchableFields.USERNAME, ASCENDING)) .map(entityToAdapterFunc(realm)); } @Override public UserModel addUser(RealmModel realm, String username) { return addUser(realm, null, username, true, true); } @Override public boolean removeUser(RealmModel realm, UserModel user) { String userId = user.getId(); Optional<MapUserEntity> userById = getEntityById(realm, userId); if (userById.isPresent()) { session.invalidate(USER_BEFORE_REMOVE, realm, user); tx.delete(userId); session.invalidate(USER_AFTER_REMOVE, realm, user); return true; } return false; } @Override public Stream<UserModel> getRoleMembersStream(RealmModel realm, RoleModel role, Integer firstResult, Integer maxResults) { LOG.tracef("getRoleMembersStream(%s, %s, %d, %d)%s", realm, role, firstResult, maxResults, getShortStackTrace()); DefaultModelCriteria<UserModel> mcb = criteria(); mcb = mcb.compare(SearchableFields.REALM_ID, Operator.EQ, realm.getId()) .compare(SearchableFields.ASSIGNED_ROLE, Operator.EQ, role.getId()); return tx.read(withCriteria(mcb).pagination(firstResult, maxResults, SearchableFields.USERNAME)) .map(entityToAdapterFunc(realm)); } @Override public void close() { } public static <T> Stream<T> getCredentialProviders(KeycloakSession session, Class<T> type) { return session.getKeycloakSessionFactory().getProviderFactoriesStream(CredentialProvider.class) .filter(f -> Types.supports(type, f, CredentialProviderFactory.class)) .map(f -> (T) session.getProvider(CredentialProvider.class, f.getId())); } @Override public CredentialValidationOutput getUserByCredential(RealmModel realm, CredentialInput input) { // TODO: future implementations would narrow down the stream to those provider enabled for the specific realm Stream<CredentialAuthentication> credentialAuthenticationStream = getCredentialProviders(session, CredentialAuthentication.class); CredentialValidationOutput r = credentialAuthenticationStream .filter(credentialAuthentication -> credentialAuthentication.supportsCredentialAuthenticationFor(input.getType())) .map(credentialAuthentication -> credentialAuthentication.authenticate(realm, input)) .filter(Objects::nonNull) .findFirst().orElse(null); if (r == null && tx instanceof MapKeycloakTransactionWithAuth) { MapCredentialValidationOutput<MapUserEntity> result = ((MapKeycloakTransactionWithAuth<MapUserEntity, UserModel>) tx).authenticate(realm, input); if (result != null) { UserModel user = null; if (result.getAuthenticatedUser() != null) { user = entityToAdapterFunc(realm).apply(result.getAuthenticatedUser()); } r = new CredentialValidationOutput(user, result.getAuthStatus(), result.getState()); } } return r; } private DefaultModelCriteria<UserModel> addSearchToModelCriteria(RealmModel realm, String value, DefaultModelCriteria<UserModel> mcb) { if (value.length() >= 2 && value.charAt(0) == '"' && value.charAt(value.length() - 1) == '"') { // exact search value = value.substring(1, value.length() - 1); } else { if (value.length() >= 2 && value.charAt(0) == '*' && value.charAt(value.length() - 1) == '*') { // infix search value = "%" + value.substring(1, value.length() - 1) + "%"; } else { // default to prefix search if (value.length() > 0 && value.charAt(value.length() - 1) == '*') { value = value.substring(0, value.length() - 1); } value += "%"; } } return mcb.or( getUsernameCaseSensitiveAttribute(realm) ? mcb.compare(SearchableFields.USERNAME, Operator.LIKE, value) : mcb.compare(SearchableFields.USERNAME_CASE_INSENSITIVE, Operator.ILIKE, value), mcb.compare(SearchableFields.EMAIL, Operator.ILIKE, value), mcb.compare(SearchableFields.FIRST_NAME, Operator.ILIKE, value), mcb.compare(SearchableFields.LAST_NAME, Operator.ILIKE, value)); } }
model/map/src/main/java/org/keycloak/models/map/user/MapUserProvider.java
/* * Copyright 2022 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * 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.keycloak.models.map.user; import org.jboss.logging.Logger; import org.keycloak.authorization.AuthorizationProvider; import org.keycloak.authorization.model.Resource; import org.keycloak.authorization.store.ResourceStore; import org.keycloak.common.util.Time; import org.keycloak.common.util.reflections.Types; import org.keycloak.component.ComponentModel; import org.keycloak.credential.CredentialAuthentication; import org.keycloak.credential.CredentialInput; import org.keycloak.credential.CredentialProvider; import org.keycloak.credential.CredentialProviderFactory; import org.keycloak.models.ClientModel; import org.keycloak.models.ClientScopeModel; import org.keycloak.models.CredentialValidationOutput; import org.keycloak.models.FederatedIdentityModel; import org.keycloak.models.GroupModel; import org.keycloak.models.IdentityProviderModel; import org.keycloak.models.KeycloakSession; import org.keycloak.models.ModelDuplicateException; import org.keycloak.models.ModelException; import org.keycloak.models.ProtocolMapperModel; import org.keycloak.models.RealmModel; import org.keycloak.models.RequiredActionProviderModel; import org.keycloak.models.RoleModel; import org.keycloak.models.SubjectCredentialManager; import org.keycloak.models.UserConsentModel; import org.keycloak.models.UserModel; import org.keycloak.models.UserModel.SearchableFields; import org.keycloak.models.UserProvider; import org.keycloak.models.map.common.TimeAdapter; import org.keycloak.models.map.credential.MapUserCredentialManager; import org.keycloak.models.map.storage.MapKeycloakTransactionWithAuth; import org.keycloak.models.map.storage.MapKeycloakTransaction; import org.keycloak.models.map.storage.MapStorage; import org.keycloak.models.map.storage.ModelCriteriaBuilder.Operator; import org.keycloak.models.map.storage.criteria.DefaultModelCriteria; import org.keycloak.models.utils.KeycloakModelUtils; import java.util.Collection; import java.util.EnumMap; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.keycloak.common.util.StackUtil.getShortStackTrace; import static org.keycloak.models.UserModel.EMAIL; import static org.keycloak.models.UserModel.EMAIL_VERIFIED; import static org.keycloak.models.UserModel.FIRST_NAME; import static org.keycloak.models.UserModel.LAST_NAME; import static org.keycloak.models.UserModel.USERNAME; import static org.keycloak.models.map.common.AbstractMapProviderFactory.MapProviderObjectType.USER_AFTER_REMOVE; import static org.keycloak.models.map.common.AbstractMapProviderFactory.MapProviderObjectType.USER_BEFORE_REMOVE; import static org.keycloak.models.map.storage.QueryParameters.Order.ASCENDING; import static org.keycloak.models.map.storage.QueryParameters.withCriteria; import static org.keycloak.models.map.storage.criteria.DefaultModelCriteria.criteria; import static org.keycloak.models.map.user.MapUserProviderFactory.REALM_ATTR_USERNAME_CASE_SENSITIVE; import static org.keycloak.models.map.user.MapUserProviderFactory.REALM_ATTR_USERNAME_CASE_SENSITIVE_DEFAULT; public class MapUserProvider implements UserProvider.Streams { private static final Logger LOG = Logger.getLogger(MapUserProvider.class); private final KeycloakSession session; final MapKeycloakTransaction<MapUserEntity, UserModel> tx; public MapUserProvider(KeycloakSession session, MapStorage<MapUserEntity, UserModel> store) { this.session = session; this.tx = store.createTransaction(session); session.getTransactionManager().enlist(tx); } private Boolean getUsernameCaseSensitiveAttribute(RealmModel realm) { return realm.getAttribute(REALM_ATTR_USERNAME_CASE_SENSITIVE, REALM_ATTR_USERNAME_CASE_SENSITIVE_DEFAULT); } private Function<MapUserEntity, UserModel> entityToAdapterFunc(RealmModel realm) { // Clone entity before returning back, to avoid giving away a reference to the live object to the caller return origEntity -> new MapUserAdapter(session, realm, origEntity) { @Override public boolean checkEmailUniqueness(RealmModel realm, String email) { return getUserByEmail(realm, email) != null; } @Override public boolean checkUsernameUniqueness(RealmModel realm, String username) { return getUserByUsername(realm, username) != null; } @Override public SubjectCredentialManager credentialManager() { return new MapUserCredentialManager(session, realm, this, entity); } }; } private Predicate<MapUserEntity> entityRealmFilter(RealmModel realm) { if (realm == null || realm.getId() == null) { return c -> false; } String realmId = realm.getId(); return entity -> entity.getRealmId() == null || Objects.equals(realmId, entity.getRealmId()); } private ModelException userDoesntExistException() { return new ModelException("Specified user doesn't exist."); } private Optional<MapUserEntity> getEntityById(RealmModel realm, String id) { try { MapUserEntity mapUserEntity = tx.read(id); if (mapUserEntity != null && entityRealmFilter(realm).test(mapUserEntity)) { return Optional.of(mapUserEntity); } return Optional.empty(); } catch (IllegalArgumentException ex) { return Optional.empty(); } } private MapUserEntity getEntityByIdOrThrow(RealmModel realm, String id) { return getEntityById(realm, id) .orElseThrow(this::userDoesntExistException); } @Override public void addFederatedIdentity(RealmModel realm, UserModel user, FederatedIdentityModel socialLink) { if (user == null || user.getId() == null) { return; } LOG.tracef("addFederatedIdentity(%s, %s, %s)%s", realm, user.getId(), socialLink.getIdentityProvider(), getShortStackTrace()); getEntityById(realm, user.getId()) .ifPresent(userEntity -> userEntity.addFederatedIdentity(MapUserFederatedIdentityEntity.fromModel(socialLink))); } @Override public boolean removeFederatedIdentity(RealmModel realm, UserModel user, String socialProvider) { LOG.tracef("removeFederatedIdentity(%s, %s, %s)%s", realm, user.getId(), socialProvider, getShortStackTrace()); Optional<MapUserEntity> entityById = getEntityById(realm, user.getId()); if (!entityById.isPresent()) return false; Boolean result = entityById.get().removeFederatedIdentity(socialProvider); return result == null ? true : result; // TODO: make removeFederatedIdentity return Boolean so the caller can correctly handle "I don't know" null answer } @Override public void preRemove(RealmModel realm, IdentityProviderModel provider) { String socialProvider = provider.getAlias(); LOG.tracef("preRemove[RealmModel realm, IdentityProviderModel provider](%s, %s)%s", realm, socialProvider, getShortStackTrace()); DefaultModelCriteria<UserModel> mcb = criteria(); mcb = mcb.compare(SearchableFields.REALM_ID, Operator.EQ, realm.getId()) .compare(SearchableFields.IDP_AND_USER, Operator.EQ, socialProvider); tx.read(withCriteria(mcb)) .forEach(userEntity -> userEntity.removeFederatedIdentity(socialProvider)); } @Override public void updateFederatedIdentity(RealmModel realm, UserModel federatedUser, FederatedIdentityModel federatedIdentityModel) { LOG.tracef("updateFederatedIdentity(%s, %s, %s)%s", realm, federatedUser.getId(), federatedIdentityModel.getIdentityProvider(), getShortStackTrace()); getEntityById(realm, federatedUser.getId()) .flatMap(u -> u.getFederatedIdentity(federatedIdentityModel.getIdentityProvider())) .ifPresent(fi -> { fi.setUserId(federatedIdentityModel.getUserId()); fi.setUserName(federatedIdentityModel.getUserName()); fi.setToken(federatedIdentityModel.getToken()); }); } @Override public Stream<FederatedIdentityModel> getFederatedIdentitiesStream(RealmModel realm, UserModel user) { LOG.tracef("getFederatedIdentitiesStream(%s, %s)%s", realm, user.getId(), getShortStackTrace()); return getEntityById(realm, user.getId()) .map(MapUserEntity::getFederatedIdentities) .map(Collection::stream) .orElseGet(Stream::empty) .map(MapUserFederatedIdentityEntity::toModel); } @Override public FederatedIdentityModel getFederatedIdentity(RealmModel realm, UserModel user, String socialProvider) { LOG.tracef("getFederatedIdentity(%s, %s, %s)%s", realm, user.getId(), socialProvider, getShortStackTrace()); return getEntityById(realm, user.getId()) .flatMap(userEntity -> userEntity.getFederatedIdentity(socialProvider)) .map(MapUserFederatedIdentityEntity::toModel) .orElse(null); } @Override public UserModel getUserByFederatedIdentity(RealmModel realm, FederatedIdentityModel socialLink) { LOG.tracef("getUserByFederatedIdentity(%s, %s)%s", realm, socialLink, getShortStackTrace()); DefaultModelCriteria<UserModel> mcb = criteria(); mcb = mcb.compare(SearchableFields.REALM_ID, Operator.EQ, realm.getId()) .compare(SearchableFields.IDP_AND_USER, Operator.EQ, socialLink.getIdentityProvider(), socialLink.getUserId()); return tx.read(withCriteria(mcb)) .collect(Collectors.collectingAndThen( Collectors.toList(), list -> { if (list.isEmpty()) { return null; } else if (list.size() != 1) { throw new IllegalStateException("More results found for identityProvider=" + socialLink.getIdentityProvider() + ", userId=" + socialLink.getUserId() + ", results=" + list); } return entityToAdapterFunc(realm).apply(list.get(0)); })); } @Override public void addConsent(RealmModel realm, String userId, UserConsentModel consent) { LOG.tracef("addConsent(%s, %s, %s)%s", realm, userId, consent, getShortStackTrace()); getEntityByIdOrThrow(realm, userId) .addUserConsent(MapUserConsentEntity.fromModel(consent)); } @Override public UserConsentModel getConsentByClient(RealmModel realm, String userId, String clientInternalId) { LOG.tracef("getConsentByClient(%s, %s, %s)%s", realm, userId, clientInternalId, getShortStackTrace()); return getEntityById(realm, userId) .flatMap(userEntity -> userEntity.getUserConsent(clientInternalId)) .map(consent -> MapUserConsentEntity.toModel(realm, consent)) .orElse(null); } @Override public Stream<UserConsentModel> getConsentsStream(RealmModel realm, String userId) { LOG.tracef("getConsentByClientStream(%s, %s)%s", realm, userId, getShortStackTrace()); return getEntityById(realm, userId) .map(MapUserEntity::getUserConsents) .map(Collection::stream) .orElseGet(Stream::empty) .map(consent -> MapUserConsentEntity.toModel(realm, consent)); } @Override public void updateConsent(RealmModel realm, String userId, UserConsentModel consent) { LOG.tracef("updateConsent(%s, %s, %s)%s", realm, userId, consent, getShortStackTrace()); MapUserEntity user = getEntityByIdOrThrow(realm, userId); MapUserConsentEntity userConsentEntity = user.getUserConsent(consent.getClient().getId()) .orElseThrow(() -> new ModelException("Consent not found for client [" + consent.getClient().getId() + "] and user [" + userId + "]")); userConsentEntity.setGrantedClientScopesIds( consent.getGrantedClientScopes().stream() .map(ClientScopeModel::getId) .collect(Collectors.toSet()) ); userConsentEntity.setLastUpdatedDate(Time.currentTimeMillis()); } @Override public boolean revokeConsentForClient(RealmModel realm, String userId, String clientInternalId) { LOG.tracef("revokeConsentForClient(%s, %s, %s)%s", realm, userId, clientInternalId, getShortStackTrace()); Optional<MapUserEntity> entityById = getEntityById(realm, userId); if (!entityById.isPresent()) return false; Boolean result = entityById.get().removeUserConsent(clientInternalId); return result == null ? true : result; // TODO: make revokeConsentForClient return Boolean so the caller can correctly handle "I don't know" null answer } @Override public void setNotBeforeForUser(RealmModel realm, UserModel user, int notBefore) { LOG.tracef("setNotBeforeForUser(%s, %s, %d)%s", realm, user.getId(), notBefore, getShortStackTrace()); getEntityByIdOrThrow(realm, user.getId()).setNotBefore(TimeAdapter.fromIntegerWithTimeInSecondsToLongWithTimeAsInSeconds(notBefore)); } @Override public int getNotBeforeOfUser(RealmModel realm, UserModel user) { LOG.tracef("getNotBeforeOfUser(%s, %s)%s", realm, user.getId(), getShortStackTrace()); Long notBefore = getEntityById(realm, user.getId()) .orElseThrow(this::userDoesntExistException) .getNotBefore(); return notBefore == null ? 0 : TimeAdapter.fromLongWithTimeInSecondsToIntegerWithTimeInSeconds(notBefore); } @Override public UserModel getServiceAccount(ClientModel client) { LOG.tracef("getServiceAccount(%s)%s", client.getId(), getShortStackTrace()); DefaultModelCriteria<UserModel> mcb = criteria(); mcb = mcb.compare(SearchableFields.REALM_ID, Operator.EQ, client.getRealm().getId()) .compare(SearchableFields.SERVICE_ACCOUNT_CLIENT, Operator.EQ, client.getId()); return tx.read(withCriteria(mcb)) .collect(Collectors.collectingAndThen( Collectors.toList(), list -> { if (list.isEmpty()) { return null; } else if (list.size() != 1) { throw new IllegalStateException("More service account linked users found for client=" + client.getClientId() + ", results=" + list); } return entityToAdapterFunc(client.getRealm()).apply(list.get(0)); } )); } @Override public UserModel addUser(RealmModel realm, String id, String username, boolean addDefaultRoles, boolean addDefaultRequiredActions) { LOG.tracef("addUser(%s, %s, %s, %s, %s)%s", realm, id, username, addDefaultRoles, addDefaultRequiredActions, getShortStackTrace()); DefaultModelCriteria<UserModel> mcb = criteria(); mcb = mcb.compare(SearchableFields.REALM_ID, Operator.EQ, realm.getId()) .compare(getUsernameCaseSensitiveAttribute(realm) ? SearchableFields.USERNAME : SearchableFields.USERNAME_CASE_INSENSITIVE, Operator.EQ, username); if (tx.getCount(withCriteria(mcb)) > 0) { throw new ModelDuplicateException("User with username '" + username + "' in realm " + realm.getName() + " already exists" ); } if (id != null && tx.read(id) != null) { throw new ModelDuplicateException("User exists: " + id); } MapUserEntity entity = new MapUserEntityImpl(); entity.setId(id); entity.setRealmId(realm.getId()); entity.setEmailConstraint(KeycloakModelUtils.generateId()); entity.setUsername(username); entity.setCreatedTimestamp(Time.currentTimeMillis()); entity = tx.create(entity); final UserModel userModel = entityToAdapterFunc(realm).apply(entity); if (addDefaultRoles) { userModel.grantRole(realm.getDefaultRole()); // No need to check if user has group as it's new user realm.getDefaultGroupsStream().forEach(userModel::joinGroup); } if (addDefaultRequiredActions){ realm.getRequiredActionProvidersStream() .filter(RequiredActionProviderModel::isEnabled) .filter(RequiredActionProviderModel::isDefaultAction) .map(RequiredActionProviderModel::getAlias) .forEach(userModel::addRequiredAction); } return userModel; } @Override public void preRemove(RealmModel realm) { LOG.tracef("preRemove[RealmModel](%s)%s", realm, getShortStackTrace()); DefaultModelCriteria<UserModel> mcb = criteria(); mcb = mcb.compare(SearchableFields.REALM_ID, Operator.EQ, realm.getId()); tx.delete(withCriteria(mcb)); } @Override public void removeImportedUsers(RealmModel realm, String storageProviderId) { LOG.tracef("removeImportedUsers(%s, %s)%s", realm, storageProviderId, getShortStackTrace()); DefaultModelCriteria<UserModel> mcb = criteria(); mcb = mcb.compare(SearchableFields.REALM_ID, Operator.EQ, realm.getId()) .compare(SearchableFields.FEDERATION_LINK, Operator.EQ, storageProviderId); tx.delete(withCriteria(mcb)); } @Override public void unlinkUsers(RealmModel realm, String storageProviderId) { LOG.tracef("unlinkUsers(%s, %s)%s", realm, storageProviderId, getShortStackTrace()); DefaultModelCriteria<UserModel> mcb = criteria(); mcb = mcb.compare(SearchableFields.REALM_ID, Operator.EQ, realm.getId()) .compare(SearchableFields.FEDERATION_LINK, Operator.EQ, storageProviderId); try (Stream<MapUserEntity> s = tx.read(withCriteria(mcb))) { s.forEach(userEntity -> userEntity.setFederationLink(null)); } } @Override public void preRemove(RealmModel realm, RoleModel role) { String roleId = role.getId(); LOG.tracef("preRemove[RoleModel](%s, %s)%s", realm, roleId, getShortStackTrace()); DefaultModelCriteria<UserModel> mcb = criteria(); mcb = mcb.compare(SearchableFields.REALM_ID, Operator.EQ, realm.getId()) .compare(SearchableFields.ASSIGNED_ROLE, Operator.EQ, roleId); try (Stream<MapUserEntity> s = tx.read(withCriteria(mcb))) { s.forEach(userEntity -> userEntity.removeRolesMembership(roleId)); } } @Override public void preRemove(RealmModel realm, GroupModel group) { String groupId = group.getId(); LOG.tracef("preRemove[GroupModel](%s, %s)%s", realm, groupId, getShortStackTrace()); DefaultModelCriteria<UserModel> mcb = criteria(); mcb = mcb.compare(SearchableFields.REALM_ID, Operator.EQ, realm.getId()) .compare(SearchableFields.ASSIGNED_GROUP, Operator.EQ, groupId); try (Stream<MapUserEntity> s = tx.read(withCriteria(mcb))) { s.forEach(userEntity -> userEntity.removeGroupsMembership(groupId)); } } @Override public void preRemove(RealmModel realm, ClientModel client) { String clientId = client.getId(); LOG.tracef("preRemove[ClientModel](%s, %s)%s", realm, clientId, getShortStackTrace()); DefaultModelCriteria<UserModel> mcb = criteria(); mcb = mcb.compare(SearchableFields.REALM_ID, Operator.EQ, realm.getId()) .compare(SearchableFields.CONSENT_FOR_CLIENT, Operator.EQ, clientId); try (Stream<MapUserEntity> s = tx.read(withCriteria(mcb))) { s.forEach(userEntity -> userEntity.removeUserConsent(clientId)); } } @Override public void preRemove(ProtocolMapperModel protocolMapper) { // No-op } @Override public void preRemove(ClientScopeModel clientScope) { String clientScopeId = clientScope.getId(); LOG.tracef("preRemove[ClientScopeModel](%s)%s", clientScopeId, getShortStackTrace()); DefaultModelCriteria<UserModel> mcb = criteria(); mcb = mcb.compare(SearchableFields.REALM_ID, Operator.EQ, clientScope.getRealm().getId()) .compare(SearchableFields.CONSENT_WITH_CLIENT_SCOPE, Operator.EQ, clientScopeId); try (Stream<MapUserEntity> s = tx.read(withCriteria(mcb))) { s.map(MapUserEntity::getUserConsents) .filter(Objects::nonNull) .flatMap(Collection::stream) .forEach(consent -> consent.removeGrantedClientScopesId(clientScopeId)); } } @Override public void preRemove(RealmModel realm, ComponentModel component) { } @Override public void grantToAllUsers(RealmModel realm, RoleModel role) { String roleId = role.getId(); LOG.tracef("grantToAllUsers(%s, %s)%s", realm, roleId, getShortStackTrace()); DefaultModelCriteria<UserModel> mcb = criteria(); mcb = mcb.compare(SearchableFields.REALM_ID, Operator.EQ, realm.getId()); try (Stream<MapUserEntity> s = tx.read(withCriteria(mcb))) { s.forEach(entity -> entity.addRolesMembership(roleId)); } } @Override public UserModel getUserById(RealmModel realm, String id) { LOG.tracef("getUserById(%s, %s)%s", realm, id, getShortStackTrace()); return getEntityById(realm, id).map(entityToAdapterFunc(realm)).orElse(null); } @Override public UserModel getUserByUsername(RealmModel realm, String username) { if (username == null) return null; LOG.tracef("getUserByUsername(%s, %s)%s", realm, username, getShortStackTrace()); DefaultModelCriteria<UserModel> mcb = criteria(); mcb = mcb.compare(SearchableFields.REALM_ID, Operator.EQ, realm.getId()) .compare(getUsernameCaseSensitiveAttribute(realm) ? SearchableFields.USERNAME : SearchableFields.USERNAME_CASE_INSENSITIVE, Operator.EQ, username); // there is orderBy used to always return the same user in case multiple users are returned from the store try (Stream<MapUserEntity> s = tx.read(withCriteria(mcb).orderBy(SearchableFields.USERNAME, ASCENDING))) { List<MapUserEntity> users = s.collect(Collectors.toList()); if (users.isEmpty()) return null; if (users.size() != 1) { LOG.warnf("There are colliding usernames for users with usernames and ids: %s", users.stream().collect(Collectors.toMap(MapUserEntity::getUsername, MapUserEntity::getId))); } return entityToAdapterFunc(realm).apply(users.get(0)); } } @Override public UserModel getUserByEmail(RealmModel realm, String email) { LOG.tracef("getUserByEmail(%s, %s)%s", realm, email, getShortStackTrace()); DefaultModelCriteria<UserModel> mcb = criteria(); mcb = mcb.compare(SearchableFields.REALM_ID, Operator.EQ, realm.getId()) .compare(SearchableFields.EMAIL, Operator.EQ, email); List<MapUserEntity> usersWithEmail = tx.read(withCriteria(mcb)).collect(Collectors.toList()); if (usersWithEmail.isEmpty()) return null; if (usersWithEmail.size() > 1) { // Realm settings have been changed from allowing duplicate emails to not allowing them // but duplicates haven't been removed. throw new ModelDuplicateException("Multiple users with email '" + email + "' exist in Keycloak."); } MapUserEntity userEntity = usersWithEmail.get(0); if (!realm.isDuplicateEmailsAllowed()) { if (userEntity.getEmail() != null && !userEntity.getEmail().equals(userEntity.getEmailConstraint())) { // Realm settings have been changed from allowing duplicate emails to not allowing them. // We need to update the email constraint to reflect this change in the user entities. userEntity.setEmailConstraint(userEntity.getEmail()); } } return entityToAdapterFunc(realm).apply(userEntity); } @Override public int getUsersCount(RealmModel realm, boolean includeServiceAccount) { LOG.tracef("getUsersCount(%s, %s)%s", realm, includeServiceAccount, getShortStackTrace()); DefaultModelCriteria<UserModel> mcb = criteria(); mcb = mcb.compare(SearchableFields.REALM_ID, Operator.EQ, realm.getId()); if (! includeServiceAccount) { mcb = mcb.compare(SearchableFields.SERVICE_ACCOUNT_CLIENT, Operator.NOT_EXISTS); } return (int) tx.getCount(withCriteria(mcb)); } @Override public Stream<UserModel> searchForUserStream(RealmModel realm, String search, Integer firstResult, Integer maxResults) { LOG.tracef("searchForUserStream(%s, %s, %d, %d)%s", realm, search, firstResult, maxResults, getShortStackTrace()); Map<String, String> attributes = new HashMap<>(); attributes.put(UserModel.SEARCH, search); attributes.put(UserModel.INCLUDE_SERVICE_ACCOUNT, Boolean.FALSE.toString()); return searchForUserStream(realm, attributes, firstResult, maxResults); } @Override public Stream<UserModel> searchForUserStream(RealmModel realm, Map<String, String> attributes, Integer firstResult, Integer maxResults) { LOG.tracef("searchForUserStream(%s, %s, %d, %d)%s", realm, attributes, firstResult, maxResults, getShortStackTrace()); final DefaultModelCriteria<UserModel> mcb = criteria(); DefaultModelCriteria<UserModel> criteria = mcb.compare(SearchableFields.REALM_ID, Operator.EQ, realm.getId()); final boolean exactSearch = Boolean.parseBoolean(attributes.getOrDefault(UserModel.EXACT, Boolean.FALSE.toString())); for (Map.Entry<String, String> entry : attributes.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); if (value == null) { continue; } value = value.trim(); final String searchedString = exactSearch ? value : ("%" + value + "%"); switch (key) { case UserModel.SEARCH: DefaultModelCriteria<UserModel> searchCriteria = null; for (String stringToSearch : value.split("\\s+")) { if (searchCriteria == null) { searchCriteria = addSearchToModelCriteria(realm, stringToSearch, mcb); } else { searchCriteria = mcb.and(searchCriteria, addSearchToModelCriteria(realm, stringToSearch, mcb)); } } criteria = mcb.and(criteria, searchCriteria); break; case USERNAME: criteria = getUsernameCaseSensitiveAttribute(realm) ? criteria.compare(SearchableFields.USERNAME, Operator.LIKE, searchedString) : criteria.compare(SearchableFields.USERNAME_CASE_INSENSITIVE, Operator.ILIKE, searchedString); break; case FIRST_NAME: criteria = criteria.compare(SearchableFields.FIRST_NAME, Operator.ILIKE, searchedString); break; case LAST_NAME: criteria = criteria.compare(SearchableFields.LAST_NAME, Operator.ILIKE, searchedString); break; case EMAIL: criteria = criteria.compare(SearchableFields.EMAIL, Operator.ILIKE, searchedString); break; case EMAIL_VERIFIED: { boolean booleanValue = Boolean.parseBoolean(value); criteria = criteria.compare(SearchableFields.EMAIL_VERIFIED, Operator.EQ, booleanValue); break; } case UserModel.ENABLED: { boolean booleanValue = Boolean.parseBoolean(value); criteria = criteria.compare(SearchableFields.ENABLED, Operator.EQ, booleanValue); break; } case UserModel.IDP_ALIAS: { if (!attributes.containsKey(UserModel.IDP_USER_ID)) { criteria = criteria.compare(SearchableFields.IDP_AND_USER, Operator.EQ, value); } break; } case UserModel.IDP_USER_ID: { criteria = criteria.compare(SearchableFields.IDP_AND_USER, Operator.EQ, attributes.get(UserModel.IDP_ALIAS), value); break; } case UserModel.INCLUDE_SERVICE_ACCOUNT: { if (!attributes.containsKey(UserModel.INCLUDE_SERVICE_ACCOUNT) || !Boolean.parseBoolean(attributes.get(UserModel.INCLUDE_SERVICE_ACCOUNT))) { criteria = criteria.compare(SearchableFields.SERVICE_ACCOUNT_CLIENT, Operator.NOT_EXISTS); } break; } case UserModel.EXACT: break; default: criteria = criteria.compare(SearchableFields.ATTRIBUTE, Operator.EQ, key, value); break; } } // Only return those results that the current user is authorized to view, // i.e. there is an intersection of groups with view permission of the current // user (passed in via UserModel.GROUPS attribute), the groups for the returned // users, and the respective group resource available from the authorization provider @SuppressWarnings("unchecked") Set<String> userGroups = (Set<String>) session.getAttribute(UserModel.GROUPS); if (userGroups != null) { if (userGroups.isEmpty()) { return Stream.empty(); } final ResourceStore resourceStore = session.getProvider(AuthorizationProvider.class).getStoreFactory().getResourceStore(); HashSet<String> authorizedGroups = new HashSet<>(userGroups); authorizedGroups.removeIf(id -> { Map<Resource.FilterOption, String[]> values = new EnumMap<>(Resource.FilterOption.class); values.put(Resource.FilterOption.EXACT_NAME, new String[] {"group.resource." + id}); return resourceStore.find(realm, null, values, 0, 1).isEmpty(); }); criteria = criteria.compare(SearchableFields.ASSIGNED_GROUP, Operator.IN, authorizedGroups); } return tx.read(withCriteria(criteria).pagination(firstResult, maxResults, SearchableFields.USERNAME)) .map(entityToAdapterFunc(realm)) .filter(Objects::nonNull); } @Override public Stream<UserModel> getGroupMembersStream(RealmModel realm, GroupModel group, Integer firstResult, Integer maxResults) { LOG.tracef("getGroupMembersStream(%s, %s, %d, %d)%s", realm, group.getId(), firstResult, maxResults, getShortStackTrace()); DefaultModelCriteria<UserModel> mcb = criteria(); mcb = mcb.compare(SearchableFields.REALM_ID, Operator.EQ, realm.getId()) .compare(SearchableFields.ASSIGNED_GROUP, Operator.EQ, group.getId()); return tx.read(withCriteria(mcb).pagination(firstResult, maxResults, SearchableFields.USERNAME)) .map(entityToAdapterFunc(realm)); } @Override public Stream<UserModel> searchForUserByUserAttributeStream(RealmModel realm, String attrName, String attrValue) { LOG.tracef("searchForUserByUserAttributeStream(%s, %s, %s)%s", realm, attrName, attrValue, getShortStackTrace()); DefaultModelCriteria<UserModel> mcb = criteria(); mcb = mcb.compare(SearchableFields.REALM_ID, Operator.EQ, realm.getId()) .compare(SearchableFields.ATTRIBUTE, Operator.EQ, attrName, attrValue); return tx.read(withCriteria(mcb).orderBy(SearchableFields.USERNAME, ASCENDING)) .map(entityToAdapterFunc(realm)); } @Override public UserModel addUser(RealmModel realm, String username) { return addUser(realm, null, username, true, true); } @Override public boolean removeUser(RealmModel realm, UserModel user) { String userId = user.getId(); Optional<MapUserEntity> userById = getEntityById(realm, userId); if (userById.isPresent()) { session.invalidate(USER_BEFORE_REMOVE, realm, user); tx.delete(userId); session.invalidate(USER_AFTER_REMOVE, realm, user); return true; } return false; } @Override public Stream<UserModel> getRoleMembersStream(RealmModel realm, RoleModel role, Integer firstResult, Integer maxResults) { LOG.tracef("getRoleMembersStream(%s, %s, %d, %d)%s", realm, role, firstResult, maxResults, getShortStackTrace()); DefaultModelCriteria<UserModel> mcb = criteria(); mcb = mcb.compare(SearchableFields.REALM_ID, Operator.EQ, realm.getId()) .compare(SearchableFields.ASSIGNED_ROLE, Operator.EQ, role.getId()); return tx.read(withCriteria(mcb).pagination(firstResult, maxResults, SearchableFields.USERNAME)) .map(entityToAdapterFunc(realm)); } @Override public void close() { } public static <T> Stream<T> getCredentialProviders(KeycloakSession session, Class<T> type) { return session.getKeycloakSessionFactory().getProviderFactoriesStream(CredentialProvider.class) .filter(f -> Types.supports(type, f, CredentialProviderFactory.class)) .map(f -> (T) session.getProvider(CredentialProvider.class, f.getId())); } @Override public CredentialValidationOutput getUserByCredential(RealmModel realm, CredentialInput input) { // TODO: future implementations would narrow down the stream to those provider enabled for the specific realm Stream<CredentialAuthentication> credentialAuthenticationStream = getCredentialProviders(session, CredentialAuthentication.class); CredentialValidationOutput r = credentialAuthenticationStream .filter(credentialAuthentication -> credentialAuthentication.supportsCredentialAuthenticationFor(input.getType())) .map(credentialAuthentication -> credentialAuthentication.authenticate(realm, input)) .filter(Objects::nonNull) .findFirst().orElse(null); if (r == null && tx instanceof MapKeycloakTransactionWithAuth) { MapCredentialValidationOutput<MapUserEntity> result = ((MapKeycloakTransactionWithAuth<MapUserEntity, UserModel>) tx).authenticate(realm, input); if (result != null) { UserModel user = null; if (result.getAuthenticatedUser() != null) { user = entityToAdapterFunc(realm).apply(result.getAuthenticatedUser()); } r = new CredentialValidationOutput(user, result.getAuthStatus(), result.getState()); } } return r; } private DefaultModelCriteria<UserModel> addSearchToModelCriteria(RealmModel realm, String value, DefaultModelCriteria<UserModel> mcb) { if (value.length() >= 2 && value.charAt(0) == '"' && value.charAt(value.length() - 1) == '"') { // exact search value = value.substring(1, value.length() - 1); } else { if (value.length() >= 2 && value.charAt(0) == '*' && value.charAt(value.length() - 1) == '*') { // infix search value = "%" + value.substring(1, value.length() - 1) + "%"; } else { // default to prefix search if (value.length() > 0 && value.charAt(value.length() - 1) == '*') { value = value.substring(0, value.length() - 1); } value += "%"; } } return mcb.or( getUsernameCaseSensitiveAttribute(realm) ? mcb.compare(SearchableFields.USERNAME, Operator.LIKE, value) : mcb.compare(SearchableFields.USERNAME_CASE_INSENSITIVE, Operator.ILIKE, value), mcb.compare(SearchableFields.EMAIL, Operator.ILIKE, value), mcb.compare(SearchableFields.FIRST_NAME, Operator.ILIKE, value), mcb.compare(SearchableFields.LAST_NAME, Operator.ILIKE, value)); } }
MapUserProvider should throw an exception for more than one user Closes #14672
model/map/src/main/java/org/keycloak/models/map/user/MapUserProvider.java
MapUserProvider should throw an exception for more than one user
<ide><path>odel/map/src/main/java/org/keycloak/models/map/user/MapUserProvider.java <ide> List<MapUserEntity> users = s.collect(Collectors.toList()); <ide> if (users.isEmpty()) return null; <ide> if (users.size() != 1) { <del> LOG.warnf("There are colliding usernames for users with usernames and ids: %s", <del> users.stream().collect(Collectors.toMap(MapUserEntity::getUsername, MapUserEntity::getId))); <add> throw new ModelDuplicateException(String.format("There are colliding usernames for users with usernames and ids: %s", <add> users.stream().collect(Collectors.toMap(MapUserEntity::getUsername, MapUserEntity::getId)))); <ide> } <ide> return entityToAdapterFunc(realm).apply(users.get(0)); <ide> }
Java
lgpl-2.1
6f3f0637e9df8759b3993854cb6c4427b49f2dc7
0
ekiwi/jade-mirror,ekiwi/jade-mirror,ekiwi/jade-mirror,ekiwi/jade-mirror
/***************************************************************** JADE - Java Agent DEvelopment Framework is a framework to develop multi-agent systems in compliance with the FIPA specifications. Copyright (C) 2000 CSELT S.p.A. GNU Lesser General Public License 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 2.1 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 library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *****************************************************************/ package jade.core; //#MIDP_EXCLUDE_FILE import jade.security.AuthException; import jade.util.leap.Map; import jade.util.leap.HashMap; import jade.util.leap.List; import jade.util.leap.LinkedList; import jade.util.leap.Iterator; /** The <code>ServiceManagerImpl</code> class is the actual implementation of JADE platform <i>Service Manager</i> and <i>Service Finder</i> components. It holds a set of services and manages them. @author Giovanni Rimassa - FRAMeTech s.r.l. */ public class ServiceManagerImpl implements ServiceManager, ServiceFinder { private class ServiceEntry { public ServiceEntry(Service s) { myService = s; slices = new HashMap(); } public void addSlice(String name, Service.Slice s, Node n) { SliceEntry e = new SliceEntry(s, n); slices.put(name, e); } public void removeSlice(String name) { slices.remove(name); } public Service.Slice[] getSlices() { Object[] sliceEntries = slices.values().toArray(); Service.Slice[] result = new Service.Slice[sliceEntries.length]; for(int i = 0; i < result.length; i++) { SliceEntry e = (SliceEntry)sliceEntries[i]; result[i] = e.getSlice(); } return result; } public Service.Slice getSlice(String name) { SliceEntry e = (SliceEntry)slices.get(name); if(e == null) { return null; } else { return e.getSlice(); } } public Node[] getNodes() { Object[] sliceEntries = slices.values().toArray(); Node[] result = new Node[sliceEntries.length]; for(int i = 0; i < result.length; i++) { SliceEntry e = (SliceEntry)sliceEntries[i]; result[i] = e.getNode(); } return result; } public Node getNode(String name) { SliceEntry e = (SliceEntry)slices.get(name); if(e == null) { return null; } else { return e.getNode(); } } public void setService(Service svc) { myService = svc; } public Service getService() { return myService; } private Service myService; private Map slices; } // End of ServiceEntry class private class SliceEntry { public SliceEntry(Service.Slice s, Node n) { mySlice = s; myNode = n; } public Service.Slice getSlice() { return mySlice; } public Node getNode() { return myNode; } private Service.Slice mySlice; private Node myNode; } // End of SliceEntry class private static class DummyService extends BaseService { public DummyService(String name, Class itf) { serviceName = name; horizontalInterface = itf; } public String getName() { return serviceName; } public Class getHorizontalInterface() { return horizontalInterface; } public Service.Slice getLocalSlice() { return null; } public Filter getCommandFilter(boolean direction) { return null; } public Sink getCommandSink(boolean side) { return null; } public String[] getOwnedCommands() { return OWNED_COMMANDS; } private static final String[] OWNED_COMMANDS = new String[0]; private String serviceName; private Class horizontalInterface; } // End of DummyService class /** Constructs a new Service Manager implementation complying with a given JADE profile. This constructor is package-scoped, so that only the JADE kernel is allowed to create a new Service Manager implementation. @param p The platform profile describing how the JADE platform is to be configured. */ ServiceManagerImpl(Profile p, MainContainerImpl mc) throws ProfileException, IMTPException { myCommandProcessor = p.getCommandProcessor(); myIMTPManager = p.getIMTPManager(); myMain = mc; services = new HashMap(); } // FIXME: The association between MainContainer and ServiceManagerImpl need be clarified... private MainContainerImpl myMain; // Implementation of the ServiceManager interface public String getPlatformName() throws IMTPException { return myMain.getPlatformName(); } public void addAddress(String addr) throws IMTPException { myIMTPManager.addServiceManagerAddress(addr); } public void removeAddress(String addr) throws IMTPException { myIMTPManager.removeServiceManagerAddress(addr); } public String getLocalAddress() throws IMTPException { return localAddress; } public void addNode(NodeDescriptor desc, ServiceDescriptor[] services) throws IMTPException, ServiceException, AuthException { Node n = desc.getNode(); ContainerID cid = desc.getContainer(); adjustContainerName(n, cid); // Add the node as a local agent container and activate the new container with the IMTP manager myMain.addLocalContainer(desc); myIMTPManager.connect(desc.getContainer()); // Activate all the node services List failedServices = new LinkedList(); for(int i = 0; i < services.length; i++) { try { // No need to notify other Service Manager replicas doActivateService(services[i]); } catch(IMTPException imtpe) { // This should never happen, because it's a local call... imtpe.printStackTrace(); } catch(ServiceException se) { failedServices.add(services[i].getName()); } } // Throw a failure exception, if needed if(!failedServices.isEmpty()) { // All service activations failed: throw a single exception if(failedServices.size() == services.length) { throw new ServiceException("Total failure in installing the services for local node"); } else { // Only some service activations failed: throw a single exception with the list of the failed services Iterator it = failedServices.iterator(); String names = "[ "; while(it.hasNext()) { names = names.concat((String)it.next() + " "); } names = names.concat("]"); throw new ServiceException("Partial failure in installing the services " + names); } } // Tell all the other service managers about the new node String[] svcNames = new String[services.length]; Class[] svcInterfaces = new Class[services.length]; // Fill the parameter arrays for(int i = 0; i < services.length; i++) { svcNames[i] = services[i].getName(); svcInterfaces[i] = services[i].getService().getHorizontalInterface(); } myIMTPManager.nodeAdded(desc, svcNames, svcInterfaces, nodeNo, mainNodeNo); } public void removeNode(NodeDescriptor desc) throws IMTPException, ServiceException { // Retrieve the node information Node localNode = desc.getNode(); if(!localNode.equals(myIMTPManager.getLocalNode())) { throw new ServiceException("A remote node cannot be added with this method call"); } // Deactivate all the node services Object[] names = services.keySet().toArray(); for(int i = 0; i < names.length; i++) { try { String svcName = (String)names[i]; ServiceEntry e = (ServiceEntry)services.get(svcName); Service svc = e.getService(); ServiceDescriptor svcDesc = new ServiceDescriptor(svcName, svc); // No need to notify other Service Manager replicas doDeactivateService(svcDesc); } catch(IMTPException imtpe) { // This should never happen, because it's a local call... imtpe.printStackTrace(); } catch(ServiceException se) { se.printStackTrace(); } } // Remove the node as a local agent container myMain.removeLocalContainer(desc.getContainer()); // Tell all the other service managers about the new node myIMTPManager.nodeRemoved(desc); } public void activateService(ServiceDescriptor desc) throws IMTPException, ServiceException { doActivateService(desc); myIMTPManager.serviceActivated(desc.getName(), desc.getService().getHorizontalInterface(), myIMTPManager.getLocalNode()); } public void deactivateService(ServiceDescriptor desc) throws IMTPException, ServiceException { doDeactivateService(desc); myIMTPManager.serviceDeactivated(desc.getName(), myIMTPManager.getLocalNode()); } // Implementation of the ServiceFinder interface public Service findService(String key) throws IMTPException, ServiceException { ServiceEntry e = (ServiceEntry)services.get(key); return e.getService(); } public Service.Slice findSlice(String serviceKey, String sliceKey) throws IMTPException, ServiceException { ServiceEntry e = (ServiceEntry)services.get(serviceKey); if(e == null) { return null; } else { // If the special MAIN_SLICE name is used, return the local slice if(CaseInsensitiveString.equalsIgnoreCase(sliceKey, MAIN_SLICE)) { sliceKey = myIMTPManager.getLocalNode().getName(); } return e.getSlice(sliceKey); } } public Service.Slice[] findAllSlices(String serviceKey) throws IMTPException, ServiceException { ServiceEntry e = (ServiceEntry)services.get(serviceKey); if(e == null) { return null; } else { return e.getSlices(); } } public Node[] findAllNodes(String serviceKey) throws IMTPException, ServiceException { ServiceEntry e = (ServiceEntry)services.get(serviceKey); if(e == null) { return null; } else { return e.getNodes(); } } public Node findSliceNode(String serviceKey, String nodeKey) throws IMTPException, ServiceException { ServiceEntry e = (ServiceEntry)services.get(serviceKey); if(e == null) { return null; } else { // If the special MAIN_SLICE name is used, return the local slice if(CaseInsensitiveString.equalsIgnoreCase(nodeKey, MAIN_SLICE)) { nodeKey = myIMTPManager.getLocalNode().getName(); } return e.getNode(nodeKey); } } // Slice management methods public String addRemoteNode(NodeDescriptor desc, boolean control) throws AuthException { Node n = desc.getNode(); ContainerID cid = desc.getContainer(); adjustContainerName(n, cid); // Add the node as a remote agent container myMain.addRemoteContainer(desc); desc.setName(cid.getName()); String name = desc.getName(); Node node = desc.getNode(); node.setName(name); if(control) { monitor(n); } // Return the name given to the new container return cid.getName(); } public void removeRemoteNode(NodeDescriptor desc, boolean propagate) throws IMTPException { System.out.println("Removing node <" + desc.getName() + "> from the platform"); // Remove all the slices corresponding to the removed node Object[] allServices = services.values().toArray(); for(int i = 0; i < allServices.length; i++) { ServiceEntry e = (ServiceEntry)allServices[i]; // System.out.println("Removing slice for node <" + desc.getName() + "> from service " + e.getService().getName()); e.removeSlice(desc.getName()); } // Remove the node as a remote container myMain.removeRemoteContainer(desc); if(propagate) { // Tell all the other service managers about the new node myIMTPManager.nodeRemoved(desc); } } public void addRemoteSlice(String serviceKey, String sliceKey, Service.Slice slice, Node remoteNode) { ServiceEntry e = (ServiceEntry)services.get(serviceKey); if(e == null) { Service svc = new DummyService(serviceKey, Service.Slice.class); e = new ServiceEntry(svc); services.put(serviceKey, e); } e.addSlice(sliceKey, slice, remoteNode); } public void removeRemoteSlice(String serviceKey, String sliceKey) { // FIXME: To be implemented... } public void setNodeCounters(int nodeCnt, int mainCnt) { nodeNo = nodeCnt; mainNodeNo = mainCnt; } public int getNodeCounter() { return nodeNo; } public int getMainNodeCounter() { return mainNodeNo; } public void setLocalAddress(String addr) { localAddress = addr; } public static class NodeInfo { public NodeInfo(Node n, Object[]names, Object[] interfaces) { ContainerID cid = new ContainerID(n.getName(), null); nodeDesc = new NodeDescriptor(cid, n, "", new byte[0]); // FIXME: Temporary Hack svcNames = new String[names.length]; for(int i = 0; i < names.length; i++) { svcNames[i] = (String)names[i]; } svcInterfaces = new Class[interfaces.length]; for(int i = 0; i < interfaces.length; i++) { svcInterfaces[i] = (Class)interfaces[i]; } } public NodeDescriptor getNodeDescriptor() { return nodeDesc; } public String[] getServiceNames() { return svcNames; } public Class[] getServiceInterfaces() { return svcInterfaces; } public String[] getServiceInterfacesNames() { String[] names = new String[svcInterfaces.length]; for(int i = 0; i < names.length; i++) { names[i] = svcInterfaces[i].getName(); } return names; } private NodeDescriptor nodeDesc; private String[] svcNames; private Class[] svcInterfaces; } public List getAllNodesInfo() { // Map: Node name -> List of service names Map serviceNames = new HashMap(); // Map: Node name -> List of horizontal interfaces Map serviceInterfaces = new HashMap(); // Map: Node name -> Node Map nodes = new HashMap(); Iterator it = services.values().iterator(); while(it.hasNext()) { ServiceEntry e = (ServiceEntry)it.next(); Node[] serviceNodes = e.getNodes(); for(int i = 0; i < serviceNodes.length; i++) { String nodeName = serviceNodes[i].getName(); List l1 = (List)serviceNames.get(nodeName); if(l1 == null) { l1 = new LinkedList(); serviceNames.put(nodeName, l1); } l1.add(e.getService().getName()); List l2 = (List)serviceInterfaces.get(nodeName); if(l2 == null) { l2 = new LinkedList(); serviceInterfaces.put(nodeName, l2); } l2.add(e.getService().getHorizontalInterface()); Node n = (Node)nodes.get(nodeName); if(n == null) { nodes.put(nodeName, serviceNodes[i]); } } } List result = new LinkedList(); it = nodes.keySet().iterator(); while(it.hasNext()) { String nodeName = (String)it.next(); Node n = (Node)nodes.get(nodeName); Object[] sn = ((List)serviceNames.get(nodeName)).toArray(); Object[] si = ((List)serviceInterfaces.get(nodeName)).toArray(); result.add(new NodeInfo(n, sn, si)); } return result; } private IMTPManager myIMTPManager; private CommandProcessor myCommandProcessor; private String localAddress; private List addresses; private Map services; // These variables hold two progressive numbers just used to name new nodes. // By convention, nodes with a local copy of the Service Manager are called // Main-Container-<N>, whereas nodes without their own Service Manager are // called Container-<M>. private int nodeNo = 1; private int mainNodeNo = 0; private void adjustContainerName(Node n, ContainerID cid) { // Do nothing if a custom name is already supplied if((n != null) && !n.getName().equals(AgentManager.UNNAMED_CONTAINER_NAME)) { return; } if(n.hasServiceManager()) { // Use the Main-Container-<N> name schema if(mainNodeNo == 0) { cid.setName(AgentManager.MAIN_CONTAINER_NAME); } else { cid.setName(AgentManager.MAIN_CONTAINER_NAME + '-' + mainNodeNo); } try { while(true) { // Try until a non-existing name is found... myMain.getContainerNode(cid); mainNodeNo++; cid.setName(AgentManager.MAIN_CONTAINER_NAME + '-' + mainNodeNo); } } catch(NotFoundException nfe) { // There is no such named container, so the name is OK. } } else { // Use the Container-<M> name schema cid.setName(AgentManager.AUX_CONTAINER_NAME + '-' + nodeNo); try { while(true) { // Try until a non-existing name is found... myMain.getContainerNode(cid); nodeNo++; cid.setName(AgentManager.AUX_CONTAINER_NAME + '-' + nodeNo); } } catch(NotFoundException nfe) { // There is no such named container, so the name is OK. } } } private void doActivateService(ServiceDescriptor desc) throws IMTPException, ServiceException { String name = desc.getName(); Service svc = desc.getService(); ServiceEntry e = (ServiceEntry)services.get(name); if(e != null) { Service old = e.getService(); if(old instanceof DummyService) { // A dummy service: replace it with the real thing, while keeping the slice table e.setService(svc); } else { // A real service is already installed: abort activation throw new ServiceException("A service named <" + name + "> is already active."); } } else { // Create an entry for the new service e = new ServiceEntry(svc); services.put(name, e); } // Export the *REAL* local slice so that it can be reached through the network Service.Slice localSlice = svc.getLocalSlice(); if(localSlice != null) { myIMTPManager.exportSlice(name, localSlice); } // Put the *PROXY* local slice into the Service Finder so that it can be found later Node here = myIMTPManager.getLocalNode(); Service.Slice localProxy = myIMTPManager.createSliceProxy(name, null, here); e.addSlice(here.getName(), localProxy, here); // System.out.println("Added a local slice <" + name + ";" + here.getName() + ">"); // Install the service filters Filter fOut = svc.getCommandFilter(Filter.OUTGOING); if(fOut != null) { myCommandProcessor.addFilter(fOut, Filter.OUTGOING); } Filter fIn = svc.getCommandFilter(Filter.INCOMING); if(fIn != null) { myCommandProcessor.addFilter(fIn, Filter.INCOMING); } // Install the service sinks String[] commandNames = svc.getOwnedCommands(); Sink sSrc = svc.getCommandSink(Sink.COMMAND_SOURCE); if(sSrc != null) { myCommandProcessor.registerSink(sSrc, Sink.COMMAND_SOURCE, commandNames); } Sink sTgt = svc.getCommandSink(Sink.COMMAND_TARGET); if(sTgt != null) { myCommandProcessor.registerSink(sTgt, Sink.COMMAND_TARGET, commandNames); } } private void doDeactivateService(ServiceDescriptor desc) throws IMTPException, ServiceException { String name = desc.getName(); ServiceEntry e = (ServiceEntry)services.get(name); if(e != null) { Service svc = e.getService(); // Uninstall the service filters Filter fOut = svc.getCommandFilter(Filter.OUTGOING); if(fOut != null) { myCommandProcessor.removeFilter(fOut, Filter.OUTGOING); } Filter fIn = svc.getCommandFilter(Filter.INCOMING); if(fIn != null) { myCommandProcessor.removeFilter(fIn, Filter.INCOMING); } // Uninistall the service sinks String[] commandNames = svc.getOwnedCommands(); Sink sSrc = svc.getCommandSink(Sink.COMMAND_SOURCE); if(sSrc != null) { myCommandProcessor.deregisterSink(Sink.COMMAND_SOURCE, commandNames); } Sink sTgt = svc.getCommandSink(Sink.COMMAND_TARGET); if(sTgt != null) { myCommandProcessor.deregisterSink(Sink.COMMAND_TARGET, commandNames); } // Uninstall the service services.remove(name); } } public void monitor(Node target) { // Set up a failure monitor using the blocking ping... NodeFailureMonitor failureMonitor = new NodeFailureMonitor(target, new NodeEventListener() { // FIXME: Should notify all the interested service slices... public void nodeAdded(Node n) { System.out.println("--- Node <" + n.getName() + "> ADDED ---"); } public void nodeRemoved(Node n) { System.out.println("--- Node <" + n.getName() + "> REMOVED ---"); try { removeRemoteNode(new NodeDescriptor(n.getName(), n), true); } catch(IMTPException imtpe) { imtpe.printStackTrace(); } } public void nodeUnreachable(Node n) { System.out.println("--- Node <" + n.getName() + "> UNREACHABLE ---"); } public void nodeReachable(Node n) { System.out.println("--- Node <" + n.getName() + "> REACHABLE ---"); } }); // Start a new node failure monitor Thread t = new Thread(failureMonitor); t.start(); } }
src/jade/core/ServiceManagerImpl.java
/***************************************************************** JADE - Java Agent DEvelopment Framework is a framework to develop multi-agent systems in compliance with the FIPA specifications. Copyright (C) 2000 CSELT S.p.A. GNU Lesser General Public License 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 2.1 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 library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *****************************************************************/ package jade.core; //#MIDP_EXCLUDE_FILE import jade.security.AuthException; import jade.util.leap.Map; import jade.util.leap.HashMap; import jade.util.leap.List; import jade.util.leap.LinkedList; import jade.util.leap.Iterator; /** The <code>ServiceManagerImpl</code> class is the actual implementation of JADE platform <i>Service Manager</i> and <i>Service Finder</i> components. It holds a set of services and manages them. @author Giovanni Rimassa - FRAMeTech s.r.l. */ public class ServiceManagerImpl implements ServiceManager, ServiceFinder { private class ServiceEntry { public ServiceEntry(Service s) { myService = s; slices = new HashMap(); } public void addSlice(String name, Service.Slice s, Node n) { SliceEntry e = new SliceEntry(s, n); slices.put(name, e); } public void removeSlice(String name) { slices.remove(name); } public Service.Slice[] getSlices() { Object[] sliceEntries = slices.values().toArray(); Service.Slice[] result = new Service.Slice[sliceEntries.length]; for(int i = 0; i < result.length; i++) { SliceEntry e = (SliceEntry)sliceEntries[i]; result[i] = e.getSlice(); } return result; } public Service.Slice getSlice(String name) { SliceEntry e = (SliceEntry)slices.get(name); if(e == null) { return null; } else { return e.getSlice(); } } public Node[] getNodes() { Object[] sliceEntries = slices.values().toArray(); Node[] result = new Node[sliceEntries.length]; for(int i = 0; i < result.length; i++) { SliceEntry e = (SliceEntry)sliceEntries[i]; result[i] = e.getNode(); } return result; } public Node getNode(String name) { SliceEntry e = (SliceEntry)slices.get(name); if(e == null) { return null; } else { return e.getNode(); } } public void setService(Service svc) { myService = svc; } public Service getService() { return myService; } private Service myService; private Map slices; } // End of ServiceEntry class private class SliceEntry { public SliceEntry(Service.Slice s, Node n) { mySlice = s; myNode = n; } public Service.Slice getSlice() { return mySlice; } public Node getNode() { return myNode; } private Service.Slice mySlice; private Node myNode; } // End of SliceEntry class private static class DummyService extends BaseService { public DummyService(String name, Class itf) { serviceName = name; horizontalInterface = itf; } public String getName() { return serviceName; } public Class getHorizontalInterface() { return horizontalInterface; } public Service.Slice getLocalSlice() { return null; } public Filter getCommandFilter(boolean direction) { return null; } public Sink getCommandSink(boolean side) { return null; } public String[] getOwnedCommands() { return OWNED_COMMANDS; } private static final String[] OWNED_COMMANDS = new String[0]; private String serviceName; private Class horizontalInterface; } // End of DummyService class /** Constructs a new Service Manager implementation complying with a given JADE profile. This constructor is package-scoped, so that only the JADE kernel is allowed to create a new Service Manager implementation. @param p The platform profile describing how the JADE platform is to be configured. */ ServiceManagerImpl(Profile p, MainContainerImpl mc) throws ProfileException, IMTPException { myCommandProcessor = p.getCommandProcessor(); myIMTPManager = p.getIMTPManager(); myMain = mc; services = new HashMap(); } // FIXME: The association between MainContainer and ServiceManagerImpl need be clarified... private MainContainerImpl myMain; // Implementation of the ServiceManager interface public String getPlatformName() throws IMTPException { return myMain.getPlatformName(); } public void addAddress(String addr) throws IMTPException { myIMTPManager.addServiceManagerAddress(addr); } public void removeAddress(String addr) throws IMTPException { myIMTPManager.removeServiceManagerAddress(addr); } public String getLocalAddress() throws IMTPException { return localAddress; } public void addNode(NodeDescriptor desc, ServiceDescriptor[] services) throws IMTPException, ServiceException, AuthException { Node n = desc.getNode(); ContainerID cid = desc.getContainer(); adjustContainerName(n, cid); // Add the node as a local agent container and activate the new container with the IMTP manager myMain.addLocalContainer(desc); myIMTPManager.connect(desc.getContainer()); // Activate all the node services List failedServices = new LinkedList(); for(int i = 0; i < services.length; i++) { try { // No need to notify other Service Manager replicas doActivateService(services[i]); } catch(IMTPException imtpe) { // This should never happen, because it's a local call... imtpe.printStackTrace(); } catch(ServiceException se) { failedServices.add(services[i].getName()); } } // Throw a failure exception, if needed if(!failedServices.isEmpty()) { // All service activations failed: throw a single exception if(failedServices.size() == services.length) { throw new ServiceException("Total failure in installing the services for local node"); } else { // Only some service activations failed: throw a single exception with the list of the failed services Iterator it = failedServices.iterator(); String names = "[ "; while(it.hasNext()) { names = names.concat((String)it.next() + " "); } names = names.concat("]"); throw new ServiceException("Partial failure in installing the services " + names); } } // Tell all the other service managers about the new node String[] svcNames = new String[services.length]; Class[] svcInterfaces = new Class[services.length]; // Fill the parameter arrays for(int i = 0; i < services.length; i++) { svcNames[i] = services[i].getName(); svcInterfaces[i] = services[i].getService().getHorizontalInterface(); } myIMTPManager.nodeAdded(desc, svcNames, svcInterfaces, nodeNo, mainNodeNo); } public void removeNode(NodeDescriptor desc) throws IMTPException, ServiceException { // Retrieve the node information Node localNode = desc.getNode(); if(!localNode.equals(myIMTPManager.getLocalNode())) { throw new ServiceException("A remote node cannot be added with this method call"); } // Deactivate all the node services Object[] names = services.keySet().toArray(); for(int i = 0; i < names.length; i++) { try { String svcName = (String)names[i]; ServiceEntry e = (ServiceEntry)services.get(svcName); Service svc = e.getService(); ServiceDescriptor svcDesc = new ServiceDescriptor(svcName, svc); // No need to notify other Service Manager replicas doDeactivateService(svcDesc); } catch(IMTPException imtpe) { // This should never happen, because it's a local call... imtpe.printStackTrace(); } catch(ServiceException se) { se.printStackTrace(); } } // Remove the node as a local agent container myMain.removeLocalContainer(desc.getContainer()); // Tell all the other service managers about the new node myIMTPManager.nodeRemoved(desc); } public void activateService(ServiceDescriptor desc) throws IMTPException, ServiceException { doActivateService(desc); myIMTPManager.serviceActivated(desc.getName(), desc.getService().getHorizontalInterface(), myIMTPManager.getLocalNode()); } public void deactivateService(ServiceDescriptor desc) throws IMTPException, ServiceException { doDeactivateService(desc); myIMTPManager.serviceDeactivated(desc.getName(), myIMTPManager.getLocalNode()); } // Implementation of the ServiceFinder interface public Service findService(String key) throws IMTPException, ServiceException { ServiceEntry e = (ServiceEntry)services.get(key); return e.getService(); } public Service.Slice findSlice(String serviceKey, String sliceKey) throws IMTPException, ServiceException { ServiceEntry e = (ServiceEntry)services.get(serviceKey); if(e == null) { return null; } else { // If the special MAIN_SLICE name is used, return the local slice if(CaseInsensitiveString.equalsIgnoreCase(sliceKey, MAIN_SLICE)) { sliceKey = myIMTPManager.getLocalNode().getName(); } return e.getSlice(sliceKey); } } public Service.Slice[] findAllSlices(String serviceKey) throws IMTPException, ServiceException { ServiceEntry e = (ServiceEntry)services.get(serviceKey); if(e == null) { return null; } else { return e.getSlices(); } } public Node[] findAllNodes(String serviceKey) throws IMTPException, ServiceException { ServiceEntry e = (ServiceEntry)services.get(serviceKey); if(e == null) { return null; } else { return e.getNodes(); } } public Node findSliceNode(String serviceKey, String nodeKey) throws IMTPException, ServiceException { ServiceEntry e = (ServiceEntry)services.get(serviceKey); if(e == null) { return null; } else { // If the special MAIN_SLICE name is used, return the local slice if(CaseInsensitiveString.equalsIgnoreCase(nodeKey, MAIN_SLICE)) { nodeKey = myIMTPManager.getLocalNode().getName(); } return e.getNode(nodeKey); } } // Slice management methods public String addRemoteNode(NodeDescriptor desc, boolean control) throws AuthException { Node n = desc.getNode(); ContainerID cid = desc.getContainer(); adjustContainerName(n, cid); // Add the node as a remote agent container myMain.addRemoteContainer(desc); desc.setName(cid.getName()); String name = desc.getName(); Node node = desc.getNode(); node.setName(name); if(control) { // Set up a failure monitor using the blocking ping... NodeFailureMonitor monitor = new NodeFailureMonitor(node, new NodeEventListener() { // FIXME: Should notify all the interested service slices... public void nodeAdded(Node n) { System.out.println("--- Node <" + n.getName() + "> ADDED ---"); } public void nodeRemoved(Node n) { System.out.println("--- Node <" + n.getName() + "> REMOVED ---"); try { removeRemoteNode(new NodeDescriptor(n.getName(), n), true); } catch(IMTPException imtpe) { imtpe.printStackTrace(); } } public void nodeUnreachable(Node n) { System.out.println("--- Node <" + n.getName() + "> UNREACHABLE ---"); } public void nodeReachable(Node n) { System.out.println("--- Node <" + n.getName() + "> REACHABLE ---"); } }); // Start a new node failure monitor Thread t = new Thread(monitor); t.start(); } // Return the name given to the new container return cid.getName(); } public void removeRemoteNode(NodeDescriptor desc, boolean propagate) throws IMTPException { System.out.println("Removing node <" + desc.getName() + "> from the platform"); // Remove all the slices corresponding to the removed node Object[] allServices = services.values().toArray(); for(int i = 0; i < allServices.length; i++) { ServiceEntry e = (ServiceEntry)allServices[i]; // System.out.println("Removing slice for node <" + desc.getName() + "> from service " + e.getService().getName()); e.removeSlice(desc.getName()); } // Remove the node as a remote container myMain.removeRemoteContainer(desc); if(propagate) { // Tell all the other service managers about the new node myIMTPManager.nodeRemoved(desc); } } public void addRemoteSlice(String serviceKey, String sliceKey, Service.Slice slice, Node remoteNode) { ServiceEntry e = (ServiceEntry)services.get(serviceKey); if(e == null) { Service svc = new DummyService(serviceKey, Service.Slice.class); e = new ServiceEntry(svc); services.put(serviceKey, e); } e.addSlice(sliceKey, slice, remoteNode); } public void removeRemoteSlice(String serviceKey, String sliceKey) { // FIXME: To be implemented... } public void setNodeCounters(int nodeCnt, int mainCnt) { nodeNo = nodeCnt; mainNodeNo = mainCnt; } public int getNodeCounter() { return nodeNo; } public int getMainNodeCounter() { return mainNodeNo; } public void setLocalAddress(String addr) { localAddress = addr; } public static class NodeInfo { public NodeInfo(Node n, Object[]names, Object[] interfaces) { ContainerID cid = new ContainerID(n.getName(), null); nodeDesc = new NodeDescriptor(cid, n, "", new byte[0]); // FIXME: Temporary Hack svcNames = new String[names.length]; for(int i = 0; i < names.length; i++) { svcNames[i] = (String)names[i]; } svcInterfaces = new Class[interfaces.length]; for(int i = 0; i < interfaces.length; i++) { svcInterfaces[i] = (Class)interfaces[i]; } } public NodeDescriptor getNodeDescriptor() { return nodeDesc; } public String[] getServiceNames() { return svcNames; } public Class[] getServiceInterfaces() { return svcInterfaces; } public String[] getServiceInterfacesNames() { String[] names = new String[svcInterfaces.length]; for(int i = 0; i < names.length; i++) { names[i] = svcInterfaces[i].getName(); } return names; } private NodeDescriptor nodeDesc; private String[] svcNames; private Class[] svcInterfaces; } public List getAllNodesInfo() { // Map: Node name -> List of service names Map serviceNames = new HashMap(); // Map: Node name -> List of horizontal interfaces Map serviceInterfaces = new HashMap(); // Map: Node name -> Node Map nodes = new HashMap(); Iterator it = services.values().iterator(); while(it.hasNext()) { ServiceEntry e = (ServiceEntry)it.next(); Node[] serviceNodes = e.getNodes(); for(int i = 0; i < serviceNodes.length; i++) { String nodeName = serviceNodes[i].getName(); List l1 = (List)serviceNames.get(nodeName); if(l1 == null) { l1 = new LinkedList(); serviceNames.put(nodeName, l1); } l1.add(e.getService().getName()); List l2 = (List)serviceInterfaces.get(nodeName); if(l2 == null) { l2 = new LinkedList(); serviceInterfaces.put(nodeName, l2); } l2.add(e.getService().getHorizontalInterface()); Node n = (Node)nodes.get(nodeName); if(n == null) { nodes.put(nodeName, serviceNodes[i]); } } } List result = new LinkedList(); it = nodes.keySet().iterator(); while(it.hasNext()) { String nodeName = (String)it.next(); Node n = (Node)nodes.get(nodeName); Object[] sn = ((List)serviceNames.get(nodeName)).toArray(); Object[] si = ((List)serviceInterfaces.get(nodeName)).toArray(); result.add(new NodeInfo(n, sn, si)); } return result; } private IMTPManager myIMTPManager; private CommandProcessor myCommandProcessor; private String localAddress; private List addresses; private Map services; // These variables hold two progressive numbers just used to name new nodes. // By convention, nodes with a local copy of the Service Manager are called // Main-Container-<N>, whereas nodes without their own Service Manager are // called Container-<M>. private int nodeNo = 1; private int mainNodeNo = 0; private void adjustContainerName(Node n, ContainerID cid) { // Do nothing if a custom name is already supplied if((n != null) && !n.getName().equals(AgentManager.UNNAMED_CONTAINER_NAME)) { return; } if(n.hasServiceManager()) { // Use the Main-Container-<N> name schema if(mainNodeNo == 0) { cid.setName(AgentManager.MAIN_CONTAINER_NAME); } else { cid.setName(AgentManager.MAIN_CONTAINER_NAME + '-' + mainNodeNo); } try { while(true) { // Try until a non-existing name is found... myMain.getContainerNode(cid); mainNodeNo++; cid.setName(AgentManager.MAIN_CONTAINER_NAME + '-' + mainNodeNo); } } catch(NotFoundException nfe) { // There is no such named container, so the name is OK. } } else { // Use the Container-<M> name schema cid.setName(AgentManager.AUX_CONTAINER_NAME + '-' + nodeNo); try { while(true) { // Try until a non-existing name is found... myMain.getContainerNode(cid); nodeNo++; cid.setName(AgentManager.AUX_CONTAINER_NAME + '-' + nodeNo); } } catch(NotFoundException nfe) { // There is no such named container, so the name is OK. } } } private void doActivateService(ServiceDescriptor desc) throws IMTPException, ServiceException { String name = desc.getName(); Service svc = desc.getService(); ServiceEntry e = (ServiceEntry)services.get(name); if(e != null) { Service old = e.getService(); if(old instanceof DummyService) { // A dummy service: replace it with the real thing, while keeping the slice table e.setService(svc); } else { // A real service is already installed: abort activation throw new ServiceException("A service named <" + name + "> is already active."); } } else { // Create an entry for the new service e = new ServiceEntry(svc); services.put(name, e); } // Export the *REAL* local slice so that it can be reached through the network Service.Slice localSlice = svc.getLocalSlice(); if(localSlice != null) { myIMTPManager.exportSlice(name, localSlice); } // Put the *PROXY* local slice into the Service Finder so that it can be found later Node here = myIMTPManager.getLocalNode(); Service.Slice localProxy = myIMTPManager.createSliceProxy(name, null, here); e.addSlice(here.getName(), localProxy, here); // System.out.println("Added a local slice <" + name + ";" + here.getName() + ">"); // Install the service filters Filter fOut = svc.getCommandFilter(Filter.OUTGOING); if(fOut != null) { myCommandProcessor.addFilter(fOut, Filter.OUTGOING); } Filter fIn = svc.getCommandFilter(Filter.INCOMING); if(fIn != null) { myCommandProcessor.addFilter(fIn, Filter.INCOMING); } // Install the service sinks String[] commandNames = svc.getOwnedCommands(); Sink sSrc = svc.getCommandSink(Sink.COMMAND_SOURCE); if(sSrc != null) { myCommandProcessor.registerSink(sSrc, Sink.COMMAND_SOURCE, commandNames); } Sink sTgt = svc.getCommandSink(Sink.COMMAND_TARGET); if(sTgt != null) { myCommandProcessor.registerSink(sTgt, Sink.COMMAND_TARGET, commandNames); } } private void doDeactivateService(ServiceDescriptor desc) throws IMTPException, ServiceException { String name = desc.getName(); ServiceEntry e = (ServiceEntry)services.get(name); if(e != null) { Service svc = e.getService(); // Uninstall the service filters Filter fOut = svc.getCommandFilter(Filter.OUTGOING); if(fOut != null) { myCommandProcessor.removeFilter(fOut, Filter.OUTGOING); } Filter fIn = svc.getCommandFilter(Filter.INCOMING); if(fIn != null) { myCommandProcessor.removeFilter(fIn, Filter.INCOMING); } // Uninistall the service sinks String[] commandNames = svc.getOwnedCommands(); Sink sSrc = svc.getCommandSink(Sink.COMMAND_SOURCE); if(sSrc != null) { myCommandProcessor.deregisterSink(Sink.COMMAND_SOURCE, commandNames); } Sink sTgt = svc.getCommandSink(Sink.COMMAND_TARGET); if(sTgt != null) { myCommandProcessor.deregisterSink(Sink.COMMAND_TARGET, commandNames); } // Uninstall the service services.remove(name); } } }
Fixed a bug: when a new node became leader, it didn't set up failure monitors for the orphaned containers.
src/jade/core/ServiceManagerImpl.java
Fixed a bug: when a new node became leader, it didn't set up failure monitors for the orphaned containers.
<ide><path>rc/jade/core/ServiceManagerImpl.java <ide> node.setName(name); <ide> <ide> if(control) { <del> // Set up a failure monitor using the blocking ping... <del> NodeFailureMonitor monitor = new NodeFailureMonitor(node, new NodeEventListener() { <del> <del> // FIXME: Should notify all the interested service slices... <del> <del> public void nodeAdded(Node n) { <del> System.out.println("--- Node <" + n.getName() + "> ADDED ---"); <del> } <del> <del> public void nodeRemoved(Node n) { <del> System.out.println("--- Node <" + n.getName() + "> REMOVED ---"); <del> try { <del> removeRemoteNode(new NodeDescriptor(n.getName(), n), true); <del> } <del> catch(IMTPException imtpe) { <del> imtpe.printStackTrace(); <del> } <del> } <del> <del> public void nodeUnreachable(Node n) { <del> System.out.println("--- Node <" + n.getName() + "> UNREACHABLE ---"); <del> } <del> <del> public void nodeReachable(Node n) { <del> System.out.println("--- Node <" + n.getName() + "> REACHABLE ---"); <del> } <del> <del> }); <del> <del> // Start a new node failure monitor <del> Thread t = new Thread(monitor); <del> t.start(); <add> monitor(n); <ide> } <ide> <ide> // Return the name given to the new container <ide> <ide> } <ide> <add> public void monitor(Node target) { <add> <add> // Set up a failure monitor using the blocking ping... <add> NodeFailureMonitor failureMonitor = new NodeFailureMonitor(target, new NodeEventListener() { <add> <add> // FIXME: Should notify all the interested service slices... <add> <add> public void nodeAdded(Node n) { <add> System.out.println("--- Node <" + n.getName() + "> ADDED ---"); <add> } <add> <add> public void nodeRemoved(Node n) { <add> System.out.println("--- Node <" + n.getName() + "> REMOVED ---"); <add> try { <add> removeRemoteNode(new NodeDescriptor(n.getName(), n), true); <add> } <add> catch(IMTPException imtpe) { <add> imtpe.printStackTrace(); <add> } <add> } <add> <add> public void nodeUnreachable(Node n) { <add> System.out.println("--- Node <" + n.getName() + "> UNREACHABLE ---"); <add> } <add> <add> public void nodeReachable(Node n) { <add> System.out.println("--- Node <" + n.getName() + "> REACHABLE ---"); <add> } <add> <add> }); <add> <add> // Start a new node failure monitor <add> Thread t = new Thread(failureMonitor); <add> t.start(); <add> } <ide> <ide> }
Java
apache-2.0
a8064c8e09e9b3ec8e3f983c3b76834212a7bd88
0
KoriSamui/PlayN,KoriSamui/PlayN,KoriSamui/PlayN,KoriSamui/PlayN
/** * Copyright 2012 The PlayN Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package playn.ios; import cli.System.IntPtr; import cli.OpenTK.Graphics.ES20.All; import cli.OpenTK.Graphics.ES20.GL; import playn.core.gl.GLBuffer; import playn.core.gl.GLProgram; import playn.core.gl.GLShader; import static playn.core.PlayN.log; public class IOSGLProgram implements GLProgram { private final int program, vertexShader, fragmentShader; public IOSGLProgram(IOSGLContext ctx, String vertexSource, String fragmentSource) { int program = 0, vertexShader = 0, fragmentShader = 0; try { program = GL.CreateProgram(); if (program == 0) throw new RuntimeException("Failed to create program: " + GL.GetError()); vertexShader = compileShader(All.wrap(All.VertexShader), vertexSource); GL.AttachShader(program, vertexShader); ctx.checkGLError("Attached vertex shader"); fragmentShader = compileShader(All.wrap(All.FragmentShader), fragmentSource); GL.AttachShader(program, fragmentShader); ctx.checkGLError("Attached fragment shader"); GL.LinkProgram(program); int[] linkStatus = new int[1]; GL.GetProgram(program, All.wrap(All.LinkStatus), linkStatus); if (linkStatus[0] != All.True) { int[] llength = new int[1]; GL.GetProgram(program, All.wrap(All.InfoLogLength), llength); cli.System.Text.StringBuilder log = new cli.System.Text.StringBuilder(llength[0]); GL.GetProgramInfoLog(program, llength[0], llength, log); throw new RuntimeException("Failed to link program: " + log.ToString()); } this.program = program; this.vertexShader = vertexShader; this.fragmentShader = fragmentShader; program = vertexShader = fragmentShader = 0; } finally { if (program != 0) GL.DeleteProgram(program); if (vertexShader != 0) GL.DeleteShader(vertexShader); if (fragmentShader != 0) GL.DeleteShader(program); } } @Override public GLShader.Uniform1f getUniform1f(String name) { final int loc = GL.GetUniformLocation(program, name); return (loc < 0) ? null : new GLShader.Uniform1f() { public void bind(float a) { GL.Uniform1(loc, a); } }; } @Override public GLShader.Uniform2f getUniform2f(String name) { final int loc = GL.GetUniformLocation(program, name); return (loc < 0) ? null : new GLShader.Uniform2f() { public void bind(float a, float b) { GL.Uniform2(loc, a, b); } }; } @Override public GLShader.Uniform3f getUniform3f(String name) { final int loc = GL.GetUniformLocation(program, name); return (loc < 0) ? null : new GLShader.Uniform3f() { public void bind(float a, float b, float c) { GL.Uniform3(loc, a, b, c); } }; } @Override public GLShader.Uniform4f getUniform4f(String name) { final int loc = GL.GetUniformLocation(program, name); return (loc < 0) ? null : new GLShader.Uniform4f() { public void bind(float a, float b, float c, float d) { GL.Uniform4(loc, a, b, c, d); } }; } @Override public GLShader.Uniform1i getUniform1i(String name) { final int loc = GL.GetUniformLocation(program, name); return (loc < 0) ? null : new GLShader.Uniform1i() { public void bind(int a) { GL.Uniform1(loc, a); } }; } @Override public GLShader.Uniform2i getUniform2i(String name) { final int loc = GL.GetUniformLocation(program, name); return (loc < 0) ? null : new GLShader.Uniform2i() { public void bind(int a, int b) { GL.Uniform2(loc, a, b); } }; } @Override public GLShader.Uniform2fv getUniform2fv(String name) { final int loc = GL.GetUniformLocation(program, name); return (loc < 0) ? null : new GLShader.Uniform2fv() { public void bind(GLBuffer.Float data, int count) { IOSGLBuffer.FloatImpl idata = (IOSGLBuffer.FloatImpl) data; idata.position = 0; GL.Uniform2(loc, count, idata.data); } }; } @Override public GLShader.UniformMatrix4fv getUniformMatrix4fv(String name) { final int loc = GL.GetUniformLocation(program, name); return (loc < 0) ? null : new GLShader.UniformMatrix4fv() { public void bind(GLBuffer.Float data, int count) { IOSGLBuffer.FloatImpl idata = (IOSGLBuffer.FloatImpl) data; idata.position = 0; GL.UniformMatrix4(loc, count, false, idata.data); } }; } @Override public GLShader.Attrib getAttrib(String name, final int size, final int type) { final int loc = GL.GetAttribLocation(program, name); return (loc < 0) ? null : new GLShader.Attrib() { public void bind(int stride, int offset) { GL.EnableVertexAttribArray(loc); GL.VertexAttribPointer(loc, size, All.wrap(type), false, stride, new IntPtr(offset)); } }; } @Override public void bind() { GL.UseProgram(program); } @Override public void destroy() { GL.DeleteShader(vertexShader); GL.DeleteShader(fragmentShader); GL.DeleteProgram(program); } private int compileShader(All type, final String shaderSource) { int shader = GL.CreateShader(type); if (shader == 0) throw new RuntimeException("Failed to create shader: " + GL.GetError()); GL.ShaderSource(shader, 1, new String[] { shaderSource }, null); GL.CompileShader(shader); int[] compiled = new int[1]; GL.GetShader(shader, All.wrap(All.CompileStatus), compiled); if (compiled[0] == All.False) { int[] llength = new int[1]; GL.GetShader(shader, All.wrap(All.InfoLogLength), llength); cli.System.Text.StringBuilder log = new cli.System.Text.StringBuilder(llength[0]); GL.GetShaderInfoLog(shader, llength[0], llength, log); GL.DeleteShader(shader); throw new RuntimeException("Failed to compile shader (" + type + "): " + log.ToString()); } return shader; } }
ios/src/playn/ios/IOSGLProgram.java
/** * Copyright 2012 The PlayN Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package playn.ios; import cli.System.IntPtr; import cli.OpenTK.Graphics.ES20.All; import cli.OpenTK.Graphics.ES20.GL; import playn.core.gl.GLBuffer; import playn.core.gl.GLProgram; import playn.core.gl.GLShader; import static playn.core.PlayN.log; public class IOSGLProgram implements GLProgram { private final int program, vertexShader, fragmentShader; public IOSGLProgram(IOSGLContext ctx, String vertexSource, String fragmentSource) { int program = 0, vertexShader = 0, fragmentShader = 0; try { program = GL.CreateProgram(); if (program == 0) throw new RuntimeException("Failed to create program: " + GL.GetError()); vertexShader = compileShader(All.wrap(All.VertexShader), vertexSource); GL.AttachShader(program, vertexShader); ctx.checkGLError("Attached vertex shader"); fragmentShader = compileShader(All.wrap(All.FragmentShader), fragmentSource); GL.AttachShader(program, fragmentShader); ctx.checkGLError("Attached fragment shader"); GL.LinkProgram(program); int[] linkStatus = new int[1]; GL.GetProgram(program, All.wrap(All.LinkStatus), linkStatus); if (linkStatus[0] != All.True) { int[] llength = new int[1]; GL.GetProgram(program, All.wrap(All.InfoLogLength), llength); cli.System.Text.StringBuilder log = new cli.System.Text.StringBuilder(llength[0]); GL.GetProgramInfoLog(program, llength[0], llength, log); throw new RuntimeException("Failed to link program: " + log.ToString()); } this.program = program; this.vertexShader = vertexShader; this.fragmentShader = fragmentShader; program = vertexShader = fragmentShader = 0; } finally { if (program != 0) GL.DeleteProgram(program); if (vertexShader != 0) GL.DeleteShader(vertexShader); if (fragmentShader != 0) GL.DeleteShader(program); } } @Override public GLShader.Uniform1f getUniform1f(String name) { final int loc = GL.GetUniformLocation(program, name); return (loc < 0) ? null : new GLShader.Uniform1f() { public void bind(float a) { GL.Uniform1(loc, a); } }; } @Override public GLShader.Uniform2f getUniform2f(String name) { final int loc = GL.GetUniformLocation(program, name); return (loc < 0) ? null : new GLShader.Uniform2f() { public void bind(float a, float b) { GL.Uniform2(loc, a, b); } }; } @Override public GLShader.Uniform3f getUniform3f(String name) { final int loc = GL.GetUniformLocation(program, name); return (loc < 0) ? null : new GLShader.Uniform3f() { public void bind(float a, float b, float c) { GL.Uniform3(loc, a, b, c); } }; } @Override public GLShader.Uniform4f getUniform4f(String name) { final int loc = GL.GetUniformLocation(program, name); return (loc < 0) ? null : new GLShader.Uniform4f() { public void bind(float a, float b, float c, float d) { GL.Uniform4(loc, a, b, c, d); } }; } @Override public GLShader.Uniform1i getUniform1i(String name) { final int loc = GL.GetUniformLocation(program, name); return (loc < 0) ? null : new GLShader.Uniform1i() { public void bind(int a) { GL.Uniform1(loc, a); } }; } @Override public GLShader.Uniform2i getUniform2i(String name) { final int loc = GL.GetUniformLocation(program, name); return (loc < 0) ? null : new GLShader.Uniform2i() { public void bind(int a, int b) { GL.Uniform2(loc, a, b); } }; } @Override public GLShader.UniformMatrix4fv getUniformMatrix4fv(String name) { final int loc = GL.GetUniformLocation(program, name); return (loc < 0) ? null : new GLShader.UniformMatrix4fv() { public void bind(GLBuffer.Float data, int count) { IOSGLBuffer.FloatImpl idata = (IOSGLBuffer.FloatImpl) data; idata.position = 0; GL.UniformMatrix4(loc, count, false, idata.data); } }; } @Override public GLShader.Attrib getAttrib(String name, final int size, final int type) { final int loc = GL.GetAttribLocation(program, name); return (loc < 0) ? null : new GLShader.Attrib() { public void bind(int stride, int offset) { GL.EnableVertexAttribArray(loc); GL.VertexAttribPointer(loc, size, All.wrap(type), false, stride, new IntPtr(offset)); } }; } @Override public void bind() { GL.UseProgram(program); } @Override public void destroy() { GL.DeleteShader(vertexShader); GL.DeleteShader(fragmentShader); GL.DeleteProgram(program); } private int compileShader(All type, final String shaderSource) { int shader = GL.CreateShader(type); if (shader == 0) throw new RuntimeException("Failed to create shader: " + GL.GetError()); GL.ShaderSource(shader, 1, new String[] { shaderSource }, null); GL.CompileShader(shader); int[] compiled = new int[1]; GL.GetShader(shader, All.wrap(All.CompileStatus), compiled); if (compiled[0] == All.False) { int[] llength = new int[1]; GL.GetShader(shader, All.wrap(All.InfoLogLength), llength); cli.System.Text.StringBuilder log = new cli.System.Text.StringBuilder(llength[0]); GL.GetShaderInfoLog(shader, llength[0], llength, log); GL.DeleteShader(shader); throw new RuntimeException("Failed to compile shader (" + type + "): " + log.ToString()); } return shader; } }
Added missing getUniform2fv.
ios/src/playn/ios/IOSGLProgram.java
Added missing getUniform2fv.
<ide><path>os/src/playn/ios/IOSGLProgram.java <ide> } <ide> <ide> @Override <add> public GLShader.Uniform2fv getUniform2fv(String name) { <add> final int loc = GL.GetUniformLocation(program, name); <add> return (loc < 0) ? null : new GLShader.Uniform2fv() { <add> public void bind(GLBuffer.Float data, int count) { <add> IOSGLBuffer.FloatImpl idata = (IOSGLBuffer.FloatImpl) data; <add> idata.position = 0; <add> GL.Uniform2(loc, count, idata.data); <add> } <add> }; <add> } <add> <add> @Override <ide> public GLShader.UniformMatrix4fv getUniformMatrix4fv(String name) { <ide> final int loc = GL.GetUniformLocation(program, name); <ide> return (loc < 0) ? null : new GLShader.UniformMatrix4fv() {
Java
bsd-3-clause
983f82d554d6f98585c9123d0113480e315ba7f2
0
Polidea/the-missing-android-xml-junit-test-runner
package pl.polidea.instrumentation; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.text.SimpleDateFormat; import java.util.LinkedHashMap; import java.util.Map; import junit.framework.AssertionFailedError; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestListener; import org.xmlpull.v1.XmlSerializer; import android.os.Bundle; import android.test.AndroidTestRunner; import android.test.InstrumentationTestRunner; import android.util.Log; import android.util.Xml; /** * Test runner that should produce Junit-compatible test results. It can be used * to produce output that is parseable by a CI reporting tool which understands * Junit XML format (Jenkins, Hudson, Bamboo ...). * * @author potiuk * */ public class PolideaInstrumentationTestRunner extends InstrumentationTestRunner { private static final String TESTSUITES = "testsuites"; private static final String TESTSUITE = "testsuite"; private static final String ERRORS = "errors"; private static final String FAILURES = "failures"; private static final String ERROR = "errors"; private static final String FAILURE = "failures"; private static final String NAME = "name"; private static final String PACKAGE = "package"; private static final String TESTS = "tests"; private static final String TESTCASE = "testcase"; private static final String CLASSNAME = "classname"; private static final String TIME = "time"; private static final String TIMESTAMP = "timestamp"; private static final String PROPERTIES = "properties"; private static final String SYSTEM_OUT = "system-out"; private static final String SYSTEM_ERR = "system-err"; private static final String TAG = PolideaInstrumentationTestRunner.class.getSimpleName(); private static final String DEFAULT_JUNIT_FILE_POSTFIX = "-TEST.xml"; private String junitOutputDirectory = null; private String junitOutputFilePostfix = null; private boolean junitOutputEnabled; private boolean justCount; private XmlSerializer currentXmlSerializer; public static class TestInfo { public Package thePackage; public Class< ? extends TestCase> testCase; public String name; public Throwable error; public AssertionFailedError failure; public long time; @Override public String toString() { return name + "[" + testCase.getClass() + "] <" + thePackage + ">. Time: " + time + " ms. E<" + error + ">, F <" + failure + ">"; } } public static class TestPackageInfo { public Package thePackage; public Map<Class< ? extends TestCase>, TestCaseInfo> testCaseList = new LinkedHashMap<Class< ? extends TestCase>, TestCaseInfo>(); } public static class TestCaseInfo { public Package thePackage; public Class< ? extends TestCase> testCaseClass; public Map<String, TestInfo> testMap = new LinkedHashMap<String, TestInfo>(); } private final LinkedHashMap<Package, TestCaseInfo> caseMap = new LinkedHashMap<Package, TestCaseInfo>(); /** * The last test class we executed code from. */ private boolean outputEnabled; private AndroidTestRunner runner; private boolean logOnly; private PrintWriter currentFileWriter; private class JunitTestListener implements TestListener { /** * The minimum time we expect a test to take. */ private static final int MINIMUM_TIME = 100; private final ThreadLocal<Long> startTime = new ThreadLocal<Long>(); @Override public void startTest(final Test test) { if (test instanceof TestCase) { Thread.currentThread().setContextClassLoader(test.getClass().getClassLoader()); startTime.set(System.currentTimeMillis()); } } @Override public void endTest(final Test t) { Log.d(TAG, "Ending test " + t); if (t instanceof TestCase) { final TestCase testCase = (TestCase) t; cleanup(testCase); /* * Make sure all tests take at least MINIMUM_TIME to complete. * If they don't, we wait a bit. The Cupcake Binder can't handle * too many operations in a very short time, which causes * headache for the CTS. */ final long timeTaken = System.currentTimeMillis() - startTime.get(); getTestInfo(testCase).time = timeTaken; if (timeTaken < MINIMUM_TIME) { try { Thread.sleep(MINIMUM_TIME - timeTaken); } catch (final InterruptedException ignored) { // We don't care. } } } Log.d(TAG, "Ended test " + t); } @Override public void addError(final Test test, final Throwable t) { if (test instanceof TestCase) { getTestInfo((TestCase) test).error = t; } } @Override public void addFailure(final Test test, final AssertionFailedError f) { if (test instanceof TestCase) { getTestInfo((TestCase) test).failure = f; } } /** * Nulls all non-static reference fields in the given test class. This * method helps us with those test classes that don't have an explicit * tearDown() method. Normally the garbage collector should take care of * everything, but since JUnit keeps references to all test cases, a * little help might be a good idea. * * Note! This is copied from InstrumentationCoreTestRunner in android * code */ private void cleanup(final TestCase test) { Log.d(TAG, "Cleaning up: " + test); Class< ? > clazz = test.getClass(); while (clazz != TestCase.class) { final Field[] fields = clazz.getDeclaredFields(); for (final Field field : fields) { final Field f = field; if (!f.getType().isPrimitive() && !Modifier.isStatic(f.getModifiers())) { try { f.setAccessible(true); f.set(test, null); } catch (final Exception ignored) { // Nothing we can do about it. } } } clazz = clazz.getSuperclass(); } Log.d(TAG, "Cleaned up: " + test); } } private synchronized TestInfo getTestInfo(final TestCase testCase) { final Class< ? extends TestCase> clazz = testCase.getClass(); final Package thePackage = clazz.getPackage(); final String name = testCase.getName(); TestCaseInfo caseInfo = caseMap.get(thePackage); if (caseInfo == null) { caseInfo = new TestCaseInfo(); caseInfo.testCaseClass = testCase.getClass(); caseInfo.thePackage = thePackage; caseMap.put(thePackage, caseInfo); } TestInfo ti = caseInfo.testMap.get(name); if (ti == null) { ti = new TestInfo(); ti.name = name; ti.testCase = testCase.getClass(); ti.thePackage = thePackage; caseInfo.testMap.put(name, ti); } return ti; } public void startFile(final Package p) throws IOException { Log.d(TAG, "Starting Package " + p); final File outputFile = new File(getJunitOutputFilePath(p)); Log.d(TAG, "Writing to file " + outputFile); currentXmlSerializer = Xml.newSerializer(); currentFileWriter = new PrintWriter(outputFile, "UTF-8"); currentXmlSerializer.setOutput(currentFileWriter); currentXmlSerializer.startDocument("UTF-8", null); currentXmlSerializer.startTag(null, TESTSUITES); } private void endFile() throws IOException { Log.d(TAG, "closing file"); try { currentXmlSerializer.endTag(null, TESTSUITES); } finally { currentFileWriter.flush(); currentFileWriter.close(); } } protected String getTimestamp() { final long time = System.currentTimeMillis(); final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); return sdf.format(time); } private void writeClassToFile(final TestCaseInfo tci) throws IllegalArgumentException, IllegalStateException, IOException { final Package thePackage = tci.thePackage; final Class< ? extends TestCase> clazz = tci.testCaseClass; final int tests = tci.testMap.size(); final String timestamp = getTimestamp(); int errors = 0; int failures = 0; int time = 0; for (final TestInfo testInfo : tci.testMap.values()) { if (testInfo.error != null) { errors++; } if (testInfo.failure != null) { failures++; } time += testInfo.time; } currentXmlSerializer.startTag(null, TESTSUITE); currentXmlSerializer.attribute(null, ERRORS, Integer.toString(errors)); currentXmlSerializer.attribute(null, FAILURES, Integer.toString(failures)); currentXmlSerializer.attribute(null, NAME, clazz.getName()); currentXmlSerializer.attribute(null, PACKAGE, thePackage == null ? "" : thePackage.getName()); currentXmlSerializer.attribute(null, TESTS, Integer.toString(tests)); currentXmlSerializer.attribute(null, TIME, Double.toString(time / 1000.0)); currentXmlSerializer.attribute(null, TIMESTAMP, timestamp); for (final TestInfo testInfo : tci.testMap.values()) { writeTestInfo(testInfo); } currentXmlSerializer.startTag(null, PROPERTIES); currentXmlSerializer.endTag(null, PROPERTIES); currentXmlSerializer.startTag(null, SYSTEM_OUT); currentXmlSerializer.endTag(null, SYSTEM_OUT); currentXmlSerializer.startTag(null, SYSTEM_ERR); currentXmlSerializer.endTag(null, SYSTEM_ERR); currentXmlSerializer.endTag(null, TESTSUITE); } private void writeTestInfo(final TestInfo testInfo) throws IllegalArgumentException, IllegalStateException, IOException { currentXmlSerializer.startTag(null, TESTCASE); currentXmlSerializer.attribute(null, CLASSNAME, testInfo.testCase.getName()); currentXmlSerializer.attribute(null, NAME, testInfo.name); currentXmlSerializer.attribute(null, TIME, Double.toString(testInfo.time / 1000.0)); if (testInfo.error != null) { currentXmlSerializer.startTag(null, ERROR); final StringWriter sw = new StringWriter(); final PrintWriter pw = new PrintWriter(sw, true); testInfo.error.printStackTrace(pw); currentXmlSerializer.text(sw.toString()); currentXmlSerializer.endTag(null, ERROR); } if (testInfo.failure != null) { currentXmlSerializer.startTag(null, FAILURE); final StringWriter sw = new StringWriter(); final PrintWriter pw = new PrintWriter(sw, true); testInfo.failure.printStackTrace(pw); currentXmlSerializer.text(sw.toString()); currentXmlSerializer.endTag(null, FAILURE); } currentXmlSerializer.endTag(null, TESTCASE); } private String getJunitOutputFilePath(final Package p) { return junitOutputDirectory + File.separator + (p == null ? "NO_PACKAGE" : p.getName()) + junitOutputFilePostfix; } private void setOutputProperties() { if (junitOutputDirectory == null) { junitOutputDirectory = getTargetContext().getFilesDir().getAbsolutePath(); } if (junitOutputFilePostfix == null) { junitOutputFilePostfix = DEFAULT_JUNIT_FILE_POSTFIX; } } private boolean getBooleanArgument(final Bundle arguments, final String tag, final boolean defaultValue) { final String tagString = arguments.getString(tag); if (tagString == null) { return defaultValue; } return Boolean.parseBoolean(tagString); } @Override public void onCreate(final Bundle arguments) { Log.d(TAG, "Creating the Test Runner with arguments: " + arguments.keySet()); if (arguments != null) { junitOutputEnabled = getBooleanArgument(arguments, "junitXmlOutput", true); junitOutputDirectory = arguments.getString("junitOutputDirectory"); junitOutputFilePostfix = arguments.getString("junitOutputFilePostFix"); justCount = getBooleanArgument(arguments, "count", false); logOnly = getBooleanArgument(arguments, "log", false); } setOutputProperties(); deleteOldFiles(); super.onCreate(arguments); } private void deleteOldFiles() { for (final File f : new File(junitOutputDirectory).listFiles(new FilenameFilter() { @Override public boolean accept(final File dir, final String filename) { return filename.endsWith(junitOutputFilePostfix); } })) { f.delete(); } } @Override public void finish(final int resultCode, final Bundle results) { Log.d(TAG, "Finishing test"); if (outputEnabled) { Log.d(TAG, "Packages: " + caseMap.size()); for (final Package p : caseMap.keySet()) { Log.d(TAG, "Processing package " + p); try { startFile(p); try { final TestCaseInfo tc = caseMap.get(p); writeClassToFile(tc); } finally { endFile(); } } catch (final IOException e) { Log.e(TAG, "Error: " + e, e); } } } super.finish(resultCode, results); } @Override protected AndroidTestRunner getAndroidTestRunner() { Log.d(TAG, "Getting android test runner"); runner = super.getAndroidTestRunner(); if (junitOutputEnabled && !justCount && !logOnly) { Log.d(TAG, "JUnit test output enabled"); outputEnabled = true; runner.addTestListener(new JunitTestListener()); } else { outputEnabled = false; Log.d(TAG, "JUnit test output disabled"); } return runner; } }
src/pl/polidea/instrumentation/PolideaInstrumentationTestRunner.java
package pl.polidea.instrumentation; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.text.SimpleDateFormat; import java.util.LinkedHashMap; import java.util.Map; import junit.framework.AssertionFailedError; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestListener; import org.xmlpull.v1.XmlSerializer; import android.os.Bundle; import android.test.AndroidTestRunner; import android.test.InstrumentationTestRunner; import android.util.Log; import android.util.Xml; /** * Test runner that should produce Junit-compatible test results. It can be used * to produce output that is parseable by a CI reporting tool which understands * Junit XML format (Jenkins, Hudson, Bamboo ...). * * @author potiuk * */ public class PolideaInstrumentationTestRunner extends InstrumentationTestRunner { private static final String TESTSUITES = "testsuites"; private static final String TESTSUITE = "testsuite"; private static final String ERRORS = "errors"; private static final String FAILURES = "failures"; private static final String ERROR = "errors"; private static final String FAILURE = "failures"; private static final String NAME = "name"; private static final String PACKAGE = "package"; private static final String TESTS = "tests"; private static final String TESTCASE = "testcase"; private static final String CLASSNAME = "classname"; private static final String TIME = "time"; private static final String TIMESTAMP = "timestamp"; private static final String PROPERTIES = "properties"; private static final String SYSTEM_OUT = "system-out"; private static final String SYSTEM_ERR = "system-err"; private static final String TAG = PolideaInstrumentationTestRunner.class.getSimpleName(); private static final String DEFAULT_JUNIT_FILE_POSTFIX = "-TEST.xml"; private String junitOutputDirectory = null; private String junitOutputFilePostfix = null; private boolean junitOutputEnabled; private boolean justCount; private XmlSerializer currentXmlSerializer; public static class TestInfo { public Package thePackage; public Class< ? extends TestCase> testCase; public String name; public Throwable error; public AssertionFailedError failure; public long time; @Override public String toString() { return name + "[" + testCase.getClass() + "] <" + thePackage + ">. Time: " + time + " ms. E<" + error + ">, F <" + failure + ">"; } } public static class TestPackageInfo { public Package thePackage; public Map<Class< ? extends TestCase>, TestCaseInfo> testCaseList = new LinkedHashMap<Class< ? extends TestCase>, TestCaseInfo>(); } public static class TestCaseInfo { public Package thePackage; public Class< ? extends TestCase> testCaseClass; public Map<String, TestInfo> testMap = new LinkedHashMap<String, TestInfo>(); } private final LinkedHashMap<Package, TestCaseInfo> caseMap = new LinkedHashMap<Package, TestCaseInfo>(); /** * The last test class we executed code from. */ private boolean outputEnabled; private AndroidTestRunner runner; private boolean logOnly; private PrintWriter currentFileWriter; private class JunitTestListener implements TestListener { /** * The minimum time we expect a test to take. */ private static final int MINIMUM_TIME = 100; private final ThreadLocal<Long> startTime = new ThreadLocal<Long>(); @Override public void startTest(final Test test) { if (test instanceof TestCase) { Thread.currentThread().setContextClassLoader(test.getClass().getClassLoader()); startTime.set(System.currentTimeMillis()); } } @Override public void endTest(final Test t) { Log.d(TAG, "Ending test " + t); if (t instanceof TestCase) { final TestCase testCase = (TestCase) t; cleanup(testCase); /* * Make sure all tests take at least MINIMUM_TIME to complete. * If they don't, we wait a bit. The Cupcake Binder can't handle * too many operations in a very short time, which causes * headache for the CTS. */ final long timeTaken = System.currentTimeMillis() - startTime.get(); getTestInfo(testCase).time = timeTaken; if (timeTaken < MINIMUM_TIME) { try { Thread.sleep(MINIMUM_TIME - timeTaken); } catch (final InterruptedException ignored) { // We don't care. } } } Log.d(TAG, "Ended test " + t); } @Override public void addError(final Test test, final Throwable t) { if (test instanceof TestCase) { getTestInfo((TestCase) test).error = t; } } @Override public void addFailure(final Test test, final AssertionFailedError f) { if (test instanceof TestCase) { getTestInfo((TestCase) test).failure = f; } } /** * Nulls all non-static reference fields in the given test class. This * method helps us with those test classes that don't have an explicit * tearDown() method. Normally the garbage collector should take care of * everything, but since JUnit keeps references to all test cases, a * little help might be a good idea. * * Note! This is copied from InstrumentationCoreTestRunner in android * code */ private void cleanup(final TestCase test) { Log.d(TAG, "Cleaning up: " + test); Class< ? > clazz = test.getClass(); while (clazz != TestCase.class) { final Field[] fields = clazz.getDeclaredFields(); for (final Field field : fields) { final Field f = field; if (!f.getType().isPrimitive() && !Modifier.isStatic(f.getModifiers())) { try { f.setAccessible(true); f.set(test, null); } catch (final Exception ignored) { // Nothing we can do about it. } } } clazz = clazz.getSuperclass(); } Log.d(TAG, "Cleaned up: " + test); } } private synchronized TestInfo getTestInfo(final TestCase testCase) { final Class< ? extends TestCase> clazz = testCase.getClass(); final Package thePackage = clazz.getPackage(); final String name = testCase.getName(); TestCaseInfo caseInfo = caseMap.get(thePackage); if (caseInfo == null) { caseInfo = new TestCaseInfo(); caseInfo.testCaseClass = testCase.getClass(); caseInfo.thePackage = thePackage; caseMap.put(thePackage, caseInfo); } TestInfo ti = caseInfo.testMap.get(name); if (ti == null) { ti = new TestInfo(); ti.name = name; ti.testCase = testCase.getClass(); ti.thePackage = thePackage; caseInfo.testMap.put(name, ti); } return ti; } public void startFile(final Package p) throws IOException { Log.d(TAG, "Starting Package " + p); final File outputFile = new File(getJunitOutputFilePath(p)); Log.d(TAG, "Writing to file " + outputFile); currentXmlSerializer = Xml.newSerializer(); currentFileWriter = new PrintWriter(outputFile, "UTF-8"); currentXmlSerializer.setOutput(currentFileWriter); currentXmlSerializer.startDocument("UTF-8", null); currentXmlSerializer.startTag(null, TESTSUITES); } private void endFile() throws IOException { Log.d(TAG, "closing file"); try { currentXmlSerializer.endTag(null, TESTSUITES); } finally { currentFileWriter.flush(); currentFileWriter.close(); } } protected String getTimestamp() { final long time = System.currentTimeMillis(); final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); return sdf.format(time); } private void writeClassToFile(final TestCaseInfo tci) throws IllegalArgumentException, IllegalStateException, IOException { final Package thePackage = tci.thePackage; final Class< ? extends TestCase> clazz = tci.testCaseClass; final int tests = tci.testMap.size(); final String timestamp = getTimestamp(); int errors = 0; int failures = 0; int time = 0; for (final TestInfo testInfo : tci.testMap.values()) { if (testInfo.error != null) { errors++; } if (testInfo.failure != null) { failures++; } time += testInfo.time; } currentXmlSerializer.startTag(null, TESTSUITE); currentXmlSerializer.attribute(null, ERRORS, Integer.toString(errors)); currentXmlSerializer.attribute(null, FAILURES, Integer.toString(failures)); currentXmlSerializer.attribute(null, NAME, clazz.getName()); currentXmlSerializer.attribute(null, PACKAGE, thePackage == null ? "" : thePackage.getName()); currentXmlSerializer.attribute(null, TESTS, Integer.toString(tests)); currentXmlSerializer.attribute(null, TIME, Double.toString(time / 1000.0)); currentXmlSerializer.attribute(null, TIMESTAMP, timestamp); for (final TestInfo testInfo : tci.testMap.values()) { writeTestInfo(testInfo); } currentXmlSerializer.startTag(null, PROPERTIES); currentXmlSerializer.endTag(null, PROPERTIES); currentXmlSerializer.startTag(null, SYSTEM_OUT); currentXmlSerializer.endTag(null, SYSTEM_OUT); currentXmlSerializer.startTag(null, SYSTEM_ERR); currentXmlSerializer.endTag(null, SYSTEM_ERR); currentXmlSerializer.endTag(null, TESTSUITE); } private void writeTestInfo(final TestInfo testInfo) throws IllegalArgumentException, IllegalStateException, IOException { currentXmlSerializer.startTag(null, TESTCASE); currentXmlSerializer.attribute(null, CLASSNAME, testInfo.testCase.getName()); currentXmlSerializer.attribute(null, NAME, testInfo.name); currentXmlSerializer.attribute(null, TIME, Double.toString(testInfo.time / 1000.0)); if (testInfo.error != null) { currentXmlSerializer.startTag(null, ERROR); final StringWriter sw = new StringWriter(); final PrintWriter pw = new PrintWriter(sw, true); testInfo.error.printStackTrace(pw); currentXmlSerializer.text(sw.toString()); currentXmlSerializer.endTag(null, ERROR); } if (testInfo.failure != null) { currentXmlSerializer.startTag(null, FAILURE); final StringWriter sw = new StringWriter(); final PrintWriter pw = new PrintWriter(sw, true); testInfo.failure.printStackTrace(pw); currentXmlSerializer.text(sw.toString()); currentXmlSerializer.endTag(null, FAILURE); } currentXmlSerializer.endTag(null, TESTCASE); } private String getJunitOutputFilePath(final Package p) { return junitOutputDirectory + File.separator + p == null ? "NO_PACKAGE" : p.getName() + junitOutputFilePostfix; } private void setOutputProperties() { if (junitOutputDirectory == null) { junitOutputDirectory = getTargetContext().getFilesDir().getAbsolutePath(); } if (junitOutputFilePostfix == null) { junitOutputFilePostfix = DEFAULT_JUNIT_FILE_POSTFIX; } } private boolean getBooleanArgument(final Bundle arguments, final String tag, final boolean defaultValue) { final String tagString = arguments.getString(tag); if (tagString == null) { return defaultValue; } return Boolean.parseBoolean(tagString); } @Override public void onCreate(final Bundle arguments) { Log.d(TAG, "Creating the Test Runner with arguments: " + arguments.keySet()); if (arguments != null) { junitOutputEnabled = getBooleanArgument(arguments, "junitXmlOutput", true); junitOutputDirectory = arguments.getString("junitOutputDirectory"); junitOutputFilePostfix = arguments.getString("junitOutputFilePostFix"); justCount = getBooleanArgument(arguments, "count", false); logOnly = getBooleanArgument(arguments, "log", false); } setOutputProperties(); deleteOldFiles(); super.onCreate(arguments); } private void deleteOldFiles() { for (final File f : new File(junitOutputDirectory).listFiles(new FilenameFilter() { @Override public boolean accept(final File dir, final String filename) { return filename.endsWith(junitOutputFilePostfix); } })) { f.delete(); } } @Override public void finish(final int resultCode, final Bundle results) { Log.d(TAG, "Finishing test"); if (outputEnabled) { Log.d(TAG, "Packages: " + caseMap.size()); for (final Package p : caseMap.keySet()) { Log.d(TAG, "Processing package " + p); try { startFile(p); try { final TestCaseInfo tc = caseMap.get(p); writeClassToFile(tc); } finally { endFile(); } } catch (final IOException e) { Log.e(TAG, "Error: " + e, e); } } } super.finish(resultCode, results); } @Override protected AndroidTestRunner getAndroidTestRunner() { Log.d(TAG, "Getting android test runner"); runner = super.getAndroidTestRunner(); if (junitOutputEnabled && !justCount && !logOnly) { Log.d(TAG, "JUnit test output enabled"); outputEnabled = true; runner.addTestListener(new JunitTestListener()); } else { outputEnabled = false; Log.d(TAG, "JUnit test output disabled"); } return runner; } }
Final NPE Fix
src/pl/polidea/instrumentation/PolideaInstrumentationTestRunner.java
Final NPE Fix
<ide><path>rc/pl/polidea/instrumentation/PolideaInstrumentationTestRunner.java <ide> } <ide> <ide> private String getJunitOutputFilePath(final Package p) { <del> return junitOutputDirectory + File.separator + p == null ? "NO_PACKAGE" : p.getName() + junitOutputFilePostfix; <add> return junitOutputDirectory + File.separator + (p == null ? "NO_PACKAGE" : p.getName()) <add> + junitOutputFilePostfix; <ide> } <ide> <ide> private void setOutputProperties() {
Java
apache-2.0
f4570710c18e8c99b9cd6aed6595d77f75484827
0
scottfrederick/spring-boot,zhanhb/spring-boot,tiarebalbi/spring-boot,zhanhb/spring-boot,ptahchiev/spring-boot,dreis2211/spring-boot,hello2009chen/spring-boot,bclozel/spring-boot,ihoneymon/spring-boot,philwebb/spring-boot,eddumelendez/spring-boot,tiarebalbi/spring-boot,ilayaperumalg/spring-boot,philwebb/spring-boot,vpavic/spring-boot,wilkinsona/spring-boot,donhuvy/spring-boot,tiarebalbi/spring-boot,vpavic/spring-boot,ptahchiev/spring-boot,mbenson/spring-boot,joshiste/spring-boot,yangdd1205/spring-boot,isopov/spring-boot,NetoDevel/spring-boot,shakuzen/spring-boot,philwebb/spring-boot,zhanhb/spring-boot,tiarebalbi/spring-boot,aahlenst/spring-boot,michael-simons/spring-boot,michael-simons/spring-boot,scottfrederick/spring-boot,joshiste/spring-boot,NetoDevel/spring-boot,hello2009chen/spring-boot,lburgazzoli/spring-boot,NetoDevel/spring-boot,mdeinum/spring-boot,felipeg48/spring-boot,michael-simons/spring-boot,mbenson/spring-boot,mdeinum/spring-boot,chrylis/spring-boot,kdvolder/spring-boot,scottfrederick/spring-boot,kdvolder/spring-boot,htynkn/spring-boot,isopov/spring-boot,isopov/spring-boot,aahlenst/spring-boot,habuma/spring-boot,vpavic/spring-boot,jxblum/spring-boot,rweisleder/spring-boot,aahlenst/spring-boot,mbenson/spring-boot,lburgazzoli/spring-boot,chrylis/spring-boot,scottfrederick/spring-boot,ilayaperumalg/spring-boot,habuma/spring-boot,zhanhb/spring-boot,rweisleder/spring-boot,chrylis/spring-boot,ptahchiev/spring-boot,wilkinsona/spring-boot,shakuzen/spring-boot,hello2009chen/spring-boot,eddumelendez/spring-boot,ihoneymon/spring-boot,kdvolder/spring-boot,wilkinsona/spring-boot,habuma/spring-boot,dreis2211/spring-boot,tiarebalbi/spring-boot,mbenson/spring-boot,ihoneymon/spring-boot,rweisleder/spring-boot,royclarkson/spring-boot,isopov/spring-boot,joshiste/spring-boot,htynkn/spring-boot,felipeg48/spring-boot,ihoneymon/spring-boot,royclarkson/spring-boot,dreis2211/spring-boot,Buzzardo/spring-boot,tsachev/spring-boot,drumonii/spring-boot,eddumelendez/spring-boot,dreis2211/spring-boot,vpavic/spring-boot,chrylis/spring-boot,ihoneymon/spring-boot,lburgazzoli/spring-boot,joshiste/spring-boot,eddumelendez/spring-boot,michael-simons/spring-boot,donhuvy/spring-boot,ilayaperumalg/spring-boot,spring-projects/spring-boot,tsachev/spring-boot,shakuzen/spring-boot,htynkn/spring-boot,isopov/spring-boot,NetoDevel/spring-boot,bclozel/spring-boot,shakuzen/spring-boot,felipeg48/spring-boot,bclozel/spring-boot,jxblum/spring-boot,rweisleder/spring-boot,eddumelendez/spring-boot,vpavic/spring-boot,ilayaperumalg/spring-boot,shakuzen/spring-boot,Buzzardo/spring-boot,ilayaperumalg/spring-boot,felipeg48/spring-boot,yangdd1205/spring-boot,spring-projects/spring-boot,zhanhb/spring-boot,felipeg48/spring-boot,joshiste/spring-boot,spring-projects/spring-boot,Buzzardo/spring-boot,spring-projects/spring-boot,drumonii/spring-boot,joshiste/spring-boot,philwebb/spring-boot,bclozel/spring-boot,dreis2211/spring-boot,aahlenst/spring-boot,bclozel/spring-boot,habuma/spring-boot,mbenson/spring-boot,royclarkson/spring-boot,wilkinsona/spring-boot,mdeinum/spring-boot,htynkn/spring-boot,habuma/spring-boot,royclarkson/spring-boot,ilayaperumalg/spring-boot,michael-simons/spring-boot,jxblum/spring-boot,drumonii/spring-boot,rweisleder/spring-boot,mdeinum/spring-boot,tsachev/spring-boot,donhuvy/spring-boot,lburgazzoli/spring-boot,yangdd1205/spring-boot,kdvolder/spring-boot,kdvolder/spring-boot,tiarebalbi/spring-boot,wilkinsona/spring-boot,scottfrederick/spring-boot,eddumelendez/spring-boot,NetoDevel/spring-boot,mdeinum/spring-boot,dreis2211/spring-boot,habuma/spring-boot,hello2009chen/spring-boot,mbenson/spring-boot,ptahchiev/spring-boot,htynkn/spring-boot,ptahchiev/spring-boot,mdeinum/spring-boot,aahlenst/spring-boot,Buzzardo/spring-boot,jxblum/spring-boot,ptahchiev/spring-boot,tsachev/spring-boot,jxblum/spring-boot,drumonii/spring-boot,wilkinsona/spring-boot,spring-projects/spring-boot,isopov/spring-boot,Buzzardo/spring-boot,chrylis/spring-boot,ihoneymon/spring-boot,donhuvy/spring-boot,tsachev/spring-boot,bclozel/spring-boot,felipeg48/spring-boot,chrylis/spring-boot,drumonii/spring-boot,tsachev/spring-boot,Buzzardo/spring-boot,michael-simons/spring-boot,donhuvy/spring-boot,scottfrederick/spring-boot,shakuzen/spring-boot,philwebb/spring-boot,htynkn/spring-boot,royclarkson/spring-boot,spring-projects/spring-boot,aahlenst/spring-boot,hello2009chen/spring-boot,lburgazzoli/spring-boot,philwebb/spring-boot,rweisleder/spring-boot,jxblum/spring-boot,drumonii/spring-boot,zhanhb/spring-boot,kdvolder/spring-boot,donhuvy/spring-boot,vpavic/spring-boot
/* * Copyright 2012-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.autoconfigure.web.servlet; import javax.servlet.Servlet; import javax.servlet.ServletRequest; import io.undertow.Undertow; import org.apache.catalina.startup.Tomcat; import org.apache.coyote.UpgradeProtocol; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.util.Loader; import org.eclipse.jetty.webapp.WebAppContext; import org.xnio.SslClientAuthMode; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.boot.autoconfigure.AutoConfigureOrder; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication.Type; import org.springframework.boot.autoconfigure.condition.SearchStrategy; import org.springframework.boot.autoconfigure.web.ServerProperties; import org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration.BeanPostProcessorsRegistrar; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.web.embedded.jetty.JettyServletWebServerFactory; import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; import org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory; import org.springframework.boot.web.server.ErrorPageRegistrarBeanPostProcessor; import org.springframework.boot.web.server.WebServerFactoryCustomizerBeanPostProcessor; import org.springframework.boot.web.servlet.server.ServletWebServerFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.context.annotation.ImportBeanDefinitionRegistrar; import org.springframework.core.Ordered; import org.springframework.core.type.AnnotationMetadata; import org.springframework.util.ObjectUtils; /** * {@link EnableAutoConfiguration Auto-configuration} for servlet web servers. * * @author Phillip Webb * @author Dave Syer * @author Ivan Sopov * @author Brian Clozel * @author Stephane Nicoll */ @AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE) @Configuration @ConditionalOnClass(ServletRequest.class) @ConditionalOnWebApplication(type = Type.SERVLET) @EnableConfigurationProperties(ServerProperties.class) @Import(BeanPostProcessorsRegistrar.class) public class ServletWebServerFactoryAutoConfiguration { @Bean @ConditionalOnMissingBean public DefaultServletWebServerFactoryCustomizer serverPropertiesWebServerFactoryCustomizer( ServerProperties serverProperties) { return new DefaultServletWebServerFactoryCustomizer(serverProperties); } /** * Nested configuration if Tomcat is being used. */ @Configuration @ConditionalOnClass({ Servlet.class, Tomcat.class, UpgradeProtocol.class }) @ConditionalOnMissingBean(value = ServletWebServerFactory.class, search = SearchStrategy.CURRENT) public static class EmbeddedTomcat { @Bean public TomcatServletWebServerFactory tomcatServletWebServerFactory() { return new TomcatServletWebServerFactory(); } } /** * Nested configuration if Jetty is being used. */ @Configuration @ConditionalOnClass({ Servlet.class, Server.class, Loader.class, WebAppContext.class }) @ConditionalOnMissingBean(value = ServletWebServerFactory.class, search = SearchStrategy.CURRENT) public static class EmbeddedJetty { @Bean public JettyServletWebServerFactory JettyServletWebServerFactory() { return new JettyServletWebServerFactory(); } } /** * Nested configuration if Undertow is being used. */ @Configuration @ConditionalOnClass({ Servlet.class, Undertow.class, SslClientAuthMode.class }) @ConditionalOnMissingBean(value = ServletWebServerFactory.class, search = SearchStrategy.CURRENT) public static class EmbeddedUndertow { @Bean public UndertowServletWebServerFactory undertowServletWebServerFactory() { return new UndertowServletWebServerFactory(); } } /** * Registers a {@link WebServerFactoryCustomizerBeanPostProcessor}. Registered via * {@link ImportBeanDefinitionRegistrar} for early registration. */ public static class BeanPostProcessorsRegistrar implements ImportBeanDefinitionRegistrar, BeanFactoryAware { private ConfigurableListableBeanFactory beanFactory; @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { if (beanFactory instanceof ConfigurableListableBeanFactory) { this.beanFactory = (ConfigurableListableBeanFactory) beanFactory; } } @Override public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { if (this.beanFactory == null) { return; } registerSyntheticBeanIfMissing(registry, "webServerFactoryCustomizerBeanPostProcessor", WebServerFactoryCustomizerBeanPostProcessor.class); registerSyntheticBeanIfMissing(registry, "errorPageRegistrarBeanPostProcessor", ErrorPageRegistrarBeanPostProcessor.class); } private void registerSyntheticBeanIfMissing(BeanDefinitionRegistry registry, String name, Class<?> beanClass) { if (ObjectUtils.isEmpty( this.beanFactory.getBeanNamesForType(beanClass, true, false))) { RootBeanDefinition beanDefinition = new RootBeanDefinition(beanClass); beanDefinition.setSynthetic(true); registry.registerBeanDefinition(name, beanDefinition); } } } }
spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/ServletWebServerFactoryAutoConfiguration.java
/* * Copyright 2012-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.autoconfigure.web.servlet; import javax.servlet.Servlet; import javax.servlet.ServletRequest; import io.undertow.Undertow; import org.apache.catalina.startup.Tomcat; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.util.Loader; import org.eclipse.jetty.webapp.WebAppContext; import org.xnio.SslClientAuthMode; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.boot.autoconfigure.AutoConfigureOrder; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication.Type; import org.springframework.boot.autoconfigure.condition.SearchStrategy; import org.springframework.boot.autoconfigure.web.ServerProperties; import org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration.BeanPostProcessorsRegistrar; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.web.embedded.jetty.JettyServletWebServerFactory; import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; import org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory; import org.springframework.boot.web.server.ErrorPageRegistrarBeanPostProcessor; import org.springframework.boot.web.server.WebServerFactoryCustomizerBeanPostProcessor; import org.springframework.boot.web.servlet.server.ServletWebServerFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.context.annotation.ImportBeanDefinitionRegistrar; import org.springframework.core.Ordered; import org.springframework.core.type.AnnotationMetadata; import org.springframework.util.ObjectUtils; /** * {@link EnableAutoConfiguration Auto-configuration} for servlet web servers. * * @author Phillip Webb * @author Dave Syer * @author Ivan Sopov * @author Brian Clozel * @author Stephane Nicoll */ @AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE) @Configuration @ConditionalOnClass(ServletRequest.class) @ConditionalOnWebApplication(type = Type.SERVLET) @EnableConfigurationProperties(ServerProperties.class) @Import(BeanPostProcessorsRegistrar.class) public class ServletWebServerFactoryAutoConfiguration { @Bean @ConditionalOnMissingBean public DefaultServletWebServerFactoryCustomizer serverPropertiesWebServerFactoryCustomizer( ServerProperties serverProperties) { return new DefaultServletWebServerFactoryCustomizer(serverProperties); } /** * Nested configuration if Tomcat is being used. */ @Configuration @ConditionalOnClass({ Servlet.class, Tomcat.class }) @ConditionalOnMissingBean(value = ServletWebServerFactory.class, search = SearchStrategy.CURRENT) public static class EmbeddedTomcat { @Bean public TomcatServletWebServerFactory tomcatServletWebServerFactory() { return new TomcatServletWebServerFactory(); } } /** * Nested configuration if Jetty is being used. */ @Configuration @ConditionalOnClass({ Servlet.class, Server.class, Loader.class, WebAppContext.class }) @ConditionalOnMissingBean(value = ServletWebServerFactory.class, search = SearchStrategy.CURRENT) public static class EmbeddedJetty { @Bean public JettyServletWebServerFactory JettyServletWebServerFactory() { return new JettyServletWebServerFactory(); } } /** * Nested configuration if Undertow is being used. */ @Configuration @ConditionalOnClass({ Servlet.class, Undertow.class, SslClientAuthMode.class }) @ConditionalOnMissingBean(value = ServletWebServerFactory.class, search = SearchStrategy.CURRENT) public static class EmbeddedUndertow { @Bean public UndertowServletWebServerFactory undertowServletWebServerFactory() { return new UndertowServletWebServerFactory(); } } /** * Registers a {@link WebServerFactoryCustomizerBeanPostProcessor}. Registered via * {@link ImportBeanDefinitionRegistrar} for early registration. */ public static class BeanPostProcessorsRegistrar implements ImportBeanDefinitionRegistrar, BeanFactoryAware { private ConfigurableListableBeanFactory beanFactory; @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { if (beanFactory instanceof ConfigurableListableBeanFactory) { this.beanFactory = (ConfigurableListableBeanFactory) beanFactory; } } @Override public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { if (this.beanFactory == null) { return; } registerSyntheticBeanIfMissing(registry, "webServerFactoryCustomizerBeanPostProcessor", WebServerFactoryCustomizerBeanPostProcessor.class); registerSyntheticBeanIfMissing(registry, "errorPageRegistrarBeanPostProcessor", ErrorPageRegistrarBeanPostProcessor.class); } private void registerSyntheticBeanIfMissing(BeanDefinitionRegistry registry, String name, Class<?> beanClass) { if (ObjectUtils.isEmpty( this.beanFactory.getBeanNamesForType(beanClass, true, false))) { RootBeanDefinition beanDefinition = new RootBeanDefinition(beanClass); beanDefinition.setSynthetic(true); registry.registerBeanDefinition(name, beanDefinition); } } } }
Make Tomcat auto-config back off when UpgradeProtocol is absent Closes gh-10960
spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/ServletWebServerFactoryAutoConfiguration.java
Make Tomcat auto-config back off when UpgradeProtocol is absent
<ide><path>pring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/ServletWebServerFactoryAutoConfiguration.java <ide> <ide> import io.undertow.Undertow; <ide> import org.apache.catalina.startup.Tomcat; <add>import org.apache.coyote.UpgradeProtocol; <ide> import org.eclipse.jetty.server.Server; <ide> import org.eclipse.jetty.util.Loader; <ide> import org.eclipse.jetty.webapp.WebAppContext; <ide> * Nested configuration if Tomcat is being used. <ide> */ <ide> @Configuration <del> @ConditionalOnClass({ Servlet.class, Tomcat.class }) <add> @ConditionalOnClass({ Servlet.class, Tomcat.class, UpgradeProtocol.class }) <ide> @ConditionalOnMissingBean(value = ServletWebServerFactory.class, search = SearchStrategy.CURRENT) <ide> public static class EmbeddedTomcat { <ide>
JavaScript
mit
f7e836358cfe8c1bdd6d39d0ecc7e51b98510139
0
silklabs/silk,silklabs/silk,silklabs/silk,silklabs/silk,silklabs/silk,silklabs/silk
'use strict'; const path = require('path'); const fs = require('fs'); const findPackage = require('./src/find_package.js'); const webpack = require('webpack'); const resolve = require('resolve'); const mkdirp = require('mkdirp'); // We must place our files in a special folder for integration /w the android // build system. const destination = process.env.SILK_BUILDJS_DEST; const modulePath = findPackage(process.env.SILK_BUILDJS_SOURCE); const pkg = require(path.join(modulePath, 'package.json')); const localWebpack = path.join(modulePath, 'webpack.config.js'); let babelCache; if (!process.env.BABEL_CACHE || process.env.BABEL_CACHE === '1') { babelCache = path.join(destination, '../.babelcache'); mkdirp.sync(babelCache); } else { console.log('~ babel cache has been disabled ~'); babelCache = false; } const name = pkg.name; let main = pkg.main || './index.js'; if (!path.extname(main)) { main += '.js'; } if (main.indexOf('./') !== 0) { main = `./${main}`; } const absMain = path.resolve(modulePath, main); let mainDir; try { mainDir = fs.realpathSync(path.dirname(absMain)); } catch (err) { mainDir = path.dirname(absMain); } // XXX: Would be nicer to abort this in the bash script rather than after we // have booted up node here... if ( main.indexOf('build/Release') === 0 || main.indexOf('./build/Release') === 0 || /\.node$/.test(main) ) { console.log(`Module contains no JS main skipping webpack ...`); process.exit(0); } if (!main) { throw new Error(`package.json must have main in ${process.cwd()}`); } const externals = [ // TODO: auto generate these ... 'base_version', 'bleno', 'mic', 'noble', 'node-hid', 'node-webrtc', 'opencv', 'segfault-handler', 'silk-alog', 'silk-battery', 'silk-camera', 'silk-core-version', 'silk-cv', 'silk-dialog-engine', 'silk-gc1', 'silk-input', 'silk-kws', 'silk-lights', 'silk-modwatcher', 'silk-movie', 'silk-netstatus', 'silk-ntp', 'silk-properties', 'silk-say', 'silk-sensors', 'silk-sysutils', 'silk-vad', 'silk-vibrator', 'silk-volume', 'silk-wifi', 'v8-profiler', 'kissfft', 'silk-caffe', (context, request, callback) => { if (resolve.isCore(request)) { callback(null, true); return; } // For extra fun node will allow resolving .main without a ./ this behavior // makes .main look nicer but is completely different than how requiring // without a specific path is handled elsewhere... To ensure we don't // accidentally resolve a node module to a local file we handle this case // very specifically. if (context === modulePath && pkg.main === request) { const resolvedPath = path.resolve(context, request); if (!fs.existsSync(resolvedPath)) { callback(new Error(`${modulePath} has a .main which is missing ...`)); return; } } // Handle path rewriting for native modules if ( /\.node$/.test(request) || request.indexOf('build/Release') !== -1 ) { if (path.isAbsolute(request)) { callback(null, true); return; } const absExternalPath = path.resolve(context, request); let relativeExternalPath = path.relative(mainDir, absExternalPath); if (relativeExternalPath.indexOf('.') !== 0) { relativeExternalPath = `./${relativeExternalPath}`; } callback(null, relativeExternalPath); return; } resolve(request, { basedir: context, package: pkg, extensions: ['.js', '.json'], }, (err, resolvedPath) => { if (err) { console.log(`Missing module imported from ${context} (${request})`); callback(null, true); return; } callback(null, false); }); } ]; const entry = {}; entry[main] = main; const config = { context: modulePath, externals, target: 'node', node: { __dirname: false, __filename: false, }, devtool: 'source-map', entry, output: { path: path.join(destination), libraryTarget: 'commonjs2', filename: `[name]`, }, resolve: { extensions: ['', '.js', '.json'], // Common "gothcha" modules ... alias: { 'any-promise': require.resolve('./shims/any-promise.js'), 'json3': require.resolve('./shims/json3.js'), }, }, babel: { cacheDirectory: babelCache, presets: [ require('babel-preset-silk-node4'), ], }, module : { loaders: [ { test: /\.json$/, loader: require.resolve('json-loader') }, { test: /\.js$/, loader: require.resolve('babel-loader'), query: { babelrc: false, } } ] } } if (fs.existsSync(localWebpack)) { console.log(`${localWebpack} found agumenting buildjs ...`); const rules = Object.assign({}, require(localWebpack)); if (rules.externals && Array.isArray(rules.externals)) { // Order is important here the rules should be ordered such that the // webpack.config comes from the module first and our global rules second. config.externals = rules.externals.concat(config.externals); delete rules.externals; } Object.assign(config, rules); } module.exports = config;
buildjs/webpack.config.js
'use strict'; const path = require('path'); const fs = require('fs'); const findPackage = require('./src/find_package.js'); const webpack = require('webpack'); const resolve = require('resolve'); const mkdirp = require('mkdirp'); // We must place our files in a special folder for integration /w the android // build system. const destination = process.env.SILK_BUILDJS_DEST; const modulePath = findPackage(process.env.SILK_BUILDJS_SOURCE); const pkg = require(path.join(modulePath, 'package.json')); const localWebpack = path.join(modulePath, 'webpack.config.js'); let babelCache; if (!process.env.BABEL_CACHE || process.env.BABEL_CACHE === '1') { babelCache = path.join(destination, '../.babelcache'); mkdirp.sync(babelCache); } else { console.log('~ babel cache has been disabled ~'); babelCache = false; } const name = pkg.name; let main = pkg.main || './index.js'; if (!path.extname(main)) { main += '.js'; } if (main.indexOf('./') !== 0) { main = `./${main}`; } const absMain = path.resolve(modulePath, main); let mainDir; try { mainDir = fs.realpathSync(path.dirname(absMain)); } catch (err) { mainDir = path.dirname(absMain); } // XXX: Would be nicer to abort this in the bash script rather than after we // have booted up node here... if ( main.indexOf('build/Release') === 0 || main.indexOf('./build/Release') === 0 || /\.node$/.test(main) ) { console.log(`Module contains no JS main skipping webpack ...`); process.exit(0); } if (!main) { throw new Error(`package.json must have main in ${process.cwd()}`); } const externals = [ // TODO: auto generate these ... 'base_version', 'bleno', 'mic', 'noble', 'node-hid', 'node-webrtc', 'opencv', 'segfault-handler', 'silk-alog', 'silk-battery', 'silk-camera', 'silk-core-version', 'silk-cv', 'silk-dialog-engine', 'silk-gc1', 'silk-input', 'silk-kws', 'silk-lights', 'silk-modwatcher', 'silk-movie', 'silk-netstatus', 'silk-ntp', 'silk-properties', 'silk-sensors', 'silk-sysutils', 'silk-vad', 'silk-vibrator', 'silk-volume', 'silk-wifi', 'v8-profiler', 'kissfft', 'silk-caffe', (context, request, callback) => { if (resolve.isCore(request)) { callback(null, true); return; } // For extra fun node will allow resolving .main without a ./ this behavior // makes .main look nicer but is completely different than how requiring // without a specific path is handled elsewhere... To ensure we don't // accidentally resolve a node module to a local file we handle this case // very specifically. if (context === modulePath && pkg.main === request) { const resolvedPath = path.resolve(context, request); if (!fs.existsSync(resolvedPath)) { callback(new Error(`${modulePath} has a .main which is missing ...`)); return; } } // Handle path rewriting for native modules if ( /\.node$/.test(request) || request.indexOf('build/Release') !== -1 ) { if (path.isAbsolute(request)) { callback(null, true); return; } const absExternalPath = path.resolve(context, request); let relativeExternalPath = path.relative(mainDir, absExternalPath); if (relativeExternalPath.indexOf('.') !== 0) { relativeExternalPath = `./${relativeExternalPath}`; } callback(null, relativeExternalPath); return; } resolve(request, { basedir: context, package: pkg, extensions: ['.js', '.json'], }, (err, resolvedPath) => { if (err) { console.log(`Missing module imported from ${context} (${request})`); callback(null, true); return; } callback(null, false); }); } ]; const entry = {}; entry[main] = main; const config = { context: modulePath, externals, target: 'node', node: { __dirname: false, __filename: false, }, devtool: 'source-map', entry, output: { path: path.join(destination), libraryTarget: 'commonjs2', filename: `[name]`, }, resolve: { extensions: ['', '.js', '.json'], // Common "gothcha" modules ... alias: { 'any-promise': require.resolve('./shims/any-promise.js'), 'json3': require.resolve('./shims/json3.js'), }, }, babel: { cacheDirectory: babelCache, presets: [ require('babel-preset-silk-node4'), ], }, module : { loaders: [ { test: /\.json$/, loader: require.resolve('json-loader') }, { test: /\.js$/, loader: require.resolve('babel-loader'), query: { babelrc: false, } } ] } } if (fs.existsSync(localWebpack)) { console.log(`${localWebpack} found agumenting buildjs ...`); const rules = Object.assign({}, require(localWebpack)); if (rules.externals && Array.isArray(rules.externals)) { // Order is important here the rules should be ordered such that the // webpack.config comes from the module first and our global rules second. config.externals = rules.externals.concat(config.externals); delete rules.externals; } Object.assign(config, rules); } module.exports = config;
Update webpack.config
buildjs/webpack.config.js
Update webpack.config
<ide><path>uildjs/webpack.config.js <ide> 'silk-netstatus', <ide> 'silk-ntp', <ide> 'silk-properties', <add> 'silk-say', <ide> 'silk-sensors', <ide> 'silk-sysutils', <ide> 'silk-vad',
Java
apache-2.0
4bc3f0d7ad8fdbf7a44bf2ce75d0717e9e87e84c
0
MSG134/IVCT_Framework,MSG134/IVCT_Framework,MSG134/IVCT_Framework
package nato.ivct.gui.server.sut; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.InvalidPathException; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.Map.Entry; import java.util.regex.Pattern; import java.util.stream.Stream; import org.eclipse.scout.rt.platform.BEANS; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonIOException; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.JsonSyntaxException; import nato.ivct.commander.BadgeDescription; import nato.ivct.commander.Factory; import nato.ivct.commander.SutDescription; import nato.ivct.commander.CmdListTestSuites.TestSuiteDescription; import nato.ivct.gui.server.cb.CbService; import nato.ivct.gui.server.ts.TsService; import nato.ivct.gui.shared.cb.ICbService; import nato.ivct.gui.shared.cb.ITsService; import nato.ivct.gui.shared.sut.ISuTTcService; import net.sf.jasperreports.engine.JRDataSource; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JasperCompileManager; import net.sf.jasperreports.engine.JasperExportManager; import net.sf.jasperreports.engine.JasperFillManager; import net.sf.jasperreports.engine.JasperPrint; import net.sf.jasperreports.engine.JasperReport; import net.sf.jasperreports.engine.data.JsonQLDataSource; class TestReport { private static final Logger LOG = LoggerFactory.getLogger(TestReport.class); private TestReport() {} static String createReportJsonFile(final String sutId, final String resultFile) { final Path reportFolder = Paths.get(Factory.getSutPathsFiles().getReportPath(sutId)); final String reportFile = Paths.get(reportFolder.toString(), "Report.json").toString(); final JsonObject jReport = new JsonObject(); //Result.json to JSON Object final Optional<JsonObject> jResults = readJsonResultFile(sutId, resultFile); if (!jResults.isPresent()) { return ""; } //Create JSON Report Structure /* * 1.SuT * 2.VerdictSummary * 3.Badges * 3.1. TestSuites * 3.1.1. TestCases * 3.1.1.1. TcResults */ //SuT section transformSuTDesc(jReport, sutId); //VerdictSummary section transformVerdictSummary(jResults.get(), jReport); //Badges section transformBadges(jResults.get(), jReport, sutId); //Fill with calculated SuT Verdict addSutVerdict(jReport); return reportJSONFile(jReport, reportFile); } private static String reportJSONFile(final JsonElement jReport, final String reportFile) { try { LOG.debug("store report json object to file {}", reportFile); Files.write(Paths.get(reportFile), jReport.toString().getBytes(), StandardOpenOption.TRUNCATE_EXISTING); } catch (final InvalidPathException e) { LOG.error("invalid path for report json file", reportFile); } catch (final IOException e) { LOG.error("could not write report json object to file {}", reportFile); } return reportFile; } private static void transformSuTDesc(final JsonObject jReport, final String sutId) { final String SUT_KW = "SuT"; final String SUTID_KW = "SutId"; final String SUTNAME_KW = "SutName"; final String SUTREV_KW = "SutRev"; final String SUTVENDOR_KW = "SutVendor"; // SuT information final SutDescription sutDesc = BEANS.get(SuTService.class).getSutDescription(sutId); // Insert the SuT section JsonObject sutSection = new JsonObject(); sutSection.addProperty(SUTID_KW, sutDesc.ID); sutSection.addProperty(SUTNAME_KW, sutDesc.name); sutSection.addProperty(SUTREV_KW, sutDesc.version); sutSection.addProperty(SUTVENDOR_KW, sutDesc.vendor); jReport.add(SUT_KW, sutSection); } private static void transformVerdictSummary(final JsonObject jResults, final JsonObject jReport) { final String VERDICTSUMMARY_KW = "VerdictSummary"; JsonObject verdictSection = (JsonObject) jResults.get(VERDICTSUMMARY_KW); jReport.add(VERDICTSUMMARY_KW, verdictSection); } private static void transformBadges(final JsonObject jResults, final JsonObject jReport, final String sutId) { final String BADGES_KW = "Badges"; final String BADGEID_KW = "BadgeId"; final String BADGENAME_KW = "BadgeName"; final String BADGEVERDICT_KW = "BadgeVerdict"; //SuT information final SutDescription sutDesc = BEANS.get(SuTService.class).getSutDescription(sutId); //Badge information Set<String> badges = sutDesc.badges; JsonArray badgeArray = new JsonArray(); jReport.add(BADGES_KW, badgeArray); badges.stream().sorted().forEachOrdered(badgeId ->{ BadgeDescription badgeDesc = BEANS.get(CbService.class).getBadgeDescription(badgeId); JsonObject badgeObj = new JsonObject(); badgeObj.addProperty(BADGEID_KW, badgeDesc.ID); badgeObj.addProperty(BADGENAME_KW, badgeDesc.name); badgeObj.addProperty(BADGEVERDICT_KW, getBadgeConformanceStatus(sutId, badgeId)); badgeArray.add(badgeObj); //TestSuite section transformTestSuites(jResults, badgeObj, badgeId); }); } static String getBadgeConformanceStatus(final String sutId, final String badgeId) { String bdVerdict = "PASSED"; //(tsId(tcSet)) HashMap<String, HashSet<String>> tcList = BEANS.get(ITsService.class).getTcListForBadge(badgeId); for (Entry<String, HashSet<String>> entry: tcList.entrySet()) { String tsId = entry.getKey(); HashSet<String> value = entry.getValue(); for (String tcId: value) { final String tcVerdict = BEANS.get(ISuTTcService.class).getTcLastVerdict(sutId, tsId, tcId); bdVerdict = evalVerdicts(bdVerdict, tcVerdict); } } return bdVerdict; } private static void transformTestSuites(final JsonObject jResults, final JsonObject badgeObj, final String badgeId) { final String TESTSUITES_KW = "TestSuites"; final String TSID_KW = "TsId"; final String TSNAME_KW = "TsName"; //TestSuite information final Set<String> tsList = BEANS.get(ITsService.class).getTsForIr(BEANS.get(ICbService.class).getIrForCb(badgeId)); JsonArray tsArray = new JsonArray(); badgeObj.add(TESTSUITES_KW, tsArray); tsList.stream().sorted().forEachOrdered(tsId ->{ TestSuiteDescription tsDesc = BEANS.get(TsService.class).getTsDescription(tsId); JsonObject tsObj = new JsonObject(); tsObj.addProperty(TSID_KW, tsDesc.id); tsObj.addProperty(TSNAME_KW, tsDesc.name); tsArray.add(tsObj); //TestCase section transformTestCases(jResults, tsObj, badgeId, tsId); }); } private static void transformTestCases(final JsonObject jResults, final JsonObject tsObj, final String bdId, final String tsId) { final String TESTCASES_KW = "TestCases"; final String TCID_KW = "TcId"; final String TCNAME_KW = "TcName"; final String TCRESULTS_KW = "TcResults"; //TestCase information final Map<String, HashSet<String>> tcList = BEANS.get(ITsService.class).getTcListForBadge(bdId); JsonArray tcArray = new JsonArray(); tsObj.add(TESTCASES_KW, tcArray); tcList.getOrDefault(tsId, new HashSet<String>()).stream().sorted().forEachOrdered(tcId -> { String tcName = Stream.of(tcId.split(Pattern.quote("."))).reduce((a, b) -> b).get(); JsonObject tcObj = new JsonObject(); tcObj.addProperty(TCID_KW, tcId); tcObj.addProperty(TCNAME_KW, tcName); tcArray.add(tcObj); JsonObject results = (JsonObject) jResults.get(TCRESULTS_KW); JsonObject tsSection = Optional.ofNullable((JsonObject) results.get(tsId)).orElseGet(JsonObject::new); JsonArray tcSection = Optional.ofNullable((JsonArray) tsSection.get(tcId)).orElseGet(JsonArray::new); //TcResult section transformTcResults(tcSection, tcObj); }); } private static void transformTcResults(JsonArray tcSection, JsonObject tcObj) { final String TCRESULTS_KW = "TcResults"; //TcResult information JsonArray tcResultArray = new JsonArray(); tcObj.add(TCRESULTS_KW, tcResultArray); if (tcSection == null) return; tcSection.forEach(result ->{ tcResultArray.add(result); }); } private static void addSutVerdict(final JsonObject jReport) { final String VERDICTSUMMARY_KW = "VerdictSummary"; final String SUTVERDICT_KW = "SutVerdict"; String sutConformanceStatus = getSutConformanceStatus(jReport); jReport.getAsJsonObject(VERDICTSUMMARY_KW).addProperty(SUTVERDICT_KW, sutConformanceStatus); } private static String getSutConformanceStatus(final JsonObject jReport) { final String BADGES_KW = "Badges"; final String BADGEVERDICT_KW = "BadgeVerdict"; String sutVerdict = "PASSED"; for (JsonElement badge : jReport.getAsJsonArray(BADGES_KW)){ String bdVerdict = badge.getAsJsonObject().get(BADGEVERDICT_KW).getAsString(); sutVerdict = evalVerdicts(sutVerdict, bdVerdict); } return sutVerdict; } private static String evalVerdicts(final String summaryVerdict, final String individualVerdict) { //PASSED < UNKNOWN < INCONCLUSIVE < FAILED String verdict = summaryVerdict; if (!"PASSED".equalsIgnoreCase(individualVerdict)) { if ("FAILED".equalsIgnoreCase(individualVerdict) || "FAILED".equalsIgnoreCase(summaryVerdict)) verdict = "FAILED"; else if ("INCONCLUSIVE".equalsIgnoreCase(individualVerdict) || "INCONCLUSIVE".equalsIgnoreCase(summaryVerdict)) verdict = "INCONCLUSIVE"; else verdict = "UNKNOWN"; } return verdict; } private static Optional<JsonObject> readJsonResultFile(final String sutId, final String resultFile) { try { return Optional.ofNullable(JsonParser.parseReader((Files.newBufferedReader(Paths.get(resultFile)))).getAsJsonObject()); } catch (IOException | JsonIOException | JsonSyntaxException exc) { LOG.error("Result file does not exist", resultFile); return Optional.empty(); } } static String createPDFTestreport(final String templateFolder, final Path reportFolder) { try { final String pathToReports = reportFolder.toString() +"\\"; final String pathToTemplates = templateFolder +"\\"; JRDataSource jrDataSource = new JsonQLDataSource(new File(pathToReports + "Report.json")); JasperReport jasperReport = JasperCompileManager.compileReport(pathToTemplates + "Report.jrxml"); JasperCompileManager.compileReportToFile(pathToTemplates + "subreport_SuT.jrxml", "subreport_SuT.jasper"); JasperCompileManager.compileReportToFile(pathToTemplates + "subreport_Verdict.jrxml", "subreport_Verdict.jasper"); JasperCompileManager.compileReportToFile(pathToTemplates + "subreport_BadgeSummary.jrxml", "subreport_BadgeSummary.jasper"); JasperCompileManager.compileReportToFile(pathToTemplates + "subreport_TcResults.jrxml", "subreport_TcResults.jasper"); JasperCompileManager.compileReportToFile(pathToTemplates + "subreport_TestCases.jrxml", "subreport_TestCases.jasper"); JasperCompileManager.compileReportToFile(pathToTemplates + "subreport_TS.jrxml", "subreport_TS.jasper"); JasperCompileManager.compileReportToFile(pathToTemplates + "subreport_Badge.jrxml", "subreport_Badge.jasper"); JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, new HashMap(), jrDataSource); Date time = new Date(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("_yyyyMMdd-HHmmss"); final String fileName = "Report" + simpleDateFormat.format(time) + ".pdf"; JasperExportManager.exportReportToPdfFile(jasperPrint, pathToReports + fileName); return fileName; } catch (JRException e) { e.printStackTrace(); } return null; } }
GUI/nato.ivct.gui.server/src/main/java/nato/ivct/gui/server/sut/TestReport.java
package nato.ivct.gui.server.sut; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.InvalidPathException; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.Map.Entry; import java.util.regex.Pattern; import java.util.stream.Stream; import org.eclipse.scout.rt.platform.BEANS; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonIOException; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.JsonSyntaxException; import nato.ivct.commander.BadgeDescription; import nato.ivct.commander.Factory; import nato.ivct.commander.SutDescription; import nato.ivct.commander.CmdListTestSuites.TestSuiteDescription; import nato.ivct.gui.server.cb.CbService; import nato.ivct.gui.server.ts.TsService; import nato.ivct.gui.shared.cb.ICbService; import nato.ivct.gui.shared.cb.ITsService; import nato.ivct.gui.shared.sut.ISuTTcService; import net.sf.jasperreports.engine.JRDataSource; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JasperCompileManager; import net.sf.jasperreports.engine.JasperExportManager; import net.sf.jasperreports.engine.JasperFillManager; import net.sf.jasperreports.engine.JasperPrint; import net.sf.jasperreports.engine.JasperReport; import net.sf.jasperreports.engine.data.JsonQLDataSource; class TestReport { private static final Logger LOG = LoggerFactory.getLogger(TestReport.class); private TestReport() {} static String createReportJsonFile(final String sutId, final String resultFile) { final Path reportFolder = Paths.get(Factory.getSutPathsFiles().getReportPath(sutId)); final String reportFile = Paths.get(reportFolder.toString(), "Report.json").toString(); final JsonObject jReport = new JsonObject(); //Result.json to JSON Object final Optional<JsonObject> jResults = readJsonResultFile(sutId, resultFile); if (!jResults.isPresent()) { return ""; } //Create JSON Report Structure /* * 1.SuT * 2.VerdictSummary * 3.Badges * 3.1. TestSuites * 3.1.1. TestCases * 3.1.1.1. TcResults */ //SuT section transformSuTDesc(jReport, sutId); //VerdictSummary section transformVerdictSummary(jResults.get(), jReport); //Badges section transformBadges(jResults.get(), jReport, sutId); //Fill with calculated SuT Verdict addSutVerdict(jReport); return reportJSONFile(jReport, reportFile); } private static String reportJSONFile(final JsonElement jReport, final String reportFile) { try { LOG.debug("store report json object to file {}", reportFile); Files.write(Paths.get(reportFile), jReport.toString().getBytes(), StandardOpenOption.TRUNCATE_EXISTING); } catch (final InvalidPathException e) { LOG.error("invalid path for report json file", reportFile); } catch (final IOException e) { LOG.error("could not write report json object to file {}", reportFile); } return reportFile; } private static void transformSuTDesc(final JsonObject jReport, final String sutId) { final String SUT_KW = "SuT"; final String SUTID_KW = "SutId"; final String SUTNAME_KW = "SutName"; final String SUTREV_KW = "SutRev"; final String SUTVENDOR_KW = "SutVendor"; // SuT information final SutDescription sutDesc = BEANS.get(SuTService.class).getSutDescription(sutId); // Insert the SuT section JsonObject sutSection = new JsonObject(); sutSection.addProperty(SUTID_KW, sutDesc.ID); sutSection.addProperty(SUTNAME_KW, sutDesc.name); sutSection.addProperty(SUTREV_KW, sutDesc.version); sutSection.addProperty(SUTVENDOR_KW, sutDesc.vendor); jReport.add(SUT_KW, sutSection); } private static void transformVerdictSummary(final JsonObject jResults, final JsonObject jReport) { final String VERDICTSUMMARY_KW = "VerdictSummary"; JsonObject verdictSection = (JsonObject) jResults.get(VERDICTSUMMARY_KW); jReport.add(VERDICTSUMMARY_KW, verdictSection); } private static void transformBadges(final JsonObject jResults, final JsonObject jReport, final String sutId) { final String BADGES_KW = "Badges"; final String BADGEID_KW = "BadgeId"; final String BADGENAME_KW = "BadgeName"; final String BADGEVERDICT_KW = "BadgeVerdict"; //SuT information final SutDescription sutDesc = BEANS.get(SuTService.class).getSutDescription(sutId); //Badge information Set<String> badges = sutDesc.badges; JsonArray badgeArray = new JsonArray(); jReport.add(BADGES_KW, badgeArray); badges.stream().sorted().forEachOrdered(badgeId ->{ BadgeDescription badgeDesc = BEANS.get(CbService.class).getBadgeDescription(badgeId); JsonObject badgeObj = new JsonObject(); badgeObj.addProperty(BADGEID_KW, badgeDesc.ID); badgeObj.addProperty(BADGENAME_KW, badgeDesc.name); badgeObj.addProperty(BADGEVERDICT_KW, getBadgeConformanceStatus(sutId, badgeId)); badgeArray.add(badgeObj); //TestSuite section transformTestSuites(jResults, badgeObj, badgeId); }); } static String getBadgeConformanceStatus(final String sutId, final String badgeId) { String bdVerdict = "PASSED"; //(tsId(tcSet)) HashMap<String, HashSet<String>> tcList = BEANS.get(ITsService.class).getTcListForBadge(badgeId); for (Entry<String, HashSet<String>> entry: tcList.entrySet()) { String tsId = entry.getKey(); HashSet<String> value = entry.getValue(); for (String tcId: value) { final String tcVerdict = BEANS.get(ISuTTcService.class).getTcLastVerdict(sutId, tsId, tcId); bdVerdict = evalVerdicts(bdVerdict, tcVerdict); } } return bdVerdict; } private static void transformTestSuites(final JsonObject jResults, final JsonObject badgeObj, final String badgeId) { final String TESTSUITES_KW = "TestSuites"; final String TSID_KW = "TsId"; final String TSNAME_KW = "TsName"; //TestSuite information final Set<String> tsList = BEANS.get(ITsService.class).getTsForIr(BEANS.get(ICbService.class).getIrForCb(badgeId)); JsonArray tsArray = new JsonArray(); badgeObj.add(TESTSUITES_KW, tsArray); tsList.stream().sorted().forEachOrdered(tsId ->{ TestSuiteDescription tsDesc = BEANS.get(TsService.class).getTsDescription(tsId); JsonObject tsObj = new JsonObject(); tsObj.addProperty(TSID_KW, tsDesc.id); tsObj.addProperty(TSNAME_KW, tsDesc.name); tsArray.add(tsObj); //TestCase section transformTestCases(jResults, tsObj, badgeId, tsId); }); } private static void transformTestCases(final JsonObject jResults, final JsonObject tsObj, final String bdId, final String tsId) { final String TESTCASES_KW = "TestCases"; final String TCID_KW = "TcId"; final String TCNAME_KW = "TcName"; final String TCRESULTS_KW = "TcResults"; //TestCase information final Map<String, HashSet<String>> tcList = BEANS.get(ITsService.class).getTcListForBadge(bdId); JsonArray tcArray = new JsonArray(); tsObj.add(TESTCASES_KW, tcArray); tcList.getOrDefault(tsId, new HashSet<String>()).stream().sorted().forEachOrdered(tcId -> { String tcName = Stream.of(tcId.split(Pattern.quote("."))).reduce((a, b) -> b).get(); JsonObject tcObj = new JsonObject(); tcObj.addProperty(TCID_KW, tcId); tcObj.addProperty(TCNAME_KW, tcName); tcArray.add(tcObj); JsonObject results = (JsonObject) jResults.get(TCRESULTS_KW); JsonObject tsSection = Optional.ofNullable((JsonObject) results.get(tsId)).orElseGet(JsonObject::new); JsonArray tcSection = Optional.ofNullable((JsonArray) tsSection.get(tcId)).orElseGet(JsonArray::new); //TcResult section transformTcResults(tcSection, tcObj); }); } private static void transformTcResults(JsonArray tcSection, JsonObject tcObj) { final String TCRESULTS_KW = "TcResults"; //TcResult information JsonArray tcResultArray = new JsonArray(); tcObj.add(TCRESULTS_KW, tcResultArray); if (tcSection == null) return; tcSection.forEach(result ->{ tcResultArray.add(result); }); } private static void addSutVerdict(final JsonObject jReport) { final String VERDICTSUMMARY_KW = "VerdictSummary"; final String SUTVERDICT_KW = "SutVerdict"; String sutConformanceStatus = getSutConformanceStatus(jReport); jReport.getAsJsonObject(VERDICTSUMMARY_KW).addProperty(SUTVERDICT_KW, sutConformanceStatus); } private static String getSutConformanceStatus(final JsonObject jReport) { final String BADGES_KW = "Badges"; final String BADGEVERDICT_KW = "BadgeVerdict"; String sutVerdict = "PASSED"; for (JsonElement badge : jReport.getAsJsonArray(BADGES_KW)){ String bdVerdict = badge.getAsJsonObject().get(BADGEVERDICT_KW).getAsString(); sutVerdict = evalVerdicts(sutVerdict, bdVerdict); } return sutVerdict; } private static String evalVerdicts(final String summaryVerdict, final String individualVerdict) { //PASSED < UNKNOWN < INCONCLUSIVE < FAILED String verdict = summaryVerdict; if (!"PASSED".equalsIgnoreCase(individualVerdict)) { if ("FAILED".equalsIgnoreCase(individualVerdict) || "FAILED".equalsIgnoreCase(summaryVerdict)) verdict = "FAILED"; else if ("INCONCLUSIVE".equalsIgnoreCase(individualVerdict) || "INCONCLUSIVE".equalsIgnoreCase(summaryVerdict)) verdict = "INCONCLUSIVE"; else verdict = "UNKNOWN"; } return verdict; } private static Optional<JsonObject> readJsonResultFile(final String sutId, final String resultFile) { try { return Optional.ofNullable(JsonParser.parseReader((Files.newBufferedReader(Paths.get(resultFile)))).getAsJsonObject()); } catch (IOException | JsonIOException | JsonSyntaxException exc) { LOG.error("Result file does not exist", resultFile); return Optional.empty(); } } static String createPDFTestreport(final String templateFolder, final Path reportFolder) { try { final String pathToReports = reportFolder.toString() +"\\"; final String pathToTemplates = templateFolder +"\\"; JRDataSource jrDataSource = new JsonQLDataSource(new File(pathToReports + "Report.json")); JasperReport jasperReport = JasperCompileManager.compileReport(pathToTemplates + "Report.jrxml"); JasperCompileManager.compileReportToFile(pathToTemplates + "subreport_SuT.jrxml", "subreport_SuT.jasper"); JasperCompileManager.compileReportToFile(pathToTemplates + "subreport_Verdict.jrxml", "subreport_Verdict.jasper"); JasperCompileManager.compileReportToFile(pathToTemplates + "subreport_TcResults.jrxml", "subreport_TcResults.jasper"); JasperCompileManager.compileReportToFile(pathToTemplates + "subreport_TestCases.jrxml", "subreport_TestCases.jasper"); JasperCompileManager.compileReportToFile(pathToTemplates + "subreport_TS.jrxml", "subreport_TS.jasper"); JasperCompileManager.compileReportToFile(pathToTemplates + "subreport_Badge.jrxml", "subreport_Badge.jasper"); JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, new HashMap(), jrDataSource); Date time = new Date(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("_yyyyMMdd-HHmmss"); final String fileName = "Report" + simpleDateFormat.format(time) + ".pdf"; JasperExportManager.exportReportToPdfFile(jasperPrint, pathToReports + fileName); return fileName; } catch (JRException e) { e.printStackTrace(); } return null; } }
Add subreport badge summary
GUI/nato.ivct.gui.server/src/main/java/nato/ivct/gui/server/sut/TestReport.java
Add subreport badge summary
<ide><path>UI/nato.ivct.gui.server/src/main/java/nato/ivct/gui/server/sut/TestReport.java <ide> JasperReport jasperReport = JasperCompileManager.compileReport(pathToTemplates + "Report.jrxml"); <ide> JasperCompileManager.compileReportToFile(pathToTemplates + "subreport_SuT.jrxml", "subreport_SuT.jasper"); <ide> JasperCompileManager.compileReportToFile(pathToTemplates + "subreport_Verdict.jrxml", "subreport_Verdict.jasper"); <add> JasperCompileManager.compileReportToFile(pathToTemplates + "subreport_BadgeSummary.jrxml", "subreport_BadgeSummary.jasper"); <ide> JasperCompileManager.compileReportToFile(pathToTemplates + "subreport_TcResults.jrxml", "subreport_TcResults.jasper"); <ide> JasperCompileManager.compileReportToFile(pathToTemplates + "subreport_TestCases.jrxml", "subreport_TestCases.jasper"); <ide> JasperCompileManager.compileReportToFile(pathToTemplates + "subreport_TS.jrxml", "subreport_TS.jasper");
JavaScript
mit
6a768950b61eb699f40b5cc339d191b9b035b148
0
bevacqua/dragula,bevacqua/dragula
'use strict'; var emitter = require('contra/emitter'); var crossvent = require('crossvent'); var classes = require('./classes'); var doc = document; var documentElement = doc.documentElement; function dragula (initialContainers, options) { var len = arguments.length; if (len === 1 && Array.isArray(initialContainers) === false) { options = initialContainers; initialContainers = []; } var _mirror; // mirror image var _source; // source container var _item; // item being dragged var _offsetX; // reference x var _offsetY; // reference y var _moveX; // reference move x var _moveY; // reference move y var _initialSibling; // reference sibling when grabbed var _currentSibling; // reference sibling now var _copy; // item used for copying var _renderTimer; // timer for setTimeout renderMirrorImage var _lastDropTarget = null; // last container item was over var _grabbed; // holds mousedown context until first mousemove var o = options || {}; if (o.moves === void 0) { o.moves = always; } if (o.accepts === void 0) { o.accepts = always; } if (o.invalid === void 0) { o.invalid = invalidTarget; } if (o.containers === void 0) { o.containers = initialContainers || []; } if (o.isContainer === void 0) { o.isContainer = never; } if (o.copy === void 0) { o.copy = false; } if (o.copySortSource === void 0) { o.copySortSource = false; } if (o.revertOnSpill === void 0) { o.revertOnSpill = false; } if (o.removeOnSpill === void 0) { o.removeOnSpill = false; } if (o.direction === void 0) { o.direction = 'vertical'; } if (o.ignoreInputTextSelection === void 0) { o.ignoreInputTextSelection = true; } if (o.mirrorContainer === void 0) { o.mirrorContainer = doc.body; } var drake = emitter({ containers: o.containers, start: manualStart, end: end, cancel: cancel, remove: remove, destroy: destroy, canMove: canMove, dragging: false }); if (o.removeOnSpill === true) { drake.on('over', spillOver).on('out', spillOut); } events(); return drake; function isContainer (el) { return drake.containers.indexOf(el) !== -1 || o.isContainer(el); } function events (remove) { var op = remove ? 'remove' : 'add'; touchy(documentElement, op, 'mousedown', grab); touchy(documentElement, op, 'mouseup', release); } function eventualMovements (remove) { var op = remove ? 'remove' : 'add'; touchy(documentElement, op, 'mousemove', startBecauseMouseMoved); } function movements (remove) { var op = remove ? 'remove' : 'add'; crossvent[op](documentElement, 'selectstart', preventGrabbed); // IE8 crossvent[op](documentElement, 'click', preventGrabbed); } function destroy () { events(true); release({}); } function preventGrabbed (e) { if (_grabbed) { e.preventDefault(); } } function grab (e) { _moveX = e.clientX; _moveY = e.clientY; var ignore = whichMouseButton(e) !== 1 || e.metaKey || e.ctrlKey; if (ignore) { return; // we only care about honest-to-god left clicks and touch events } var item = e.target; var context = canStart(item); if (!context) { return; } _grabbed = context; eventualMovements(); if (e.type === 'mousedown') { if (isInput(item)) { // see also: https://github.com/bevacqua/dragula/issues/208 item.focus(); // fixes https://github.com/bevacqua/dragula/issues/176 } else { e.preventDefault(); // fixes https://github.com/bevacqua/dragula/issues/155 } } } function startBecauseMouseMoved (e) { if (!_grabbed) { return; } if (whichMouseButton(e) === 0) { release({}); return; // when text is selected on an input and then dragged, mouseup doesn't fire. this is our only hope } // truthy check fixes #239, equality fixes #207 if (e.clientX !== void 0 && e.clientX === _moveX && e.clientY !== void 0 && e.clientY === _moveY) { return; } if (o.ignoreInputTextSelection) { var clientX = getCoord('clientX', e) || 0; var clientY = getCoord('clientY', e) || 0; var elementBehindCursor = doc.elementFromPoint(clientX, clientY); if (isInput(elementBehindCursor)) { return; } } var grabbed = _grabbed; // call to end() unsets _grabbed eventualMovements(true); movements(); end(); start(grabbed); var offset = getOffset(_item); _offsetX = getCoord('pageX', e) - offset.left; _offsetY = getCoord('pageY', e) - offset.top; classes.add(_copy || _item, 'gu-transit'); renderMirrorImage(); drag(e); } function canStart (item) { if (drake.dragging && _mirror) { return; } if (isContainer(item)) { return; // don't drag container itself } var handle = item; while (getParent(item) && isContainer(getParent(item)) === false) { if (o.invalid(item, handle)) { return; } item = getParent(item); // drag target should be a top element if (!item) { return; } } var source = getParent(item); if (!source) { return; } if (o.invalid(item, handle)) { return; } var movable = o.moves(item, source, handle, nextEl(item)); if (!movable) { return; } return { item: item, source: source }; } function canMove (item) { return !!canStart(item); } function manualStart (item) { var context = canStart(item); if (context) { start(context); } } function start (context) { if (isCopy(context.item, context.source)) { _copy = context.item.cloneNode(true); drake.emit('cloned', _copy, context.item, 'copy'); } _source = context.source; _item = context.item; _initialSibling = _currentSibling = nextEl(context.item); drake.dragging = true; drake.emit('drag', _item, _source); } function invalidTarget () { return false; } function end () { if (!drake.dragging) { return; } var item = _copy || _item; drop(item, getParent(item)); } function ungrab () { _grabbed = false; eventualMovements(true); movements(true); } function release (e) { ungrab(); if (!drake.dragging) { return; } var item = _copy || _item; var clientX = getCoord('clientX', e) || 0; var clientY = getCoord('clientY', e) || 0; var elementBehindCursor = getElementBehindPoint(_mirror, clientX, clientY); var dropTarget = findDropTarget(elementBehindCursor, clientX, clientY); if (dropTarget && ((_copy && o.copySortSource) || (!_copy || dropTarget !== _source))) { drop(item, dropTarget); } else if (o.removeOnSpill) { remove(); } else { cancel(); } } function drop (item, target) { var parent = getParent(item); if (_copy && o.copySortSource && target === _source) { parent.removeChild(_item); } if (isInitialPlacement(target)) { drake.emit('cancel', item, _source, _source); } else { drake.emit('drop', item, target, _source, _currentSibling); } cleanup(); } function remove () { if (!drake.dragging) { return; } var item = _copy || _item; var parent = getParent(item); if (parent) { parent.removeChild(item); } drake.emit(_copy ? 'cancel' : 'remove', item, parent, _source); cleanup(); } function cancel (revert) { if (!drake.dragging) { return; } var reverts = arguments.length > 0 ? revert : o.revertOnSpill; var item = _copy || _item; var parent = getParent(item); var initial = isInitialPlacement(parent); if (initial === false && reverts) { if (_copy) { if (parent) { parent.removeChild(_copy); } } else { _source.insertBefore(item, _initialSibling); } } if (initial || reverts) { drake.emit('cancel', item, _source, _source); } else { drake.emit('drop', item, parent, _source, _currentSibling); } cleanup(); } function cleanup () { var item = _copy || _item; ungrab(); removeMirrorImage(); if (item) { classes.rm(item, 'gu-transit'); } if (_renderTimer) { clearTimeout(_renderTimer); } drake.dragging = false; if (_lastDropTarget) { drake.emit('out', item, _lastDropTarget, _source); } drake.emit('dragend', item); _source = _item = _copy = _initialSibling = _currentSibling = _renderTimer = _lastDropTarget = null; } function isInitialPlacement (target, s) { var sibling; if (s !== void 0) { sibling = s; } else if (_mirror) { sibling = _currentSibling; } else { sibling = nextEl(_copy || _item); } return target === _source && sibling === _initialSibling; } function findDropTarget (elementBehindCursor, clientX, clientY) { var target = elementBehindCursor; while (target && !accepted()) { target = getParent(target); } return target; function accepted () { var droppable = isContainer(target); if (droppable === false) { return false; } var immediate = getImmediateChild(target, elementBehindCursor); var reference = getReference(target, immediate, clientX, clientY); var initial = isInitialPlacement(target, reference); if (initial) { return true; // should always be able to drop it right back where it was } return o.accepts(_item, target, _source, reference); } } function drag (e) { if (!_mirror) { return; } e.preventDefault(); var clientX = getCoord('clientX', e) || 0; var clientY = getCoord('clientY', e) || 0; var x = clientX - _offsetX; var y = clientY - _offsetY; _mirror.style.left = x + 'px'; _mirror.style.top = y + 'px'; var item = _copy || _item; var elementBehindCursor = getElementBehindPoint(_mirror, clientX, clientY); var dropTarget = findDropTarget(elementBehindCursor, clientX, clientY); var changed = dropTarget !== null && dropTarget !== _lastDropTarget; if (changed || dropTarget === null) { out(); _lastDropTarget = dropTarget; over(); } var parent = getParent(item); if (dropTarget === _source && _copy && !o.copySortSource) { if (parent) { parent.removeChild(item); } return; } var reference; var immediate = getImmediateChild(dropTarget, elementBehindCursor); if (immediate !== null) { reference = getReference(dropTarget, immediate, clientX, clientY); } else if (o.revertOnSpill === true && !_copy) { reference = _initialSibling; dropTarget = _source; } else { if (_copy && parent) { parent.removeChild(item); } return; } if ( (reference === null && changed) || reference !== item && reference !== nextEl(item) ) { _currentSibling = reference; dropTarget.insertBefore(item, reference); drake.emit('shadow', item, dropTarget, _source); } function moved (type) { drake.emit(type, item, _lastDropTarget, _source); } function over () { if (changed) { moved('over'); } } function out () { if (_lastDropTarget) { moved('out'); } } } function spillOver (el) { classes.rm(el, 'gu-hide'); } function spillOut (el) { if (drake.dragging) { classes.add(el, 'gu-hide'); } } function renderMirrorImage () { if (_mirror) { return; } var rect = _item.getBoundingClientRect(); _mirror = _item.cloneNode(true); _mirror.style.width = getRectWidth(rect) + 'px'; _mirror.style.height = getRectHeight(rect) + 'px'; classes.rm(_mirror, 'gu-transit'); classes.add(_mirror, 'gu-mirror'); o.mirrorContainer.appendChild(_mirror); touchy(documentElement, 'add', 'mousemove', drag); classes.add(o.mirrorContainer, 'gu-unselectable'); drake.emit('cloned', _mirror, _item, 'mirror'); } function removeMirrorImage () { if (_mirror) { classes.rm(o.mirrorContainer, 'gu-unselectable'); touchy(documentElement, 'remove', 'mousemove', drag); getParent(_mirror).removeChild(_mirror); _mirror = null; } } function getImmediateChild (dropTarget, target) { var immediate = target; while (immediate !== dropTarget && getParent(immediate) !== dropTarget) { immediate = getParent(immediate); } if (immediate === documentElement) { return null; } return immediate; } function getReference (dropTarget, target, x, y) { var horizontal = o.direction === 'horizontal'; var reference = target !== dropTarget ? inside() : outside(); return reference; function outside () { // slower, but able to figure out any position var len = dropTarget.children.length; var i; var el; var rect; for (i = 0; i < len; i++) { el = dropTarget.children[i]; rect = el.getBoundingClientRect(); if (horizontal && (rect.left + rect.width / 2) > x) { return el; } if (!horizontal && (rect.top + rect.height / 2) > y) { return el; } } return null; } function inside () { // faster, but only available if dropped inside a child element var rect = target.getBoundingClientRect(); if (horizontal) { return resolve(x > rect.left + getRectWidth(rect) / 2); } return resolve(y > rect.top + getRectHeight(rect) / 2); } function resolve (after) { return after ? nextEl(target) : target; } } function isCopy (item, container) { return typeof o.copy === 'boolean' ? o.copy : o.copy(item, container); } } function touchy (el, op, type, fn) { var touch = { mouseup: 'touchend', mousedown: 'touchstart', mousemove: 'touchmove' }; var pointers = { mouseup: 'pointerup', mousedown: 'pointerdown', mousemove: 'pointermove' }; var microsoft = { mouseup: 'MSPointerUp', mousedown: 'MSPointerDown', mousemove: 'MSPointerMove' }; if (global.navigator.pointerEnabled) { crossvent[op](el, pointers[type], fn); } else if (global.navigator.msPointerEnabled) { crossvent[op](el, microsoft[type], fn); } else { crossvent[op](el, touch[type], fn); crossvent[op](el, type, fn); } } function whichMouseButton (e) { if (e.touches !== void 0) { return e.touches.length; } if (e.which !== void 0 && e.which !== 0) { return e.which; } // see https://github.com/bevacqua/dragula/issues/261 if (e.buttons !== void 0) { return e.buttons; } var button = e.button; if (button !== void 0) { // see https://github.com/jquery/jquery/blob/99e8ff1baa7ae341e94bb89c3e84570c7c3ad9ea/src/event.js#L573-L575 return button & 1 ? 1 : button & 2 ? 3 : (button & 4 ? 2 : 0); } } function getOffset (el) { var rect = el.getBoundingClientRect(); return { left: rect.left + getScroll('scrollLeft', 'pageXOffset'), top: rect.top + getScroll('scrollTop', 'pageYOffset') }; } function getScroll (scrollProp, offsetProp) { if (typeof global[offsetProp] !== 'undefined') { return global[offsetProp]; } if (documentElement.clientHeight) { return documentElement[scrollProp]; } return doc.body[scrollProp]; } function getElementBehindPoint (point, x, y) { point = point || {}; var state = point.className || ''; var el; point.className += ' gu-hide'; el = doc.elementFromPoint(x, y); point.className = state; return el; } function never () { return false; } function always () { return true; } function getRectWidth (rect) { return rect.width || (rect.right - rect.left); } function getRectHeight (rect) { return rect.height || (rect.bottom - rect.top); } function getParent (el) { return el.parentNode === doc ? null : el.parentNode; } function isInput (el) { return el.tagName === 'INPUT' || el.tagName === 'TEXTAREA' || el.tagName === 'SELECT' || isEditable(el); } function isEditable (el) { if (!el) { return false; } // no parents were editable if (el.contentEditable === 'false') { return false; } // stop the lookup if (el.contentEditable === 'true') { return true; } // found a contentEditable element in the chain return isEditable(getParent(el)); // contentEditable is set to 'inherit' } function nextEl (el) { return el.nextElementSibling || manually(); function manually () { var sibling = el; do { sibling = sibling.nextSibling; } while (sibling && sibling.nodeType !== 1); return sibling; } } function getEventHost (e) { // on touchend event, we have to use `e.changedTouches` // see http://stackoverflow.com/questions/7192563/touchend-event-properties // see https://github.com/bevacqua/dragula/issues/34 if (e.targetTouches && e.targetTouches.length) { return e.targetTouches[0]; } if (e.changedTouches && e.changedTouches.length) { return e.changedTouches[0]; } return e; } function getCoord (coord, e) { var host = getEventHost(e); var missMap = { pageX: 'clientX', // IE8 pageY: 'clientY' // IE8 }; if (coord in missMap && !(coord in host) && missMap[coord] in host) { coord = missMap[coord]; } return host[coord]; } module.exports = dragula;
dragula.js
'use strict'; var emitter = require('contra/emitter'); var crossvent = require('crossvent'); var classes = require('./classes'); var doc = document; var documentElement = doc.documentElement; function dragula (initialContainers, options) { var len = arguments.length; if (len === 1 && Array.isArray(initialContainers) === false) { options = initialContainers; initialContainers = []; } var _mirror; // mirror image var _source; // source container var _item; // item being dragged var _offsetX; // reference x var _offsetY; // reference y var _moveX; // reference move x var _moveY; // reference move y var _initialSibling; // reference sibling when grabbed var _currentSibling; // reference sibling now var _copy; // item used for copying var _renderTimer; // timer for setTimeout renderMirrorImage var _lastDropTarget = null; // last container item was over var _grabbed; // holds mousedown context until first mousemove var o = options || {}; if (o.moves === void 0) { o.moves = always; } if (o.accepts === void 0) { o.accepts = always; } if (o.invalid === void 0) { o.invalid = invalidTarget; } if (o.containers === void 0) { o.containers = initialContainers || []; } if (o.isContainer === void 0) { o.isContainer = never; } if (o.copy === void 0) { o.copy = false; } if (o.copySortSource === void 0) { o.copySortSource = false; } if (o.revertOnSpill === void 0) { o.revertOnSpill = false; } if (o.removeOnSpill === void 0) { o.removeOnSpill = false; } if (o.direction === void 0) { o.direction = 'vertical'; } if (o.ignoreInputTextSelection === void 0) { o.ignoreInputTextSelection = true; } if (o.mirrorContainer === void 0) { o.mirrorContainer = doc.body; } var drake = emitter({ containers: o.containers, start: manualStart, end: end, cancel: cancel, remove: remove, destroy: destroy, canMove: canMove, dragging: false }); if (o.removeOnSpill === true) { drake.on('over', spillOver).on('out', spillOut); } events(); return drake; function isContainer (el) { return drake.containers.indexOf(el) !== -1 || o.isContainer(el); } function events (remove) { var op = remove ? 'remove' : 'add'; touchy(documentElement, op, 'mousedown', grab); touchy(documentElement, op, 'mouseup', release); } function eventualMovements (remove) { var op = remove ? 'remove' : 'add'; touchy(documentElement, op, 'mousemove', startBecauseMouseMoved); } function movements (remove) { var op = remove ? 'remove' : 'add'; crossvent[op](documentElement, 'selectstart', preventGrabbed); // IE8 crossvent[op](documentElement, 'click', preventGrabbed); } function destroy () { events(true); release({}); } function preventGrabbed (e) { if (_grabbed) { e.preventDefault(); } } function grab (e) { _moveX = e.clientX; _moveY = e.clientY; var ignore = whichMouseButton(e) !== 1 || e.metaKey || e.ctrlKey; if (ignore) { return; // we only care about honest-to-god left clicks and touch events } var item = e.target; var context = canStart(item); if (!context) { return; } _grabbed = context; eventualMovements(); if (e.type === 'mousedown') { if (isInput(item)) { // see also: https://github.com/bevacqua/dragula/issues/208 item.focus(); // fixes https://github.com/bevacqua/dragula/issues/176 } else { e.preventDefault(); // fixes https://github.com/bevacqua/dragula/issues/155 } } } function startBecauseMouseMoved (e) { if (!_grabbed) { return; } if (whichMouseButton(e) === 0) { release({}); return; // when text is selected on an input and then dragged, mouseup doesn't fire. this is our only hope } // truthy check fixes #239, equality fixes #207 if (e.clientX !== void 0 && e.clientX === _moveX && e.clientY !== void 0 && e.clientY === _moveY) { return; } if (o.ignoreInputTextSelection) { var clientX = getCoord('clientX', e); var clientY = getCoord('clientY', e); var elementBehindCursor = doc.elementFromPoint(clientX, clientY); if (isInput(elementBehindCursor)) { return; } } var grabbed = _grabbed; // call to end() unsets _grabbed eventualMovements(true); movements(); end(); start(grabbed); var offset = getOffset(_item); _offsetX = getCoord('pageX', e) - offset.left; _offsetY = getCoord('pageY', e) - offset.top; classes.add(_copy || _item, 'gu-transit'); renderMirrorImage(); drag(e); } function canStart (item) { if (drake.dragging && _mirror) { return; } if (isContainer(item)) { return; // don't drag container itself } var handle = item; while (getParent(item) && isContainer(getParent(item)) === false) { if (o.invalid(item, handle)) { return; } item = getParent(item); // drag target should be a top element if (!item) { return; } } var source = getParent(item); if (!source) { return; } if (o.invalid(item, handle)) { return; } var movable = o.moves(item, source, handle, nextEl(item)); if (!movable) { return; } return { item: item, source: source }; } function canMove (item) { return !!canStart(item); } function manualStart (item) { var context = canStart(item); if (context) { start(context); } } function start (context) { if (isCopy(context.item, context.source)) { _copy = context.item.cloneNode(true); drake.emit('cloned', _copy, context.item, 'copy'); } _source = context.source; _item = context.item; _initialSibling = _currentSibling = nextEl(context.item); drake.dragging = true; drake.emit('drag', _item, _source); } function invalidTarget () { return false; } function end () { if (!drake.dragging) { return; } var item = _copy || _item; drop(item, getParent(item)); } function ungrab () { _grabbed = false; eventualMovements(true); movements(true); } function release (e) { ungrab(); if (!drake.dragging) { return; } var item = _copy || _item; var clientX = getCoord('clientX', e); var clientY = getCoord('clientY', e); var elementBehindCursor = getElementBehindPoint(_mirror, clientX, clientY); var dropTarget = findDropTarget(elementBehindCursor, clientX, clientY); if (dropTarget && ((_copy && o.copySortSource) || (!_copy || dropTarget !== _source))) { drop(item, dropTarget); } else if (o.removeOnSpill) { remove(); } else { cancel(); } } function drop (item, target) { var parent = getParent(item); if (_copy && o.copySortSource && target === _source) { parent.removeChild(_item); } if (isInitialPlacement(target)) { drake.emit('cancel', item, _source, _source); } else { drake.emit('drop', item, target, _source, _currentSibling); } cleanup(); } function remove () { if (!drake.dragging) { return; } var item = _copy || _item; var parent = getParent(item); if (parent) { parent.removeChild(item); } drake.emit(_copy ? 'cancel' : 'remove', item, parent, _source); cleanup(); } function cancel (revert) { if (!drake.dragging) { return; } var reverts = arguments.length > 0 ? revert : o.revertOnSpill; var item = _copy || _item; var parent = getParent(item); var initial = isInitialPlacement(parent); if (initial === false && reverts) { if (_copy) { if (parent) { parent.removeChild(_copy); } } else { _source.insertBefore(item, _initialSibling); } } if (initial || reverts) { drake.emit('cancel', item, _source, _source); } else { drake.emit('drop', item, parent, _source, _currentSibling); } cleanup(); } function cleanup () { var item = _copy || _item; ungrab(); removeMirrorImage(); if (item) { classes.rm(item, 'gu-transit'); } if (_renderTimer) { clearTimeout(_renderTimer); } drake.dragging = false; if (_lastDropTarget) { drake.emit('out', item, _lastDropTarget, _source); } drake.emit('dragend', item); _source = _item = _copy = _initialSibling = _currentSibling = _renderTimer = _lastDropTarget = null; } function isInitialPlacement (target, s) { var sibling; if (s !== void 0) { sibling = s; } else if (_mirror) { sibling = _currentSibling; } else { sibling = nextEl(_copy || _item); } return target === _source && sibling === _initialSibling; } function findDropTarget (elementBehindCursor, clientX, clientY) { var target = elementBehindCursor; while (target && !accepted()) { target = getParent(target); } return target; function accepted () { var droppable = isContainer(target); if (droppable === false) { return false; } var immediate = getImmediateChild(target, elementBehindCursor); var reference = getReference(target, immediate, clientX, clientY); var initial = isInitialPlacement(target, reference); if (initial) { return true; // should always be able to drop it right back where it was } return o.accepts(_item, target, _source, reference); } } function drag (e) { if (!_mirror) { return; } e.preventDefault(); var clientX = getCoord('clientX', e); var clientY = getCoord('clientY', e); var x = clientX - _offsetX; var y = clientY - _offsetY; _mirror.style.left = x + 'px'; _mirror.style.top = y + 'px'; var item = _copy || _item; var elementBehindCursor = getElementBehindPoint(_mirror, clientX, clientY); var dropTarget = findDropTarget(elementBehindCursor, clientX, clientY); var changed = dropTarget !== null && dropTarget !== _lastDropTarget; if (changed || dropTarget === null) { out(); _lastDropTarget = dropTarget; over(); } var parent = getParent(item); if (dropTarget === _source && _copy && !o.copySortSource) { if (parent) { parent.removeChild(item); } return; } var reference; var immediate = getImmediateChild(dropTarget, elementBehindCursor); if (immediate !== null) { reference = getReference(dropTarget, immediate, clientX, clientY); } else if (o.revertOnSpill === true && !_copy) { reference = _initialSibling; dropTarget = _source; } else { if (_copy && parent) { parent.removeChild(item); } return; } if ( (reference === null && changed) || reference !== item && reference !== nextEl(item) ) { _currentSibling = reference; dropTarget.insertBefore(item, reference); drake.emit('shadow', item, dropTarget, _source); } function moved (type) { drake.emit(type, item, _lastDropTarget, _source); } function over () { if (changed) { moved('over'); } } function out () { if (_lastDropTarget) { moved('out'); } } } function spillOver (el) { classes.rm(el, 'gu-hide'); } function spillOut (el) { if (drake.dragging) { classes.add(el, 'gu-hide'); } } function renderMirrorImage () { if (_mirror) { return; } var rect = _item.getBoundingClientRect(); _mirror = _item.cloneNode(true); _mirror.style.width = getRectWidth(rect) + 'px'; _mirror.style.height = getRectHeight(rect) + 'px'; classes.rm(_mirror, 'gu-transit'); classes.add(_mirror, 'gu-mirror'); o.mirrorContainer.appendChild(_mirror); touchy(documentElement, 'add', 'mousemove', drag); classes.add(o.mirrorContainer, 'gu-unselectable'); drake.emit('cloned', _mirror, _item, 'mirror'); } function removeMirrorImage () { if (_mirror) { classes.rm(o.mirrorContainer, 'gu-unselectable'); touchy(documentElement, 'remove', 'mousemove', drag); getParent(_mirror).removeChild(_mirror); _mirror = null; } } function getImmediateChild (dropTarget, target) { var immediate = target; while (immediate !== dropTarget && getParent(immediate) !== dropTarget) { immediate = getParent(immediate); } if (immediate === documentElement) { return null; } return immediate; } function getReference (dropTarget, target, x, y) { var horizontal = o.direction === 'horizontal'; var reference = target !== dropTarget ? inside() : outside(); return reference; function outside () { // slower, but able to figure out any position var len = dropTarget.children.length; var i; var el; var rect; for (i = 0; i < len; i++) { el = dropTarget.children[i]; rect = el.getBoundingClientRect(); if (horizontal && (rect.left + rect.width / 2) > x) { return el; } if (!horizontal && (rect.top + rect.height / 2) > y) { return el; } } return null; } function inside () { // faster, but only available if dropped inside a child element var rect = target.getBoundingClientRect(); if (horizontal) { return resolve(x > rect.left + getRectWidth(rect) / 2); } return resolve(y > rect.top + getRectHeight(rect) / 2); } function resolve (after) { return after ? nextEl(target) : target; } } function isCopy (item, container) { return typeof o.copy === 'boolean' ? o.copy : o.copy(item, container); } } function touchy (el, op, type, fn) { var touch = { mouseup: 'touchend', mousedown: 'touchstart', mousemove: 'touchmove' }; var pointers = { mouseup: 'pointerup', mousedown: 'pointerdown', mousemove: 'pointermove' }; var microsoft = { mouseup: 'MSPointerUp', mousedown: 'MSPointerDown', mousemove: 'MSPointerMove' }; if (global.navigator.pointerEnabled) { crossvent[op](el, pointers[type], fn); } else if (global.navigator.msPointerEnabled) { crossvent[op](el, microsoft[type], fn); } else { crossvent[op](el, touch[type], fn); crossvent[op](el, type, fn); } } function whichMouseButton (e) { if (e.touches !== void 0) { return e.touches.length; } if (e.which !== void 0 && e.which !== 0) { return e.which; } // see https://github.com/bevacqua/dragula/issues/261 if (e.buttons !== void 0) { return e.buttons; } var button = e.button; if (button !== void 0) { // see https://github.com/jquery/jquery/blob/99e8ff1baa7ae341e94bb89c3e84570c7c3ad9ea/src/event.js#L573-L575 return button & 1 ? 1 : button & 2 ? 3 : (button & 4 ? 2 : 0); } } function getOffset (el) { var rect = el.getBoundingClientRect(); return { left: rect.left + getScroll('scrollLeft', 'pageXOffset'), top: rect.top + getScroll('scrollTop', 'pageYOffset') }; } function getScroll (scrollProp, offsetProp) { if (typeof global[offsetProp] !== 'undefined') { return global[offsetProp]; } if (documentElement.clientHeight) { return documentElement[scrollProp]; } return doc.body[scrollProp]; } function getElementBehindPoint (point, x, y) { var p = point || {}; var state = p.className; var el; p.className += ' gu-hide'; el = doc.elementFromPoint(x, y); p.className = state; return el; } function never () { return false; } function always () { return true; } function getRectWidth (rect) { return rect.width || (rect.right - rect.left); } function getRectHeight (rect) { return rect.height || (rect.bottom - rect.top); } function getParent (el) { return el.parentNode === doc ? null : el.parentNode; } function isInput (el) { return el.tagName === 'INPUT' || el.tagName === 'TEXTAREA' || el.tagName === 'SELECT' || isEditable(el); } function isEditable (el) { if (!el) { return false; } // no parents were editable if (el.contentEditable === 'false') { return false; } // stop the lookup if (el.contentEditable === 'true') { return true; } // found a contentEditable element in the chain return isEditable(getParent(el)); // contentEditable is set to 'inherit' } function nextEl (el) { return el.nextElementSibling || manually(); function manually () { var sibling = el; do { sibling = sibling.nextSibling; } while (sibling && sibling.nodeType !== 1); return sibling; } } function getEventHost (e) { // on touchend event, we have to use `e.changedTouches` // see http://stackoverflow.com/questions/7192563/touchend-event-properties // see https://github.com/bevacqua/dragula/issues/34 if (e.targetTouches && e.targetTouches.length) { return e.targetTouches[0]; } if (e.changedTouches && e.changedTouches.length) { return e.changedTouches[0]; } return e; } function getCoord (coord, e) { var host = getEventHost(e); var missMap = { pageX: 'clientX', // IE8 pageY: 'clientY' // IE8 }; if (coord in missMap && !(coord in host) && missMap[coord] in host) { coord = missMap[coord]; } return host[coord]; } module.exports = dragula;
fixing default values - causing tests to crash - throw errors when e is undefined and math is attempted on it
dragula.js
fixing default values
<ide><path>ragula.js <ide> return; <ide> } <ide> if (o.ignoreInputTextSelection) { <del> var clientX = getCoord('clientX', e); <del> var clientY = getCoord('clientY', e); <add> var clientX = getCoord('clientX', e) || 0; <add> var clientY = getCoord('clientY', e) || 0; <ide> var elementBehindCursor = doc.elementFromPoint(clientX, clientY); <ide> if (isInput(elementBehindCursor)) { <ide> return; <ide> return; <ide> } <ide> var item = _copy || _item; <del> var clientX = getCoord('clientX', e); <del> var clientY = getCoord('clientY', e); <add> var clientX = getCoord('clientX', e) || 0; <add> var clientY = getCoord('clientY', e) || 0; <ide> var elementBehindCursor = getElementBehindPoint(_mirror, clientX, clientY); <ide> var dropTarget = findDropTarget(elementBehindCursor, clientX, clientY); <ide> if (dropTarget && ((_copy && o.copySortSource) || (!_copy || dropTarget !== _source))) { <ide> } <ide> e.preventDefault(); <ide> <del> var clientX = getCoord('clientX', e); <del> var clientY = getCoord('clientY', e); <add> var clientX = getCoord('clientX', e) || 0; <add> var clientY = getCoord('clientY', e) || 0; <ide> var x = clientX - _offsetX; <ide> var y = clientY - _offsetY; <ide> <ide> } <ide> <ide> function getElementBehindPoint (point, x, y) { <del> var p = point || {}; <del> var state = p.className; <add> point = point || {}; <add> var state = point.className || ''; <ide> var el; <del> p.className += ' gu-hide'; <add> point.className += ' gu-hide'; <ide> el = doc.elementFromPoint(x, y); <del> p.className = state; <add> point.className = state; <ide> return el; <ide> } <ide>
JavaScript
mit
41163944c9daa29093d1af63e47ad276136c9f37
0
fvilers/angular2-training,fvilers/angular2-training,fvilers/angular2-training
'use strict'; const mongoose = require('mongoose'); const options = require('./default-options'); const schema = new mongoose.Schema({ name: { required: true, type: String, unique: true }, title: { type: String }, universe: { index: true, required: true, type: Number }, roles: [{ index: true, required: true, type: Number }], image: { type: String, required: true }, description: { type: String } }, Object.assign(options, { collection: 'heroes' })); schema.plugin(require('mongoose-slug-hero'), { doc: 'filter', field: 'name' }); module.exports = schema;
server/models/schemas/hero.js
'use strict'; const mongoose = require('mongoose'); const options = require('./default-options'); const schema = new mongoose.Schema({ name: { required: true, type: String, unique: true }, title: { type: String }, universe: { index: true, required: true, type: Number }, roles: [{ index: true, required: true, type: Number }], image: { type: String, required: true }, }, Object.assign(options, { collection: 'heroes' })); schema.plugin(require('mongoose-slug-hero'), { doc: 'filter', field: 'name' }); module.exports = schema;
Add missing description field
server/models/schemas/hero.js
Add missing description field
<ide><path>erver/models/schemas/hero.js <ide> type: String, <ide> required: true <ide> }, <add> description: { <add> type: String <add> } <ide> }, Object.assign(options, { collection: 'heroes' })); <ide> <ide> schema.plugin(require('mongoose-slug-hero'), { doc: 'filter', field: 'name' });
Java
mpl-2.0
210cf0fda0c9aa2483e1df4a0637bce78a0a076b
0
Vexatos/Tropicraft,ReikaKalseki/Tropicraft,cbaakman/Tropicraft
package net.tropicraft.registry; import net.minecraft.item.Item; import net.minecraft.item.Item.ToolMaterial; import net.minecraft.item.ItemArmor.ArmorMaterial; import net.minecraft.item.ItemHoe; import net.minecraft.item.ItemSword; import net.minecraftforge.common.util.EnumHelper; import net.minecraftforge.oredict.OreDictionary; import net.tropicraft.entity.EntityTCItemFrame; import net.tropicraft.info.TCNames; import net.tropicraft.item.ItemBambooChute; import net.tropicraft.item.ItemBambooDoor; import net.tropicraft.item.ItemCocktail; import net.tropicraft.item.ItemCoconutBomb; import net.tropicraft.item.ItemCoffeeBean; import net.tropicraft.item.ItemCurare; import net.tropicraft.item.ItemDagger; import net.tropicraft.item.ItemDart; import net.tropicraft.item.ItemDartGun; import net.tropicraft.item.ItemFertilizer; import net.tropicraft.item.ItemFishBucket; import net.tropicraft.item.ItemFlippers; import net.tropicraft.item.ItemFlowerPot; import net.tropicraft.item.ItemMobEgg; import net.tropicraft.item.ItemPortalEnchanter; import net.tropicraft.item.ItemShell; import net.tropicraft.item.ItemSnareTrap; import net.tropicraft.item.ItemSnorkel; import net.tropicraft.item.ItemTCItemFrame; import net.tropicraft.item.ItemTikiTorch; import net.tropicraft.item.ItemTropBook; import net.tropicraft.item.ItemTropicraft; import net.tropicraft.item.ItemTropicraftFood; import net.tropicraft.item.ItemTropicraftLeafballNew; import net.tropicraft.item.ItemTropicraftMulti; import net.tropicraft.item.ItemTropicraftMusicDisk; import net.tropicraft.item.ItemTropicraftOre; import net.tropicraft.item.ItemTropicsWaterBucket; import net.tropicraft.item.ItemWaterWand; import net.tropicraft.item.armor.ItemAshenMask; import net.tropicraft.item.armor.ItemFireArmor; import net.tropicraft.item.armor.ItemScaleArmor; import net.tropicraft.item.armor.ItemTropicraftArmor; import net.tropicraft.item.placeable.ItemChair; import net.tropicraft.item.placeable.ItemUmbrella; import net.tropicraft.item.tool.ItemTropicraftAxe; import net.tropicraft.item.tool.ItemTropicraftHoe; import net.tropicraft.item.tool.ItemTropicraftPickaxe; import net.tropicraft.item.tool.ItemTropicraftShovel; import net.tropicraft.item.tool.ItemTropicraftSword; import net.tropicraft.item.tool.ItemTropicraftTool; import CoroUtil.entity.ItemTropicalFishingRod; import cpw.mods.fml.common.registry.GameRegistry; public class TCItemRegistry { public static final ItemTropicraft frogLeg = new ItemTropicraft(); public static final ItemTropicraftFood cookedFrogLeg = new ItemTropicraftFood(2, 0.15F); public static final ItemTropicraft poisonFrogSkin = new ItemTropicraft(); public static final ItemTropicraftFood freshMarlin = new ItemTropicraftFood(2, 0.3F); public static final ItemTropicraftFood searedMarlin = new ItemTropicraftFood(8, 0.65F); public static final ItemTropicraftFood grapefruit = new ItemTropicraftFood(2, 0.2F); public static final ItemTropicraftFood lemon = new ItemTropicraftFood(2, 0.2F); public static final ItemTropicraftFood lime = new ItemTropicraftFood(2, 0.2F); public static final ItemTropicraftFood orange = new ItemTropicraftFood(2, 0.2F); public static final ItemTropicraft scale = (ItemTropicraft) new ItemTropicraft().setMaxStackSize(64); public static final ItemTropicraftFood coconutChunk = new ItemTropicraftFood(1, 0.1F); public static final ItemTropicraftFood pineappleCubes = new ItemTropicraftFood(1, 0.1F); public static final ItemTropicraft bambooStick = (ItemTropicraft) new ItemTropicraft().setMaxStackSize(64); public static final ItemTropicraftFood seaUrchinRoe = new ItemTropicraftFood(3, 0.3F); public static final ItemTropicraft pearl = new ItemTropicraftMulti(TCNames.pearlNames); public static final ItemTropicraft ore = new ItemTropicraftOre(TCNames.oreNames); public static final ItemTropicraft waterWand = new ItemWaterWand(); public static final ItemTropicraft fishingNet = new ItemTropicraft(); public static final ItemTropicraft coffeeBean = new ItemCoffeeBean(); // Armor public static final ArmorMaterial materialScaleArmor = EnumHelper.addArmorMaterial("scale", 18, new int[]{2, 6, 5, 2}, 9); public static final ItemTropicraftArmor scaleBoots = new ItemScaleArmor(materialScaleArmor, 0, 3); public static final ItemTropicraftArmor scaleLeggings = new ItemScaleArmor(materialScaleArmor, 0, 2); public static final ItemTropicraftArmor scaleChestplate = new ItemScaleArmor(materialScaleArmor, 0, 1); public static final ItemTropicraftArmor scaleHelmet = new ItemScaleArmor(materialScaleArmor, 0, 0); public static final ArmorMaterial materialFireArmor = EnumHelper.addArmorMaterial("fire", 12, new int[]{2, 4, 5, 6}, 9); public static final ItemTropicraftArmor fireBoots = new ItemFireArmor(materialFireArmor, 0, 3); public static final ItemTropicraftArmor fireLeggings = new ItemFireArmor(materialFireArmor, 0, 2); public static final ItemTropicraftArmor fireChestplate = new ItemFireArmor(materialFireArmor, 0, 1); public static final ItemTropicraftArmor fireHelmet = new ItemFireArmor(materialFireArmor, 0, 0); public static final ArmorMaterial materialMaskArmor = EnumHelper.addArmorMaterial("mask", 18, new int[]{2, 6, 5, 2}, 9); public static final ItemTropicraftArmor ashenMask = (ItemTropicraftArmor) new ItemAshenMask(materialMaskArmor, 0, 0, getMaskDisplayNames(), getMaskImageNames()).setCreativeTab(TCCreativeTabRegistry.tabDecorations); // End Armor // Tools public static ToolMaterial materialZirconTools = EnumHelper.addToolMaterial("zircon", 2, 500, 6.5F, 2.5F, 14); public static ToolMaterial materialEudialyteTools = EnumHelper.addToolMaterial("eudialyte", 2, 750, 5.5F, 1.5F, 14); public static ToolMaterial materialZirconiumTools = EnumHelper.addToolMaterial("zirconium", 3, 1800, 8.5F, 3.5F, 10); public static final ItemHoe hoeEudialyte = new ItemTropicraftHoe(materialEudialyteTools, TCNames.hoeEudialyte); public static final ItemHoe hoeZircon = new ItemTropicraftHoe(materialZirconTools, TCNames.hoeZircon); public static final ItemHoe hoeZirconium = new ItemTropicraftHoe(materialZirconiumTools, TCNames.hoeZirconium); public static final ItemTropicraftTool shovelEudialyte = new ItemTropicraftShovel(materialEudialyteTools, TCNames.shovelEudialyte); public static final ItemTropicraftTool shovelZircon = new ItemTropicraftShovel(materialZirconTools, TCNames.shovelZircon); public static final ItemTropicraftTool shovelZirconium = new ItemTropicraftShovel(materialZirconiumTools, TCNames.shovelZirconium); public static final ItemTropicraftTool pickaxeEudialyte = new ItemTropicraftPickaxe(materialEudialyteTools, TCNames.pickaxeEudialyte); public static final ItemTropicraftTool pickaxeZircon = new ItemTropicraftPickaxe(materialZirconTools, TCNames.pickaxeZircon); public static final ItemTropicraftTool pickaxeZirconium = new ItemTropicraftPickaxe(materialZirconiumTools, TCNames.pickaxeZirconium); public static final ItemTropicraftTool axeEudialyte = new ItemTropicraftAxe(materialEudialyteTools, TCNames.axeEudialyte); public static final ItemTropicraftTool axeZircon = new ItemTropicraftAxe(materialZirconTools, TCNames.axeZircon); public static final ItemTropicraftTool axeZirconium = new ItemTropicraftAxe(materialZirconiumTools, TCNames.axeZirconium); public static final ItemSword swordEudialyte = new ItemTropicraftSword(materialEudialyteTools, TCNames.swordEudialyte); public static final ItemSword swordZircon = new ItemTropicraftSword(materialZirconTools, TCNames.swordZircon); public static final ItemSword swordZirconium = new ItemTropicraftSword(materialZirconiumTools, TCNames.swordZirconium); // End Tools public static final ItemTropicraft tikiTorch = new ItemTikiTorch(); public static final ItemTropicraft bambooDoor = new ItemBambooDoor(); public static final ItemTropicsWaterBucket bucketTropicsWater = new ItemTropicsWaterBucket(); public static final ItemFishBucket fishBucket = new ItemFishBucket(); public static final ItemChair chair = new ItemChair(); public static final ItemUmbrella umbrella = new ItemUmbrella(); public static final ItemFlowerPot flowerPot = new ItemFlowerPot(TCBlockRegistry.flowerPot); public static final ItemFertilizer fertilizer = new ItemFertilizer(); public static final ItemTropicraft coconutBomb = (ItemTropicraft) new ItemCoconutBomb().setMaxStackSize(64); /* public static final ArmorMaterial materialDrySuit = EnumHelper.addArmorMaterial("fire", 50, new int[]{2, 4, 5, 6}, 9); public static final ItemTropicraftArmor dryFlippers = new ItemScubaFlippers(materialDrySuit, ItemScubaGear.ScubaMaterial.DRY, 0, 3); public static final ItemTropicraftArmor dryLeggings = new ItemScubaLeggings(materialDrySuit, ItemScubaGear.ScubaMaterial.DRY, 0, 2); public static final ItemTropicraftArmor dryChestplate = new ItemScubaChestplate(materialDrySuit, ItemScubaGear.ScubaMaterial.DRY, 0, 1); public static final ItemTropicraftArmor dryChestplateGear = new ItemScubaChestplateGear(materialDrySuit, ItemScubaGear.ScubaMaterial.DRY, 0, 1); public static final ItemTropicraftArmor dryHelmet = new ItemScubaHelmet(materialDrySuit, ItemScubaGear.ScubaMaterial.DRY, 0, 0); public static final ArmorMaterial materialWetSuit = EnumHelper.addArmorMaterial("fire", 50, new int[]{2, 4, 5, 6}, 9); public static final ItemTropicraftArmor wetFlippers = new ItemScubaFlippers(materialWetSuit, ItemScubaGear.ScubaMaterial.WET, 0, 3); public static final ItemTropicraftArmor wetLeggings = new ItemScubaLeggings(materialWetSuit, ItemScubaGear.ScubaMaterial.WET, 0, 2); public static final ItemTropicraftArmor wetChestplate = new ItemScubaChestplate(materialWetSuit, ItemScubaGear.ScubaMaterial.WET, 0, 1); public static final ItemTropicraftArmor wetChestplateGear = new ItemScubaChestplateGear(materialWetSuit, ItemScubaGear.ScubaMaterial.WET, 0, 1); public static final ItemTropicraftArmor wetHelmet = new ItemScubaHelmet(materialWetSuit, ItemScubaGear.ScubaMaterial.WET, 0, 0); public static final ItemScubaTank scubaTank = new ItemScubaTank(); public static final ItemDiveComputer diveComputer = new ItemDiveComputer(); public static final ItemBCD bcd = new ItemBCD();*/ public static final ItemCurare curare = new ItemCurare(); public static final ItemDart dart = new ItemDart(); public static final ItemDartGun blowGun = new ItemDartGun(); /* TODO public static ToolMaterial materialUnderwaterTools = EnumHelper.addToolMaterial("tcaqua", 2, 500, 6.5F, 2.5F, 14); public static final ItemTropicraftTool aquaAxe = new ItemUnderwaterAxe(materialUnderwaterTools, TCNames.aquaAxe); public static final ItemUnderwaterHoe aquaHoe = new ItemUnderwaterHoe(materialUnderwaterTools, TCNames.aquaHoe); public static final ItemTropicraftTool aquaPickaxe = new ItemUnderwaterPickaxe(materialUnderwaterTools, TCNames.aquaPickaxe); public static final ItemTropicraftTool aquaShovel = new ItemUnderwaterShovel(materialUnderwaterTools, TCNames.aquaShovel); */ public static final Item shells = new ItemShell(TCNames.shellNames); public static ToolMaterial materialBambooTools = EnumHelper.addToolMaterial("bamboo", 1, 110, 1.2F, 1F, 6); public static final Item bambooSpear = new ItemTropicraftSword(materialBambooTools, TCNames.bambooSpear); public static Item leafBall = (new ItemTropicraftLeafballNew()).setUnlocalizedName("leaf_green").setCreativeTab(TCCreativeTabRegistry.tabCombat); public static Item dagger = (new ItemDagger(materialZirconTools)).setUnlocalizedName("dagger"); //public static ItemStaffFireball staffFire = (ItemStaffFireball) (new ItemStaffFireball()).setUnlocalizedName("staff_fire").setCreativeTab(TCCreativeTabRegistry.tabCombat); //public static ItemStaffIceball staffIce; //public static ItemStaffOfTaming staffTaming = (ItemStaffOfTaming) (new ItemStaffOfTaming()).setUnlocalizedName("staff_taming").setCreativeTab(TCCreativeTabRegistry.tabCombat); public static Item fishingRodTropical = (new ItemTropicalFishingRod()).setUnlocalizedName("FishingRodTropical"); public static Item bambooChute = new ItemBambooChute(TCBlockRegistry.bambooChute).setUnlocalizedName("BambooChute"); public static final ArmorMaterial materialSnorkelGear = EnumHelper.addArmorMaterial("watergear", 40, new int[]{2, 4, 5, 6}, 9); public static Item flippers = new ItemFlippers(materialSnorkelGear, 0, 3); public static Item snorkel = new ItemSnorkel(materialSnorkelGear, 0, 0); public static Item recordBuriedTreasure = new ItemTropicraftMusicDisk("buriedtreasure", "buriedtreasure", "Punchaface").setUnlocalizedName("Buried Treasure"); public static Item recordEasternIsles = new ItemTropicraftMusicDisk("easternisles", "easternisles", "Frox").setUnlocalizedName("Eastern Isles"); public static Item recordLowTide = new ItemTropicraftMusicDisk("lowtide", "lowtide", "Punchaface").setUnlocalizedName("Low Tide"); public static Item recordSummering = new ItemTropicraftMusicDisk("summering", "summering", "Billy Christiansen").setUnlocalizedName("Summering"); public static Item recordTheTribe = new ItemTropicraftMusicDisk("thetribe", "thetribe", "Emile Van Krieken").setUnlocalizedName("The Tribe"); public static Item recordTradeWinds = new ItemTropicraftMusicDisk("tradewinds", "tradewinds", "Frox").setUnlocalizedName("Trade Winds"); public static Item portalEnchanter = new ItemPortalEnchanter(); public static Item bambooMug = new ItemTropicraft().setMaxStackSize(16); public static Item tropiFrame = (new ItemTCItemFrame(EntityTCItemFrame.class, true)).setUnlocalizedName("tropiFrame"); public static Item koaFrame = (new ItemTCItemFrame(EntityTCItemFrame.class, false)).setUnlocalizedName("koaFrame"); public static Item cocktail = new ItemCocktail(TCCreativeTabRegistry.tabFood); // public static Item rodOld = new ItemRod().setType(ItemRod.TYPE_OLD).setUnlocalizedName("rodOld"); // public static Item rodGood = new ItemRod().setType(ItemRod.TYPE_GOOD).setUnlocalizedName("rodGood"); // public static Item rodSuper = new ItemRod().setType(ItemRod.TYPE_SUPER).setUnlocalizedName("rodSuper"); // public static Item lureSuper = new ItemTropicraft().setUnlocalizedName("lureSuper"); //public static Item ashenMasks = new ItemAshenMask(ModIds.ITEM_ASHENMASK_ID, getMaskDisplayNames(), getMaskImageNames()).setUnlocalizedName("ashenMasks"); public static Item snareTrap = new ItemSnareTrap().setUnlocalizedName("snareTrap"); public static Item encTropica = new ItemTropBook("encTropica").setUnlocalizedName("encTropica"); public static Item mobEgg = new ItemMobEgg(TCNames.eggTextureNames); /** * Register all the items */ public static void init() { registerItem(frogLeg, TCNames.frogLeg); registerItem(cookedFrogLeg, TCNames.cookedFrogLeg); registerItem(poisonFrogSkin, TCNames.poisonFrogSkin); registerItem(freshMarlin, TCNames.freshMarlin); registerItem(searedMarlin, TCNames.searedMarlin); registerItem(grapefruit, TCNames.grapefruit); registerItem(lemon, TCNames.lemon); registerItem(lime, TCNames.lime); registerItem(orange, TCNames.orange); registerItem(scale, TCNames.scale); registerItem(coconutChunk, TCNames.coconutChunk); registerItem(pineappleCubes, TCNames.pineappleCubes); registerItem(bambooStick, TCNames.bambooStick); registerItem(seaUrchinRoe, TCNames.seaUrchinRoe); registerItem(pearl, TCNames.pearl); registerItem(ore, TCNames.ore); registerItem(waterWand, TCNames.waterWand); registerItem(fishingNet, TCNames.fishingNet); registerItem(coffeeBean, TCNames.coffeeBean); // Armor registerItem(scaleBoots, TCNames.scaleBoots); registerItem(scaleLeggings, TCNames.scaleLeggings); registerItem(scaleChestplate, TCNames.scaleChestplate); registerItem(scaleHelmet, TCNames.scaleHelmet); registerItem(fireBoots, TCNames.fireBoots); registerItem(fireLeggings, TCNames.fireLeggings); registerItem(fireChestplate, TCNames.fireChestplate); registerItem(fireHelmet, TCNames.fireHelmet); registerItem(axeEudialyte, TCNames.axeEudialyte); registerItem(hoeEudialyte, TCNames.hoeEudialyte); registerItem(pickaxeEudialyte, TCNames.pickaxeEudialyte); registerItem(shovelEudialyte, TCNames.shovelEudialyte); registerItem(swordEudialyte, TCNames.swordEudialyte); registerItem(axeZircon, TCNames.axeZircon); registerItem(hoeZircon, TCNames.hoeZircon); registerItem(pickaxeZircon, TCNames.pickaxeZircon); registerItem(shovelZircon, TCNames.shovelZircon); registerItem(swordZircon, TCNames.swordZircon); registerItem(tikiTorch, TCNames.tikiTorch); registerItem(bambooDoor, TCNames.bambooDoor); registerItem(bucketTropicsWater, TCNames.bucketTropicsWater); registerItem(chair, TCNames.chair); registerItem(umbrella, TCNames.umbrella); registerItem(flowerPot, TCNames.flowerPot); registerItem(fertilizer, TCNames.fertilizer); /* registerItem(dryFlippers, TCNames.dryFlippers); registerItem(dryLeggings, TCNames.dryLeggings); registerItem(dryChestplate, TCNames.dryChestplate); registerItem(dryChestplateGear, TCNames.dryChestplateGear); registerItem(dryHelmet, TCNames.dryHelmet); registerItem(wetFlippers, TCNames.wetFlippers); registerItem(wetLeggings, TCNames.wetLeggings); registerItem(wetChestplate, TCNames.wetChestplate); registerItem(wetChestplateGear, TCNames.wetChestplateGear); registerItem(wetHelmet, TCNames.wetHelmet); registerItem(scubaTank, TCNames.scubaTank); registerItem(diveComputer, TCNames.diveComputer); registerItem(bcd, TCNames.bcd);*/ registerItem(curare, TCNames.curare); registerItem(dart, TCNames.dart); registerItem(blowGun, TCNames.dartGun); registerItem(axeZirconium, TCNames.axeZirconium); registerItem(hoeZirconium, TCNames.hoeZirconium); registerItem(pickaxeZirconium, TCNames.pickaxeZirconium); registerItem(shovelZirconium, TCNames.shovelZirconium); registerItem(swordZirconium, TCNames.swordZirconium); /* registerItem(aquaAxe, TCNames.aquaAxe); registerItem(aquaHoe, TCNames.aquaHoe); registerItem(aquaPickaxe, TCNames.aquaPickaxe); registerItem(aquaShovel, TCNames.aquaShovel);*/ registerItem(shells, TCNames.shell); registerItem(bambooSpear, TCNames.bambooSpear); registerItem(coconutBomb, TCNames.coconutBomb); registerItem(bambooChute, TCNames.bambooChute); registerItem(snorkel, TCNames.snorkel); registerItem(flippers, TCNames.flippers); registerItem(dagger, TCNames.dagger); // registerItem(staffFire, TCNames.staffFire); // registerItem(staffTaming, TCNames.staffTaming); registerItem(fishingRodTropical, TCNames.fishingRodTropical); registerItem(recordBuriedTreasure, TCNames.recordBuriedTreasure); registerItem(recordEasternIsles, TCNames.recordEasternIsles); registerItem(recordLowTide, TCNames.recordLowTide); registerItem(recordSummering, TCNames.recordSummering); registerItem(recordTheTribe, TCNames.recordTheTribe); registerItem(recordTradeWinds, TCNames.recordTradeWinds); registerItem(portalEnchanter, TCNames.portalEnchanter); registerItem(bambooMug, TCNames.bambooMug); registerItem(tropiFrame, TCNames.tropiFrame); registerItem(koaFrame, TCNames.koaFrame); registerItem(cocktail, TCNames.cocktail); registerItem(leafBall, TCNames.leafBall); registerItem(fishBucket, TCNames.fishBucket); registerItem(snareTrap, TCNames.snareTrap); registerItem(encTropica, TCNames.encTropica); registerItem(mobEgg, TCNames.egg); //registerItem(ashenMask, TCNames.ashenMask); } /** * Register an item with the game and give it a name * @param item Item to register * @param name Name to give */ private static void registerItem(Item item, String name) { GameRegistry.registerItem(item, name); item.setUnlocalizedName(name); OreDictionary.registerOre(name, item); } public static String[] getShellImageNames() { return new String[]{"shell_solo", "shell_frox", "shell_pab", "shell_rube", "shell_starfish", "shell_turtle"}; } public static String[] getMaskDisplayNames() { return new String[] {"Square Zord", "Horn Monkey", "Oblongatron", "Headinator", "Square Horn", "Screw Attack", "The Brain", "Bat Boy", "Ashen Mask", "Ashen Mask", "Ashen Mask", "Ashen Mask", "Ashen Mask"}; } public static String[] getMaskImageNames() { String[] strArr = new String[getMaskDisplayNames().length]; for (int i = 0; i < strArr.length; i++) { strArr[i] = "mask_" + i; } return strArr; } }
src/main/java/net/tropicraft/registry/TCItemRegistry.java
package net.tropicraft.registry; import net.minecraft.item.Item; import net.minecraft.item.Item.ToolMaterial; import net.minecraft.item.ItemArmor.ArmorMaterial; import net.minecraft.item.ItemHoe; import net.minecraft.item.ItemSword; import net.minecraftforge.common.util.EnumHelper; import net.minecraftforge.oredict.OreDictionary; import net.tropicraft.entity.EntityTCItemFrame; import net.tropicraft.info.TCNames; import net.tropicraft.item.ItemBambooChute; import net.tropicraft.item.ItemBambooDoor; import net.tropicraft.item.ItemCocktail; import net.tropicraft.item.ItemCoconutBomb; import net.tropicraft.item.ItemCoffeeBean; import net.tropicraft.item.ItemCurare; import net.tropicraft.item.ItemDagger; import net.tropicraft.item.ItemDart; import net.tropicraft.item.ItemDartGun; import net.tropicraft.item.ItemFertilizer; import net.tropicraft.item.ItemFishBucket; import net.tropicraft.item.ItemFlippers; import net.tropicraft.item.ItemFlowerPot; import net.tropicraft.item.ItemMobEgg; import net.tropicraft.item.ItemPortalEnchanter; import net.tropicraft.item.ItemShell; import net.tropicraft.item.ItemSnareTrap; import net.tropicraft.item.ItemSnorkel; import net.tropicraft.item.ItemTCItemFrame; import net.tropicraft.item.ItemTikiTorch; import net.tropicraft.item.ItemTropBook; import net.tropicraft.item.ItemTropicraft; import net.tropicraft.item.ItemTropicraftFood; import net.tropicraft.item.ItemTropicraftLeafballNew; import net.tropicraft.item.ItemTropicraftMulti; import net.tropicraft.item.ItemTropicraftMusicDisk; import net.tropicraft.item.ItemTropicraftOre; import net.tropicraft.item.ItemTropicsWaterBucket; import net.tropicraft.item.ItemWaterWand; import net.tropicraft.item.armor.ItemAshenMask; import net.tropicraft.item.armor.ItemFireArmor; import net.tropicraft.item.armor.ItemScaleArmor; import net.tropicraft.item.armor.ItemTropicraftArmor; import net.tropicraft.item.placeable.ItemChair; import net.tropicraft.item.placeable.ItemUmbrella; import net.tropicraft.item.tool.ItemTropicraftAxe; import net.tropicraft.item.tool.ItemTropicraftHoe; import net.tropicraft.item.tool.ItemTropicraftPickaxe; import net.tropicraft.item.tool.ItemTropicraftShovel; import net.tropicraft.item.tool.ItemTropicraftSword; import net.tropicraft.item.tool.ItemTropicraftTool; import CoroUtil.entity.ItemTropicalFishingRod; import cpw.mods.fml.common.registry.GameRegistry; public class TCItemRegistry { public static final ItemTropicraft frogLeg = new ItemTropicraft(); public static final ItemTropicraftFood cookedFrogLeg = new ItemTropicraftFood(2, 0.15F); public static final ItemTropicraft poisonFrogSkin = new ItemTropicraft(); public static final ItemTropicraftFood freshMarlin = new ItemTropicraftFood(2, 0.3F); public static final ItemTropicraftFood searedMarlin = new ItemTropicraftFood(8, 0.65F); public static final ItemTropicraftFood grapefruit = new ItemTropicraftFood(2, 0.2F); public static final ItemTropicraftFood lemon = new ItemTropicraftFood(2, 0.2F); public static final ItemTropicraftFood lime = new ItemTropicraftFood(2, 0.2F); public static final ItemTropicraftFood orange = new ItemTropicraftFood(2, 0.2F); public static final ItemTropicraft scale = (ItemTropicraft) new ItemTropicraft().setMaxStackSize(64); public static final ItemTropicraftFood coconutChunk = new ItemTropicraftFood(1, 0.1F); public static final ItemTropicraftFood pineappleCubes = new ItemTropicraftFood(1, 0.1F); public static final ItemTropicraft bambooStick = (ItemTropicraft) new ItemTropicraft().setMaxStackSize(64); public static final ItemTropicraftFood seaUrchinRoe = new ItemTropicraftFood(3, 0.3F); public static final ItemTropicraft pearl = new ItemTropicraftMulti(TCNames.pearlNames); public static final ItemTropicraft ore = new ItemTropicraftOre(TCNames.oreNames); public static final ItemTropicraft waterWand = new ItemWaterWand(); public static final ItemTropicraft fishingNet = new ItemTropicraft(); public static final ItemTropicraft coffeeBean = new ItemCoffeeBean(); // Armor public static final ArmorMaterial materialScaleArmor = EnumHelper.addArmorMaterial("scale", 18, new int[]{2, 6, 5, 2}, 9); public static final ItemTropicraftArmor scaleBoots = new ItemScaleArmor(materialScaleArmor, 0, 3); public static final ItemTropicraftArmor scaleLeggings = new ItemScaleArmor(materialScaleArmor, 0, 2); public static final ItemTropicraftArmor scaleChestplate = new ItemScaleArmor(materialScaleArmor, 0, 1); public static final ItemTropicraftArmor scaleHelmet = new ItemScaleArmor(materialScaleArmor, 0, 0); public static final ArmorMaterial materialFireArmor = EnumHelper.addArmorMaterial("fire", 12, new int[]{2, 4, 5, 6}, 9); public static final ItemTropicraftArmor fireBoots = new ItemFireArmor(materialFireArmor, 0, 3); public static final ItemTropicraftArmor fireLeggings = new ItemFireArmor(materialFireArmor, 0, 2); public static final ItemTropicraftArmor fireChestplate = new ItemFireArmor(materialFireArmor, 0, 1); public static final ItemTropicraftArmor fireHelmet = new ItemFireArmor(materialFireArmor, 0, 0); public static final ArmorMaterial materialMaskArmor = EnumHelper.addArmorMaterial("mask", 18, new int[]{2, 6, 5, 2}, 9); public static final ItemTropicraftArmor ashenMask = (ItemTropicraftArmor) new ItemAshenMask(materialMaskArmor, 0, 0, getMaskDisplayNames(), getMaskImageNames()).setCreativeTab(TCCreativeTabRegistry.tabDecorations); // End Armor // Tools public static ToolMaterial materialZirconTools = EnumHelper.addToolMaterial("zircon", 2, 500, 6.5F, 2.5F, 14); public static ToolMaterial materialEudialyteTools = EnumHelper.addToolMaterial("eudialyte", 2, 750, 5.5F, 1.5F, 14); public static ToolMaterial materialZirconiumTools = EnumHelper.addToolMaterial("zirconium", 3, 1800, 8.5F, 3.5F, 10); public static final ItemHoe hoeEudialyte = new ItemTropicraftHoe(materialEudialyteTools, TCNames.hoeEudialyte); public static final ItemHoe hoeZircon = new ItemTropicraftHoe(materialZirconTools, TCNames.hoeZircon); public static final ItemHoe hoeZirconium = new ItemTropicraftHoe(materialZirconiumTools, TCNames.hoeZirconium); public static final ItemTropicraftTool shovelEudialyte = new ItemTropicraftShovel(materialEudialyteTools, TCNames.shovelEudialyte); public static final ItemTropicraftTool shovelZircon = new ItemTropicraftShovel(materialZirconTools, TCNames.shovelZircon); public static final ItemTropicraftTool shovelZirconium = new ItemTropicraftShovel(materialZirconiumTools, TCNames.shovelZirconium); public static final ItemTropicraftTool pickaxeEudialyte = new ItemTropicraftPickaxe(materialEudialyteTools, TCNames.pickaxeEudialyte); public static final ItemTropicraftTool pickaxeZircon = new ItemTropicraftPickaxe(materialZirconTools, TCNames.pickaxeZircon); public static final ItemTropicraftTool pickaxeZirconium = new ItemTropicraftPickaxe(materialZirconiumTools, TCNames.pickaxeZirconium); public static final ItemTropicraftTool axeEudialyte = new ItemTropicraftAxe(materialEudialyteTools, TCNames.axeEudialyte); public static final ItemTropicraftTool axeZircon = new ItemTropicraftAxe(materialZirconTools, TCNames.axeZircon); public static final ItemTropicraftTool axeZirconium = new ItemTropicraftAxe(materialZirconiumTools, TCNames.axeZirconium); public static final ItemSword swordEudialyte = new ItemTropicraftSword(materialEudialyteTools, TCNames.swordEudialyte); public static final ItemSword swordZircon = new ItemTropicraftSword(materialZirconTools, TCNames.swordZircon); public static final ItemSword swordZirconium = new ItemTropicraftSword(materialZirconiumTools, TCNames.swordZirconium); // End Tools public static final ItemTropicraft tikiTorch = new ItemTikiTorch(); public static final ItemTropicraft bambooDoor = new ItemBambooDoor(); public static final ItemTropicsWaterBucket bucketTropicsWater = new ItemTropicsWaterBucket(); public static final ItemFishBucket fishBucket = new ItemFishBucket(); public static final ItemChair chair = new ItemChair(); public static final ItemUmbrella umbrella = new ItemUmbrella(); public static final ItemFlowerPot flowerPot = new ItemFlowerPot(TCBlockRegistry.flowerPot); public static final ItemFertilizer fertilizer = new ItemFertilizer(); public static final ItemTropicraft coconutBomb = (ItemTropicraft) new ItemCoconutBomb().setMaxStackSize(64); /* public static final ArmorMaterial materialDrySuit = EnumHelper.addArmorMaterial("fire", 50, new int[]{2, 4, 5, 6}, 9); public static final ItemTropicraftArmor dryFlippers = new ItemScubaFlippers(materialDrySuit, ItemScubaGear.ScubaMaterial.DRY, 0, 3); public static final ItemTropicraftArmor dryLeggings = new ItemScubaLeggings(materialDrySuit, ItemScubaGear.ScubaMaterial.DRY, 0, 2); public static final ItemTropicraftArmor dryChestplate = new ItemScubaChestplate(materialDrySuit, ItemScubaGear.ScubaMaterial.DRY, 0, 1); public static final ItemTropicraftArmor dryChestplateGear = new ItemScubaChestplateGear(materialDrySuit, ItemScubaGear.ScubaMaterial.DRY, 0, 1); public static final ItemTropicraftArmor dryHelmet = new ItemScubaHelmet(materialDrySuit, ItemScubaGear.ScubaMaterial.DRY, 0, 0); public static final ArmorMaterial materialWetSuit = EnumHelper.addArmorMaterial("fire", 50, new int[]{2, 4, 5, 6}, 9); public static final ItemTropicraftArmor wetFlippers = new ItemScubaFlippers(materialWetSuit, ItemScubaGear.ScubaMaterial.WET, 0, 3); public static final ItemTropicraftArmor wetLeggings = new ItemScubaLeggings(materialWetSuit, ItemScubaGear.ScubaMaterial.WET, 0, 2); public static final ItemTropicraftArmor wetChestplate = new ItemScubaChestplate(materialWetSuit, ItemScubaGear.ScubaMaterial.WET, 0, 1); public static final ItemTropicraftArmor wetChestplateGear = new ItemScubaChestplateGear(materialWetSuit, ItemScubaGear.ScubaMaterial.WET, 0, 1); public static final ItemTropicraftArmor wetHelmet = new ItemScubaHelmet(materialWetSuit, ItemScubaGear.ScubaMaterial.WET, 0, 0); public static final ItemScubaTank scubaTank = new ItemScubaTank(); public static final ItemDiveComputer diveComputer = new ItemDiveComputer(); public static final ItemBCD bcd = new ItemBCD();*/ public static final ItemCurare curare = new ItemCurare(); public static final ItemDart dart = new ItemDart(); public static final ItemDartGun blowGun = new ItemDartGun(); /* TODO public static ToolMaterial materialUnderwaterTools = EnumHelper.addToolMaterial("tcaqua", 2, 500, 6.5F, 2.5F, 14); public static final ItemTropicraftTool aquaAxe = new ItemUnderwaterAxe(materialUnderwaterTools, TCNames.aquaAxe); public static final ItemUnderwaterHoe aquaHoe = new ItemUnderwaterHoe(materialUnderwaterTools, TCNames.aquaHoe); public static final ItemTropicraftTool aquaPickaxe = new ItemUnderwaterPickaxe(materialUnderwaterTools, TCNames.aquaPickaxe); public static final ItemTropicraftTool aquaShovel = new ItemUnderwaterShovel(materialUnderwaterTools, TCNames.aquaShovel); */ public static final Item shells = new ItemShell(TCNames.shellNames); public static ToolMaterial materialBambooTools = EnumHelper.addToolMaterial("bamboo", 1, 110, 1.2F, 1F, 6); public static final Item bambooSpear = new ItemTropicraftSword(materialBambooTools, TCNames.bambooSpear); public static Item leafBall = (new ItemTropicraftLeafballNew()).setUnlocalizedName("leaf_green").setCreativeTab(TCCreativeTabRegistry.tabCombat); public static Item dagger = (new ItemDagger(materialZirconTools)).setUnlocalizedName("dagger"); //public static ItemStaffFireball staffFire = (ItemStaffFireball) (new ItemStaffFireball()).setUnlocalizedName("staff_fire").setCreativeTab(TCCreativeTabRegistry.tabCombat); //public static ItemStaffIceball staffIce; //public static ItemStaffOfTaming staffTaming = (ItemStaffOfTaming) (new ItemStaffOfTaming()).setUnlocalizedName("staff_taming").setCreativeTab(TCCreativeTabRegistry.tabCombat); public static Item fishingRodTropical = (new ItemTropicalFishingRod()).setUnlocalizedName("FishingRodTropical"); public static Item bambooChute = new ItemBambooChute(TCBlockRegistry.bambooChute).setUnlocalizedName("BambooChute"); public static final ArmorMaterial materialSnorkelGear = EnumHelper.addArmorMaterial("watergear", 40, new int[]{2, 4, 5, 6}, 9); public static Item flippers = new ItemFlippers(materialSnorkelGear, 0, 3); public static Item snorkel = new ItemSnorkel(materialSnorkelGear, 0, 0); public static Item recordBuriedTreasure = new ItemTropicraftMusicDisk("buriedtreasure", "buriedtreasure", "Punchaface").setUnlocalizedName("Buried Treasure"); public static Item recordEasternIsles = new ItemTropicraftMusicDisk("easternisles", "easternisles", "Frox").setUnlocalizedName("Eastern Isles"); public static Item recordLowTide = new ItemTropicraftMusicDisk("lowtide", "lowtide", "Punchaface").setUnlocalizedName("Low Tide"); public static Item recordSummering = new ItemTropicraftMusicDisk("summering", "summering", "Billy Christiansen").setUnlocalizedName("Summering"); public static Item recordTheTribe = new ItemTropicraftMusicDisk("thetribe", "thetribe", "Emile Van Krieken").setUnlocalizedName("The Tribe"); public static Item recordTradeWinds = new ItemTropicraftMusicDisk("tradewinds", "tradewinds", "Frox").setUnlocalizedName("Trade Winds"); public static Item portalEnchanter = new ItemPortalEnchanter(); public static Item bambooMug = new ItemTropicraft().setMaxStackSize(16); public static Item tropiFrame = (new ItemTCItemFrame(EntityTCItemFrame.class, true)).setUnlocalizedName("tropiFrame"); public static Item koaFrame = (new ItemTCItemFrame(EntityTCItemFrame.class, false)).setUnlocalizedName("koaFrame"); public static Item cocktail = new ItemCocktail(TCCreativeTabRegistry.tabFood); // public static Item rodOld = new ItemRod().setType(ItemRod.TYPE_OLD).setUnlocalizedName("rodOld"); // public static Item rodGood = new ItemRod().setType(ItemRod.TYPE_GOOD).setUnlocalizedName("rodGood"); // public static Item rodSuper = new ItemRod().setType(ItemRod.TYPE_SUPER).setUnlocalizedName("rodSuper"); // public static Item lureSuper = new ItemTropicraft().setUnlocalizedName("lureSuper"); //public static Item ashenMasks = new ItemAshenMask(ModIds.ITEM_ASHENMASK_ID, getMaskDisplayNames(), getMaskImageNames()).setUnlocalizedName("ashenMasks"); public static Item snareTrap = new ItemSnareTrap().setUnlocalizedName("snareTrap"); public static Item encTropica = new ItemTropBook("encTropica").setUnlocalizedName("encTropica"); public static Item mobEgg = new ItemMobEgg(TCNames.eggTextureNames); /** * Register all the items */ public static void init() { registerItem(frogLeg, TCNames.frogLeg); registerItem(cookedFrogLeg, TCNames.cookedFrogLeg); registerItem(poisonFrogSkin, TCNames.poisonFrogSkin); registerItem(freshMarlin, TCNames.freshMarlin); registerItem(searedMarlin, TCNames.searedMarlin); registerItem(grapefruit, TCNames.grapefruit); registerItem(lemon, TCNames.lemon); registerItem(lime, TCNames.lime); registerItem(orange, TCNames.orange); registerItem(scale, TCNames.scale); registerItem(coconutChunk, TCNames.coconutChunk); registerItem(pineappleCubes, TCNames.pineappleCubes); registerItem(bambooStick, TCNames.bambooStick); registerItem(seaUrchinRoe, TCNames.seaUrchinRoe); registerItem(pearl, TCNames.pearl); registerItem(ore, TCNames.ore); registerItem(waterWand, TCNames.waterWand); registerItem(fishingNet, TCNames.fishingNet); registerItem(coffeeBean, TCNames.coffeeBean); // Armor registerItem(scaleBoots, TCNames.scaleBoots); registerItem(scaleLeggings, TCNames.scaleLeggings); registerItem(scaleChestplate, TCNames.scaleChestplate); registerItem(scaleHelmet, TCNames.scaleHelmet); registerItem(fireBoots, TCNames.fireBoots); registerItem(fireLeggings, TCNames.fireLeggings); registerItem(fireChestplate, TCNames.fireChestplate); registerItem(fireHelmet, TCNames.fireHelmet); registerItem(axeEudialyte, TCNames.axeEudialyte); registerItem(hoeEudialyte, TCNames.hoeEudialyte); registerItem(pickaxeEudialyte, TCNames.pickaxeEudialyte); registerItem(shovelEudialyte, TCNames.shovelEudialyte); registerItem(swordEudialyte, TCNames.swordEudialyte); registerItem(axeZircon, TCNames.axeZircon); registerItem(hoeZircon, TCNames.hoeZircon); registerItem(pickaxeZircon, TCNames.pickaxeZircon); registerItem(shovelZircon, TCNames.shovelZircon); registerItem(swordZircon, TCNames.swordZircon); registerItem(tikiTorch, TCNames.tikiTorch); registerItem(bambooDoor, TCNames.bambooDoor); registerItem(bucketTropicsWater, TCNames.bucketTropicsWater); registerItem(chair, TCNames.chair); registerItem(umbrella, TCNames.umbrella); registerItem(flowerPot, TCNames.flowerPot); registerItem(fertilizer, TCNames.fertilizer); /* registerItem(dryFlippers, TCNames.dryFlippers); registerItem(dryLeggings, TCNames.dryLeggings); registerItem(dryChestplate, TCNames.dryChestplate); registerItem(dryChestplateGear, TCNames.dryChestplateGear); registerItem(dryHelmet, TCNames.dryHelmet); registerItem(wetFlippers, TCNames.wetFlippers); registerItem(wetLeggings, TCNames.wetLeggings); registerItem(wetChestplate, TCNames.wetChestplate); registerItem(wetChestplateGear, TCNames.wetChestplateGear); registerItem(wetHelmet, TCNames.wetHelmet); registerItem(scubaTank, TCNames.scubaTank); registerItem(diveComputer, TCNames.diveComputer); registerItem(bcd, TCNames.bcd);*/ registerItem(curare, TCNames.curare); registerItem(dart, TCNames.dart); registerItem(blowGun, TCNames.dartGun); registerItem(axeZirconium, TCNames.axeZirconium); registerItem(hoeZirconium, TCNames.hoeZirconium); registerItem(pickaxeZirconium, TCNames.pickaxeZirconium); registerItem(shovelZirconium, TCNames.shovelZirconium); registerItem(swordZirconium, TCNames.swordZirconium); /* registerItem(aquaAxe, TCNames.aquaAxe); registerItem(aquaHoe, TCNames.aquaHoe); registerItem(aquaPickaxe, TCNames.aquaPickaxe); registerItem(aquaShovel, TCNames.aquaShovel);*/ registerItem(shells, TCNames.shell); registerItem(bambooSpear, TCNames.bambooSpear); registerItem(coconutBomb, TCNames.coconutBomb); registerItem(bambooChute, TCNames.bambooChute); registerItem(snorkel, TCNames.snorkel); registerItem(flippers, TCNames.flippers); registerItem(dagger, TCNames.dagger); // registerItem(staffFire, TCNames.staffFire); // registerItem(staffTaming, TCNames.staffTaming); registerItem(fishingRodTropical, TCNames.fishingRodTropical); registerItem(recordBuriedTreasure, TCNames.recordBuriedTreasure); registerItem(recordEasternIsles, TCNames.recordEasternIsles); registerItem(recordLowTide, TCNames.recordLowTide); registerItem(recordSummering, TCNames.recordSummering); registerItem(recordTheTribe, TCNames.recordTheTribe); registerItem(recordTradeWinds, TCNames.recordTradeWinds); registerItem(portalEnchanter, TCNames.portalEnchanter); registerItem(bambooMug, TCNames.bambooMug); registerItem(tropiFrame, TCNames.tropiFrame); registerItem(koaFrame, TCNames.koaFrame); registerItem(cocktail, TCNames.cocktail); registerItem(leafBall, TCNames.leafBall); registerItem(fishBucket, TCNames.fishBucket); registerItem(snareTrap, TCNames.snareTrap); registerItem(encTropica, TCNames.encTropica); registerItem(mobEgg, TCNames.egg); registerItem(ashenMask, TCNames.ashenMask); } /** * Register an item with the game and give it a name * @param item Item to register * @param name Name to give */ private static void registerItem(Item item, String name) { GameRegistry.registerItem(item, name); item.setUnlocalizedName(name); OreDictionary.registerOre(name, item); } public static String[] getShellImageNames() { return new String[]{"shell_solo", "shell_frox", "shell_pab", "shell_rube", "shell_starfish", "shell_turtle"}; } public static String[] getMaskDisplayNames() { return new String[] {"Square Zord", "Horn Monkey", "Oblongatron", "Headinator", "Square Horn", "Screw Attack", "The Brain", "Bat Boy", "Ashen Mask", "Ashen Mask", "Ashen Mask", "Ashen Mask", "Ashen Mask"}; } public static String[] getMaskImageNames() { String[] strArr = new String[getMaskDisplayNames().length]; for (int i = 0; i < strArr.length; i++) { strArr[i] = "mask_" + i; } return strArr; } }
removed unfinished ashen item masks
src/main/java/net/tropicraft/registry/TCItemRegistry.java
removed unfinished ashen item masks
<ide><path>rc/main/java/net/tropicraft/registry/TCItemRegistry.java <ide> registerItem(encTropica, TCNames.encTropica); <ide> registerItem(mobEgg, TCNames.egg); <ide> <del> registerItem(ashenMask, TCNames.ashenMask); <add> //registerItem(ashenMask, TCNames.ashenMask); <ide> } <ide> <ide> /**
Java
bsd-3-clause
24e467a8719221489392fe95d8e4ff4a862d58fa
0
atomixnmc/jmonkeyengine,jMonkeyEngine/jmonkeyengine,zzuegg/jmonkeyengine,zzuegg/jmonkeyengine,jMonkeyEngine/jmonkeyengine,jMonkeyEngine/jmonkeyengine,atomixnmc/jmonkeyengine,atomixnmc/jmonkeyengine,atomixnmc/jmonkeyengine,zzuegg/jmonkeyengine,zzuegg/jmonkeyengine,atomixnmc/jmonkeyengine,atomixnmc/jmonkeyengine,jMonkeyEngine/jmonkeyengine
/* * Copyright (c) 2009-2012 jMonkeyEngine * 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 'jMonkeyEngine' 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.jme3.scene.control; import com.jme3.export.InputCapsule; import com.jme3.export.JmeExporter; import com.jme3.export.JmeImporter; import com.jme3.export.OutputCapsule; import com.jme3.light.DirectionalLight; import com.jme3.light.Light; import com.jme3.light.PointLight; import com.jme3.light.SpotLight; import com.jme3.math.Vector3f; import com.jme3.renderer.RenderManager; import com.jme3.renderer.ViewPort; import com.jme3.util.TempVars; import com.jme3.util.clone.Cloner; import java.io.IOException; /** * This Control maintains a reference to a Camera, * which will be synched with the position (worldTranslation) * of the current spatial. * @author tim */ public class LightControl extends AbstractControl { private static final String CONTROL_DIR_NAME = "controlDir"; private static final String LIGHT_NAME = "light"; public enum ControlDirection { /** * Means, that the Light's transform is "copied" * to the Transform of the Spatial. */ LightToSpatial, /** * Means, that the Spatial's transform is "copied" * to the Transform of the light. */ SpatialToLight; } private Light light; private ControlDirection controlDir = ControlDirection.SpatialToLight; /** * Constructor used for Serialization. */ public LightControl() { } /** * @param light The light to be synced. */ public LightControl(Light light) { this.light = light; } /** * @param light The light to be synced. */ public LightControl(Light light, ControlDirection controlDir) { this.light = light; this.controlDir = controlDir; } public Light getLight() { return light; } public void setLight(Light light) { this.light = light; } public ControlDirection getControlDir() { return controlDir; } public void setControlDir(ControlDirection controlDir) { this.controlDir = controlDir; } // fields used, when inversing ControlDirection: @Override protected void controlUpdate(float tpf) { if (spatial != null && light != null) { switch (controlDir) { case SpatialToLight: spatialToLight(light); break; case LightToSpatial: lightToSpatial(light); break; } } } private void spatialToLight(Light light) { final Vector3f worldTranslation = spatial.getWorldTranslation(); if (light instanceof PointLight) { ((PointLight) light).setPosition(worldTranslation); return; } final TempVars vars = TempVars.get(); final Vector3f vec = vars.vect1; if (light instanceof DirectionalLight) { ((DirectionalLight) light).setDirection(vec.set(worldTranslation).multLocal(-1.0f)); } if (light instanceof SpotLight) { final SpotLight spotLight = (SpotLight) light; spotLight.setPosition(worldTranslation); spotLight.setDirection(spatial.getWorldRotation().multLocal(vec.set(Vector3f.UNIT_Y).multLocal(-1))); } vars.release(); } private void lightToSpatial(Light light) { TempVars vars = TempVars.get(); if (light instanceof PointLight) { PointLight pLight = (PointLight) light; Vector3f vecDiff = vars.vect1.set(pLight.getPosition()).subtractLocal(spatial.getWorldTranslation()); spatial.setLocalTranslation(vecDiff.addLocal(spatial.getLocalTranslation())); } if (light instanceof DirectionalLight) { DirectionalLight dLight = (DirectionalLight) light; vars.vect1.set(dLight.getDirection()).multLocal(-1.0f); Vector3f vecDiff = vars.vect1.subtractLocal(spatial.getWorldTranslation()); spatial.setLocalTranslation(vecDiff.addLocal(spatial.getLocalTranslation())); } vars.release(); //TODO add code for Spot light here when it's done } @Override protected void controlRender(RenderManager rm, ViewPort vp) { // nothing to do } @Override public void cloneFields(final Cloner cloner, final Object original) { super.cloneFields(cloner, original); light = cloner.clone(light); } @Override public void read(JmeImporter im) throws IOException { super.read(im); InputCapsule ic = im.getCapsule(this); controlDir = ic.readEnum(CONTROL_DIR_NAME, ControlDirection.class, ControlDirection.SpatialToLight); light = (Light) ic.readSavable(LIGHT_NAME, null); } @Override public void write(JmeExporter ex) throws IOException { super.write(ex); OutputCapsule oc = ex.getCapsule(this); oc.write(controlDir, CONTROL_DIR_NAME, ControlDirection.SpatialToLight); oc.write(light, LIGHT_NAME, null); } }
jme3-core/src/main/java/com/jme3/scene/control/LightControl.java
/* * Copyright (c) 2009-2012 jMonkeyEngine * 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 'jMonkeyEngine' 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.jme3.scene.control; import com.jme3.export.InputCapsule; import com.jme3.export.JmeExporter; import com.jme3.export.JmeImporter; import com.jme3.export.OutputCapsule; import com.jme3.light.DirectionalLight; import com.jme3.light.Light; import com.jme3.light.PointLight; import com.jme3.light.SpotLight; import com.jme3.math.Vector3f; import com.jme3.renderer.RenderManager; import com.jme3.renderer.ViewPort; import com.jme3.scene.Spatial; import com.jme3.util.TempVars; import java.io.IOException; /** * This Control maintains a reference to a Camera, * which will be synched with the position (worldTranslation) * of the current spatial. * @author tim */ public class LightControl extends AbstractControl { public static enum ControlDirection { /** * Means, that the Light's transform is "copied" * to the Transform of the Spatial. */ LightToSpatial, /** * Means, that the Spatial's transform is "copied" * to the Transform of the light. */ SpatialToLight; } private Light light; private ControlDirection controlDir = ControlDirection.SpatialToLight; /** * Constructor used for Serialization. */ public LightControl() { } /** * @param light The light to be synced. */ public LightControl(Light light) { this.light = light; } /** * @param light The light to be synced. */ public LightControl(Light light, ControlDirection controlDir) { this.light = light; this.controlDir = controlDir; } public Light getLight() { return light; } public void setLight(Light light) { this.light = light; } public ControlDirection getControlDir() { return controlDir; } public void setControlDir(ControlDirection controlDir) { this.controlDir = controlDir; } // fields used, when inversing ControlDirection: @Override protected void controlUpdate(float tpf) { if (spatial != null && light != null) { switch (controlDir) { case SpatialToLight: spatialTolight(light); break; case LightToSpatial: lightToSpatial(light); break; } } } private void spatialTolight(Light light) { if (light instanceof PointLight) { ((PointLight) light).setPosition(spatial.getWorldTranslation()); } TempVars vars = TempVars.get(); if (light instanceof DirectionalLight) { ((DirectionalLight) light).setDirection(vars.vect1.set(spatial.getWorldTranslation()).multLocal(-1.0f)); } if (light instanceof SpotLight) { ((SpotLight) light).setPosition(spatial.getWorldTranslation()); ((SpotLight) light).setDirection(spatial.getWorldRotation().multLocal(vars.vect1.set(Vector3f.UNIT_Y).multLocal(-1))); } vars.release(); } private void lightToSpatial(Light light) { TempVars vars = TempVars.get(); if (light instanceof PointLight) { PointLight pLight = (PointLight) light; Vector3f vecDiff = vars.vect1.set(pLight.getPosition()).subtractLocal(spatial.getWorldTranslation()); spatial.setLocalTranslation(vecDiff.addLocal(spatial.getLocalTranslation())); } if (light instanceof DirectionalLight) { DirectionalLight dLight = (DirectionalLight) light; vars.vect1.set(dLight.getDirection()).multLocal(-1.0f); Vector3f vecDiff = vars.vect1.subtractLocal(spatial.getWorldTranslation()); spatial.setLocalTranslation(vecDiff.addLocal(spatial.getLocalTranslation())); } vars.release(); //TODO add code for Spot light here when it's done } @Override protected void controlRender(RenderManager rm, ViewPort vp) { // nothing to do } // default implementation from AbstractControl is equivalent //@Override //public Control cloneForSpatial(Spatial newSpatial) { // LightControl control = new LightControl(light, controlDir); // control.setSpatial(newSpatial); // control.setEnabled(isEnabled()); // return control; //} private static final String CONTROL_DIR_NAME = "controlDir"; private static final String LIGHT_NAME = "light"; @Override public void read(JmeImporter im) throws IOException { super.read(im); InputCapsule ic = im.getCapsule(this); controlDir = ic.readEnum(CONTROL_DIR_NAME, ControlDirection.class, ControlDirection.SpatialToLight); light = (Light)ic.readSavable(LIGHT_NAME, null); } @Override public void write(JmeExporter ex) throws IOException { super.write(ex); OutputCapsule oc = ex.getCapsule(this); oc.write(controlDir, CONTROL_DIR_NAME, ControlDirection.SpatialToLight); oc.write(light, LIGHT_NAME, null); } }
fixed the problem with the reference to light, when we had incorrect reference to the light after loading/cloning spatial of this control.
jme3-core/src/main/java/com/jme3/scene/control/LightControl.java
fixed the problem with the reference to light, when we had incorrect reference to the light after loading/cloning spatial of this control.
<ide><path>me3-core/src/main/java/com/jme3/scene/control/LightControl.java <ide> import com.jme3.math.Vector3f; <ide> import com.jme3.renderer.RenderManager; <ide> import com.jme3.renderer.ViewPort; <del>import com.jme3.scene.Spatial; <ide> import com.jme3.util.TempVars; <add>import com.jme3.util.clone.Cloner; <add> <ide> import java.io.IOException; <ide> <ide> /** <ide> */ <ide> public class LightControl extends AbstractControl { <ide> <del> public static enum ControlDirection { <add> private static final String CONTROL_DIR_NAME = "controlDir"; <add> private static final String LIGHT_NAME = "light"; <add> <add> public enum ControlDirection { <ide> <ide> /** <ide> * Means, that the Light's transform is "copied" <ide> */ <ide> SpatialToLight; <ide> } <add> <ide> private Light light; <ide> private ControlDirection controlDir = ControlDirection.SpatialToLight; <ide> <ide> if (spatial != null && light != null) { <ide> switch (controlDir) { <ide> case SpatialToLight: <del> spatialTolight(light); <add> spatialToLight(light); <ide> break; <ide> case LightToSpatial: <ide> lightToSpatial(light); <ide> } <ide> } <ide> <del> private void spatialTolight(Light light) { <add> private void spatialToLight(Light light) { <add> <add> final Vector3f worldTranslation = spatial.getWorldTranslation(); <add> <ide> if (light instanceof PointLight) { <del> ((PointLight) light).setPosition(spatial.getWorldTranslation()); <del> } <del> TempVars vars = TempVars.get(); <add> ((PointLight) light).setPosition(worldTranslation); <add> return; <add> } <add> <add> final TempVars vars = TempVars.get(); <add> final Vector3f vec = vars.vect1; <ide> <ide> if (light instanceof DirectionalLight) { <del> ((DirectionalLight) light).setDirection(vars.vect1.set(spatial.getWorldTranslation()).multLocal(-1.0f)); <add> ((DirectionalLight) light).setDirection(vec.set(worldTranslation).multLocal(-1.0f)); <ide> } <ide> <ide> if (light instanceof SpotLight) { <del> ((SpotLight) light).setPosition(spatial.getWorldTranslation()); <del> ((SpotLight) light).setDirection(spatial.getWorldRotation().multLocal(vars.vect1.set(Vector3f.UNIT_Y).multLocal(-1))); <del> } <add> final SpotLight spotLight = (SpotLight) light; <add> spotLight.setPosition(worldTranslation); <add> spotLight.setDirection(spatial.getWorldRotation().multLocal(vec.set(Vector3f.UNIT_Y).multLocal(-1))); <add> } <add> <ide> vars.release(); <del> <ide> } <ide> <ide> private void lightToSpatial(Light light) { <ide> } <ide> vars.release(); <ide> //TODO add code for Spot light here when it's done <del> <del> <ide> } <ide> <ide> @Override <ide> // nothing to do <ide> } <ide> <del> // default implementation from AbstractControl is equivalent <del> //@Override <del> //public Control cloneForSpatial(Spatial newSpatial) { <del> // LightControl control = new LightControl(light, controlDir); <del> // control.setSpatial(newSpatial); <del> // control.setEnabled(isEnabled()); <del> // return control; <del> //} <del> private static final String CONTROL_DIR_NAME = "controlDir"; <del> private static final String LIGHT_NAME = "light"; <del> <add> @Override <add> public void cloneFields(final Cloner cloner, final Object original) { <add> super.cloneFields(cloner, original); <add> light = cloner.clone(light); <add> } <add> <ide> @Override <ide> public void read(JmeImporter im) throws IOException { <ide> super.read(im); <ide> InputCapsule ic = im.getCapsule(this); <ide> controlDir = ic.readEnum(CONTROL_DIR_NAME, ControlDirection.class, ControlDirection.SpatialToLight); <del> light = (Light)ic.readSavable(LIGHT_NAME, null); <add> light = (Light) ic.readSavable(LIGHT_NAME, null); <ide> } <ide> <ide> @Override
Java
mit
95e5d2f928e8f20ac507656f78db741f5ad4e7ab
0
markovandooren/chameleon
package be.kuleuven.cs.distrinet.chameleon.ui.widget; import be.kuleuven.cs.distrinet.chameleon.ui.widget.checkbox.CheckboxListener; import be.kuleuven.cs.distrinet.chameleon.ui.widget.list.ComboBoxController; import be.kuleuven.cs.distrinet.chameleon.ui.widget.list.ComboBoxListener; import be.kuleuven.cs.distrinet.chameleon.ui.widget.list.ListContentProvider; import be.kuleuven.cs.distrinet.chameleon.ui.widget.tree.CheckStateProvider; import be.kuleuven.cs.distrinet.chameleon.ui.widget.tree.TreeContentProvider; import be.kuleuven.cs.distrinet.chameleon.ui.widget.tree.TreeListener; import be.kuleuven.cs.distrinet.chameleon.ui.widget.tree.TristateTreeController; /** * A factory interface for creating UI widgets. Each factory method * return a controller that allows setting the input for the control. * * @author Marko van Dooren * * @param <W> The type of the widgets. */ public interface WidgetFactory<W> { /** * Create a checkbox widget. * * @param text The label of the checkbox. * @param initialState The initial state of the checkbox. * @param listener A listener that is notified when the state of the checkbox changes. */ public SelectionController<? extends W> createCheckbox(String text, boolean initialState, CheckboxListener listener); public <V> TristateTreeController<? extends W> createTristateTree( TreeContentProvider<V> contentProvider, LabelProvider provider, TreeListener<V> listener, CheckStateProvider<V> checkStateProvider); public <V> ComboBoxController<? extends W> createComboBox(ListContentProvider<V> contentProvider, LabelProvider provider, ComboBoxListener listener, int baseOneDefaultSelection); }
src/be/kuleuven/cs/distrinet/chameleon/ui/widget/WidgetFactory.java
package be.kuleuven.cs.distrinet.chameleon.ui.widget; import be.kuleuven.cs.distrinet.chameleon.ui.widget.checkbox.CheckboxListener; import be.kuleuven.cs.distrinet.chameleon.ui.widget.list.ComboBoxController; import be.kuleuven.cs.distrinet.chameleon.ui.widget.list.ComboBoxListener; import be.kuleuven.cs.distrinet.chameleon.ui.widget.list.ListContentProvider; import be.kuleuven.cs.distrinet.chameleon.ui.widget.tree.TreeContentProvider; import be.kuleuven.cs.distrinet.chameleon.ui.widget.tree.TreeListener; import be.kuleuven.cs.distrinet.chameleon.ui.widget.tree.TristateTreeController; public interface WidgetFactory<W> { public SelectionController<? extends W> createCheckbox(String text, boolean initialState, CheckboxListener listener); public <V> TristateTreeController<? extends W> createTristateTree(TreeContentProvider<V> contentProvider, LabelProvider provider, TreeListener<V> listener); public <V> ComboBoxController<? extends W> createComboBox(ListContentProvider<V> contentProvider, LabelProvider provider, ComboBoxListener listener, int baseOneDefaultSelection); }
added check state provider parameter for tristate trees
src/be/kuleuven/cs/distrinet/chameleon/ui/widget/WidgetFactory.java
added check state provider parameter for tristate trees
<ide><path>rc/be/kuleuven/cs/distrinet/chameleon/ui/widget/WidgetFactory.java <ide> import be.kuleuven.cs.distrinet.chameleon.ui.widget.list.ComboBoxController; <ide> import be.kuleuven.cs.distrinet.chameleon.ui.widget.list.ComboBoxListener; <ide> import be.kuleuven.cs.distrinet.chameleon.ui.widget.list.ListContentProvider; <add>import be.kuleuven.cs.distrinet.chameleon.ui.widget.tree.CheckStateProvider; <ide> import be.kuleuven.cs.distrinet.chameleon.ui.widget.tree.TreeContentProvider; <ide> import be.kuleuven.cs.distrinet.chameleon.ui.widget.tree.TreeListener; <ide> import be.kuleuven.cs.distrinet.chameleon.ui.widget.tree.TristateTreeController; <ide> <ide> <del> <add>/** <add> * A factory interface for creating UI widgets. Each factory method <add> * return a controller that allows setting the input for the control. <add> * <add> * @author Marko van Dooren <add> * <add> * @param <W> The type of the widgets. <add> */ <ide> public interface WidgetFactory<W> { <ide> <add> /** <add> * Create a checkbox widget. <add> * <add> * @param text The label of the checkbox. <add> * @param initialState The initial state of the checkbox. <add> * @param listener A listener that is notified when the state of the checkbox changes. <add> */ <ide> public SelectionController<? extends W> createCheckbox(String text, boolean initialState, CheckboxListener listener); <ide> <del> public <V> TristateTreeController<? extends W> createTristateTree(TreeContentProvider<V> contentProvider, LabelProvider provider, TreeListener<V> listener); <add> public <V> TristateTreeController<? extends W> createTristateTree( <add> TreeContentProvider<V> contentProvider, <add> LabelProvider provider, <add> TreeListener<V> listener, <add> CheckStateProvider<V> checkStateProvider); <ide> <ide> public <V> ComboBoxController<? extends W> createComboBox(ListContentProvider<V> contentProvider, LabelProvider provider, ComboBoxListener listener, int baseOneDefaultSelection); <ide> }
JavaScript
mit
1adece490ae74dd93eb828f20499d51b6c94ca73
0
JastonHu/skynet,5kittys22/firstphasergame,JennaWu-Cardona/firstPhaserGame,dreamsxin/phaser,fmflame/phaser,TukekeSoft/phaser,Acaki/WWW_project,TukekeSoft/phaser,aakaash710/firstphasergame,stoneman1/phaser,photonstorm/phaser-ce,HannahCacapit/firstphasergame,yupaul/phaser-ce,Flash5509/firstphasergame,natlot/phaser-ce,tallzabby/phaser,englercj/phaser,GGAlanSmithee/phaser,samme/phaser-ce,clark-stevenson/phaser,Acaki/WWW_project,MasahiroWard/MVPgamedev,GGAlanSmithee/phaser,BeanSeed/phaser,yupaul/phaser-ce,orange-games/phaser-multires,tallzabby/phaser,rblopes/phaser,jamesgroat/phaser,nexiuhm/phaser,samme/phaser-ce,fmflame/phaser,djom20/phaser,photonstorm/phaser,Flash5509/firstphasergame,natlot/phaser-ce,orange-games/phaser-multires,fmflame/phaser,JennaWu-Cardona/firstPhaserGame,adamlabadorf/bobodyssey,photonstorm/phaser,pixelpicosean/phaser,aakaash710/firstphasergame,mahill/phaser,BeanSeed/phaser,yupaul/phaser-ce,djom20/phaser,SHOCK122/systole,GGAlanSmithee/phaser,spayton/phaser,cloakedninjas/phaser,alexus85/phaser-ce,stoneman1/phaser,alexus85/phaser-ce,MasahiroWard/MVPgamedev,TukekeSoft/phaser,MasahiroWard/MVPgamedev,5kittys22/firstphasergame,SHOCK122/systole,adamlabadorf/bobodyssey,adamlabadorf/bobodyssey,spayton/phaser,audreybongalon/weebisoft,samme/phaser-ce,natlot/phaser-ce,clark-stevenson/phaser,orange-games/phaser-multires,JastonHu/skynet,JastonHu/skynet,djom20/phaser,tallzabby/phaser,nexiuhm/phaser,Remus22/First-Pahser,MasahiroWard/MVPgamedev,Acaki/WWW_project,cloakedninjas/phaser,Flash5509/firstphasergame,yupaul/phaser-ce,SHOCK122/systole,jamesgroat/phaser,JennaWu-Cardona/firstPhaserGame,Remus22/First-Pahser,clark-stevenson/phaser,HannahCacapit/firstphasergame,photonstorm/phaser-ce,dreamsxin/phaser,dreamsxin/phaser,jamesgroat/phaser,5kittys22/firstphasergame,stoneman1/phaser,audreybongalon/weebisoft,audreybongalon/weebisoft,HannahCacapit/firstphasergame,natlot/phaser-ce,photonstorm/phaser-ce,mahill/phaser,alexus85/phaser-ce,aakaash710/firstphasergame,Remus22/First-Pahser,photonstorm/phaser-ce,cloakedninjas/phaser,nexiuhm/phaser
/** * @author Richard Davey <[email protected]> * @copyright 2016 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * The Events component is a collection of events fired by the parent game object. * * Phaser uses what are known as 'Signals' for all event handling. All of the events in * this class are signals you can subscribe to, much in the same way you'd "listen" for * an event. * * For example to tell when a Sprite has been added to a new group, you can bind a function * to the `onAddedToGroup` signal: * * `sprite.events.onAddedToGroup.add(yourFunction, this);` * * Where `yourFunction` is the function you want called when this event occurs. * * For more details about how signals work please see the Phaser.Signal class. * * The Input-related events will only be dispatched if the Sprite has had `inputEnabled` set to `true` * and the Animation-related events only apply to game objects with animations like {@link Phaser.Sprite}. * * @class Phaser.Events * @constructor * @param {Phaser.Sprite} sprite - A reference to the game object / Sprite that owns this Events object. */ Phaser.Events = function (sprite) { /** * @property {Phaser.Sprite} parent - The Sprite that owns these events. */ this.parent = sprite; // The signals are automatically added by the corresponding proxy properties }; Phaser.Events.prototype = { /** * Removes all events. * * @method Phaser.Events#destroy */ destroy: function () { this._parent = null; if (this._onDestroy) { this._onDestroy.dispose(); } if (this._onAddedToGroup) { this._onAddedToGroup.dispose(); } if (this._onRemovedFromGroup) { this._onRemovedFromGroup.dispose(); } if (this._onRemovedFromWorld) { this._onRemovedFromWorld.dispose(); } if (this._onKilled) { this._onKilled.dispose(); } if (this._onRevived) { this._onRevived.dispose(); } if (this._onEnterBounds) { this._onEnterBounds.dispose(); } if (this._onOutOfBounds) { this._onOutOfBounds.dispose(); } if (this._onInputOver) { this._onInputOver.dispose(); } if (this._onInputOut) { this._onInputOut.dispose(); } if (this._onInputDown) { this._onInputDown.dispose(); } if (this._onInputUp) { this._onInputUp.dispose(); } if (this._onDragStart) { this._onDragStart.dispose(); } if (this._onDragUpdate) { this._onDragUpdate.dispose(); } if (this._onDragStop) { this._onDragStop.dispose(); } if (this._onAnimationStart) { this._onAnimationStart.dispose(); } if (this._onAnimationComplete) { this._onAnimationComplete.dispose(); } if (this._onAnimationLoop) { this._onAnimationLoop.dispose(); } }, // The following properties are sentinels that will be replaced with getters /** * @property {Phaser.Signal} onAddedToGroup - This signal is dispatched when the parent is added to a new Group. */ onAddedToGroup: null, /** * @property {Phaser.Signal} onRemovedFromGroup - This signal is dispatched when the parent is removed from a Group. */ onRemovedFromGroup: null, /** * @property {Phaser.Signal} onRemovedFromWorld - This signal is dispatched if this item or any of its parents are removed from the game world. */ onRemovedFromWorld: null, /** * @property {Phaser.Signal} onDestroy - This signal is dispatched when the parent is destroyed. */ onDestroy: null, /** * @property {Phaser.Signal} onKilled - This signal is dispatched when the parent is killed. */ onKilled: null, /** * @property {Phaser.Signal} onRevived - This signal is dispatched when the parent is revived. */ onRevived: null, /** * @property {Phaser.Signal} onOutOfBounds - This signal is dispatched when the parent leaves the world bounds (only if Sprite.checkWorldBounds is true). */ onOutOfBounds: null, /** * @property {Phaser.Signal} onEnterBounds - This signal is dispatched when the parent returns within the world bounds (only if Sprite.checkWorldBounds is true). */ onEnterBounds: null, /** * @property {Phaser.Signal} onInputOver - This signal is dispatched if the parent is inputEnabled and receives an over event from a Pointer. */ onInputOver: null, /** * @property {Phaser.Signal} onInputOut - This signal is dispatched if the parent is inputEnabled and receives an out event from a Pointer. */ onInputOut: null, /** * @property {Phaser.Signal} onInputDown - This signal is dispatched if the parent is inputEnabled and receives a down event from a Pointer. */ onInputDown: null, /** * @property {Phaser.Signal} onInputUp - This signal is dispatched if the parent is inputEnabled and receives an up event from a Pointer. */ onInputUp: null, /** * @property {Phaser.Signal} onDragStart - This signal is dispatched if the parent is inputEnabled and receives a drag start event from a Pointer. */ onDragStart: null, /** * @property {Phaser.Signal} onDragUpdate - This signal is dispatched if the parent is inputEnabled and receives a drag update event from a Pointer. */ onDragUpdate: null, /** * @property {Phaser.Signal} onDragStop - This signal is dispatched if the parent is inputEnabled and receives a drag stop event from a Pointer. */ onDragStop: null, /** * @property {Phaser.Signal} onAnimationStart - This signal is dispatched when the parent has an animation that is played. */ onAnimationStart: null, /** * @property {Phaser.Signal} onAnimationComplete - This signal is dispatched when the parent has an animation that finishes playing. */ onAnimationComplete: null, /** * @property {Phaser.Signal} onAnimationLoop - This signal is dispatched when the parent has an animation that loops playback. */ onAnimationLoop: null }; Phaser.Events.prototype.constructor = Phaser.Events; // Create an auto-create proxy getter and dispatch method for all events. // The backing property is the same as the event name, prefixed with '_' // and the dispatch method is the same as the event name postfixed with '$dispatch'. for (var prop in Phaser.Events.prototype) { if (!Phaser.Events.prototype.hasOwnProperty(prop) || prop.indexOf('on') !== 0 || Phaser.Events.prototype[prop] !== null) { continue; } (function (prop, backing) { 'use strict'; // The accessor creates a new Signal; and so it should only be used from user-code. Object.defineProperty(Phaser.Events.prototype, prop, { get: function () { return this[backing] || (this[backing] = new Phaser.Signal()); } }); // The dispatcher will only broadcast on an already-created signal; call this internally. Phaser.Events.prototype[prop + '$dispatch'] = function () { return this[backing] ? this[backing].dispatch.apply(this[backing], arguments) : null; }; })(prop, '_' + prop); }
src/gameobjects/components/Events.js
/** * @author Richard Davey <[email protected]> * @copyright 2016 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * The Events component is a collection of events fired by the parent game object. * * For example to tell when a Sprite has been added to a new group: * * `sprite.events.onAddedToGroup.add(yourFunction, this);` * * Where `yourFunction` is the function you want called when this event occurs. * * The Input-related events will only be dispatched if the Sprite has had `inputEnabled` set to `true` * and the Animation-related events only apply to game objects with animations like {@link Phaser.Sprite}. * * @class Phaser.Events * @constructor * @param {Phaser.Sprite} sprite - A reference to the game object / Sprite that owns this Events object. */ Phaser.Events = function (sprite) { /** * @property {Phaser.Sprite} parent - The Sprite that owns these events. */ this.parent = sprite; // The signals are automatically added by the corresponding proxy properties }; Phaser.Events.prototype = { /** * Removes all events. * * @method Phaser.Events#destroy */ destroy: function () { this._parent = null; if (this._onDestroy) { this._onDestroy.dispose(); } if (this._onAddedToGroup) { this._onAddedToGroup.dispose(); } if (this._onRemovedFromGroup) { this._onRemovedFromGroup.dispose(); } if (this._onRemovedFromWorld) { this._onRemovedFromWorld.dispose(); } if (this._onKilled) { this._onKilled.dispose(); } if (this._onRevived) { this._onRevived.dispose(); } if (this._onEnterBounds) { this._onEnterBounds.dispose(); } if (this._onOutOfBounds) { this._onOutOfBounds.dispose(); } if (this._onInputOver) { this._onInputOver.dispose(); } if (this._onInputOut) { this._onInputOut.dispose(); } if (this._onInputDown) { this._onInputDown.dispose(); } if (this._onInputUp) { this._onInputUp.dispose(); } if (this._onDragStart) { this._onDragStart.dispose(); } if (this._onDragUpdate) { this._onDragUpdate.dispose(); } if (this._onDragStop) { this._onDragStop.dispose(); } if (this._onAnimationStart) { this._onAnimationStart.dispose(); } if (this._onAnimationComplete) { this._onAnimationComplete.dispose(); } if (this._onAnimationLoop) { this._onAnimationLoop.dispose(); } }, // The following properties are sentinels that will be replaced with getters /** * @property {Phaser.Signal} onAddedToGroup - This signal is dispatched when the parent is added to a new Group. */ onAddedToGroup: null, /** * @property {Phaser.Signal} onRemovedFromGroup - This signal is dispatched when the parent is removed from a Group. */ onRemovedFromGroup: null, /** * @property {Phaser.Signal} onRemovedFromWorld - This signal is dispatched if this item or any of its parents are removed from the game world. */ onRemovedFromWorld: null, /** * @property {Phaser.Signal} onDestroy - This signal is dispatched when the parent is destroyed. */ onDestroy: null, /** * @property {Phaser.Signal} onKilled - This signal is dispatched when the parent is killed. */ onKilled: null, /** * @property {Phaser.Signal} onRevived - This signal is dispatched when the parent is revived. */ onRevived: null, /** * @property {Phaser.Signal} onOutOfBounds - This signal is dispatched when the parent leaves the world bounds (only if Sprite.checkWorldBounds is true). */ onOutOfBounds: null, /** * @property {Phaser.Signal} onEnterBounds - This signal is dispatched when the parent returns within the world bounds (only if Sprite.checkWorldBounds is true). */ onEnterBounds: null, /** * @property {Phaser.Signal} onInputOver - This signal is dispatched if the parent is inputEnabled and receives an over event from a Pointer. */ onInputOver: null, /** * @property {Phaser.Signal} onInputOut - This signal is dispatched if the parent is inputEnabled and receives an out event from a Pointer. */ onInputOut: null, /** * @property {Phaser.Signal} onInputDown - This signal is dispatched if the parent is inputEnabled and receives a down event from a Pointer. */ onInputDown: null, /** * @property {Phaser.Signal} onInputUp - This signal is dispatched if the parent is inputEnabled and receives an up event from a Pointer. */ onInputUp: null, /** * @property {Phaser.Signal} onDragStart - This signal is dispatched if the parent is inputEnabled and receives a drag start event from a Pointer. */ onDragStart: null, /** * @property {Phaser.Signal} onDragUpdate - This signal is dispatched if the parent is inputEnabled and receives a drag update event from a Pointer. */ onDragUpdate: null, /** * @property {Phaser.Signal} onDragStop - This signal is dispatched if the parent is inputEnabled and receives a drag stop event from a Pointer. */ onDragStop: null, /** * @property {Phaser.Signal} onAnimationStart - This signal is dispatched when the parent has an animation that is played. */ onAnimationStart: null, /** * @property {Phaser.Signal} onAnimationComplete - This signal is dispatched when the parent has an animation that finishes playing. */ onAnimationComplete: null, /** * @property {Phaser.Signal} onAnimationLoop - This signal is dispatched when the parent has an animation that loops playback. */ onAnimationLoop: null }; Phaser.Events.prototype.constructor = Phaser.Events; // Create an auto-create proxy getter and dispatch method for all events. // The backing property is the same as the event name, prefixed with '_' // and the dispatch method is the same as the event name postfixed with '$dispatch'. for (var prop in Phaser.Events.prototype) { if (!Phaser.Events.prototype.hasOwnProperty(prop) || prop.indexOf('on') !== 0 || Phaser.Events.prototype[prop] !== null) { continue; } (function (prop, backing) { 'use strict'; // The accessor creates a new Signal; and so it should only be used from user-code. Object.defineProperty(Phaser.Events.prototype, prop, { get: function () { return this[backing] || (this[backing] = new Phaser.Signal()); } }); // The dispatcher will only broadcast on an already-created signal; call this internally. Phaser.Events.prototype[prop + '$dispatch'] = function () { return this[backing] ? this[backing].dispatch.apply(this[backing], arguments) : null; }; })(prop, '_' + prop); }
Docs update.
src/gameobjects/components/Events.js
Docs update.
<ide><path>rc/gameobjects/components/Events.js <ide> <ide> /** <ide> * The Events component is a collection of events fired by the parent game object. <del>* <del>* For example to tell when a Sprite has been added to a new group: <add>* <add>* Phaser uses what are known as 'Signals' for all event handling. All of the events in <add>* this class are signals you can subscribe to, much in the same way you'd "listen" for <add>* an event. <add>* <add>* For example to tell when a Sprite has been added to a new group, you can bind a function <add>* to the `onAddedToGroup` signal: <ide> * <ide> * `sprite.events.onAddedToGroup.add(yourFunction, this);` <ide> * <ide> * Where `yourFunction` is the function you want called when this event occurs. <add>* <add>* For more details about how signals work please see the Phaser.Signal class. <ide> * <ide> * The Input-related events will only be dispatched if the Sprite has had `inputEnabled` set to `true` <ide> * and the Animation-related events only apply to game objects with animations like {@link Phaser.Sprite}.
Java
mit
be73a1d3a21e4fcdd2eb28eb1788844e22d77224
0
dialex/JCDP
package com.diogonunes.jcdp.unit; import com.diogonunes.jcdp.bw.Printer; import com.diogonunes.jcdp.bw.api.IPrinter; import com.diogonunes.jcdp.bw.impl.TerminalPrinter; import org.junit.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; public class PrinterBuilderTests { @Test public void Printer_Creation_BuilderExists() { // ARRANGE // ACT Printer.Builder printerBuilder = new Printer.Builder(Printer.Types.TERM); // ASSERT assertThat(printerBuilder, not(equalTo(null))); assertThat(printerBuilder, instanceOf(Printer.Builder.class)); } @Test public void Printer_Creation_BuilderReturnsTerminalPrinter() { // ARRANGE Printer.Builder b = new Printer.Builder(Printer.Types.TERM); // ACT IPrinter printer = b.build(); // ASSERT assertThat(printer, not(equalTo(null))); assertThat(printer, instanceOf(Printer.class)); assertThat("Implementation is TerminalPrinter", printer.toString(), containsString(TerminalPrinter.class.getSimpleName())); } @Test public void Printer_Creation_BuilderHandlesLevel() { // ARRANGE Printer.Builder b = new Printer.Builder(Printer.Types.TERM); int number = 2; // ACT IPrinter printer = b.level(number).build(); // ASSERT assertThat(printer, not(equalTo(null))); assertThat(printer.getLevel(), equalTo(number)); } @Test public void Printer_Creation_BuilderChaining() { // ARRANGE Printer.Builder b = new Printer.Builder(Printer.Types.TERM); int number = 3; // ACT IPrinter printer = b.timestamping(true).level(number).build(); System.out.print(printer.toString()); // ASSERT assertThat(printer, not(equalTo(null))); assertThat(printer.getLevel(), equalTo(number)); } @Test public void Printer_Creation_PassingBuilderToConstructor() { // ARRANGE Printer.Builder b = new Printer.Builder(Printer.Types.TERM); int number = 3; // ACT b.level(3).timestamping(true); IPrinter printer = new Printer(b); // ASSERT assertThat(printer, not(equalTo(null))); assertThat(printer.getLevel(), equalTo(number)); } }
src/test/java/com/diogonunes/jcdp/unit/PrinterBuilderTests.java
package com.diogonunes.jcdp.unit; import com.diogonunes.jcdp.bw.Printer; import com.diogonunes.jcdp.bw.api.IPrinter; import com.diogonunes.jcdp.bw.impl.TerminalPrinter; import org.junit.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; public class PrinterBuilderTests { @Test public void Printer_Creation_BuilderExists() { // ARRANGE // ACT Printer.Builder printerBuilder = new Printer.Builder(Printer.Types.TERM); // ASSERT assertThat(printerBuilder, not(equalTo(null))); assertThat(printerBuilder, instanceOf(Printer.Builder.class)); } @Test public void Printer_Creation_BuilderReturnsTerminalPrinter() { // ARRANGE Printer.Builder b = new Printer.Builder(Printer.Types.TERM); // ACT IPrinter printer = b.build(); // ASSERT assertThat(printer, not(equalTo(null))); assertThat(printer, instanceOf(Printer.class)); assertThat("Implementation is TerminalPrinter", printer.toString(), containsString(TerminalPrinter.class.getSimpleName())); } @Test public void Printer_Creation_BuilderHandlesLevel() { // ARRANGE Printer.Builder b = new Printer.Builder(Printer.Types.TERM); int number = 2; // ACT IPrinter printer = b.level(number).build(); // ASSERT assertThat(printer, not(equalTo(null))); assertThat(printer.getLevel(), equalTo(number)); } @Test public void Printer_Creation_BuilderChaining() { // ARRANGE Printer.Builder b = new Printer.Builder(Printer.Types.TERM); boolean flag = true; int number = 3; // ACT IPrinter printer = b.timestamping(flag).level(number).build(); System.out.print(printer.toString()); // ASSERT assertThat(printer, not(equalTo(null))); assertThat(printer.getLevel(), equalTo(number)); } }
Add test: Printer_Creation_PassingBuilderToConstructor
src/test/java/com/diogonunes/jcdp/unit/PrinterBuilderTests.java
Add test: Printer_Creation_PassingBuilderToConstructor
<ide><path>rc/test/java/com/diogonunes/jcdp/unit/PrinterBuilderTests.java <ide> public void Printer_Creation_BuilderChaining() { <ide> // ARRANGE <ide> Printer.Builder b = new Printer.Builder(Printer.Types.TERM); <del> boolean flag = true; <ide> int number = 3; <ide> <ide> // ACT <del> IPrinter printer = b.timestamping(flag).level(number).build(); <add> IPrinter printer = b.timestamping(true).level(number).build(); <ide> System.out.print(printer.toString()); <ide> <ide> // ASSERT <ide> assertThat(printer, not(equalTo(null))); <ide> assertThat(printer.getLevel(), equalTo(number)); <ide> } <add> <add> @Test <add> public void Printer_Creation_PassingBuilderToConstructor() { <add> // ARRANGE <add> Printer.Builder b = new Printer.Builder(Printer.Types.TERM); <add> int number = 3; <add> <add> // ACT <add> b.level(3).timestamping(true); <add> IPrinter printer = new Printer(b); <add> <add> // ASSERT <add> assertThat(printer, not(equalTo(null))); <add> assertThat(printer.getLevel(), equalTo(number)); <add> } <ide> }
Java
bsd-3-clause
c7ce6dd69c54996ba8643af5c1d444a2011b660d
0
tvolkert/engine,chinmaygarde/flutter_engine,chinmaygarde/sky_engine,mikejurka/engine,jason-simmons/flutter_engine,rmacnak-google/engine,tvolkert/engine,krisgiesing/sky_engine,aam/engine,jamesr/sky_engine,jamesr/flutter_engine,mikejurka/engine,jamesr/sky_engine,jamesr/flutter_engine,jamesr/sky_engine,rmacnak-google/engine,flutter/engine,chinmaygarde/flutter_engine,aam/engine,chinmaygarde/flutter_engine,jamesr/flutter_engine,jamesr/flutter_engine,Hixie/sky_engine,jason-simmons/sky_engine,cdotstout/sky_engine,Hixie/sky_engine,krisgiesing/sky_engine,Hixie/sky_engine,tvolkert/engine,Hixie/sky_engine,cdotstout/sky_engine,devoncarew/sky_engine,devoncarew/engine,aam/engine,aam/engine,cdotstout/sky_engine,jamesr/flutter_engine,chinmaygarde/sky_engine,rmacnak-google/engine,devoncarew/sky_engine,flutter/engine,flutter/engine,chinmaygarde/sky_engine,jason-simmons/flutter_engine,jason-simmons/sky_engine,aam/engine,rmacnak-google/engine,jason-simmons/flutter_engine,jason-simmons/flutter_engine,jamesr/flutter_engine,chinmaygarde/sky_engine,chinmaygarde/flutter_engine,jason-simmons/sky_engine,devoncarew/sky_engine,jason-simmons/flutter_engine,jason-simmons/flutter_engine,flutter/engine,devoncarew/sky_engine,jason-simmons/sky_engine,jamesr/sky_engine,devoncarew/engine,mikejurka/engine,mikejurka/engine,jamesr/sky_engine,flutter/engine,jamesr/sky_engine,Hixie/sky_engine,flutter/engine,devoncarew/engine,jamesr/flutter_engine,rmacnak-google/engine,aam/engine,krisgiesing/sky_engine,cdotstout/sky_engine,mikejurka/engine,chinmaygarde/flutter_engine,chinmaygarde/sky_engine,tvolkert/engine,devoncarew/sky_engine,jason-simmons/sky_engine,aam/engine,chinmaygarde/sky_engine,Hixie/sky_engine,tvolkert/engine,jason-simmons/sky_engine,rmacnak-google/engine,krisgiesing/sky_engine,jason-simmons/flutter_engine,jamesr/flutter_engine,devoncarew/sky_engine,jamesr/sky_engine,Hixie/sky_engine,krisgiesing/sky_engine,chinmaygarde/sky_engine,krisgiesing/sky_engine,chinmaygarde/flutter_engine,devoncarew/engine,tvolkert/engine,devoncarew/engine,flutter/engine,mikejurka/engine,jason-simmons/flutter_engine,jamesr/flutter_engine,rmacnak-google/engine,mikejurka/engine,cdotstout/sky_engine,devoncarew/engine,mikejurka/engine,cdotstout/sky_engine,aam/engine,Hixie/sky_engine,krisgiesing/sky_engine,jason-simmons/sky_engine,devoncarew/sky_engine,flutter/engine,mikejurka/engine,cdotstout/sky_engine,devoncarew/engine,tvolkert/engine,chinmaygarde/flutter_engine
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.view; import android.app.Activity; import android.content.Context; import android.graphics.Rect; import android.opengl.Matrix; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityNodeInfo; import android.view.accessibility.AccessibilityNodeProvider; import io.flutter.plugin.common.BasicMessageChannel; import io.flutter.plugin.common.StandardMessageCodec; import java.nio.ByteBuffer; import java.util.*; class AccessibilityBridge extends AccessibilityNodeProvider implements BasicMessageChannel.MessageHandler<Object> { private static final String TAG = "FlutterView"; // Constants from higher API levels. // TODO(goderbauer): Get these from Android Support Library when // https://github.com/flutter/flutter/issues/11099 is resolved. private static final int ACTION_SHOW_ON_SCREEN = 16908342; // API level 23 private static final float SCROLL_EXTENT_FOR_INFINITY = 100000.0f; private static final float SCROLL_POSITION_CAP_FOR_INFINITY = 70000.0f; private static final int ROOT_NODE_ID = 0; private Map<Integer, SemanticsObject> mObjects; private Map<Integer, CustomAccessibilityAction> mCustomAccessibilityActions; private final FlutterView mOwner; private boolean mAccessibilityEnabled = false; private SemanticsObject mA11yFocusedObject; private SemanticsObject mInputFocusedObject; private SemanticsObject mHoveredObject; private int previousRouteId = ROOT_NODE_ID; private List<Integer> previousRoutes; private final View mDecorView; private Integer mLastLeftFrameInset = 0; private final BasicMessageChannel<Object> mFlutterAccessibilityChannel; enum Action { TAP(1 << 0), LONG_PRESS(1 << 1), SCROLL_LEFT(1 << 2), SCROLL_RIGHT(1 << 3), SCROLL_UP(1 << 4), SCROLL_DOWN(1 << 5), INCREASE(1 << 6), DECREASE(1 << 7), SHOW_ON_SCREEN(1 << 8), MOVE_CURSOR_FORWARD_BY_CHARACTER(1 << 9), MOVE_CURSOR_BACKWARD_BY_CHARACTER(1 << 10), SET_SELECTION(1 << 11), COPY(1 << 12), CUT(1 << 13), PASTE(1 << 14), DID_GAIN_ACCESSIBILITY_FOCUS(1 << 15), DID_LOSE_ACCESSIBILITY_FOCUS(1 << 16), CUSTOM_ACTION(1 << 17), DISMISS(1 << 18), MOVE_CURSOR_FORWARD_BY_WORD(1 << 19), MOVE_CURSOR_BACKWARD_BY_WORD(1 << 20); Action(int value) { this.value = value; } final int value; } enum Flag { HAS_CHECKED_STATE(1 << 0), IS_CHECKED(1 << 1), IS_SELECTED(1 << 2), IS_BUTTON(1 << 3), IS_TEXT_FIELD(1 << 4), IS_FOCUSED(1 << 5), HAS_ENABLED_STATE(1 << 6), IS_ENABLED(1 << 7), IS_IN_MUTUALLY_EXCLUSIVE_GROUP(1 << 8), IS_HEADER(1 << 9), IS_OBSCURED(1 << 10), SCOPES_ROUTE(1 << 11), NAMES_ROUTE(1 << 12), IS_HIDDEN(1 << 13), IS_IMAGE(1 << 14), IS_LIVE_REGION(1 << 15), HAS_TOGGLED_STATE(1 << 16), IS_TOGGLED(1 << 17), HAS_IMPLICIT_SCROLLING(1 << 18); Flag(int value) { this.value = value; } final int value; } AccessibilityBridge(FlutterView owner) { assert owner != null; mOwner = owner; mObjects = new HashMap<Integer, SemanticsObject>(); mCustomAccessibilityActions = new HashMap<Integer, CustomAccessibilityAction>(); previousRoutes = new ArrayList<>(); mFlutterAccessibilityChannel = new BasicMessageChannel<>( owner, "flutter/accessibility", StandardMessageCodec.INSTANCE); mDecorView = ((Activity) owner.getContext()).getWindow().getDecorView(); } void setAccessibilityEnabled(boolean accessibilityEnabled) { mAccessibilityEnabled = accessibilityEnabled; if (accessibilityEnabled) { mFlutterAccessibilityChannel.setMessageHandler(this); } else { mFlutterAccessibilityChannel.setMessageHandler(null); } } @Override @SuppressWarnings("deprecation") public AccessibilityNodeInfo createAccessibilityNodeInfo(int virtualViewId) { if (virtualViewId == View.NO_ID) { AccessibilityNodeInfo result = AccessibilityNodeInfo.obtain(mOwner); mOwner.onInitializeAccessibilityNodeInfo(result); if (mObjects.containsKey(ROOT_NODE_ID)) { result.addChild(mOwner, ROOT_NODE_ID); } return result; } SemanticsObject object = mObjects.get(virtualViewId); if (object == null) { return null; } AccessibilityNodeInfo result = AccessibilityNodeInfo.obtain(mOwner, virtualViewId); result.setPackageName(mOwner.getContext().getPackageName()); result.setClassName("android.view.View"); result.setSource(mOwner, virtualViewId); result.setFocusable(object.isFocusable()); if (mInputFocusedObject != null) { result.setFocused(mInputFocusedObject.id == virtualViewId); } if (mA11yFocusedObject != null) { result.setAccessibilityFocused(mA11yFocusedObject.id == virtualViewId); } if (object.hasFlag(Flag.IS_TEXT_FIELD)) { result.setPassword(object.hasFlag(Flag.IS_OBSCURED)); result.setClassName("android.widget.EditText"); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { result.setEditable(true); if (object.textSelectionBase != -1 && object.textSelectionExtent != -1) { result.setTextSelection(object.textSelectionBase, object.textSelectionExtent); } // Text fields will always be created as a live region, so that updates to // the label trigger polite announcements. This makes it easy to follow a11y // guidelines for text fields on Android. result.setLiveRegion(View.ACCESSIBILITY_LIVE_REGION_POLITE); } // Cursor movements int granularities = 0; if (object.hasAction(Action.MOVE_CURSOR_FORWARD_BY_CHARACTER)) { result.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY); granularities |= AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER; } if (object.hasAction(Action.MOVE_CURSOR_BACKWARD_BY_CHARACTER)) { result.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY); granularities |= AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER; } if (object.hasAction(Action.MOVE_CURSOR_FORWARD_BY_WORD)) { result.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY); granularities |= AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD; } if (object.hasAction(Action.MOVE_CURSOR_BACKWARD_BY_WORD)) { result.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY); granularities |= AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD; } result.setMovementGranularities(granularities); } if (object.hasAction(Action.SET_SELECTION)) { result.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION); } if (object.hasAction(Action.COPY)) { result.addAction(AccessibilityNodeInfo.ACTION_COPY); } if (object.hasAction(Action.CUT)) { result.addAction(AccessibilityNodeInfo.ACTION_CUT); } if (object.hasAction(Action.PASTE)) { result.addAction(AccessibilityNodeInfo.ACTION_PASTE); } if (object.hasFlag(Flag.IS_BUTTON)) { result.setClassName("android.widget.Button"); } if (object.hasFlag(Flag.IS_IMAGE)) { result.setClassName("android.widget.ImageView"); // TODO(jonahwilliams): Figure out a way conform to the expected id from TalkBack's // CustomLabelManager. talkback/src/main/java/labeling/CustomLabelManager.java#L525 } if (object.hasAction(Action.DISMISS)) { result.setDismissable(true); result.addAction(AccessibilityNodeInfo.ACTION_DISMISS); } if (object.parent != null) { assert object.id > ROOT_NODE_ID; result.setParent(mOwner, object.parent.id); } else { assert object.id == ROOT_NODE_ID; result.setParent(mOwner); } Rect bounds = object.getGlobalRect(); if (object.parent != null) { Rect parentBounds = object.parent.getGlobalRect(); Rect boundsInParent = new Rect(bounds); boundsInParent.offset(-parentBounds.left, -parentBounds.top); result.setBoundsInParent(boundsInParent); } else { result.setBoundsInParent(bounds); } result.setBoundsInScreen(bounds); result.setVisibleToUser(true); result.setEnabled( !object.hasFlag(Flag.HAS_ENABLED_STATE) || object.hasFlag(Flag.IS_ENABLED)); if (object.hasAction(Action.TAP)) { if (Build.VERSION.SDK_INT >= 21 && object.onTapOverride != null) { result.addAction(new AccessibilityNodeInfo.AccessibilityAction( AccessibilityNodeInfo.ACTION_CLICK, object.onTapOverride.hint)); result.setClickable(true); } else { result.addAction(AccessibilityNodeInfo.ACTION_CLICK); result.setClickable(true); } } if (object.hasAction(Action.LONG_PRESS)) { if (Build.VERSION.SDK_INT >= 21 && object.onLongPressOverride != null) { result.addAction(new AccessibilityNodeInfo.AccessibilityAction(AccessibilityNodeInfo.ACTION_LONG_CLICK, object.onLongPressOverride.hint)); result.setLongClickable(true); } else { result.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK); result.setLongClickable(true); } } if (object.hasAction(Action.SCROLL_LEFT) || object.hasAction(Action.SCROLL_UP) || object.hasAction(Action.SCROLL_RIGHT) || object.hasAction(Action.SCROLL_DOWN)) { result.setScrollable(true); // This tells Android's a11y to send scroll events when reaching the end of // the visible viewport of a scrollable, unless the node itself does not // allow implicit scrolling - then we leave the className as view.View. if (object.hasFlag(Flag.HAS_IMPLICIT_SCROLLING)) { if (object.hasAction(Action.SCROLL_LEFT) || object.hasAction(Action.SCROLL_RIGHT)) { result.setClassName("android.widget.HorizontalScrollView"); } else { result.setClassName("android.widget.ScrollView"); } } // TODO(ianh): Once we're on SDK v23+, call addAction to // expose AccessibilityAction.ACTION_SCROLL_LEFT, _RIGHT, // _UP, and _DOWN when appropriate. if (object.hasAction(Action.SCROLL_LEFT) || object.hasAction(Action.SCROLL_UP)) { result.addAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD); } if (object.hasAction(Action.SCROLL_RIGHT) || object.hasAction(Action.SCROLL_DOWN)) { result.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD); } } if (object.hasAction(Action.INCREASE) || object.hasAction(Action.DECREASE)) { // TODO(jonahwilliams): support AccessibilityAction.ACTION_SET_PROGRESS once SDK is // updated. result.setClassName("android.widget.SeekBar"); if (object.hasAction(Action.INCREASE)) { result.addAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD); } if (object.hasAction(Action.DECREASE)) { result.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD); } } if (object.hasFlag(Flag.IS_LIVE_REGION)) { result.setLiveRegion(View.ACCESSIBILITY_LIVE_REGION_POLITE); } boolean hasCheckedState = object.hasFlag(Flag.HAS_CHECKED_STATE); boolean hasToggledState = object.hasFlag(Flag.HAS_TOGGLED_STATE); assert !(hasCheckedState && hasToggledState); result.setCheckable(hasCheckedState || hasToggledState); if (hasCheckedState) { result.setChecked(object.hasFlag(Flag.IS_CHECKED)); if (object.hasFlag(Flag.IS_IN_MUTUALLY_EXCLUSIVE_GROUP)) result.setClassName("android.widget.RadioButton"); else result.setClassName("android.widget.CheckBox"); } else if (hasToggledState) { result.setChecked(object.hasFlag(Flag.IS_TOGGLED)); result.setClassName("android.widget.Switch"); } result.setSelected(object.hasFlag(Flag.IS_SELECTED)); result.setText(object.getValueLabelHint()); // Accessibility Focus if (mA11yFocusedObject != null && mA11yFocusedObject.id == virtualViewId) { result.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS); } else { result.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS); } // Actions on the local context menu if (Build.VERSION.SDK_INT >= 21) { if (object.customAccessibilityActions != null) { for (CustomAccessibilityAction action : object.customAccessibilityActions) { result.addAction(new AccessibilityNodeInfo.AccessibilityAction( action.resourceId, action.label)); } } } if (object.childrenInTraversalOrder != null) { for (SemanticsObject child : object.childrenInTraversalOrder) { if (!child.hasFlag(Flag.IS_HIDDEN)) { result.addChild(mOwner, child.id); } } } return result; } @Override public boolean performAction(int virtualViewId, int action, Bundle arguments) { SemanticsObject object = mObjects.get(virtualViewId); if (object == null) { return false; } switch (action) { case AccessibilityNodeInfo.ACTION_CLICK: { // Note: TalkBack prior to Oreo doesn't use this handler and instead simulates a // click event at the center of the SemanticsNode. Other a11y services might go // through this handler though. mOwner.dispatchSemanticsAction(virtualViewId, Action.TAP); return true; } case AccessibilityNodeInfo.ACTION_LONG_CLICK: { // Note: TalkBack doesn't use this handler and instead simulates a long click event // at the center of the SemanticsNode. Other a11y services might go through this // handler though. mOwner.dispatchSemanticsAction(virtualViewId, Action.LONG_PRESS); return true; } case AccessibilityNodeInfo.ACTION_SCROLL_FORWARD: { if (object.hasAction(Action.SCROLL_UP)) { mOwner.dispatchSemanticsAction(virtualViewId, Action.SCROLL_UP); } else if (object.hasAction(Action.SCROLL_LEFT)) { // TODO(ianh): bidi support using textDirection mOwner.dispatchSemanticsAction(virtualViewId, Action.SCROLL_LEFT); } else if (object.hasAction(Action.INCREASE)) { object.value = object.increasedValue; // Event causes Android to read out the updated value. sendAccessibilityEvent(virtualViewId, AccessibilityEvent.TYPE_VIEW_SELECTED); mOwner.dispatchSemanticsAction(virtualViewId, Action.INCREASE); } else { return false; } return true; } case AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD: { if (object.hasAction(Action.SCROLL_DOWN)) { mOwner.dispatchSemanticsAction(virtualViewId, Action.SCROLL_DOWN); } else if (object.hasAction(Action.SCROLL_RIGHT)) { // TODO(ianh): bidi support using textDirection mOwner.dispatchSemanticsAction(virtualViewId, Action.SCROLL_RIGHT); } else if (object.hasAction(Action.DECREASE)) { object.value = object.decreasedValue; // Event causes Android to read out the updated value. sendAccessibilityEvent(virtualViewId, AccessibilityEvent.TYPE_VIEW_SELECTED); mOwner.dispatchSemanticsAction(virtualViewId, Action.DECREASE); } else { return false; } return true; } case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: { return performCursorMoveAction(object, virtualViewId, arguments, false); } case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: { return performCursorMoveAction(object, virtualViewId, arguments, true); } case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: { mOwner.dispatchSemanticsAction(virtualViewId, Action.DID_LOSE_ACCESSIBILITY_FOCUS); sendAccessibilityEvent( virtualViewId, AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); mA11yFocusedObject = null; return true; } case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: { mOwner.dispatchSemanticsAction(virtualViewId, Action.DID_GAIN_ACCESSIBILITY_FOCUS); sendAccessibilityEvent( virtualViewId, AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED); if (mA11yFocusedObject == null) { // When Android focuses a node, it doesn't invalidate the view. // (It does when it sends ACTION_CLEAR_ACCESSIBILITY_FOCUS, so // we only have to worry about this when the focused node is null.) mOwner.invalidate(); } mA11yFocusedObject = object; if (object.hasAction(Action.INCREASE) || object.hasAction(Action.DECREASE)) { // SeekBars only announce themselves after this event. sendAccessibilityEvent(virtualViewId, AccessibilityEvent.TYPE_VIEW_SELECTED); } return true; } case ACTION_SHOW_ON_SCREEN: { mOwner.dispatchSemanticsAction(virtualViewId, Action.SHOW_ON_SCREEN); return true; } case AccessibilityNodeInfo.ACTION_SET_SELECTION: { final Map<String, Integer> selection = new HashMap<String, Integer>(); final boolean hasSelection = arguments != null && arguments.containsKey( AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT) && arguments.containsKey( AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT); if (hasSelection) { selection.put("base", arguments.getInt( AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT)); selection.put("extent", arguments.getInt( AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT)); } else { // Clear the selection selection.put("base", object.textSelectionExtent); selection.put("extent", object.textSelectionExtent); } mOwner.dispatchSemanticsAction(virtualViewId, Action.SET_SELECTION, selection); return true; } case AccessibilityNodeInfo.ACTION_COPY: { mOwner.dispatchSemanticsAction(virtualViewId, Action.COPY); return true; } case AccessibilityNodeInfo.ACTION_CUT: { mOwner.dispatchSemanticsAction(virtualViewId, Action.CUT); return true; } case AccessibilityNodeInfo.ACTION_PASTE: { mOwner.dispatchSemanticsAction(virtualViewId, Action.PASTE); return true; } case AccessibilityNodeInfo.ACTION_DISMISS: { mOwner.dispatchSemanticsAction(virtualViewId, Action.DISMISS); return true; } default: // might be a custom accessibility action. final int flutterId = action - firstResourceId; CustomAccessibilityAction contextAction = mCustomAccessibilityActions.get(flutterId); if (contextAction != null) { mOwner.dispatchSemanticsAction( virtualViewId, Action.CUSTOM_ACTION, contextAction.id); return true; } } return false; } boolean performCursorMoveAction( SemanticsObject object, int virtualViewId, Bundle arguments, boolean forward) { final int granularity = arguments.getInt(AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); final boolean extendSelection = arguments.getBoolean( AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); switch (granularity) { case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: { if (forward && object.hasAction(Action.MOVE_CURSOR_FORWARD_BY_CHARACTER)) { mOwner.dispatchSemanticsAction(virtualViewId, Action.MOVE_CURSOR_FORWARD_BY_CHARACTER, extendSelection); return true; } if (!forward && object.hasAction(Action.MOVE_CURSOR_BACKWARD_BY_CHARACTER)) { mOwner.dispatchSemanticsAction(virtualViewId, Action.MOVE_CURSOR_BACKWARD_BY_CHARACTER, extendSelection); return true; } break; } case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: if (forward && object.hasAction(Action.MOVE_CURSOR_FORWARD_BY_WORD)) { mOwner.dispatchSemanticsAction(virtualViewId, Action.MOVE_CURSOR_FORWARD_BY_WORD, extendSelection); return true; } if (!forward && object.hasAction(Action.MOVE_CURSOR_BACKWARD_BY_WORD)) { mOwner.dispatchSemanticsAction(virtualViewId, Action.MOVE_CURSOR_BACKWARD_BY_WORD, extendSelection); return true; } break; } return false; } // TODO(ianh): implement findAccessibilityNodeInfosByText() @Override public AccessibilityNodeInfo findFocus(int focus) { switch (focus) { case AccessibilityNodeInfo.FOCUS_INPUT: { if (mInputFocusedObject != null) return createAccessibilityNodeInfo(mInputFocusedObject.id); } // Fall through to check FOCUS_ACCESSIBILITY case AccessibilityNodeInfo.FOCUS_ACCESSIBILITY: { if (mA11yFocusedObject != null) return createAccessibilityNodeInfo(mA11yFocusedObject.id); } } return null; } private SemanticsObject getRootObject() { assert mObjects.containsKey(0); return mObjects.get(0); } private SemanticsObject getOrCreateObject(int id) { SemanticsObject object = mObjects.get(id); if (object == null) { object = new SemanticsObject(); object.id = id; mObjects.put(id, object); } return object; } private CustomAccessibilityAction getOrCreateAction(int id) { CustomAccessibilityAction action = mCustomAccessibilityActions.get(id); if (action == null) { action = new CustomAccessibilityAction(); action.id = id; action.resourceId = id + firstResourceId; mCustomAccessibilityActions.put(id, action); } return action; } void handleTouchExplorationExit() { if (mHoveredObject != null) { sendAccessibilityEvent(mHoveredObject.id, AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); mHoveredObject = null; } } void handleTouchExploration(float x, float y) { if (mObjects.isEmpty()) { return; } SemanticsObject newObject = getRootObject().hitTest(new float[] {x, y, 0, 1}); if (newObject != mHoveredObject) { // sending ENTER before EXIT is how Android wants it if (newObject != null) { sendAccessibilityEvent(newObject.id, AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); } if (mHoveredObject != null) { sendAccessibilityEvent(mHoveredObject.id, AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); } mHoveredObject = newObject; } } void updateCustomAccessibilityActions(ByteBuffer buffer, String[] strings) { ArrayList<CustomAccessibilityAction> updatedActions = new ArrayList<CustomAccessibilityAction>(); while (buffer.hasRemaining()) { int id = buffer.getInt(); CustomAccessibilityAction action = getOrCreateAction(id); action.overrideId = buffer.getInt(); int stringIndex = buffer.getInt(); action.label = stringIndex == -1 ? null : strings[stringIndex]; stringIndex = buffer.getInt(); action.hint = stringIndex == -1 ? null : strings[stringIndex]; } } void updateSemantics(ByteBuffer buffer, String[] strings) { ArrayList<SemanticsObject> updated = new ArrayList<SemanticsObject>(); while (buffer.hasRemaining()) { int id = buffer.getInt(); SemanticsObject object = getOrCreateObject(id); object.updateWith(buffer, strings); if (object.hasFlag(Flag.IS_HIDDEN)) { continue; } if (object.hasFlag(Flag.IS_FOCUSED)) { mInputFocusedObject = object; } if (object.hadPreviousConfig) { updated.add(object); } } Set<SemanticsObject> visitedObjects = new HashSet<SemanticsObject>(); SemanticsObject rootObject = getRootObject(); List<SemanticsObject> newRoutes = new ArrayList<>(); if (rootObject != null) { final float[] identity = new float[16]; Matrix.setIdentityM(identity, 0); // in android devices above AP 23, the system nav bar can be placed on the left side // of the screen in landscape mode. We must handle the translation ourselves for the // a11y nodes. if (Build.VERSION.SDK_INT >= 23) { Rect visibleFrame = new Rect(); mDecorView.getWindowVisibleDisplayFrame(visibleFrame); if (!mLastLeftFrameInset.equals(visibleFrame.left)) { rootObject.globalGeometryDirty = true; rootObject.inverseTransformDirty = true; } mLastLeftFrameInset = visibleFrame.left; Matrix.translateM(identity, 0, visibleFrame.left, 0, 0); } rootObject.updateRecursively(identity, visitedObjects, false); rootObject.collectRoutes(newRoutes); } // Dispatch a TYPE_WINDOW_STATE_CHANGED event if the most recent route id changed from the // previously cached route id. SemanticsObject lastAdded = null; for (SemanticsObject semanticsObject : newRoutes) { if (!previousRoutes.contains(semanticsObject.id)) { lastAdded = semanticsObject; } } if (lastAdded == null && newRoutes.size() > 0) { lastAdded = newRoutes.get(newRoutes.size() - 1); } if (lastAdded != null && lastAdded.id != previousRouteId) { previousRouteId = lastAdded.id; createWindowChangeEvent(lastAdded); } previousRoutes.clear(); for (SemanticsObject semanticsObject : newRoutes) { previousRoutes.add(semanticsObject.id); } Iterator<Map.Entry<Integer, SemanticsObject>> it = mObjects.entrySet().iterator(); while (it.hasNext()) { Map.Entry<Integer, SemanticsObject> entry = it.next(); SemanticsObject object = entry.getValue(); if (!visitedObjects.contains(object)) { willRemoveSemanticsObject(object); it.remove(); } } // TODO(goderbauer): Send this event only once (!) for changed subtrees, // see https://github.com/flutter/flutter/issues/14534 sendAccessibilityEvent(0, AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); for (SemanticsObject object : updated) { if (object.didScroll()) { AccessibilityEvent event = obtainAccessibilityEvent(object.id, AccessibilityEvent.TYPE_VIEW_SCROLLED); // Android doesn't support unbound scrolling. So we pretend there is a large // bound (SCROLL_EXTENT_FOR_INFINITY), which you can never reach. float position = object.scrollPosition; float max = object.scrollExtentMax; if (Float.isInfinite(object.scrollExtentMax)) { max = SCROLL_EXTENT_FOR_INFINITY; if (position > SCROLL_POSITION_CAP_FOR_INFINITY) { position = SCROLL_POSITION_CAP_FOR_INFINITY; } } if (Float.isInfinite(object.scrollExtentMin)) { max += SCROLL_EXTENT_FOR_INFINITY; if (position < -SCROLL_POSITION_CAP_FOR_INFINITY) { position = -SCROLL_POSITION_CAP_FOR_INFINITY; } position += SCROLL_EXTENT_FOR_INFINITY; } else { max -= object.scrollExtentMin; position -= object.scrollExtentMin; } if (object.hadAction(Action.SCROLL_UP) || object.hadAction(Action.SCROLL_DOWN)) { event.setScrollY((int) position); event.setMaxScrollY((int) max); } else if (object.hadAction(Action.SCROLL_LEFT) || object.hadAction(Action.SCROLL_RIGHT)) { event.setScrollX((int) position); event.setMaxScrollX((int) max); } sendAccessibilityEvent(event); } if (object.hasFlag(Flag.IS_LIVE_REGION) && !object.hadFlag(Flag.IS_LIVE_REGION)) { sendAccessibilityEvent(object.id, AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); } else if (object.hasFlag(Flag.IS_TEXT_FIELD) && object.didChangeLabel() && mInputFocusedObject != null && mInputFocusedObject.id == object.id) { // Text fields should announce when their label changes while focused. We use a live // region tag to do so, and this event triggers that update. sendAccessibilityEvent(object.id, AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); } if (mA11yFocusedObject != null && mA11yFocusedObject.id == object.id && !object.hadFlag(Flag.IS_SELECTED) && object.hasFlag(Flag.IS_SELECTED)) { AccessibilityEvent event = obtainAccessibilityEvent(object.id, AccessibilityEvent.TYPE_VIEW_SELECTED); event.getText().add(object.label); sendAccessibilityEvent(event); } if (mInputFocusedObject != null && mInputFocusedObject.id == object.id && object.hadFlag(Flag.IS_TEXT_FIELD) && object.hasFlag(Flag.IS_TEXT_FIELD)) { String oldValue = object.previousValue != null ? object.previousValue : ""; String newValue = object.value != null ? object.value : ""; AccessibilityEvent event = createTextChangedEvent(object.id, oldValue, newValue); if (event != null) { sendAccessibilityEvent(event); } if (object.previousTextSelectionBase != object.textSelectionBase || object.previousTextSelectionExtent != object.textSelectionExtent) { AccessibilityEvent selectionEvent = obtainAccessibilityEvent( object.id, AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED); selectionEvent.getText().add(newValue); selectionEvent.setFromIndex(object.textSelectionBase); selectionEvent.setToIndex(object.textSelectionExtent); selectionEvent.setItemCount(newValue.length()); sendAccessibilityEvent(selectionEvent); } } } } private AccessibilityEvent createTextChangedEvent(int id, String oldValue, String newValue) { AccessibilityEvent e = obtainAccessibilityEvent(id, AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED); e.setBeforeText(oldValue); e.getText().add(newValue); int i; for (i = 0; i < oldValue.length() && i < newValue.length(); ++i) { if (oldValue.charAt(i) != newValue.charAt(i)) { break; } } if (i >= oldValue.length() && i >= newValue.length()) { return null; // Text did not change } int firstDifference = i; e.setFromIndex(firstDifference); int oldIndex = oldValue.length() - 1; int newIndex = newValue.length() - 1; while (oldIndex >= firstDifference && newIndex >= firstDifference) { if (oldValue.charAt(oldIndex) != newValue.charAt(newIndex)) { break; } --oldIndex; --newIndex; } e.setRemovedCount(oldIndex - firstDifference + 1); e.setAddedCount(newIndex - firstDifference + 1); return e; } private AccessibilityEvent obtainAccessibilityEvent(int virtualViewId, int eventType) { assert virtualViewId != ROOT_NODE_ID; AccessibilityEvent event = AccessibilityEvent.obtain(eventType); event.setPackageName(mOwner.getContext().getPackageName()); event.setSource(mOwner, virtualViewId); return event; } private void sendAccessibilityEvent(int virtualViewId, int eventType) { if (!mAccessibilityEnabled) { return; } if (virtualViewId == ROOT_NODE_ID) { mOwner.sendAccessibilityEvent(eventType); } else { sendAccessibilityEvent(obtainAccessibilityEvent(virtualViewId, eventType)); } } private void sendAccessibilityEvent(AccessibilityEvent event) { if (!mAccessibilityEnabled) { return; } mOwner.getParent().requestSendAccessibilityEvent(mOwner, event); } // Message Handler for [mFlutterAccessibilityChannel]. public void onMessage(Object message, BasicMessageChannel.Reply<Object> reply) { @SuppressWarnings("unchecked") final HashMap<String, Object> annotatedEvent = (HashMap<String, Object>) message; final String type = (String) annotatedEvent.get("type"); @SuppressWarnings("unchecked") final HashMap<String, Object> data = (HashMap<String, Object>) annotatedEvent.get("data"); switch (type) { case "announce": mOwner.announceForAccessibility((String) data.get("message")); break; case "longPress": { Integer nodeId = (Integer) annotatedEvent.get("nodeId"); if (nodeId == null) { return; } sendAccessibilityEvent(nodeId, AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); break; } case "tap": { Integer nodeId = (Integer) annotatedEvent.get("nodeId"); if (nodeId == null) { return; } sendAccessibilityEvent(nodeId, AccessibilityEvent.TYPE_VIEW_CLICKED); break; } case "tooltip": { AccessibilityEvent e = obtainAccessibilityEvent( ROOT_NODE_ID, AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); e.getText().add((String) data.get("message")); sendAccessibilityEvent(e); } // Requires that the node id provided corresponds to a live region, or TalkBack will // ignore the event. The event will cause talkback to read out the new label even // if node is not focused. case "updateLiveRegion": { Integer nodeId = (Integer) annotatedEvent.get("nodeId"); if (nodeId == null) { return; } sendAccessibilityEvent(nodeId, AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); } } } private void createWindowChangeEvent(SemanticsObject route) { AccessibilityEvent e = obtainAccessibilityEvent(route.id, AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); String routeName = route.getRouteName(); e.getText().add(routeName); sendAccessibilityEvent(e); } private void willRemoveSemanticsObject(SemanticsObject object) { assert mObjects.containsKey(object.id); assert mObjects.get(object.id) == object; object.parent = null; if (mA11yFocusedObject == object) { sendAccessibilityEvent(mA11yFocusedObject.id, AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); mA11yFocusedObject = null; } if (mInputFocusedObject == object) { mInputFocusedObject = null; } if (mHoveredObject == object) { mHoveredObject = null; } } void reset() { mObjects.clear(); if (mA11yFocusedObject != null) sendAccessibilityEvent(mA11yFocusedObject.id, AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); mA11yFocusedObject = null; mHoveredObject = null; sendAccessibilityEvent(0, AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); } private enum TextDirection { UNKNOWN, LTR, RTL; public static TextDirection fromInt(int value) { switch (value) { case 1: return RTL; case 2: return LTR; } return UNKNOWN; } } private class CustomAccessibilityAction { CustomAccessibilityAction() {} /// Resource id is the id of the custom action plus a minimum value so that the identifier /// does not collide with existing Android accessibility actions. int resourceId = -1; int id = -1; int overrideId = -1; /// The label is the user presented value which is displayed in the local context menu. String label; /// The hint is the text used in overriden standard actions. String hint; boolean isStandardAction() { return overrideId != -1; } } /// Value is derived from ACTION_TYPE_MASK in AccessibilityNodeInfo.java static int firstResourceId = 267386881; private class SemanticsObject { SemanticsObject() {} int id = -1; int flags; int actions; int textSelectionBase; int textSelectionExtent; float scrollPosition; float scrollExtentMax; float scrollExtentMin; String label; String value; String increasedValue; String decreasedValue; String hint; TextDirection textDirection; boolean hadPreviousConfig = false; int previousFlags; int previousActions; int previousTextSelectionBase; int previousTextSelectionExtent; float previousScrollPosition; float previousScrollExtentMax; float previousScrollExtentMin; String previousValue; String previousLabel; private float left; private float top; private float right; private float bottom; private float[] transform; SemanticsObject parent; List<SemanticsObject> childrenInTraversalOrder; List<SemanticsObject> childrenInHitTestOrder; List<CustomAccessibilityAction> customAccessibilityActions; CustomAccessibilityAction onTapOverride; CustomAccessibilityAction onLongPressOverride; private boolean inverseTransformDirty = true; private float[] inverseTransform; private boolean globalGeometryDirty = true; private float[] globalTransform; private Rect globalRect; boolean hasAction(Action action) { return (actions & action.value) != 0; } boolean hadAction(Action action) { return (previousActions & action.value) != 0; } boolean hasFlag(Flag flag) { return (flags & flag.value) != 0; } boolean hadFlag(Flag flag) { assert hadPreviousConfig; return (previousFlags & flag.value) != 0; } boolean didScroll() { return !Float.isNaN(scrollPosition) && !Float.isNaN(previousScrollPosition) && previousScrollPosition != scrollPosition; } boolean didChangeLabel() { if (label == null && previousLabel == null) { return false; } return label == null || previousLabel == null || !label.equals(previousLabel); } void log(String indent, boolean recursive) { Log.i(TAG, indent + "SemanticsObject id=" + id + " label=" + label + " actions=" + actions + " flags=" + flags + "\n" + indent + " +-- textDirection=" + textDirection + "\n" + indent + " +-- rect.ltrb=(" + left + ", " + top + ", " + right + ", " + bottom + ")\n" + indent + " +-- transform=" + Arrays.toString(transform) + "\n"); if (childrenInTraversalOrder != null && recursive) { String childIndent = indent + " "; for (SemanticsObject child : childrenInTraversalOrder) { child.log(childIndent, recursive); } } } void updateWith(ByteBuffer buffer, String[] strings) { hadPreviousConfig = true; previousValue = value; previousLabel = label; previousFlags = flags; previousActions = actions; previousTextSelectionBase = textSelectionBase; previousTextSelectionExtent = textSelectionExtent; previousScrollPosition = scrollPosition; previousScrollExtentMax = scrollExtentMax; previousScrollExtentMin = scrollExtentMin; flags = buffer.getInt(); actions = buffer.getInt(); textSelectionBase = buffer.getInt(); textSelectionExtent = buffer.getInt(); scrollPosition = buffer.getFloat(); scrollExtentMax = buffer.getFloat(); scrollExtentMin = buffer.getFloat(); int stringIndex = buffer.getInt(); label = stringIndex == -1 ? null : strings[stringIndex]; stringIndex = buffer.getInt(); value = stringIndex == -1 ? null : strings[stringIndex]; stringIndex = buffer.getInt(); increasedValue = stringIndex == -1 ? null : strings[stringIndex]; stringIndex = buffer.getInt(); decreasedValue = stringIndex == -1 ? null : strings[stringIndex]; stringIndex = buffer.getInt(); hint = stringIndex == -1 ? null : strings[stringIndex]; textDirection = TextDirection.fromInt(buffer.getInt()); left = buffer.getFloat(); top = buffer.getFloat(); right = buffer.getFloat(); bottom = buffer.getFloat(); if (transform == null) { transform = new float[16]; } for (int i = 0; i < 16; ++i) { transform[i] = buffer.getFloat(); } inverseTransformDirty = true; globalGeometryDirty = true; final int childCount = buffer.getInt(); if (childCount == 0) { childrenInTraversalOrder = null; childrenInHitTestOrder = null; } else { if (childrenInTraversalOrder == null) childrenInTraversalOrder = new ArrayList<SemanticsObject>(childCount); else childrenInTraversalOrder.clear(); for (int i = 0; i < childCount; ++i) { SemanticsObject child = getOrCreateObject(buffer.getInt()); child.parent = this; childrenInTraversalOrder.add(child); } if (childrenInHitTestOrder == null) childrenInHitTestOrder = new ArrayList<SemanticsObject>(childCount); else childrenInHitTestOrder.clear(); for (int i = 0; i < childCount; ++i) { SemanticsObject child = getOrCreateObject(buffer.getInt()); child.parent = this; childrenInHitTestOrder.add(child); } } final int actionCount = buffer.getInt(); if (actionCount == 0) { customAccessibilityActions = null; } else { if (customAccessibilityActions == null) customAccessibilityActions = new ArrayList<CustomAccessibilityAction>(actionCount); else customAccessibilityActions.clear(); for (int i = 0; i < actionCount; i++) { CustomAccessibilityAction action = getOrCreateAction(buffer.getInt()); if (action.overrideId == Action.TAP.value) { onTapOverride = action; } else if (action.overrideId == Action.LONG_PRESS.value) { onLongPressOverride = action; } else { // If we recieve a different overrideId it means that we were passed // a standard action to override that we don't yet support. assert action.overrideId == -1; customAccessibilityActions.add(action); } customAccessibilityActions.add(action); } } } private void ensureInverseTransform() { if (!inverseTransformDirty) { return; } inverseTransformDirty = false; if (inverseTransform == null) { inverseTransform = new float[16]; } if (!Matrix.invertM(inverseTransform, 0, transform, 0)) { Arrays.fill(inverseTransform, 0); } } Rect getGlobalRect() { assert !globalGeometryDirty; return globalRect; } SemanticsObject hitTest(float[] point) { final float w = point[3]; final float x = point[0] / w; final float y = point[1] / w; if (x < left || x >= right || y < top || y >= bottom) return null; if (childrenInHitTestOrder != null) { final float[] transformedPoint = new float[4]; for (int i = 0; i < childrenInHitTestOrder.size(); i += 1) { final SemanticsObject child = childrenInHitTestOrder.get(i); if (child.hasFlag(Flag.IS_HIDDEN)) { continue; } child.ensureInverseTransform(); Matrix.multiplyMV(transformedPoint, 0, child.inverseTransform, 0, point, 0); final SemanticsObject result = child.hitTest(transformedPoint); if (result != null) { return result; } } } return this; } // TODO(goderbauer): This should be decided by the framework once we have more information // about focusability there. boolean isFocusable() { // We enforce in the framework that no other useful semantics are merged with these // nodes. if (hasFlag(Flag.SCOPES_ROUTE)) { return false; } int scrollableActions = Action.SCROLL_RIGHT.value | Action.SCROLL_LEFT.value | Action.SCROLL_UP.value | Action.SCROLL_DOWN.value; return (actions & ~scrollableActions) != 0 || flags != 0 || (label != null && !label.isEmpty()) || (value != null && !value.isEmpty()) || (hint != null && !hint.isEmpty()); } void collectRoutes(List<SemanticsObject> edges) { if (hasFlag(Flag.SCOPES_ROUTE)) { edges.add(this); } if (childrenInTraversalOrder != null) { for (int i = 0; i < childrenInTraversalOrder.size(); ++i) { childrenInTraversalOrder.get(i).collectRoutes(edges); } } } String getRouteName() { // Returns the first non-null and non-empty semantic label of a child // with an NamesRoute flag. Otherwise returns null. if (hasFlag(Flag.NAMES_ROUTE)) { if (label != null && !label.isEmpty()) { return label; } } if (childrenInTraversalOrder != null) { for (int i = 0; i < childrenInTraversalOrder.size(); ++i) { String newName = childrenInTraversalOrder.get(i).getRouteName(); if (newName != null && !newName.isEmpty()) { return newName; } } } return null; } void updateRecursively(float[] ancestorTransform, Set<SemanticsObject> visitedObjects, boolean forceUpdate) { visitedObjects.add(this); if (globalGeometryDirty) { forceUpdate = true; } if (forceUpdate) { if (globalTransform == null) { globalTransform = new float[16]; } Matrix.multiplyMM(globalTransform, 0, ancestorTransform, 0, transform, 0); final float[] sample = new float[4]; sample[2] = 0; sample[3] = 1; final float[] point1 = new float[4]; final float[] point2 = new float[4]; final float[] point3 = new float[4]; final float[] point4 = new float[4]; sample[0] = left; sample[1] = top; transformPoint(point1, globalTransform, sample); sample[0] = right; sample[1] = top; transformPoint(point2, globalTransform, sample); sample[0] = right; sample[1] = bottom; transformPoint(point3, globalTransform, sample); sample[0] = left; sample[1] = bottom; transformPoint(point4, globalTransform, sample); if (globalRect == null) globalRect = new Rect(); globalRect.set(Math.round(min(point1[0], point2[0], point3[0], point4[0])), Math.round(min(point1[1], point2[1], point3[1], point4[1])), Math.round(max(point1[0], point2[0], point3[0], point4[0])), Math.round(max(point1[1], point2[1], point3[1], point4[1]))); globalGeometryDirty = false; } assert globalTransform != null; assert globalRect != null; if (childrenInTraversalOrder != null) { for (int i = 0; i < childrenInTraversalOrder.size(); ++i) { childrenInTraversalOrder.get(i).updateRecursively( globalTransform, visitedObjects, forceUpdate); } } } private void transformPoint(float[] result, float[] transform, float[] point) { Matrix.multiplyMV(result, 0, transform, 0, point, 0); final float w = result[3]; result[0] /= w; result[1] /= w; result[2] /= w; result[3] = 0; } private float min(float a, float b, float c, float d) { return Math.min(a, Math.min(b, Math.min(c, d))); } private float max(float a, float b, float c, float d) { return Math.max(a, Math.max(b, Math.max(c, d))); } private String getValueLabelHint() { StringBuilder sb = new StringBuilder(); String[] array = {value, label, hint}; for (String word : array) { if (word != null && word.length() > 0) { if (sb.length() > 0) sb.append(", "); sb.append(word); } } return sb.length() > 0 ? sb.toString() : null; } } }
shell/platform/android/io/flutter/view/AccessibilityBridge.java
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.view; import android.graphics.Rect; import android.opengl.Matrix; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityNodeInfo; import android.view.accessibility.AccessibilityNodeProvider; import io.flutter.plugin.common.BasicMessageChannel; import io.flutter.plugin.common.StandardMessageCodec; import java.nio.ByteBuffer; import java.util.*; class AccessibilityBridge extends AccessibilityNodeProvider implements BasicMessageChannel.MessageHandler<Object> { private static final String TAG = "FlutterView"; // Constants from higher API levels. // TODO(goderbauer): Get these from Android Support Library when // https://github.com/flutter/flutter/issues/11099 is resolved. private static final int ACTION_SHOW_ON_SCREEN = 16908342; // API level 23 private static final float SCROLL_EXTENT_FOR_INFINITY = 100000.0f; private static final float SCROLL_POSITION_CAP_FOR_INFINITY = 70000.0f; private static final int ROOT_NODE_ID = 0; private Map<Integer, SemanticsObject> mObjects; private Map<Integer, CustomAccessibilityAction> mCustomAccessibilityActions; private final FlutterView mOwner; private boolean mAccessibilityEnabled = false; private SemanticsObject mA11yFocusedObject; private SemanticsObject mInputFocusedObject; private SemanticsObject mHoveredObject; private int previousRouteId = ROOT_NODE_ID; private List<Integer> previousRoutes; private final BasicMessageChannel<Object> mFlutterAccessibilityChannel; enum Action { TAP(1 << 0), LONG_PRESS(1 << 1), SCROLL_LEFT(1 << 2), SCROLL_RIGHT(1 << 3), SCROLL_UP(1 << 4), SCROLL_DOWN(1 << 5), INCREASE(1 << 6), DECREASE(1 << 7), SHOW_ON_SCREEN(1 << 8), MOVE_CURSOR_FORWARD_BY_CHARACTER(1 << 9), MOVE_CURSOR_BACKWARD_BY_CHARACTER(1 << 10), SET_SELECTION(1 << 11), COPY(1 << 12), CUT(1 << 13), PASTE(1 << 14), DID_GAIN_ACCESSIBILITY_FOCUS(1 << 15), DID_LOSE_ACCESSIBILITY_FOCUS(1 << 16), CUSTOM_ACTION(1 << 17), DISMISS(1 << 18), MOVE_CURSOR_FORWARD_BY_WORD(1 << 19), MOVE_CURSOR_BACKWARD_BY_WORD(1 << 20); Action(int value) { this.value = value; } final int value; } enum Flag { HAS_CHECKED_STATE(1 << 0), IS_CHECKED(1 << 1), IS_SELECTED(1 << 2), IS_BUTTON(1 << 3), IS_TEXT_FIELD(1 << 4), IS_FOCUSED(1 << 5), HAS_ENABLED_STATE(1 << 6), IS_ENABLED(1 << 7), IS_IN_MUTUALLY_EXCLUSIVE_GROUP(1 << 8), IS_HEADER(1 << 9), IS_OBSCURED(1 << 10), SCOPES_ROUTE(1 << 11), NAMES_ROUTE(1 << 12), IS_HIDDEN(1 << 13), IS_IMAGE(1 << 14), IS_LIVE_REGION(1 << 15), HAS_TOGGLED_STATE(1 << 16), IS_TOGGLED(1 << 17), HAS_IMPLICIT_SCROLLING(1 << 18); Flag(int value) { this.value = value; } final int value; } AccessibilityBridge(FlutterView owner) { assert owner != null; mOwner = owner; mObjects = new HashMap<Integer, SemanticsObject>(); mCustomAccessibilityActions = new HashMap<Integer, CustomAccessibilityAction>(); previousRoutes = new ArrayList<>(); mFlutterAccessibilityChannel = new BasicMessageChannel<>( owner, "flutter/accessibility", StandardMessageCodec.INSTANCE); } void setAccessibilityEnabled(boolean accessibilityEnabled) { mAccessibilityEnabled = accessibilityEnabled; if (accessibilityEnabled) { mFlutterAccessibilityChannel.setMessageHandler(this); } else { mFlutterAccessibilityChannel.setMessageHandler(null); } } @Override @SuppressWarnings("deprecation") public AccessibilityNodeInfo createAccessibilityNodeInfo(int virtualViewId) { if (virtualViewId == View.NO_ID) { AccessibilityNodeInfo result = AccessibilityNodeInfo.obtain(mOwner); mOwner.onInitializeAccessibilityNodeInfo(result); if (mObjects.containsKey(ROOT_NODE_ID)) { result.addChild(mOwner, ROOT_NODE_ID); } return result; } SemanticsObject object = mObjects.get(virtualViewId); if (object == null) { return null; } AccessibilityNodeInfo result = AccessibilityNodeInfo.obtain(mOwner, virtualViewId); result.setPackageName(mOwner.getContext().getPackageName()); result.setClassName("android.view.View"); result.setSource(mOwner, virtualViewId); result.setFocusable(object.isFocusable()); if (mInputFocusedObject != null) { result.setFocused(mInputFocusedObject.id == virtualViewId); } if (mA11yFocusedObject != null) { result.setAccessibilityFocused(mA11yFocusedObject.id == virtualViewId); } if (object.hasFlag(Flag.IS_TEXT_FIELD)) { result.setPassword(object.hasFlag(Flag.IS_OBSCURED)); result.setClassName("android.widget.EditText"); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { result.setEditable(true); if (object.textSelectionBase != -1 && object.textSelectionExtent != -1) { result.setTextSelection(object.textSelectionBase, object.textSelectionExtent); } // Text fields will always be created as a live region, so that updates to // the label trigger polite announcements. This makes it easy to follow a11y // guidelines for text fields on Android. result.setLiveRegion(View.ACCESSIBILITY_LIVE_REGION_POLITE); } // Cursor movements int granularities = 0; if (object.hasAction(Action.MOVE_CURSOR_FORWARD_BY_CHARACTER)) { result.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY); granularities |= AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER; } if (object.hasAction(Action.MOVE_CURSOR_BACKWARD_BY_CHARACTER)) { result.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY); granularities |= AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER; } if (object.hasAction(Action.MOVE_CURSOR_FORWARD_BY_WORD)) { result.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY); granularities |= AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD; } if (object.hasAction(Action.MOVE_CURSOR_BACKWARD_BY_WORD)) { result.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY); granularities |= AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD; } result.setMovementGranularities(granularities); } if (object.hasAction(Action.SET_SELECTION)) { result.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION); } if (object.hasAction(Action.COPY)) { result.addAction(AccessibilityNodeInfo.ACTION_COPY); } if (object.hasAction(Action.CUT)) { result.addAction(AccessibilityNodeInfo.ACTION_CUT); } if (object.hasAction(Action.PASTE)) { result.addAction(AccessibilityNodeInfo.ACTION_PASTE); } if (object.hasFlag(Flag.IS_BUTTON)) { result.setClassName("android.widget.Button"); } if (object.hasFlag(Flag.IS_IMAGE)) { result.setClassName("android.widget.ImageView"); // TODO(jonahwilliams): Figure out a way conform to the expected id from TalkBack's // CustomLabelManager. talkback/src/main/java/labeling/CustomLabelManager.java#L525 } if (object.hasAction(Action.DISMISS)) { result.setDismissable(true); result.addAction(AccessibilityNodeInfo.ACTION_DISMISS); } if (object.parent != null) { assert object.id > ROOT_NODE_ID; result.setParent(mOwner, object.parent.id); } else { assert object.id == ROOT_NODE_ID; result.setParent(mOwner); } Rect bounds = object.getGlobalRect(); if (object.parent != null) { Rect parentBounds = object.parent.getGlobalRect(); Rect boundsInParent = new Rect(bounds); boundsInParent.offset(-parentBounds.left, -parentBounds.top); result.setBoundsInParent(boundsInParent); } else { result.setBoundsInParent(bounds); } result.setBoundsInScreen(bounds); result.setVisibleToUser(true); result.setEnabled( !object.hasFlag(Flag.HAS_ENABLED_STATE) || object.hasFlag(Flag.IS_ENABLED)); if (object.hasAction(Action.TAP)) { if (Build.VERSION.SDK_INT >= 21 && object.onTapOverride != null) { result.addAction(new AccessibilityNodeInfo.AccessibilityAction( AccessibilityNodeInfo.ACTION_CLICK, object.onTapOverride.hint)); result.setClickable(true); } else { result.addAction(AccessibilityNodeInfo.ACTION_CLICK); result.setClickable(true); } } if (object.hasAction(Action.LONG_PRESS)) { if (Build.VERSION.SDK_INT >= 21 && object.onLongPressOverride != null) { result.addAction(new AccessibilityNodeInfo.AccessibilityAction(AccessibilityNodeInfo.ACTION_LONG_CLICK, object.onLongPressOverride.hint)); result.setLongClickable(true); } else { result.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK); result.setLongClickable(true); } } if (object.hasAction(Action.SCROLL_LEFT) || object.hasAction(Action.SCROLL_UP) || object.hasAction(Action.SCROLL_RIGHT) || object.hasAction(Action.SCROLL_DOWN)) { result.setScrollable(true); // This tells Android's a11y to send scroll events when reaching the end of // the visible viewport of a scrollable, unless the node itself does not // allow implicit scrolling - then we leave the className as view.View. if (object.hasFlag(Flag.HAS_IMPLICIT_SCROLLING)) { if (object.hasAction(Action.SCROLL_LEFT) || object.hasAction(Action.SCROLL_RIGHT)) { result.setClassName("android.widget.HorizontalScrollView"); } else { result.setClassName("android.widget.ScrollView"); } } // TODO(ianh): Once we're on SDK v23+, call addAction to // expose AccessibilityAction.ACTION_SCROLL_LEFT, _RIGHT, // _UP, and _DOWN when appropriate. if (object.hasAction(Action.SCROLL_LEFT) || object.hasAction(Action.SCROLL_UP)) { result.addAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD); } if (object.hasAction(Action.SCROLL_RIGHT) || object.hasAction(Action.SCROLL_DOWN)) { result.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD); } } if (object.hasAction(Action.INCREASE) || object.hasAction(Action.DECREASE)) { // TODO(jonahwilliams): support AccessibilityAction.ACTION_SET_PROGRESS once SDK is // updated. result.setClassName("android.widget.SeekBar"); if (object.hasAction(Action.INCREASE)) { result.addAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD); } if (object.hasAction(Action.DECREASE)) { result.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD); } } if (object.hasFlag(Flag.IS_LIVE_REGION)) { result.setLiveRegion(View.ACCESSIBILITY_LIVE_REGION_POLITE); } boolean hasCheckedState = object.hasFlag(Flag.HAS_CHECKED_STATE); boolean hasToggledState = object.hasFlag(Flag.HAS_TOGGLED_STATE); assert !(hasCheckedState && hasToggledState); result.setCheckable(hasCheckedState || hasToggledState); if (hasCheckedState) { result.setChecked(object.hasFlag(Flag.IS_CHECKED)); if (object.hasFlag(Flag.IS_IN_MUTUALLY_EXCLUSIVE_GROUP)) result.setClassName("android.widget.RadioButton"); else result.setClassName("android.widget.CheckBox"); } else if (hasToggledState) { result.setChecked(object.hasFlag(Flag.IS_TOGGLED)); result.setClassName("android.widget.Switch"); } result.setSelected(object.hasFlag(Flag.IS_SELECTED)); result.setText(object.getValueLabelHint()); // Accessibility Focus if (mA11yFocusedObject != null && mA11yFocusedObject.id == virtualViewId) { result.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS); } else { result.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS); } // Actions on the local context menu if (Build.VERSION.SDK_INT >= 21) { if (object.customAccessibilityActions != null) { for (CustomAccessibilityAction action : object.customAccessibilityActions) { result.addAction(new AccessibilityNodeInfo.AccessibilityAction( action.resourceId, action.label)); } } } if (object.childrenInTraversalOrder != null) { for (SemanticsObject child : object.childrenInTraversalOrder) { if (!child.hasFlag(Flag.IS_HIDDEN)) { result.addChild(mOwner, child.id); } } } return result; } @Override public boolean performAction(int virtualViewId, int action, Bundle arguments) { SemanticsObject object = mObjects.get(virtualViewId); if (object == null) { return false; } switch (action) { case AccessibilityNodeInfo.ACTION_CLICK: { // Note: TalkBack prior to Oreo doesn't use this handler and instead simulates a // click event at the center of the SemanticsNode. Other a11y services might go // through this handler though. mOwner.dispatchSemanticsAction(virtualViewId, Action.TAP); return true; } case AccessibilityNodeInfo.ACTION_LONG_CLICK: { // Note: TalkBack doesn't use this handler and instead simulates a long click event // at the center of the SemanticsNode. Other a11y services might go through this // handler though. mOwner.dispatchSemanticsAction(virtualViewId, Action.LONG_PRESS); return true; } case AccessibilityNodeInfo.ACTION_SCROLL_FORWARD: { if (object.hasAction(Action.SCROLL_UP)) { mOwner.dispatchSemanticsAction(virtualViewId, Action.SCROLL_UP); } else if (object.hasAction(Action.SCROLL_LEFT)) { // TODO(ianh): bidi support using textDirection mOwner.dispatchSemanticsAction(virtualViewId, Action.SCROLL_LEFT); } else if (object.hasAction(Action.INCREASE)) { object.value = object.increasedValue; // Event causes Android to read out the updated value. sendAccessibilityEvent(virtualViewId, AccessibilityEvent.TYPE_VIEW_SELECTED); mOwner.dispatchSemanticsAction(virtualViewId, Action.INCREASE); } else { return false; } return true; } case AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD: { if (object.hasAction(Action.SCROLL_DOWN)) { mOwner.dispatchSemanticsAction(virtualViewId, Action.SCROLL_DOWN); } else if (object.hasAction(Action.SCROLL_RIGHT)) { // TODO(ianh): bidi support using textDirection mOwner.dispatchSemanticsAction(virtualViewId, Action.SCROLL_RIGHT); } else if (object.hasAction(Action.DECREASE)) { object.value = object.decreasedValue; // Event causes Android to read out the updated value. sendAccessibilityEvent(virtualViewId, AccessibilityEvent.TYPE_VIEW_SELECTED); mOwner.dispatchSemanticsAction(virtualViewId, Action.DECREASE); } else { return false; } return true; } case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: { return performCursorMoveAction(object, virtualViewId, arguments, false); } case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: { return performCursorMoveAction(object, virtualViewId, arguments, true); } case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: { mOwner.dispatchSemanticsAction(virtualViewId, Action.DID_LOSE_ACCESSIBILITY_FOCUS); sendAccessibilityEvent( virtualViewId, AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); mA11yFocusedObject = null; return true; } case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: { mOwner.dispatchSemanticsAction(virtualViewId, Action.DID_GAIN_ACCESSIBILITY_FOCUS); sendAccessibilityEvent( virtualViewId, AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED); if (mA11yFocusedObject == null) { // When Android focuses a node, it doesn't invalidate the view. // (It does when it sends ACTION_CLEAR_ACCESSIBILITY_FOCUS, so // we only have to worry about this when the focused node is null.) mOwner.invalidate(); } mA11yFocusedObject = object; if (object.hasAction(Action.INCREASE) || object.hasAction(Action.DECREASE)) { // SeekBars only announce themselves after this event. sendAccessibilityEvent(virtualViewId, AccessibilityEvent.TYPE_VIEW_SELECTED); } return true; } case ACTION_SHOW_ON_SCREEN: { mOwner.dispatchSemanticsAction(virtualViewId, Action.SHOW_ON_SCREEN); return true; } case AccessibilityNodeInfo.ACTION_SET_SELECTION: { final Map<String, Integer> selection = new HashMap<String, Integer>(); final boolean hasSelection = arguments != null && arguments.containsKey( AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT) && arguments.containsKey( AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT); if (hasSelection) { selection.put("base", arguments.getInt( AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT)); selection.put("extent", arguments.getInt( AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT)); } else { // Clear the selection selection.put("base", object.textSelectionExtent); selection.put("extent", object.textSelectionExtent); } mOwner.dispatchSemanticsAction(virtualViewId, Action.SET_SELECTION, selection); return true; } case AccessibilityNodeInfo.ACTION_COPY: { mOwner.dispatchSemanticsAction(virtualViewId, Action.COPY); return true; } case AccessibilityNodeInfo.ACTION_CUT: { mOwner.dispatchSemanticsAction(virtualViewId, Action.CUT); return true; } case AccessibilityNodeInfo.ACTION_PASTE: { mOwner.dispatchSemanticsAction(virtualViewId, Action.PASTE); return true; } case AccessibilityNodeInfo.ACTION_DISMISS: { mOwner.dispatchSemanticsAction(virtualViewId, Action.DISMISS); return true; } default: // might be a custom accessibility action. final int flutterId = action - firstResourceId; CustomAccessibilityAction contextAction = mCustomAccessibilityActions.get(flutterId); if (contextAction != null) { mOwner.dispatchSemanticsAction( virtualViewId, Action.CUSTOM_ACTION, contextAction.id); return true; } } return false; } boolean performCursorMoveAction( SemanticsObject object, int virtualViewId, Bundle arguments, boolean forward) { final int granularity = arguments.getInt(AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); final boolean extendSelection = arguments.getBoolean( AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); switch (granularity) { case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: { if (forward && object.hasAction(Action.MOVE_CURSOR_FORWARD_BY_CHARACTER)) { mOwner.dispatchSemanticsAction(virtualViewId, Action.MOVE_CURSOR_FORWARD_BY_CHARACTER, extendSelection); return true; } if (!forward && object.hasAction(Action.MOVE_CURSOR_BACKWARD_BY_CHARACTER)) { mOwner.dispatchSemanticsAction(virtualViewId, Action.MOVE_CURSOR_BACKWARD_BY_CHARACTER, extendSelection); return true; } break; } case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: if (forward && object.hasAction(Action.MOVE_CURSOR_FORWARD_BY_WORD)) { mOwner.dispatchSemanticsAction(virtualViewId, Action.MOVE_CURSOR_FORWARD_BY_WORD, extendSelection); return true; } if (!forward && object.hasAction(Action.MOVE_CURSOR_BACKWARD_BY_WORD)) { mOwner.dispatchSemanticsAction(virtualViewId, Action.MOVE_CURSOR_BACKWARD_BY_WORD, extendSelection); return true; } break; } return false; } // TODO(ianh): implement findAccessibilityNodeInfosByText() @Override public AccessibilityNodeInfo findFocus(int focus) { switch (focus) { case AccessibilityNodeInfo.FOCUS_INPUT: { if (mInputFocusedObject != null) return createAccessibilityNodeInfo(mInputFocusedObject.id); } // Fall through to check FOCUS_ACCESSIBILITY case AccessibilityNodeInfo.FOCUS_ACCESSIBILITY: { if (mA11yFocusedObject != null) return createAccessibilityNodeInfo(mA11yFocusedObject.id); } } return null; } private SemanticsObject getRootObject() { assert mObjects.containsKey(0); return mObjects.get(0); } private SemanticsObject getOrCreateObject(int id) { SemanticsObject object = mObjects.get(id); if (object == null) { object = new SemanticsObject(); object.id = id; mObjects.put(id, object); } return object; } private CustomAccessibilityAction getOrCreateAction(int id) { CustomAccessibilityAction action = mCustomAccessibilityActions.get(id); if (action == null) { action = new CustomAccessibilityAction(); action.id = id; action.resourceId = id + firstResourceId; mCustomAccessibilityActions.put(id, action); } return action; } void handleTouchExplorationExit() { if (mHoveredObject != null) { sendAccessibilityEvent(mHoveredObject.id, AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); mHoveredObject = null; } } void handleTouchExploration(float x, float y) { if (mObjects.isEmpty()) { return; } SemanticsObject newObject = getRootObject().hitTest(new float[] {x, y, 0, 1}); if (newObject != mHoveredObject) { // sending ENTER before EXIT is how Android wants it if (newObject != null) { sendAccessibilityEvent(newObject.id, AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); } if (mHoveredObject != null) { sendAccessibilityEvent(mHoveredObject.id, AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); } mHoveredObject = newObject; } } void updateCustomAccessibilityActions(ByteBuffer buffer, String[] strings) { ArrayList<CustomAccessibilityAction> updatedActions = new ArrayList<CustomAccessibilityAction>(); while (buffer.hasRemaining()) { int id = buffer.getInt(); CustomAccessibilityAction action = getOrCreateAction(id); action.overrideId = buffer.getInt(); int stringIndex = buffer.getInt(); action.label = stringIndex == -1 ? null : strings[stringIndex]; stringIndex = buffer.getInt(); action.hint = stringIndex == -1 ? null : strings[stringIndex]; } } void updateSemantics(ByteBuffer buffer, String[] strings) { ArrayList<SemanticsObject> updated = new ArrayList<SemanticsObject>(); while (buffer.hasRemaining()) { int id = buffer.getInt(); SemanticsObject object = getOrCreateObject(id); object.updateWith(buffer, strings); if (object.hasFlag(Flag.IS_HIDDEN)) { continue; } if (object.hasFlag(Flag.IS_FOCUSED)) { mInputFocusedObject = object; } if (object.hadPreviousConfig) { updated.add(object); } } Set<SemanticsObject> visitedObjects = new HashSet<SemanticsObject>(); SemanticsObject rootObject = getRootObject(); List<SemanticsObject> newRoutes = new ArrayList<>(); if (rootObject != null) { final float[] identity = new float[16]; Matrix.setIdentityM(identity, 0); rootObject.updateRecursively(identity, visitedObjects, false); rootObject.collectRoutes(newRoutes); } // Dispatch a TYPE_WINDOW_STATE_CHANGED event if the most recent route id changed from the // previously cached route id. SemanticsObject lastAdded = null; for (SemanticsObject semanticsObject : newRoutes) { if (!previousRoutes.contains(semanticsObject.id)) { lastAdded = semanticsObject; } } if (lastAdded == null && newRoutes.size() > 0) { lastAdded = newRoutes.get(newRoutes.size() - 1); } if (lastAdded != null && lastAdded.id != previousRouteId) { previousRouteId = lastAdded.id; createWindowChangeEvent(lastAdded); } previousRoutes.clear(); for (SemanticsObject semanticsObject : newRoutes) { previousRoutes.add(semanticsObject.id); } Iterator<Map.Entry<Integer, SemanticsObject>> it = mObjects.entrySet().iterator(); while (it.hasNext()) { Map.Entry<Integer, SemanticsObject> entry = it.next(); SemanticsObject object = entry.getValue(); if (!visitedObjects.contains(object)) { willRemoveSemanticsObject(object); it.remove(); } } // TODO(goderbauer): Send this event only once (!) for changed subtrees, // see https://github.com/flutter/flutter/issues/14534 sendAccessibilityEvent(0, AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); for (SemanticsObject object : updated) { if (object.didScroll()) { AccessibilityEvent event = obtainAccessibilityEvent(object.id, AccessibilityEvent.TYPE_VIEW_SCROLLED); // Android doesn't support unbound scrolling. So we pretend there is a large // bound (SCROLL_EXTENT_FOR_INFINITY), which you can never reach. float position = object.scrollPosition; float max = object.scrollExtentMax; if (Float.isInfinite(object.scrollExtentMax)) { max = SCROLL_EXTENT_FOR_INFINITY; if (position > SCROLL_POSITION_CAP_FOR_INFINITY) { position = SCROLL_POSITION_CAP_FOR_INFINITY; } } if (Float.isInfinite(object.scrollExtentMin)) { max += SCROLL_EXTENT_FOR_INFINITY; if (position < -SCROLL_POSITION_CAP_FOR_INFINITY) { position = -SCROLL_POSITION_CAP_FOR_INFINITY; } position += SCROLL_EXTENT_FOR_INFINITY; } else { max -= object.scrollExtentMin; position -= object.scrollExtentMin; } if (object.hadAction(Action.SCROLL_UP) || object.hadAction(Action.SCROLL_DOWN)) { event.setScrollY((int) position); event.setMaxScrollY((int) max); } else if (object.hadAction(Action.SCROLL_LEFT) || object.hadAction(Action.SCROLL_RIGHT)) { event.setScrollX((int) position); event.setMaxScrollX((int) max); } sendAccessibilityEvent(event); } if (object.hasFlag(Flag.IS_LIVE_REGION) && !object.hadFlag(Flag.IS_LIVE_REGION)) { sendAccessibilityEvent(object.id, AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); } else if (object.hasFlag(Flag.IS_TEXT_FIELD) && object.didChangeLabel() && mInputFocusedObject != null && mInputFocusedObject.id == object.id) { // Text fields should announce when their label changes while focused. We use a live // region tag to do so, and this event triggers that update. sendAccessibilityEvent(object.id, AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); } if (mA11yFocusedObject != null && mA11yFocusedObject.id == object.id && !object.hadFlag(Flag.IS_SELECTED) && object.hasFlag(Flag.IS_SELECTED)) { AccessibilityEvent event = obtainAccessibilityEvent(object.id, AccessibilityEvent.TYPE_VIEW_SELECTED); event.getText().add(object.label); sendAccessibilityEvent(event); } if (mInputFocusedObject != null && mInputFocusedObject.id == object.id && object.hadFlag(Flag.IS_TEXT_FIELD) && object.hasFlag(Flag.IS_TEXT_FIELD)) { String oldValue = object.previousValue != null ? object.previousValue : ""; String newValue = object.value != null ? object.value : ""; AccessibilityEvent event = createTextChangedEvent(object.id, oldValue, newValue); if (event != null) { sendAccessibilityEvent(event); } if (object.previousTextSelectionBase != object.textSelectionBase || object.previousTextSelectionExtent != object.textSelectionExtent) { AccessibilityEvent selectionEvent = obtainAccessibilityEvent( object.id, AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED); selectionEvent.getText().add(newValue); selectionEvent.setFromIndex(object.textSelectionBase); selectionEvent.setToIndex(object.textSelectionExtent); selectionEvent.setItemCount(newValue.length()); sendAccessibilityEvent(selectionEvent); } } } } private AccessibilityEvent createTextChangedEvent(int id, String oldValue, String newValue) { AccessibilityEvent e = obtainAccessibilityEvent(id, AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED); e.setBeforeText(oldValue); e.getText().add(newValue); int i; for (i = 0; i < oldValue.length() && i < newValue.length(); ++i) { if (oldValue.charAt(i) != newValue.charAt(i)) { break; } } if (i >= oldValue.length() && i >= newValue.length()) { return null; // Text did not change } int firstDifference = i; e.setFromIndex(firstDifference); int oldIndex = oldValue.length() - 1; int newIndex = newValue.length() - 1; while (oldIndex >= firstDifference && newIndex >= firstDifference) { if (oldValue.charAt(oldIndex) != newValue.charAt(newIndex)) { break; } --oldIndex; --newIndex; } e.setRemovedCount(oldIndex - firstDifference + 1); e.setAddedCount(newIndex - firstDifference + 1); return e; } private AccessibilityEvent obtainAccessibilityEvent(int virtualViewId, int eventType) { assert virtualViewId != ROOT_NODE_ID; AccessibilityEvent event = AccessibilityEvent.obtain(eventType); event.setPackageName(mOwner.getContext().getPackageName()); event.setSource(mOwner, virtualViewId); return event; } private void sendAccessibilityEvent(int virtualViewId, int eventType) { if (!mAccessibilityEnabled) { return; } if (virtualViewId == ROOT_NODE_ID) { mOwner.sendAccessibilityEvent(eventType); } else { sendAccessibilityEvent(obtainAccessibilityEvent(virtualViewId, eventType)); } } private void sendAccessibilityEvent(AccessibilityEvent event) { if (!mAccessibilityEnabled) { return; } mOwner.getParent().requestSendAccessibilityEvent(mOwner, event); } // Message Handler for [mFlutterAccessibilityChannel]. public void onMessage(Object message, BasicMessageChannel.Reply<Object> reply) { @SuppressWarnings("unchecked") final HashMap<String, Object> annotatedEvent = (HashMap<String, Object>) message; final String type = (String) annotatedEvent.get("type"); @SuppressWarnings("unchecked") final HashMap<String, Object> data = (HashMap<String, Object>) annotatedEvent.get("data"); switch (type) { case "announce": mOwner.announceForAccessibility((String) data.get("message")); break; case "longPress": { Integer nodeId = (Integer) annotatedEvent.get("nodeId"); if (nodeId == null) { return; } sendAccessibilityEvent(nodeId, AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); break; } case "tap": { Integer nodeId = (Integer) annotatedEvent.get("nodeId"); if (nodeId == null) { return; } sendAccessibilityEvent(nodeId, AccessibilityEvent.TYPE_VIEW_CLICKED); break; } case "tooltip": { AccessibilityEvent e = obtainAccessibilityEvent( ROOT_NODE_ID, AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); e.getText().add((String) data.get("message")); sendAccessibilityEvent(e); } // Requires that the node id provided corresponds to a live region, or TalkBack will // ignore the event. The event will cause talkback to read out the new label even // if node is not focused. case "updateLiveRegion": { Integer nodeId = (Integer) annotatedEvent.get("nodeId"); if (nodeId == null) { return; } sendAccessibilityEvent(nodeId, AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); } } } private void createWindowChangeEvent(SemanticsObject route) { AccessibilityEvent e = obtainAccessibilityEvent(route.id, AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); String routeName = route.getRouteName(); e.getText().add(routeName); sendAccessibilityEvent(e); } private void willRemoveSemanticsObject(SemanticsObject object) { assert mObjects.containsKey(object.id); assert mObjects.get(object.id) == object; object.parent = null; if (mA11yFocusedObject == object) { sendAccessibilityEvent(mA11yFocusedObject.id, AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); mA11yFocusedObject = null; } if (mInputFocusedObject == object) { mInputFocusedObject = null; } if (mHoveredObject == object) { mHoveredObject = null; } } void reset() { mObjects.clear(); if (mA11yFocusedObject != null) sendAccessibilityEvent(mA11yFocusedObject.id, AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); mA11yFocusedObject = null; mHoveredObject = null; sendAccessibilityEvent(0, AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); } private enum TextDirection { UNKNOWN, LTR, RTL; public static TextDirection fromInt(int value) { switch (value) { case 1: return RTL; case 2: return LTR; } return UNKNOWN; } } private class CustomAccessibilityAction { CustomAccessibilityAction() {} /// Resource id is the id of the custom action plus a minimum value so that the identifier /// does not collide with existing Android accessibility actions. int resourceId = -1; int id = -1; int overrideId = -1; /// The label is the user presented value which is displayed in the local context menu. String label; /// The hint is the text used in overriden standard actions. String hint; boolean isStandardAction() { return overrideId != -1; } } /// Value is derived from ACTION_TYPE_MASK in AccessibilityNodeInfo.java static int firstResourceId = 267386881; private class SemanticsObject { SemanticsObject() {} int id = -1; int flags; int actions; int textSelectionBase; int textSelectionExtent; float scrollPosition; float scrollExtentMax; float scrollExtentMin; String label; String value; String increasedValue; String decreasedValue; String hint; TextDirection textDirection; boolean hadPreviousConfig = false; int previousFlags; int previousActions; int previousTextSelectionBase; int previousTextSelectionExtent; float previousScrollPosition; float previousScrollExtentMax; float previousScrollExtentMin; String previousValue; String previousLabel; private float left; private float top; private float right; private float bottom; private float[] transform; SemanticsObject parent; List<SemanticsObject> childrenInTraversalOrder; List<SemanticsObject> childrenInHitTestOrder; List<CustomAccessibilityAction> customAccessibilityActions; CustomAccessibilityAction onTapOverride; CustomAccessibilityAction onLongPressOverride; private boolean inverseTransformDirty = true; private float[] inverseTransform; private boolean globalGeometryDirty = true; private float[] globalTransform; private Rect globalRect; boolean hasAction(Action action) { return (actions & action.value) != 0; } boolean hadAction(Action action) { return (previousActions & action.value) != 0; } boolean hasFlag(Flag flag) { return (flags & flag.value) != 0; } boolean hadFlag(Flag flag) { assert hadPreviousConfig; return (previousFlags & flag.value) != 0; } boolean didScroll() { return !Float.isNaN(scrollPosition) && !Float.isNaN(previousScrollPosition) && previousScrollPosition != scrollPosition; } boolean didChangeLabel() { if (label == null && previousLabel == null) { return false; } return label == null || previousLabel == null || !label.equals(previousLabel); } void log(String indent, boolean recursive) { Log.i(TAG, indent + "SemanticsObject id=" + id + " label=" + label + " actions=" + actions + " flags=" + flags + "\n" + indent + " +-- textDirection=" + textDirection + "\n" + indent + " +-- rect.ltrb=(" + left + ", " + top + ", " + right + ", " + bottom + ")\n" + indent + " +-- transform=" + Arrays.toString(transform) + "\n"); if (childrenInTraversalOrder != null && recursive) { String childIndent = indent + " "; for (SemanticsObject child : childrenInTraversalOrder) { child.log(childIndent, recursive); } } } void updateWith(ByteBuffer buffer, String[] strings) { hadPreviousConfig = true; previousValue = value; previousLabel = label; previousFlags = flags; previousActions = actions; previousTextSelectionBase = textSelectionBase; previousTextSelectionExtent = textSelectionExtent; previousScrollPosition = scrollPosition; previousScrollExtentMax = scrollExtentMax; previousScrollExtentMin = scrollExtentMin; flags = buffer.getInt(); actions = buffer.getInt(); textSelectionBase = buffer.getInt(); textSelectionExtent = buffer.getInt(); scrollPosition = buffer.getFloat(); scrollExtentMax = buffer.getFloat(); scrollExtentMin = buffer.getFloat(); int stringIndex = buffer.getInt(); label = stringIndex == -1 ? null : strings[stringIndex]; stringIndex = buffer.getInt(); value = stringIndex == -1 ? null : strings[stringIndex]; stringIndex = buffer.getInt(); increasedValue = stringIndex == -1 ? null : strings[stringIndex]; stringIndex = buffer.getInt(); decreasedValue = stringIndex == -1 ? null : strings[stringIndex]; stringIndex = buffer.getInt(); hint = stringIndex == -1 ? null : strings[stringIndex]; textDirection = TextDirection.fromInt(buffer.getInt()); left = buffer.getFloat(); top = buffer.getFloat(); right = buffer.getFloat(); bottom = buffer.getFloat(); if (transform == null) { transform = new float[16]; } for (int i = 0; i < 16; ++i) { transform[i] = buffer.getFloat(); } inverseTransformDirty = true; globalGeometryDirty = true; final int childCount = buffer.getInt(); if (childCount == 0) { childrenInTraversalOrder = null; childrenInHitTestOrder = null; } else { if (childrenInTraversalOrder == null) childrenInTraversalOrder = new ArrayList<SemanticsObject>(childCount); else childrenInTraversalOrder.clear(); for (int i = 0; i < childCount; ++i) { SemanticsObject child = getOrCreateObject(buffer.getInt()); child.parent = this; childrenInTraversalOrder.add(child); } if (childrenInHitTestOrder == null) childrenInHitTestOrder = new ArrayList<SemanticsObject>(childCount); else childrenInHitTestOrder.clear(); for (int i = 0; i < childCount; ++i) { SemanticsObject child = getOrCreateObject(buffer.getInt()); child.parent = this; childrenInHitTestOrder.add(child); } } final int actionCount = buffer.getInt(); if (actionCount == 0) { customAccessibilityActions = null; } else { if (customAccessibilityActions == null) customAccessibilityActions = new ArrayList<CustomAccessibilityAction>(actionCount); else customAccessibilityActions.clear(); for (int i = 0; i < actionCount; i++) { CustomAccessibilityAction action = getOrCreateAction(buffer.getInt()); if (action.overrideId == Action.TAP.value) { onTapOverride = action; } else if (action.overrideId == Action.LONG_PRESS.value) { onLongPressOverride = action; } else { // If we recieve a different overrideId it means that we were passed // a standard action to override that we don't yet support. assert action.overrideId == -1; customAccessibilityActions.add(action); } customAccessibilityActions.add(action); } } } private void ensureInverseTransform() { if (!inverseTransformDirty) { return; } inverseTransformDirty = false; if (inverseTransform == null) { inverseTransform = new float[16]; } if (!Matrix.invertM(inverseTransform, 0, transform, 0)) { Arrays.fill(inverseTransform, 0); } } Rect getGlobalRect() { assert !globalGeometryDirty; return globalRect; } SemanticsObject hitTest(float[] point) { final float w = point[3]; final float x = point[0] / w; final float y = point[1] / w; if (x < left || x >= right || y < top || y >= bottom) return null; if (childrenInHitTestOrder != null) { final float[] transformedPoint = new float[4]; for (int i = 0; i < childrenInHitTestOrder.size(); i += 1) { final SemanticsObject child = childrenInHitTestOrder.get(i); if (child.hasFlag(Flag.IS_HIDDEN)) { continue; } child.ensureInverseTransform(); Matrix.multiplyMV(transformedPoint, 0, child.inverseTransform, 0, point, 0); final SemanticsObject result = child.hitTest(transformedPoint); if (result != null) { return result; } } } return this; } // TODO(goderbauer): This should be decided by the framework once we have more information // about focusability there. boolean isFocusable() { // We enforce in the framework that no other useful semantics are merged with these // nodes. if (hasFlag(Flag.SCOPES_ROUTE)) { return false; } int scrollableActions = Action.SCROLL_RIGHT.value | Action.SCROLL_LEFT.value | Action.SCROLL_UP.value | Action.SCROLL_DOWN.value; return (actions & ~scrollableActions) != 0 || flags != 0 || (label != null && !label.isEmpty()) || (value != null && !value.isEmpty()) || (hint != null && !hint.isEmpty()); } void collectRoutes(List<SemanticsObject> edges) { if (hasFlag(Flag.SCOPES_ROUTE)) { edges.add(this); } if (childrenInTraversalOrder != null) { for (int i = 0; i < childrenInTraversalOrder.size(); ++i) { childrenInTraversalOrder.get(i).collectRoutes(edges); } } } String getRouteName() { // Returns the first non-null and non-empty semantic label of a child // with an NamesRoute flag. Otherwise returns null. if (hasFlag(Flag.NAMES_ROUTE)) { if (label != null && !label.isEmpty()) { return label; } } if (childrenInTraversalOrder != null) { for (int i = 0; i < childrenInTraversalOrder.size(); ++i) { String newName = childrenInTraversalOrder.get(i).getRouteName(); if (newName != null && !newName.isEmpty()) { return newName; } } } return null; } void updateRecursively(float[] ancestorTransform, Set<SemanticsObject> visitedObjects, boolean forceUpdate) { visitedObjects.add(this); if (globalGeometryDirty) { forceUpdate = true; } if (forceUpdate) { if (globalTransform == null) { globalTransform = new float[16]; } Matrix.multiplyMM(globalTransform, 0, ancestorTransform, 0, transform, 0); final float[] sample = new float[4]; sample[2] = 0; sample[3] = 1; final float[] point1 = new float[4]; final float[] point2 = new float[4]; final float[] point3 = new float[4]; final float[] point4 = new float[4]; sample[0] = left; sample[1] = top; transformPoint(point1, globalTransform, sample); sample[0] = right; sample[1] = top; transformPoint(point2, globalTransform, sample); sample[0] = right; sample[1] = bottom; transformPoint(point3, globalTransform, sample); sample[0] = left; sample[1] = bottom; transformPoint(point4, globalTransform, sample); if (globalRect == null) globalRect = new Rect(); globalRect.set(Math.round(min(point1[0], point2[0], point3[0], point4[0])), Math.round(min(point1[1], point2[1], point3[1], point4[1])), Math.round(max(point1[0], point2[0], point3[0], point4[0])), Math.round(max(point1[1], point2[1], point3[1], point4[1]))); globalGeometryDirty = false; } assert globalTransform != null; assert globalRect != null; if (childrenInTraversalOrder != null) { for (int i = 0; i < childrenInTraversalOrder.size(); ++i) { childrenInTraversalOrder.get(i).updateRecursively( globalTransform, visitedObjects, forceUpdate); } } } private void transformPoint(float[] result, float[] transform, float[] point) { Matrix.multiplyMV(result, 0, transform, 0, point, 0); final float w = result[3]; result[0] /= w; result[1] /= w; result[2] /= w; result[3] = 0; } private float min(float a, float b, float c, float d) { return Math.min(a, Math.min(b, Math.min(c, d))); } private float max(float a, float b, float c, float d) { return Math.max(a, Math.max(b, Math.max(c, d))); } private String getValueLabelHint() { StringBuilder sb = new StringBuilder(); String[] array = {value, label, hint}; for (String word : array) { if (word != null && word.length() > 0) { if (sb.length() > 0) sb.append(", "); sb.append(word); } } return sb.length() > 0 ? sb.toString() : null; } } }
Apply translation to accessibility tree when in landscape (#5950)
shell/platform/android/io/flutter/view/AccessibilityBridge.java
Apply translation to accessibility tree when in landscape (#5950)
<ide><path>hell/platform/android/io/flutter/view/AccessibilityBridge.java <ide> <ide> package io.flutter.view; <ide> <add>import android.app.Activity; <add>import android.content.Context; <ide> import android.graphics.Rect; <ide> import android.opengl.Matrix; <ide> import android.os.Build; <ide> private SemanticsObject mHoveredObject; <ide> private int previousRouteId = ROOT_NODE_ID; <ide> private List<Integer> previousRoutes; <add> private final View mDecorView; <add> private Integer mLastLeftFrameInset = 0; <ide> <ide> private final BasicMessageChannel<Object> mFlutterAccessibilityChannel; <ide> <ide> previousRoutes = new ArrayList<>(); <ide> mFlutterAccessibilityChannel = new BasicMessageChannel<>( <ide> owner, "flutter/accessibility", StandardMessageCodec.INSTANCE); <add> mDecorView = ((Activity) owner.getContext()).getWindow().getDecorView(); <ide> } <ide> <ide> void setAccessibilityEnabled(boolean accessibilityEnabled) { <ide> if (rootObject != null) { <ide> final float[] identity = new float[16]; <ide> Matrix.setIdentityM(identity, 0); <add> // in android devices above AP 23, the system nav bar can be placed on the left side <add> // of the screen in landscape mode. We must handle the translation ourselves for the <add> // a11y nodes. <add> if (Build.VERSION.SDK_INT >= 23) { <add> Rect visibleFrame = new Rect(); <add> mDecorView.getWindowVisibleDisplayFrame(visibleFrame); <add> if (!mLastLeftFrameInset.equals(visibleFrame.left)) { <add> rootObject.globalGeometryDirty = true; <add> rootObject.inverseTransformDirty = true; <add> } <add> mLastLeftFrameInset = visibleFrame.left; <add> Matrix.translateM(identity, 0, visibleFrame.left, 0, 0); <add> } <ide> rootObject.updateRecursively(identity, visitedObjects, false); <ide> rootObject.collectRoutes(newRoutes); <ide> }
Java
apache-2.0
96ee02700dcfcdea39913d4e6058fdd40c4494e3
0
yenki/overcast,reta/overcast,sarxos/overcast,xebialabs/overcast,yenki/overcast,reta/overcast,sarxos/overcast
/* License added by: GRADLE-LICENSE-PLUGIN * * Copyright 2008-2012 XebiaLabs * * 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.xebialabs.overcast.host; import java.text.MessageFormat; import java.util.Date; import java.util.List; import java.util.UUID; import org.jdom2.Document; import org.libvirt.Connect; import org.libvirt.Domain; import org.libvirt.LibvirtException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Preconditions; import com.xebialabs.overcast.command.Command; import com.xebialabs.overcast.command.CommandProcessor; import com.xebialabs.overcast.command.NonZeroCodeException; import com.xebialabs.overcast.support.libvirt.DomainWrapper; import com.xebialabs.overcast.support.libvirt.IpLookupStrategy; import com.xebialabs.overcast.support.libvirt.LibvirtRuntimeException; import com.xebialabs.overcast.support.libvirt.LibvirtUtil; import com.xebialabs.overcast.support.libvirt.LoggingOutputHandler; import com.xebialabs.overcast.support.libvirt.Metadata; import com.xebialabs.overthere.CmdLine; import com.xebialabs.overthere.OverthereConnection; import com.xebialabs.overthere.OverthereExecutionOutputHandler; import com.xebialabs.overthere.util.CapturingOverthereExecutionOutputHandler; import static com.xebialabs.overcast.OverthereUtil.overthereConnectionFromURI; import static com.xebialabs.overthere.util.CapturingOverthereExecutionOutputHandler.capturingHandler; import static com.xebialabs.overthere.util.MultipleOverthereExecutionOutputHandler.multiHandler; public class CachedLibvirtHost extends LibvirtHost { private static final Logger logger = LoggerFactory.getLogger(CachedLibvirtHost.class); public static final String DEFAULT_STALE_HOST_GRACE_TIME = "" + 1 * 60 * 60 * 1000; public static final String PROVISION_CMD = ".provision.cmd"; public static final String PROVISION_URL = ".provision.url"; public static final String CACHE_EXPIRATION_CMD = ".provision.expirationCmd"; private final String provisionCmd; private final String provisionUrl; private final String cacheExpirationCmd; private CommandProcessor cmdProcessor; private DomainWrapper provisionedClone; private String provisionedCloneIp; CachedLibvirtHost(String hostLabel, Connect libvirt, String baseDomainName, IpLookupStrategy ipLookupStrategy, String networkName, String provisionUrl, String provisionCmd, String cacheExpirationCmd, CommandProcessor cmdProcessor, int startTimeout, int bootDelay) { super(libvirt, baseDomainName, ipLookupStrategy, networkName, startTimeout, bootDelay); this.provisionUrl = checkArgument(provisionUrl, "provisionUrl"); this.provisionCmd = checkArgument(provisionCmd, "provisionCmd"); this.cacheExpirationCmd = checkArgument(cacheExpirationCmd, "cacheExpirationCmd"); this.cmdProcessor = cmdProcessor; } private String checkArgument(String arg, String argName) { Preconditions.checkArgument(arg != null && !arg.isEmpty(), "%s cannot be null or empty", argName); return arg; } @Override public void setup() { DomainWrapper cachedDomain = findFirstCachedDomain(); if (cachedDomain == null) { logger.info("No cached domain creating provisioned clone"); super.setup(); String ip = super.getHostName(); try { provisionHost(ip); } catch (RuntimeException e) { logger.error("Failed to provision clone from '{}' cleaning up", this.getBaseDomainName()); super.getClone().destroyWithDisks(); throw e; } DomainWrapper clone = super.getClone(); clone.acpiShutdown(); clone.updateMetadata(getBaseDomainName(), provisionCmd, getExpirationTag(), new Date()); provisionedClone = createProvisionedClone(); } else { String baseName = super.getBaseDomainName(); String cloneName = baseName + "-" + UUID.randomUUID().toString(); logger.info("Creating provisioned clone '{}' from base domain '{}'", cloneName, cachedDomain.getName()); provisionedClone = cachedDomain.cloneWithBackingStore(cloneName); } provisionedCloneIp = waitUntilRunningAndGetIP(provisionedClone); } protected DomainWrapper findFirstCachedDomain() { final String baseDomainName = super.getBaseDomainName(); final String checkSum = getExpirationTag(); logger.debug("Looking for a cached domain '{}' with checksum '{}'", baseDomainName, checkSum); try { List<Domain> domains = LibvirtUtil.getDefinedDomains(libvirt); for (Domain domain : domains) { String domainName = domain.getName(); Document doc = LibvirtUtil.loadDomainXml(domain); Metadata md = Metadata.fromXml(doc); if (md == null || !md.isProvisioned()) { continue; } logger.debug("Found domain '{}' with metadata {}", domainName, md); if (!md.getParentDomain().equals(baseDomainName)) { continue; } if (!md.getProvisionedWith().equals(provisionCmd)) { continue; } if (!md.getProvisionedChecksum().equals(checkSum)) { logger.debug("Domain '{}' is stale (checksum={})", domainName, md.getProvisionedChecksum()); deleteStaleDomain(new DomainWrapper(domain, doc)); continue; } logger.info("Found domain '{}' found for '{}'", domainName, baseDomainName); return new DomainWrapper(domain, doc); } logger.info("No cached domain found for '{}' with checksum '{}'", baseDomainName, checkSum); return null; } catch (LibvirtException e) { throw new LibvirtRuntimeException(e); } } protected void deleteStaleDomain(DomainWrapper staleDomain) throws LibvirtException { String staleDomainName = staleDomain.getName(); if (isDomainSafeToDelete(libvirt, staleDomainName)) { try { logger.info("Destroying stale domain '{}'", staleDomainName); staleDomain.destroyWithDisks(); } catch (LibvirtRuntimeException e) { // it may be that another job deleted the domain before us... logger.debug("Ignoring exception while cleaning stale domain", e); } } } protected static boolean isDomainSafeToDelete(Connect libvirt, String staleDomainName) throws LibvirtException { List<Domain> domains = LibvirtUtil.getRunningDomains(libvirt); for (Domain domain : domains) { Document doc = LibvirtUtil.loadDomainXml(domain); Metadata md = Metadata.fromXml(doc); if (md == null || md.isProvisioned()) { continue; } if (md.getParentDomain().equals(staleDomainName)) { logger.info("Not deleting stale domain '{}' still used by '{}'", staleDomainName, domain.getName()); return false; } } return true; } @Override public DomainWrapper getClone() { return provisionedClone; } @Override public String getHostName() { return provisionedCloneIp; } @Override public void teardown() { if (provisionedClone != null) { provisionedClone.destroyWithDisks(); provisionedClone = null; } } protected String getExpirationTag() { logger.info("Executing expiration command: {}", cacheExpirationCmd); try { String expirationTag = cmdProcessor.run(Command.fromString(cacheExpirationCmd)).getOutput().trim(); return expirationTag; } catch (NonZeroCodeException e) { throw new IllegalArgumentException( String.format( "Command %s returned code %s with the following errors: \n\n%s\n", e.getCommand().toString(), e.getResponse().getReturnCode(), e.getResponse().getErrors() + "\n\n" + e.getResponse().getOutput() )); } } protected DomainWrapper createProvisionedClone() { DomainWrapper base = super.getClone(); String baseName = super.getBaseDomainName(); String cloneName = baseName + "-" + UUID.randomUUID().toString(); logger.info("Creating clone '{}' from provisioned domain '{}'", cloneName, base.getName()); return base.cloneWithBackingStore(cloneName); } protected void provisionHost(String ip) { CmdLine cmdLine = new CmdLine(); String fragment = MessageFormat.format(provisionCmd, ip); cmdLine.addRaw(fragment); logger.info("Provisioning host with '{}'", cmdLine); OverthereConnection connection = null; try { String finalUrl = MessageFormat.format(provisionUrl, ip); connection = overthereConnectionFromURI(finalUrl); CapturingOverthereExecutionOutputHandler stdOutCapture = capturingHandler(); CapturingOverthereExecutionOutputHandler stdErrCapture = capturingHandler(); OverthereExecutionOutputHandler stdOutHandler = stdOutCapture; OverthereExecutionOutputHandler stdErrHandler = stdErrCapture; if (logger.isInfoEnabled()) { OverthereExecutionOutputHandler stdout = new LoggingOutputHandler(logger, "out"); stdOutHandler = multiHandler(stdOutCapture, stdout); OverthereExecutionOutputHandler stderr = new LoggingOutputHandler(logger, "err"); stdErrHandler = multiHandler(stdErrCapture, stderr); } int exitCode = connection.execute(stdOutHandler, stdErrHandler, cmdLine); if (exitCode != 0) { throw new RuntimeException(String.format("Provisioning of clone from '%s' failed with exit code %d", getBaseDomainName(), exitCode)); } // doesn't seem to work, we don't get stderr returned overthere/sshj bug? if (!stdErrCapture.getOutputLines().isEmpty()) { throw new RuntimeException(String.format("Provisioning of clone from '%s' failed with output to stderr: %s", getBaseDomainName(), stdErrCapture.getOutput())); } } finally { if (connection != null) { connection.close(); } } } }
src/main/java/com/xebialabs/overcast/host/CachedLibvirtHost.java
/* License added by: GRADLE-LICENSE-PLUGIN * * Copyright 2008-2012 XebiaLabs * * 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.xebialabs.overcast.host; import java.text.MessageFormat; import java.util.Date; import java.util.List; import java.util.UUID; import org.jdom2.Document; import org.libvirt.Connect; import org.libvirt.Domain; import org.libvirt.LibvirtException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Preconditions; import com.xebialabs.overcast.command.Command; import com.xebialabs.overcast.command.CommandProcessor; import com.xebialabs.overcast.command.NonZeroCodeException; import com.xebialabs.overcast.support.libvirt.DomainWrapper; import com.xebialabs.overcast.support.libvirt.IpLookupStrategy; import com.xebialabs.overcast.support.libvirt.LibvirtRuntimeException; import com.xebialabs.overcast.support.libvirt.LibvirtUtil; import com.xebialabs.overcast.support.libvirt.LoggingOutputHandler; import com.xebialabs.overcast.support.libvirt.Metadata; import com.xebialabs.overthere.CmdLine; import com.xebialabs.overthere.OverthereConnection; import com.xebialabs.overthere.OverthereExecutionOutputHandler; import com.xebialabs.overthere.util.CapturingOverthereExecutionOutputHandler; import static com.xebialabs.overcast.OverthereUtil.overthereConnectionFromURI; import static com.xebialabs.overthere.util.CapturingOverthereExecutionOutputHandler.capturingHandler; import static com.xebialabs.overthere.util.MultipleOverthereExecutionOutputHandler.multiHandler; public class CachedLibvirtHost extends LibvirtHost { private static final Logger logger = LoggerFactory.getLogger(CachedLibvirtHost.class); public static final String DEFAULT_STALE_HOST_GRACE_TIME = "" + 1 * 60 * 60 * 1000; public static final String PROVISION_CMD = ".provision.cmd"; public static final String PROVISION_URL = ".provision.url"; public static final String CACHE_EXPIRATION_CMD = ".provision.expirationCmd"; private final String provisionCmd; private final String provisionUrl; private final String cacheExpirationCmd; private CommandProcessor cmdProcessor; private DomainWrapper provisionedClone; private String provisionedCloneIp; CachedLibvirtHost(String hostLabel, Connect libvirt, String baseDomainName, IpLookupStrategy ipLookupStrategy, String networkName, String provisionUrl, String provisionCmd, String cacheExpirationCmd, CommandProcessor cmdProcessor, int startTimeout, int bootDelay) { super(libvirt, baseDomainName, ipLookupStrategy, networkName, startTimeout, bootDelay); this.provisionUrl = checkArgument(provisionUrl, "provisionUrl"); this.provisionCmd = checkArgument(provisionCmd, "provisionCmd"); this.cacheExpirationCmd = checkArgument(cacheExpirationCmd, "cacheExpirationCmd"); this.cmdProcessor = cmdProcessor; } private String checkArgument(String arg, String argName) { Preconditions.checkArgument(arg != null && !arg.isEmpty(), "%s cannot be null or empty", argName); return arg; } @Override public void setup() { DomainWrapper cachedDomain = findFirstCachedDomain(); if (cachedDomain == null) { logger.info("No cached domain creating provisioned clone"); super.setup(); String ip = super.getHostName(); try { provisionHost(ip); } catch (RuntimeException e) { logger.error("Failed to provision clone from '{}' cleaning up", this.getBaseDomainName()); // super.getClone().destroyWithDisks(); throw e; } DomainWrapper clone = super.getClone(); clone.acpiShutdown(); clone.updateMetadata(getBaseDomainName(), provisionCmd, getExpirationTag(), new Date()); provisionedClone = createProvisionedClone(); } else { String baseName = super.getBaseDomainName(); String cloneName = baseName + "-" + UUID.randomUUID().toString(); logger.info("Creating provisioned clone '{}' from base domain '{}'", cloneName, cachedDomain.getName()); provisionedClone = cachedDomain.cloneWithBackingStore(cloneName); } provisionedCloneIp = waitUntilRunningAndGetIP(provisionedClone); } protected DomainWrapper findFirstCachedDomain() { final String baseDomainName = super.getBaseDomainName(); final String checkSum = getExpirationTag(); logger.debug("Looking for a cached domain '{}' with checksum '{}'", baseDomainName, checkSum); try { List<Domain> domains = LibvirtUtil.getDefinedDomains(libvirt); for (Domain domain : domains) { String domainName = domain.getName(); Document doc = LibvirtUtil.loadDomainXml(domain); Metadata md = Metadata.fromXml(doc); if (md == null || !md.isProvisioned()) { continue; } logger.debug("Found domain '{}' with metadata {}", domainName, md); if (!md.getParentDomain().equals(baseDomainName)) { continue; } if (!md.getProvisionedWith().equals(provisionCmd)) { continue; } if (!md.getProvisionedChecksum().equals(checkSum)) { logger.debug("Domain '{}' is stale (checksum={})", domainName, md.getProvisionedChecksum()); deleteStaleDomain(new DomainWrapper(domain, doc)); continue; } logger.info("Found domain '{}' found for '{}'", domainName, baseDomainName); return new DomainWrapper(domain, doc); } logger.info("No cached domain found for '{}' with checksum '{}'", baseDomainName, checkSum); return null; } catch (LibvirtException e) { throw new LibvirtRuntimeException(e); } } protected void deleteStaleDomain(DomainWrapper staleDomain) throws LibvirtException { String staleDomainName = staleDomain.getName(); if (isDomainSafeToDelete(libvirt, staleDomainName)) { try { logger.info("Destroying stale domain '{}'", staleDomainName); staleDomain.destroyWithDisks(); } catch (LibvirtRuntimeException e) { // it may be that another job deleted the domain before us... logger.debug("Ignoring exception while cleaning stale domain", e); } } } protected static boolean isDomainSafeToDelete(Connect libvirt, String staleDomainName) throws LibvirtException { List<Domain> domains = LibvirtUtil.getRunningDomains(libvirt); for (Domain domain : domains) { Document doc = LibvirtUtil.loadDomainXml(domain); Metadata md = Metadata.fromXml(doc); if (md == null || md.isProvisioned()) { continue; } if (md.getParentDomain().equals(staleDomainName)) { logger.info("Not deleting stale domain '{}' still used by '{}'", staleDomainName, domain.getName()); return false; } } return true; } @Override public DomainWrapper getClone() { return provisionedClone; } @Override public String getHostName() { return provisionedCloneIp; } @Override public void teardown() { if (provisionedClone != null) { provisionedClone.destroyWithDisks(); provisionedClone = null; } } protected String getExpirationTag() { logger.info("Executing expiration command: {}", cacheExpirationCmd); try { String expirationTag = cmdProcessor.run(Command.fromString(cacheExpirationCmd)).getOutput().trim(); return expirationTag; } catch (NonZeroCodeException e) { throw new IllegalArgumentException( String.format( "Command %s returned code %s with the following errors: \n\n%s\n", e.getCommand().toString(), e.getResponse().getReturnCode(), e.getResponse().getErrors() + "\n\n" + e.getResponse().getOutput() )); } } protected DomainWrapper createProvisionedClone() { DomainWrapper base = super.getClone(); String baseName = super.getBaseDomainName(); String cloneName = baseName + "-" + UUID.randomUUID().toString(); logger.info("Creating clone '{}' from provisioned domain '{}'", cloneName, base.getName()); return base.cloneWithBackingStore(cloneName); } protected void provisionHost(String ip) { CmdLine cmdLine = new CmdLine(); String fragment = MessageFormat.format(provisionCmd, ip); cmdLine.addRaw(fragment); logger.info("Provisioning host with '{}'", cmdLine); OverthereConnection connection = null; try { String finalUrl = MessageFormat.format(provisionUrl, ip); connection = overthereConnectionFromURI(finalUrl); CapturingOverthereExecutionOutputHandler stdOutCapture = capturingHandler(); CapturingOverthereExecutionOutputHandler stdErrCapture = capturingHandler(); OverthereExecutionOutputHandler stdOutHandler = stdOutCapture; OverthereExecutionOutputHandler stdErrHandler = stdErrCapture; if (logger.isInfoEnabled()) { OverthereExecutionOutputHandler stdout = new LoggingOutputHandler(logger, "out"); stdOutHandler = multiHandler(stdOutCapture, stdout); OverthereExecutionOutputHandler stderr = new LoggingOutputHandler(logger, "err"); stdErrHandler = multiHandler(stdErrCapture, stderr); } int exitCode = connection.execute(stdOutHandler, stdErrHandler, cmdLine); if (exitCode != 0) { throw new RuntimeException(String.format("Provisioning of clone from '%s' failed with exit code %d", getBaseDomainName(), exitCode)); } // doesn't seem to work, we don't get stderr returned overthere/sshj bug? if (!stdErrCapture.getOutputLines().isEmpty()) { throw new RuntimeException(String.format("Provisioning of clone from '%s' failed with output to stderr: %s", getBaseDomainName(), stdErrCapture.getOutput())); } } finally { if (connection != null) { connection.close(); } } } }
Should not check in code to test that the test fails....
src/main/java/com/xebialabs/overcast/host/CachedLibvirtHost.java
Should not check in code to test that the test fails....
<ide><path>rc/main/java/com/xebialabs/overcast/host/CachedLibvirtHost.java <ide> provisionHost(ip); <ide> } catch (RuntimeException e) { <ide> logger.error("Failed to provision clone from '{}' cleaning up", this.getBaseDomainName()); <del> // super.getClone().destroyWithDisks(); <add> super.getClone().destroyWithDisks(); <ide> throw e; <ide> } <ide>
Java
apache-2.0
0cc3dcf3b17f90c7ccef16d5ab03b55ed217b64b
0
sarl/sarl,sarl/sarl,sarl/sarl,sarl/sarl,sarl/sarl,sarl/sarl
/* * $Id$ * * SARL is an general-purpose agent programming language. * More details on http://www.sarl.io * * Copyright (C) 2014-2017 the original authors or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.sarl.lang.ui.outline; import javax.inject.Named; import com.google.common.base.Strings; import com.google.inject.Inject; import org.eclipse.emf.ecore.EObject; import org.eclipse.jface.viewers.ILabelDecorator; import org.eclipse.swt.graphics.Image; import org.eclipse.xtend.core.xtend.XtendClass; import org.eclipse.xtend.core.xtend.XtendMember; import org.eclipse.xtend.core.xtend.XtendPackage; import org.eclipse.xtend.core.xtend.XtendTypeDeclaration; import org.eclipse.xtext.common.types.JvmConstructor; import org.eclipse.xtext.common.types.JvmDeclaredType; import org.eclipse.xtext.common.types.JvmFeature; import org.eclipse.xtext.common.types.JvmIdentifiableElement; import org.eclipse.xtext.common.types.JvmParameterizedTypeReference; import org.eclipse.xtext.common.types.JvmType; import org.eclipse.xtext.common.types.JvmTypeReference; import org.eclipse.xtext.nodemodel.ICompositeNode; import org.eclipse.xtext.nodemodel.util.NodeModelUtils; import org.eclipse.xtext.ui.editor.outline.IOutlineNode; import org.eclipse.xtext.ui.editor.outline.impl.DocumentRootNode; import org.eclipse.xtext.ui.editor.outline.impl.EObjectNode; import org.eclipse.xtext.ui.editor.outline.impl.EStructuralFeatureNode; import org.eclipse.xtext.xbase.annotations.ui.outline.XbaseWithAnnotationsOutlineTreeProvider; import org.eclipse.xtext.xbase.typesystem.references.LightweightTypeReference; import org.eclipse.xtext.xbase.typesystem.util.CommonTypeComputationServices; import io.sarl.lang.jvmmodel.SarlJvmModelAssociations; import io.sarl.lang.sarl.SarlAction; import io.sarl.lang.sarl.SarlBehaviorUnit; import io.sarl.lang.sarl.SarlCapacityUses; import io.sarl.lang.sarl.SarlConstructor; import io.sarl.lang.sarl.SarlField; import io.sarl.lang.sarl.SarlRequiredCapacity; import io.sarl.lang.sarl.SarlScript; import io.sarl.lang.util.Utils; /** * Customization of the default outline structure. * * @author $Author: sgalland$ * @version $FullVersion$ * @mavengroupid $GroupId$ * @mavenartifactid $ArtifactId$ * @see "https://www.eclipse.org/Xtext/documentation/304_ide_concepts.html#outline" */ public class SARLOutlineTreeProvider extends XbaseWithAnnotationsOutlineTreeProvider { @Inject private SarlJvmModelAssociations associations; @Inject @Named("DiagnosticDecorator") private ILabelDecorator diagnoticDecorator; @Inject private CommonTypeComputationServices services; /** Create a node for the SARL script. * * @param parentNode the parent node. * @param modelElement the feature container for which a node should be created. */ protected void _createChildren(DocumentRootNode parentNode, SarlScript modelElement) { if (!Strings.isNullOrEmpty(modelElement.getPackage())) { // Create the node for the package declaration. createEStructuralFeatureNode( parentNode, modelElement, XtendPackage.Literals.XTEND_FILE__PACKAGE, this.imageDispatcher.invoke(getClass().getPackage()), // Do not use the text dispatcher below for avoiding to obtain // the filename of the script. modelElement.getPackage(), true); } // Create the nodes for the import declarations. /*if (modelElement.getImportSection() != null && !modelElement.getImportSection().getImportDeclarations().isEmpty()) { createNode(parentNode, modelElement.getImportSection()); }*/ // Create a node per type declaration. for (final XtendTypeDeclaration topElement : modelElement.getXtendTypes()) { createNode(parentNode, topElement); } } /** Create a node for the given feature container. * * @param parentNode the parent node. * @param modelElement the feature container for which a node should be created. */ @SuppressWarnings("checkstyle:cyclomaticcomplexity") protected void _createNode(DocumentRootNode parentNode, XtendTypeDeclaration modelElement) { // // The text region is set to the model element, not to the model element's name as in the // default implementation of createStructuralFeatureNode(). // The text region computation is overridden in order to have a correct link to the editor. // final boolean isFeatureSet = modelElement.eIsSet(XtendPackage.Literals.XTEND_TYPE_DECLARATION__NAME); final EStructuralFeatureNode elementNode = new EStructuralFeatureNode( modelElement, XtendPackage.Literals.XTEND_TYPE_DECLARATION__NAME, parentNode, this.imageDispatcher.invoke(modelElement), this.textDispatcher.invoke(modelElement), modelElement.getMembers().isEmpty() || !isFeatureSet); final EObject primarySourceElement = this.associations.getPrimarySourceElement(modelElement); final ICompositeNode parserNode = NodeModelUtils.getNode( (primarySourceElement == null) ? modelElement : primarySourceElement); elementNode.setTextRegion(parserNode.getTextRegion()); // boolean hasConstructor = false; if (!modelElement.getMembers().isEmpty()) { EObjectNode capacityUseNode = null; EObjectNode capacityRequirementNode = null; for (final EObject feature : modelElement.getMembers()) { if (feature instanceof SarlConstructor) { hasConstructor = true; createNode(elementNode, feature); } else if (feature instanceof SarlField || feature instanceof SarlAction || feature instanceof SarlBehaviorUnit || feature instanceof XtendTypeDeclaration) { createNode(elementNode, feature); } else if (feature instanceof SarlCapacityUses) { capacityUseNode = createCapacityUseNode(elementNode, (SarlCapacityUses) feature, capacityUseNode); } else if (feature instanceof SarlRequiredCapacity) { capacityRequirementNode = createRequiredCapacityNode(elementNode, (SarlRequiredCapacity) feature, capacityRequirementNode); } } } if (!hasConstructor && modelElement instanceof XtendClass) { createInheritedConstructors(elementNode, (XtendClass) modelElement); } } private void createInheritedConstructors(EStructuralFeatureNode elementNode, XtendClass modelElement) { final JvmTypeReference extend = modelElement.getExtends(); if (extend != null) { final LightweightTypeReference reference = Utils.toLightweightTypeReference(extend, this.services); if (reference != null) { final JvmType type = reference.getType(); if (type instanceof JvmDeclaredType) { for (final JvmConstructor constructor : ((JvmDeclaredType) type).getDeclaredConstructors()) { createNode(elementNode, constructor); } } } } } private EObjectNode createCapacityUseNode(EStructuralFeatureNode elementNode, SarlCapacityUses feature, EObjectNode oldCapacityUseNode) { EObjectNode capacityUseNode = oldCapacityUseNode; if (capacityUseNode == null) { capacityUseNode = createEObjectNode( elementNode, feature, this.imageDispatcher.invoke(feature), this.textDispatcher.invoke(feature), false); } for (final JvmParameterizedTypeReference item : feature.getCapacities()) { createEObjectNode( capacityUseNode, item, this.imageDispatcher.invoke(item), this.textDispatcher.invoke(item), true); } return capacityUseNode; } private EObjectNode createRequiredCapacityNode(EStructuralFeatureNode elementNode, SarlRequiredCapacity feature, EObjectNode oldCapacityRequirementNode) { EObjectNode capacityRequirementNode = oldCapacityRequirementNode; if (capacityRequirementNode == null) { capacityRequirementNode = createEObjectNode( elementNode, feature, this.imageDispatcher.invoke(feature), this.textDispatcher.invoke(feature), false); } for (final JvmParameterizedTypeReference item : feature.getCapacities()) { createEObjectNode( capacityRequirementNode, item, this.imageDispatcher.invoke(item), this.textDispatcher.invoke(item), true); } return capacityRequirementNode; } /** Replies if the type declaration element is a leaf in the outline. * * @param modelElement the model element. * @return <code>true</code> if it is a leaf, <code>false</code> otherwise. */ @SuppressWarnings("static-method") protected boolean _isLeaf(XtendTypeDeclaration modelElement) { return modelElement.getMembers().isEmpty(); } /** Replies if the member element is a leaf in the outline. * * @param modelElement the model element. * @return <code>true</code> if it is a leaf, <code>false</code> otherwise. */ @SuppressWarnings("static-method") protected boolean _isLeaf(XtendMember modelElement) { return true; } /** Replies if the JVM elements are leafs in the outline. * * @param modelElement the model element. * @return <code>true</code> if it is a leaf, <code>false</code> otherwise. */ @SuppressWarnings("static-method") protected boolean _isLeaf(JvmIdentifiableElement modelElement) { return true; } @Override protected EObjectNode createEObjectNode( IOutlineNode parentNode, EObject modelElement, Image image, Object text, boolean isLeaf) { final SARLEObjectNode objectNode = new SARLEObjectNode(modelElement, parentNode, image, text, isLeaf); configureNode(parentNode, modelElement, objectNode); return objectNode; } private void configureNode(IOutlineNode parentNode, EObject modelElement, SARLEObjectNode objectNode) { final EObject primarySourceElement = this.associations.getPrimarySourceElement(modelElement); final ICompositeNode parserNode = NodeModelUtils.getNode( (primarySourceElement == null) ? modelElement : primarySourceElement); if (parserNode != null) { objectNode.setTextRegion(parserNode.getTextRegion()); } if (isLocalElement(parentNode, modelElement)) { objectNode.setShortTextRegion(this.locationInFileProvider.getSignificantTextRegion(modelElement)); } objectNode.setStatic(isStatic(modelElement)); } private static boolean isStatic(EObject element) { if (element instanceof JvmFeature) { return ((JvmFeature) element).isStatic(); } if (element instanceof JvmDeclaredType) { return ((JvmDeclaredType) element).isStatic(); } if (element instanceof XtendMember) { try { return ((XtendMember) element).isStatic(); } catch (Exception exception) { // Some XtendMember does not support } } return false; } /** Get the image for the Xtend members. * * @param modelElement the member. * @return the image. */ protected Image _image(XtendMember modelElement) { final Image img = super._image(modelElement); return this.diagnoticDecorator.decorateImage(img, modelElement); } }
main/coreplugins/io.sarl.lang.ui/src/io/sarl/lang/ui/outline/SARLOutlineTreeProvider.java
/* * $Id$ * * SARL is an general-purpose agent programming language. * More details on http://www.sarl.io * * Copyright (C) 2014-2017 the original authors or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.sarl.lang.ui.outline; import javax.inject.Named; import com.google.common.base.Strings; import com.google.inject.Inject; import org.eclipse.emf.ecore.EObject; import org.eclipse.jface.viewers.ILabelDecorator; import org.eclipse.swt.graphics.Image; import org.eclipse.xtend.core.xtend.XtendClass; import org.eclipse.xtend.core.xtend.XtendMember; import org.eclipse.xtend.core.xtend.XtendPackage; import org.eclipse.xtend.core.xtend.XtendTypeDeclaration; import org.eclipse.xtext.common.types.JvmConstructor; import org.eclipse.xtext.common.types.JvmDeclaredType; import org.eclipse.xtext.common.types.JvmFeature; import org.eclipse.xtext.common.types.JvmIdentifiableElement; import org.eclipse.xtext.common.types.JvmParameterizedTypeReference; import org.eclipse.xtext.common.types.JvmType; import org.eclipse.xtext.common.types.JvmTypeReference; import org.eclipse.xtext.nodemodel.ICompositeNode; import org.eclipse.xtext.nodemodel.util.NodeModelUtils; import org.eclipse.xtext.ui.editor.outline.IOutlineNode; import org.eclipse.xtext.ui.editor.outline.impl.DocumentRootNode; import org.eclipse.xtext.ui.editor.outline.impl.EObjectNode; import org.eclipse.xtext.ui.editor.outline.impl.EStructuralFeatureNode; import org.eclipse.xtext.xbase.annotations.ui.outline.XbaseWithAnnotationsOutlineTreeProvider; import org.eclipse.xtext.xbase.typesystem.references.LightweightTypeReference; import org.eclipse.xtext.xbase.typesystem.util.CommonTypeComputationServices; import io.sarl.lang.jvmmodel.SarlJvmModelAssociations; import io.sarl.lang.sarl.SarlAction; import io.sarl.lang.sarl.SarlBehaviorUnit; import io.sarl.lang.sarl.SarlCapacityUses; import io.sarl.lang.sarl.SarlConstructor; import io.sarl.lang.sarl.SarlField; import io.sarl.lang.sarl.SarlRequiredCapacity; import io.sarl.lang.sarl.SarlScript; import io.sarl.lang.util.Utils; /** * Customization of the default outline structure. * * @author $Author: sgalland$ * @version $FullVersion$ * @mavengroupid $GroupId$ * @mavenartifactid $ArtifactId$ * @see "https://www.eclipse.org/Xtext/documentation/304_ide_concepts.html#outline" */ public class SARLOutlineTreeProvider extends XbaseWithAnnotationsOutlineTreeProvider { @Inject private SarlJvmModelAssociations associations; @Inject @Named("DiagnosticDecorator") private ILabelDecorator diagnoticDecorator; @Inject private CommonTypeComputationServices services; /** Create a node for the SARL script. * * @param parentNode the parent node. * @param modelElement the feature container for which a node should be created. */ protected void _createChildren(DocumentRootNode parentNode, SarlScript modelElement) { if (!Strings.isNullOrEmpty(modelElement.getPackage())) { // Create the node for the package declaration. createEStructuralFeatureNode( parentNode, modelElement, XtendPackage.Literals.XTEND_FILE__PACKAGE, this.imageDispatcher.invoke(getClass().getPackage()), // Do not use the text dispatcher below for avoiding to obtain // the filename of the script. modelElement.getPackage(), true); } // Create the nodes for the import declarations. if (modelElement.getImportSection() != null && !modelElement.getImportSection().getImportDeclarations().isEmpty()) { createNode(parentNode, modelElement.getImportSection()); } // Create a node per type declaration. for (final XtendTypeDeclaration topElement : modelElement.getXtendTypes()) { createNode(parentNode, topElement); } } /** Create a node for the given feature container. * * @param parentNode the parent node. * @param modelElement the feature container for which a node should be created. */ @SuppressWarnings("checkstyle:cyclomaticcomplexity") protected void _createNode(DocumentRootNode parentNode, XtendTypeDeclaration modelElement) { // // The text region is set to the model element, not to the model element's name as in the // default implementation of createStructuralFeatureNode(). // The text region computation is overridden in order to have a correct link to the editor. // final boolean isFeatureSet = modelElement.eIsSet(XtendPackage.Literals.XTEND_TYPE_DECLARATION__NAME); final EStructuralFeatureNode elementNode = new EStructuralFeatureNode( modelElement, XtendPackage.Literals.XTEND_TYPE_DECLARATION__NAME, parentNode, this.imageDispatcher.invoke(modelElement), this.textDispatcher.invoke(modelElement), modelElement.getMembers().isEmpty() || !isFeatureSet); final EObject primarySourceElement = this.associations.getPrimarySourceElement(modelElement); final ICompositeNode parserNode = NodeModelUtils.getNode( (primarySourceElement == null) ? modelElement : primarySourceElement); elementNode.setTextRegion(parserNode.getTextRegion()); // boolean hasConstructor = false; if (!modelElement.getMembers().isEmpty()) { EObjectNode capacityUseNode = null; EObjectNode capacityRequirementNode = null; for (final EObject feature : modelElement.getMembers()) { if (feature instanceof SarlConstructor) { hasConstructor = true; createNode(elementNode, feature); } else if (feature instanceof SarlField || feature instanceof SarlAction || feature instanceof SarlBehaviorUnit || feature instanceof XtendTypeDeclaration) { createNode(elementNode, feature); } else if (feature instanceof SarlCapacityUses) { capacityUseNode = createCapacityUseNode(elementNode, (SarlCapacityUses) feature, capacityUseNode); } else if (feature instanceof SarlRequiredCapacity) { capacityRequirementNode = createRequiredCapacityNode(elementNode, (SarlRequiredCapacity) feature, capacityRequirementNode); } } } if (!hasConstructor && modelElement instanceof XtendClass) { createInheritedConstructors(elementNode, (XtendClass) modelElement); } } private void createInheritedConstructors(EStructuralFeatureNode elementNode, XtendClass modelElement) { final JvmTypeReference extend = modelElement.getExtends(); if (extend != null) { final LightweightTypeReference reference = Utils.toLightweightTypeReference(extend, this.services); if (reference != null) { final JvmType type = reference.getType(); if (type instanceof JvmDeclaredType) { for (final JvmConstructor constructor : ((JvmDeclaredType) type).getDeclaredConstructors()) { createNode(elementNode, constructor); } } } } } private EObjectNode createCapacityUseNode(EStructuralFeatureNode elementNode, SarlCapacityUses feature, EObjectNode oldCapacityUseNode) { EObjectNode capacityUseNode = oldCapacityUseNode; if (capacityUseNode == null) { capacityUseNode = createEObjectNode( elementNode, feature, this.imageDispatcher.invoke(feature), this.textDispatcher.invoke(feature), false); } for (final JvmParameterizedTypeReference item : feature.getCapacities()) { createEObjectNode( capacityUseNode, item, this.imageDispatcher.invoke(item), this.textDispatcher.invoke(item), true); } return capacityUseNode; } private EObjectNode createRequiredCapacityNode(EStructuralFeatureNode elementNode, SarlRequiredCapacity feature, EObjectNode oldCapacityRequirementNode) { EObjectNode capacityRequirementNode = oldCapacityRequirementNode; if (capacityRequirementNode == null) { capacityRequirementNode = createEObjectNode( elementNode, feature, this.imageDispatcher.invoke(feature), this.textDispatcher.invoke(feature), false); } for (final JvmParameterizedTypeReference item : feature.getCapacities()) { createEObjectNode( capacityRequirementNode, item, this.imageDispatcher.invoke(item), this.textDispatcher.invoke(item), true); } return capacityRequirementNode; } /** Replies if the type declaration element is a leaf in the outline. * * @param modelElement the model element. * @return <code>true</code> if it is a leaf, <code>false</code> otherwise. */ @SuppressWarnings("static-method") protected boolean _isLeaf(XtendTypeDeclaration modelElement) { return modelElement.getMembers().isEmpty(); } /** Replies if the member element is a leaf in the outline. * * @param modelElement the model element. * @return <code>true</code> if it is a leaf, <code>false</code> otherwise. */ @SuppressWarnings("static-method") protected boolean _isLeaf(XtendMember modelElement) { return true; } /** Replies if the JVM elements are leafs in the outline. * * @param modelElement the model element. * @return <code>true</code> if it is a leaf, <code>false</code> otherwise. */ @SuppressWarnings("static-method") protected boolean _isLeaf(JvmIdentifiableElement modelElement) { return true; } @Override protected EObjectNode createEObjectNode( IOutlineNode parentNode, EObject modelElement, Image image, Object text, boolean isLeaf) { final SARLEObjectNode objectNode = new SARLEObjectNode(modelElement, parentNode, image, text, isLeaf); configureNode(parentNode, modelElement, objectNode); return objectNode; } private void configureNode(IOutlineNode parentNode, EObject modelElement, SARLEObjectNode objectNode) { final EObject primarySourceElement = this.associations.getPrimarySourceElement(modelElement); final ICompositeNode parserNode = NodeModelUtils.getNode( (primarySourceElement == null) ? modelElement : primarySourceElement); if (parserNode != null) { objectNode.setTextRegion(parserNode.getTextRegion()); } if (isLocalElement(parentNode, modelElement)) { objectNode.setShortTextRegion(this.locationInFileProvider.getSignificantTextRegion(modelElement)); } objectNode.setStatic(isStatic(modelElement)); } private static boolean isStatic(EObject element) { if (element instanceof JvmFeature) { return ((JvmFeature) element).isStatic(); } if (element instanceof JvmDeclaredType) { return ((JvmDeclaredType) element).isStatic(); } if (element instanceof XtendMember) { try { return ((XtendMember) element).isStatic(); } catch (Exception exception) { // Some XtendMember does not support } } return false; } /** Get the image for the Xtend members. * * @param modelElement the member. * @return the image. */ protected Image _image(XtendMember modelElement) { final Image img = super._image(modelElement); return this.diagnoticDecorator.decorateImage(img, modelElement); } }
[ui] Remove the imports from the outline to mimic the Java outline component. Signed-off-by: Stéphane Galland <[email protected]>
main/coreplugins/io.sarl.lang.ui/src/io/sarl/lang/ui/outline/SARLOutlineTreeProvider.java
[ui] Remove the imports from the outline to mimic the Java outline component.
<ide><path>ain/coreplugins/io.sarl.lang.ui/src/io/sarl/lang/ui/outline/SARLOutlineTreeProvider.java <ide> true); <ide> } <ide> // Create the nodes for the import declarations. <del> if (modelElement.getImportSection() != null && !modelElement.getImportSection().getImportDeclarations().isEmpty()) { <add> /*if (modelElement.getImportSection() != null && !modelElement.getImportSection().getImportDeclarations().isEmpty()) { <ide> createNode(parentNode, modelElement.getImportSection()); <del> } <add> }*/ <ide> // Create a node per type declaration. <ide> for (final XtendTypeDeclaration topElement : modelElement.getXtendTypes()) { <ide> createNode(parentNode, topElement);
Java
agpl-3.0
707872aa8b6a3923e47755f791629eae0c4383d8
0
caiyingyuan/tigase-utils-71,caiyingyuan/tigase-utils-71
/* Package Jabber Server * Copyright (C) 2001, 2002, 2003, 2004, 2005 * "Artur Hefczyc" <[email protected]> * * 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. * * $Rev$ * Last modified by $Author$ * $Date$ */ package tigase.util; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Collections; import java.util.Hashtable; import java.util.Map; import java.util.Arrays; import java.util.StringTokenizer; import java.util.logging.Logger; import javax.naming.NamingException; import javax.naming.directory.Attribute; import javax.naming.directory.Attributes; import javax.naming.directory.DirContext; import javax.naming.directory.InitialDirContext; /** * Describe class DNSResolver here. * * * Created: Mon Sep 11 09:59:02 2006 * * @author <a href="mailto:[email protected]">Artur Hefczyc</a> * @version $Rev$ */ public class DNSResolver { /** * Variable <code>log</code> is a class logger. */ private static final Logger log = Logger.getLogger("tigase.util.DNSResolver"); private static Map<String, Object> cache = Collections.synchronizedMap(new SimpleCache<String, Object>(1000)); private static String[] localnames = null; static { cache.put("localhost", "127.0.0.1"); try { localnames = new String[2]; localnames[0] = InetAddress.getLocalHost().getHostName(); localnames[1] = "localhost"; InetAddress[] all = InetAddress.getAllByName(localnames[0]); cache.put(localnames[0], all[0].getHostAddress()); } // end of try catch (UnknownHostException e) { localnames = new String[] {"localhost"}; } // end of try-catch } public static String[] getDefHostNames() { // if (extrahosts != null) { // String[] hosts = extrahosts.split(","); // String[] result = new String[localnames.length + hosts.length]; // System.arraycopy(localnames, 0, result, 0, localnames.length); // System.arraycopy(hosts, 0, result, localnames.length, hosts.length); // return result; // } return (localnames != null ? Arrays.copyOf(localnames, localnames.length) : null); } public static String getHostSRV_IP(final String hostname) throws UnknownHostException { String cache_res = (String)cache.get(hostname); if (cache_res != null) { return cache_res; } // end of if (result != null) String result_host = hostname; try { Hashtable<String, String> env = new Hashtable<String, String>(); env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory"); DirContext ctx = new InitialDirContext(env); Attributes attrs = ctx.getAttributes("_xmpp-server._tcp." + hostname, new String[] {"SRV"}); Attribute att = attrs.get("SRV"); if (att != null) { String res = att.get().toString(); int idx = res.lastIndexOf(" "); result_host = res.substring(idx + 1, res.length()); } // end of if (att != null) ctx.close(); } // end of try catch (NamingException e) { result_host = hostname; } // end of try-catch InetAddress[] all = InetAddress.getAllByName(result_host); cache.put(hostname, all[0].getHostAddress()); return all[0].getHostAddress(); } /** * Describe <code>main</code> method here. * * @param args a <code>String[]</code> value */ public static void main(final String[] args) throws Exception { String host = "gmail.com"; if (args.length > 0) { host = args[0]; } System.out.println("IP: " + getHostSRV_IP(host)); // InetAddress[] all = InetAddress.getAllByName(host); // for (InetAddress ia: all) { // System.out.println("Host: " + ia.toString()); // } // end of for (InetAddress ia: all) // Hashtable env = new Hashtable(); // env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory"); // // env.put("java.naming.provider.url", "dns://10.75.32.10"); // DirContext ctx = new InitialDirContext(env); // Attributes attrs = // ctx.getAttributes("_xmpp-server._tcp." + host, // new String[] {"SRV", "A"}); // String id = "SRV"; // Attribute att = attrs.get(id); // if (att == null) { // id = "A"; // att = attrs.get(id); // } // end of if (attr == null) // System.out.println(id + ": " + att.get(0)); // System.out.println("Class: " + att.get(0).getClass().getSimpleName()); // for (NamingEnumeration ae = attrs.getAll(); ae.hasMoreElements(); ) { // Attribute attr = (Attribute)ae.next(); // String attrId = attr.getID(); // for (Enumeration vals = attr.getAll(); vals.hasMoreElements(); // System.out.println(attrId + ": " + vals.nextElement())); // } // ctx.close(); } } // DNSResolver
src/main/java/tigase/util/DNSResolver.java
/* Package Jabber Server * Copyright (C) 2001, 2002, 2003, 2004, 2005 * "Artur Hefczyc" <[email protected]> * * 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. * * $Rev$ * Last modified by $Author$ * $Date$ */ package tigase.util; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Collections; import java.util.Hashtable; import java.util.Map; import java.util.StringTokenizer; import java.util.logging.Logger; import javax.naming.NamingException; import javax.naming.directory.Attribute; import javax.naming.directory.Attributes; import javax.naming.directory.DirContext; import javax.naming.directory.InitialDirContext; /** * Describe class DNSResolver here. * * * Created: Mon Sep 11 09:59:02 2006 * * @author <a href="mailto:[email protected]">Artur Hefczyc</a> * @version $Rev$ */ public class DNSResolver { /** * Variable <code>log</code> is a class logger. */ private static final Logger log = Logger.getLogger("tigase.util.DNSResolver"); private static Map<String, Object> cache = Collections.synchronizedMap(new SimpleCache<String, Object>(1000)); private static String[] localnames = null; static { cache.put("localhost", "127.0.0.1"); try { localnames = new String[2]; localnames[0] = InetAddress.getLocalHost().getHostName(); localnames[1] = "localhost"; InetAddress[] all = InetAddress.getAllByName(localnames[0]); cache.put(localnames[0], all[0].getHostAddress()); } // end of try catch (UnknownHostException e) { localnames = new String[] {"localhost"}; } // end of try-catch } public static String[] getDefHostNames() { // if (extrahosts != null) { // String[] hosts = extrahosts.split(","); // String[] result = new String[localnames.length + hosts.length]; // System.arraycopy(localnames, 0, result, 0, localnames.length); // System.arraycopy(hosts, 0, result, localnames.length, hosts.length); // return result; // } return localnames; } public static String getHostSRV_IP(final String hostname) throws UnknownHostException { String cache_res = (String)cache.get(hostname); if (cache_res != null) { return cache_res; } // end of if (result != null) String result_host = hostname; try { Hashtable<String, String> env = new Hashtable<String, String>(); env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory"); DirContext ctx = new InitialDirContext(env); Attributes attrs = ctx.getAttributes("_xmpp-server._tcp." + hostname, new String[] {"SRV"}); Attribute att = attrs.get("SRV"); if (att != null) { String res = att.get().toString(); int idx = res.lastIndexOf(" "); result_host = res.substring(idx + 1, res.length()); } // end of if (att != null) ctx.close(); } // end of try catch (NamingException e) { result_host = hostname; } // end of try-catch InetAddress[] all = InetAddress.getAllByName(result_host); cache.put(hostname, all[0].getHostAddress()); return all[0].getHostAddress(); } /** * Describe <code>main</code> method here. * * @param args a <code>String[]</code> value */ public static void main(final String[] args) throws Exception { String host = "gmail.com"; if (args.length > 0) { host = args[0]; } System.out.println("IP: " + getHostSRV_IP(host)); // InetAddress[] all = InetAddress.getAllByName(host); // for (InetAddress ia: all) { // System.out.println("Host: " + ia.toString()); // } // end of for (InetAddress ia: all) // Hashtable env = new Hashtable(); // env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory"); // // env.put("java.naming.provider.url", "dns://10.75.32.10"); // DirContext ctx = new InitialDirContext(env); // Attributes attrs = // ctx.getAttributes("_xmpp-server._tcp." + host, // new String[] {"SRV", "A"}); // String id = "SRV"; // Attribute att = attrs.get(id); // if (att == null) { // id = "A"; // att = attrs.get(id); // } // end of if (attr == null) // System.out.println(id + ": " + att.get(0)); // System.out.println("Class: " + att.get(0).getClass().getSimpleName()); // for (NamingEnumeration ae = attrs.getAll(); ae.hasMoreElements(); ) { // Attribute attr = (Attribute)ae.next(); // String attrId = attr.getID(); // for (Enumeration vals = attr.getAll(); vals.hasMoreElements(); // System.out.println(attrId + ": " + vals.nextElement())); // } // ctx.close(); } } // DNSResolver
Code cleanup git-svn-id: 78a0b1024db9beb524bc745052f6db0c395bb78f@424 20a39203-4b1a-0410-9ea8-f7f58976c10f
src/main/java/tigase/util/DNSResolver.java
Code cleanup
<ide><path>rc/main/java/tigase/util/DNSResolver.java <ide> import java.util.Collections; <ide> import java.util.Hashtable; <ide> import java.util.Map; <add>import java.util.Arrays; <ide> import java.util.StringTokenizer; <ide> import java.util.logging.Logger; <ide> import javax.naming.NamingException; <ide> // System.arraycopy(hosts, 0, result, localnames.length, hosts.length); <ide> // return result; <ide> // } <del> return localnames; <add> return (localnames != null ? <add> Arrays.copyOf(localnames, localnames.length) : null); <ide> } <ide> <ide> public static String getHostSRV_IP(final String hostname)
Java
apache-2.0
3f89b25851c6bc770abe8d9aa6d24dcb666420e9
0
yurloc/drools,ngs-mtech/drools,ThomasLau/drools,pperboires/PocDrools,droolsjbpm/drools,292388900/drools,sotty/drools,liupugong/drools,psiroky/drools,romartin/drools,prabasn/drools,ChallenHB/drools,prabasn/drools,Buble1981/MyDroolsFork,psiroky/drools,ThiagoGarciaAlves/drools,winklerm/drools,amckee23/drools,vinodkiran/drools,ThomasLau/drools,sotty/drools,ThiagoGarciaAlves/drools,romartin/drools,sotty/drools,droolsjbpm/drools,yurloc/drools,292388900/drools,mrrodriguez/drools,sutaakar/drools,winklerm/drools,pperboires/PocDrools,rajashekharmunthakewill/drools,prabasn/drools,mrietveld/drools,ngs-mtech/drools,liupugong/drools,OnePaaS/drools,kevinpeterson/drools,prabasn/drools,kevinpeterson/drools,jomarko/drools,romartin/drools,ngs-mtech/drools,pperboires/PocDrools,romartin/drools,jomarko/drools,winklerm/drools,HHzzhz/drools,kevinpeterson/drools,sutaakar/drools,mrietveld/drools,jiripetrlik/drools,TonnyFeng/drools,mswiderski/drools,mrrodriguez/drools,winklerm/drools,psiroky/drools,jiripetrlik/drools,TonnyFeng/drools,mrrodriguez/drools,ngs-mtech/drools,mrrodriguez/drools,lanceleverich/drools,winklerm/drools,lanceleverich/drools,mswiderski/drools,ThiagoGarciaAlves/drools,prabasn/drools,droolsjbpm/drools,droolsjbpm/drools,vinodkiran/drools,reynoldsm88/drools,ChallenHB/drools,iambic69/drools,TonnyFeng/drools,romartin/drools,lanceleverich/drools,292388900/drools,mswiderski/drools,reynoldsm88/drools,iambic69/drools,sotty/drools,manstis/drools,HHzzhz/drools,mrietveld/drools,kedzie/drools-android,ThiagoGarciaAlves/drools,amckee23/drools,292388900/drools,kevinpeterson/drools,iambic69/drools,liupugong/drools,pperboires/PocDrools,sotty/drools,TonnyFeng/drools,iambic69/drools,rajashekharmunthakewill/drools,sutaakar/drools,ThomasLau/drools,HHzzhz/drools,kedzie/drools-android,liupugong/drools,Buble1981/MyDroolsFork,vinodkiran/drools,kedzie/drools-android,jomarko/drools,reynoldsm88/drools,OnePaaS/drools,pwachira/droolsexamples,ThomasLau/drools,lanceleverich/drools,psiroky/drools,ngs-mtech/drools,rajashekharmunthakewill/drools,OnePaaS/drools,reynoldsm88/drools,mrietveld/drools,vinodkiran/drools,yurloc/drools,mrrodriguez/drools,jomarko/drools,292388900/drools,OnePaaS/drools,rajashekharmunthakewill/drools,Buble1981/MyDroolsFork,droolsjbpm/drools,amckee23/drools,liupugong/drools,amckee23/drools,amckee23/drools,ThomasLau/drools,manstis/drools,yurloc/drools,jiripetrlik/drools,ChallenHB/drools,lanceleverich/drools,ChallenHB/drools,kevinpeterson/drools,jiripetrlik/drools,OnePaaS/drools,manstis/drools,kedzie/drools-android,sutaakar/drools,reynoldsm88/drools,ChallenHB/drools,sutaakar/drools,vinodkiran/drools,jomarko/drools,mrietveld/drools,HHzzhz/drools,HHzzhz/drools,mswiderski/drools,manstis/drools,rajashekharmunthakewill/drools,kedzie/drools-android,ThiagoGarciaAlves/drools,iambic69/drools,manstis/drools,jiripetrlik/drools,Buble1981/MyDroolsFork,TonnyFeng/drools
package org.drools.rule; /* * $Id: Declaration.java,v 1.1 2005/07/26 01:06:31 mproctor Exp $ * * Copyright 2001-2003 (C) The Werken Company. All Rights Reserved. * * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 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 "drools" must not be used to endorse or promote products derived * from this Software without prior written permission of The Werken Company. * For written permission, please contact [email protected]. * * 4. Products derived from this Software may not be called "drools" nor may * "drools" appear in their names without prior written permission of The Werken * Company. "drools" is a trademark of The Werken Company. * * 5. Due credit should be given to The Werken Company. (http://werken.com/) * * THIS SOFTWARE IS PROVIDED BY THE WERKEN COMPANY AND CONTRIBUTORS ``AS IS'' * AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE WERKEN COMPANY OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ import java.io.Serializable; import org.drools.base.ValueType; import org.drools.spi.Extractor; /* * Copyright 2005 JBoss 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. */ /** * @author <a href="mailto:[email protected]">Mark Proctor</a> * @author <a href="mailto:[email protected]">Bob McWhirter</a> * @author <a href="mailto:[email protected]">Simon Harris </a> * */ public class Declaration implements Serializable { // ------------------------------------------------------------ // Instance members // ------------------------------------------------------------ /** * */ private static final long serialVersionUID = 248608383490386902L; /** The identifier for the variable. */ private final String identifier; private final Extractor extractor; private Column column; // ------------------------------------------------------------ // Constructors // ------------------------------------------------------------ /** * Construct. * * @param identifier * The name of the variable. * @param objectType * The type of this variable declaration. * @param order * The index within a rule. */ public Declaration(final String identifier, final Extractor extractor, final Column column) { this.identifier = identifier; this.extractor = extractor; this.column = column; } // ------------------------------------------------------------ // Instance methods // ------------------------------------------------------------ /** * Retrieve the variable's identifier. * * @return The variable's identifier. */ public String getIdentifier() { return this.identifier; } /** * Retrieve the <code>ValueType</code>. * * @return The ValueType. */ public ValueType getValueType() { return this.extractor.getValueType(); } /** * Returns the index of the column * * @return the column */ public Column getColumn() { return this.column; } public void setColumn(final Column column) { this.column = column; } /** * Returns the Extractor expression * * @return */ public Extractor getExtractor() { return this.extractor; } public Object getValue(final Object object) { return this.extractor.getValue( object ); } public char getCharValue(Object object) { return this.extractor.getCharValue( object ); } public int getIntValue(Object object) { return this.extractor.getIntValue( object ); } public byte getByteValue(Object object) { return this.extractor.getByteValue( object ); } public short getShortValue(Object object) { return this.extractor.getShortValue( object ); } public long getLongValue(Object object) { return this.extractor.getLongValue( object ); } public float getFloatValue(Object object) { return this.extractor.getFloatValue( object ); } public double getDoubleValue(Object object) { return this.extractor.getDoubleValue( object ); } public boolean getBooleanValue(Object object) { return this.extractor.getBooleanValue( object ); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - public String toString() { return "[Declaration: type=" + this.extractor.getValueType() + " identifier=" + this.identifier + "]"; } public int hashCode() { final int PRIME = 31; int result = 1; result = PRIME * this.column.getFactIndex(); result = PRIME * this.extractor.hashCode(); result = PRIME * this.identifier.hashCode(); return result; } public boolean equals(final Object object) { if ( this == object ) { return true; } if ( object == null || getClass() != object.getClass() ) { return false; } final Declaration other = (Declaration) object; return this.column.getFactIndex() == other.column.getFactIndex() && this.identifier.equals( other.identifier ) && this.extractor.equals( other.extractor ); } }
drools-core/src/main/java/org/drools/rule/Declaration.java
package org.drools.rule; /* * $Id: Declaration.java,v 1.1 2005/07/26 01:06:31 mproctor Exp $ * * Copyright 2001-2003 (C) The Werken Company. All Rights Reserved. * * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 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 "drools" must not be used to endorse or promote products derived * from this Software without prior written permission of The Werken Company. * For written permission, please contact [email protected]. * * 4. Products derived from this Software may not be called "drools" nor may * "drools" appear in their names without prior written permission of The Werken * Company. "drools" is a trademark of The Werken Company. * * 5. Due credit should be given to The Werken Company. (http://werken.com/) * * THIS SOFTWARE IS PROVIDED BY THE WERKEN COMPANY AND CONTRIBUTORS ``AS IS'' * AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE WERKEN COMPANY OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ import java.io.Serializable; import org.drools.base.ValueType; import org.drools.spi.Extractor; /* * Copyright 2005 JBoss 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. */ /** * @author <a href="mailto:[email protected]">Mark Proctor</a> * @author <a href="mailto:[email protected]">Bob McWhirter</a> * @author <a href="mailto:[email protected]">Simon Harris </a> * */ public class Declaration implements Serializable { // ------------------------------------------------------------ // Instance members // ------------------------------------------------------------ /** * */ private static final long serialVersionUID = 248608383490386902L; /** The identifier for the variable. */ private final String identifier; private final Extractor extractor; private Column column; // ------------------------------------------------------------ // Constructors // ------------------------------------------------------------ /** * Construct. * * @param identifier * The name of the variable. * @param objectType * The type of this variable declaration. * @param order * The index within a rule. */ public Declaration(final String identifier, final Extractor extractor, final Column column) { this.identifier = identifier; this.extractor = extractor; this.column = column; } // ------------------------------------------------------------ // Instance methods // ------------------------------------------------------------ /** * Retrieve the variable's identifier. * * @return The variable's identifier. */ public String getIdentifier() { return this.identifier; } /** * Retrieve the <code>ValueType</code>. * * @return The ValueType. */ public ValueType getValueType() { return this.extractor.getValueType(); } /** * Returns the index of the column * * @return the column */ public Column getColumn() { return this.column; } public void setColumn(final Column column) { this.column = column; } /** * Returns the Extractor expression * * @return */ public Extractor getExtractor() { return this.extractor; } public Object getValue(final Object object) { return this.extractor.getValue( object ); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - public String toString() { return "[Declaration: type=" + this.extractor.getValueType() + " identifier=" + this.identifier + "]"; } public int hashCode() { final int PRIME = 31; int result = 1; result = PRIME * this.column.getFactIndex(); result = PRIME * this.extractor.hashCode(); result = PRIME * this.identifier.hashCode(); return result; } public boolean equals(final Object object) { if ( this == object ) { return true; } if ( object == null || getClass() != object.getClass() ) { return false; } final Declaration other = (Declaration) object; return this.column.getFactIndex() == other.column.getFactIndex() && this.identifier.equals( other.identifier ) && this.extractor.equals( other.extractor ); } }
Adding primitive methods to Declaration interface git-svn-id: a243bed356d289ca0d1b6d299a0597bdc4ecaa09@7031 c60d74c8-e8f6-0310-9e8f-d4a2fc68ab70
drools-core/src/main/java/org/drools/rule/Declaration.java
Adding primitive methods to Declaration interface
<ide><path>rools-core/src/main/java/org/drools/rule/Declaration.java <ide> return this.extractor.getValue( object ); <ide> } <ide> <add> public char getCharValue(Object object) { <add> return this.extractor.getCharValue( object ); <add> } <add> <add> public int getIntValue(Object object) { <add> return this.extractor.getIntValue( object ); <add> } <add> <add> public byte getByteValue(Object object) { <add> return this.extractor.getByteValue( object ); <add> } <add> <add> public short getShortValue(Object object) { <add> return this.extractor.getShortValue( object ); <add> } <add> <add> public long getLongValue(Object object) { <add> return this.extractor.getLongValue( object ); <add> } <add> <add> public float getFloatValue(Object object) { <add> return this.extractor.getFloatValue( object ); <add> } <add> <add> public double getDoubleValue(Object object) { <add> return this.extractor.getDoubleValue( object ); <add> } <add> <add> public boolean getBooleanValue(Object object) { <add> return this.extractor.getBooleanValue( object ); <add> } <add> <ide> // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - <ide> <ide> public String toString() {
JavaScript
mit
6ccb8deb7953852608a0564a9a5544bb658a0cdf
0
NAPWebProductionEditTeam/MagTool2,NAPWebProductionEditTeam/MagTool2,NAPWebProductionEditTeam/MagTool2
(function(window, Math, $, app, Medium) { var parseInt = window.parseInt; var parseFloat = window.parseFloat; var document = window.document; function ContentEditor() { var editing = false; /** * Editor status. */ this.startEdit = function() { editing = true; this.makeDraggable(); this.makeResizable(); this.makeSelectable(); this.makeEditable(); }; this.applyEdit = function($el) { this.applyDraggable($el); this.applyResizable($el); this.applySelectable($el); }; this.stopEdit = function() { this.removeSelectable(); this.removeResizable(); this.removeDraggable(); editing = false; }; this.isEditing = function() { return editing; }; this.getSelection = function() { return app.Page.get().find('.ui-selected'); }; this.getSelectionType = function() { var $selection = this.getSelection(); var types = []; if (! $selection.length) { return 'none'; } $selection.each(function() { var $this = $(this); if ($this.find('img').length) { types.push('image'); } else if ($this.filter('[class*="creditsWhole"]').length) { types.push('credits'); } else { types.push('text'); } }); types = $.unique(types); if (types.length === 1) { return types[0]; } return 'mixed'; }; /** * Content interactions. */ var $selectable, $selected, $selectables, $draggables, $resizables, $editables; $selected = $selectables = $draggables = $resizables = $editables = $([]); var triggerSelectable = function() { var selectable = $selectable.selectable('instance'); if (selectable) { $selectable.selectable('instance')._mouseStop(null); } }; this.select = function($el) { $el.addClass('ui-selecting'); triggerSelectable(); }; this.deselectAll = function() { $selected.removeClass('ui-selected'); triggerSelectable(); }; var deselect = function($el) { $el.removeClass('ui-selected'); triggerSelectable(); }; var addSelected = function(el) { $selected = $selected.add(el); $(el).addClass('ui-selected'); }; this.applySelectable = function($el) { $selectables.add($el); if ($el.length) { $el.click(function(e) { var $this = $(this); // win ctrl || OS X cmd || shift if (e.ctrlKey || e.metaKey || e.shiftKey) { if ($this.hasClass('ui-selected')) { return deselect($this); } } else { $selectable.find('.ui-selected').removeClass('ui-selected'); $selected = $([]); } app.ContentEditor.select($this); }); } }; this.makeSelectable = function() { var selectableSelector = '.draggable, .editable, .resizable, [class*="creditsWhole"]'; $selectable = app.Page.getContent(); $selectable.selectable({ filter: selectableSelector, cancel: '[class*="creditsHolder"]', selected: function(e, ui) { addSelected(ui.selected); }, unselected: function(e, ui) { $selected = $selected.not(ui.unselected); }, stop: function() { app.resolveAction('updateUI'); } }); this.applySelectable($selectable.find(selectableSelector)); }; this.removeSelectable = function() { deselect($selectables); $selectables.off('click'); if ($selectable.is('.ui-selectable')) { $selectable.selectable('destroy'); } }; this.getSelectedElements = function() { return app.Page.get().find('.ui-selected'); }; var changeXPos = function($this) { var left = parseInt($this.css('left')); if ($this.is('[class*=push-right]')) { var push_right = Math.round(left / 19); $this.removeClass(function(index, css) { return (css.match(/\bpush-right\S+/g) || []).join(' '); }); $this.addClass('push-right-' + push_right); } else { var right = 950 - left - $this.outerWidth(); var pull_left = Math.round(right / 19); $this.removeClass(function(index, css) { return (css.match(/\bpull-left-\S+/g) || []).join(' '); }); $this.addClass('pull-left-' + pull_left); } }; this.applyDraggable = function($el) { $draggables.add($el); if ($el.length) { $el.draggable({ cursor: "move", start: function(e, ui) { var $this = $(this); stopEditing($this); if ($this.hasClass('ui-selected')) { $selected = $selected.filter('.draggable').each(function() { var $this = $(this); $this.data('offset', $this.position()); }); window.$selected = $selected; } else { $selected = $([]); $this.data('offset', $this.position()); app.Page.getContent().find('.ui-selected').removeClass('ui-selected'); } addSelected($this); }, drag: function(e, ui) { var $this = $(this); var drag = { top: ui.position.top - $this.data('offset').top, left: ui.position.left - $this.data('offset').left, }; $selected.not($this).filter('.draggable').each(function() { var $this = $(this); $this.addClass('ui-draggable-dragging').css({top: $this.data('offset').top + drag.top, left: $this.data('offset').left + drag.left}); }); }, stop: function(e, ui) { $selected.each(function() { var $this = $(this); var top = parseInt($this.css('top')); if ($this.is('[class*=push-down]')) { var push_down = Math.round(top / 16); $this.removeClass(function(index, css) { return (css.match(/\bpush-down\S+/g) || []).join(' '); }); $this.addClass('push-down-' + push_down); } else { var bottom = 624 - top - $this.outerHeight(); var pull_up = Math.round(bottom / 16); $this.removeClass(function(index, css) { return (css.match(/\bpull-up\S+/g) || []).join(' '); }); $this.addClass('pull-up-' + pull_up); } changeXPos($this); }).removeClass('ui-draggable-dragging').removeAttr('style'); }, grid: [19, 16] }); } }; this.makeDraggable = function() { this.applyDraggable(app.Page.getContent().find('.draggable')); }; this.enableDraggable = function($el) { if (typeof $el !== 'undefined') { return $el.draggable('enable'); } $draggables.filter('.ui-draggable').draggable('enable'); }; this.disableDraggable = function($el) { if (typeof $el !== 'undefined') { return $el.draggable('disable'); } $draggables.filter('.ui-draggable').draggable('disable'); }; this.removeDraggable = function($el) { $draggables.filter('.ui-draggable').draggable('destroy'); }; this.move = function(axis, ticks) { var $selection = this.getSelection(); var maxCols = 50.75; var maxRows = 39.75; if (typeof ticks === 'undefined') { ticks = .25; } else { ticks = ticks / 4; } $selection.each(function() { var $el = $(this); var dir, current, result, affix, newClass; if (axis === 'y') { dir = $el.attr('class').replace(/.*(?:push|pull)-(up|down)-.*/, '$1'); current = parseFloat( $el.attr('class') .replace(/.*(?:push|pull)-(?:up|down)-(\d+(?:-[a-c])?).*/, '$1') .replace('-a', '.25') .replace('-b', '.5') .replace('-c', '.75') ); result = dir === 'down' ? (current - ticks) : (current + ticks); result = Math.min(result, maxRows); result = Math.max(result, 0); affix = result.toString().replace('.25', '-a').replace('.5', '-b').replace('.75', '-c'); newClass = $el.attr('class').replace(/(push|pull)-(up|down)-\d+(?:-[a-c])?/, '$1-$2-' + affix); $el.attr('class', newClass); } else { dir = $el.attr('class').replace(/.*(?:push|pull)-(left|right)-.*/, '$1'); current = parseFloat( $el.attr('class') .replace(/.*(?:push|pull)-(?:left|right)-(\d+(?:-[a-c])?).*/, '$1') .replace('-a', '.25') .replace('-b', '.5') .replace('-c', '.75') ); result = dir === 'left' ? (current - ticks) : (current + ticks); result = Math.min(result, maxCols); result = Math.max(result, 0); affix = result.toString().replace('.25', '-a').replace('.5', '-b').replace('.75', '-c'); newClass = $el.attr('class').replace(/(push|pull)-(left|right)-\d+(?:-[a-c])?/, '$1-$2-' + affix); $el.attr('class', newClass); } }); }; this.applyResizable = function($el) { $resizables.add($el); if ($el.length) { $el.resizable({ handles: 'e, w', grid: [19, 10], start: function() { stopEditing($(this)); }, stop: function() { var $this = $(this); var width = parseInt($this.css('width')); if ($(this).is('[class*=span]')) { var span = Math.round(width / 19); $this.removeClass(function(index, css) { return (css.match(/\bspan-\S+/g) || []).join(' '); }); $this.addClass('span-' + span); } changeXPos($this); $this.removeAttr("style"); } }); } }; this.makeResizable = function() { this.applyResizable(app.Page.getContent().find('.resizable')); }; this.enableResizable = function($el) { if (typeof $el !== 'undefined') { return $el.resizable('enable'); } $resizables.filter('.ui-resizable').resizable('enable'); }; this.disableResizable = function($el) { if (typeof $el !== 'undefined') { return $el.resizable('disable'); } $resizables.filter('.ui-resizable').resizable('disable'); }; this.removeResizable = function() { $resizables.filter('.ui-resizable').resizable('destroy'); }; var editor, $editing; var makeEditor = function(selector) { return new Medium.editor(selector, { disableExtraSpaces: true, toolbar: { buttons: [ 'b', 'i', 'anchor', 'h2', 'h3', 'h4', 'h5', 'span', 'case' ] }, extensions: { 'b': new Medium.button({ label: '<b>B</b>', start: '<strong>', end: '</strong>' }), 'i': new Medium.button({ label: '<b><i>I</i></b>', start: '<em>', end: '</em>' }), 'span': new Medium.button({ label: '<b>span</b>', start: '<span>', end: '</span>' }), 'case': new Medium.button({ label: '<b>Aa</b>', start: '<span class="upperCase">', end: '</span>' }) } }); }; var startEditing = function($el) { deselect($selectables); app.ContentEditor.select($el); if ($el.find('.dropcap3')) { var $dropcap = $el.find('.dropcap3'); var classes = []; if ($dropcap.data('class')) { classes = $dropcap.data('class').split(' '); } classes.push('dropcap3'); $dropcap.attr('data-class', classes.join(' ')).removeClass('dropcap3'); } app.ContentEditor.disableDraggable($el); app.ContentEditor.disableResizable($el); app.ContentEditor.removeSelectable(); editor = window.editor = makeEditor($el); $el.click(); // trigger a click to make sure it has focus. editor.selectElement(editor.getFocusedElement()); // Now select the element that has focus et voilá! $(document).data('click', function(e) { if (! $editing) { return; } var $target = $(e.target); var $medium = $('[id*=medium-]'); var stop = true; if ($target.is($el) || $.contains($el.get(0), e.target)) { stop = false; } for (var i = 0; i < $medium.length; i++) { if ($.contains($medium.get(i), e.target)) { stop = false; break; } } if (stop) { stopEditing(); } }); $(document).click($(document).data('click')); $editing = $el; }; window.startEdit = startEditing; var stopEditing = function() { if (! $editing) { return; } var $el = $editing; window.getSelection().collapseToStart(); editor.destroy(); $editing = null; $(document).off('click', $(document).data('click')); $el.find('[data-class]').each(function() { var $child = $(this); $child.addClass($child.data('class')); }); app.ContentEditor.enableDraggable($el); app.ContentEditor.enableResizable($el); app.ContentEditor.makeSelectable(); app.ContentEditor.makeEditable(); app.ContentEditor.select($el); }; this.applyEditable = function($el) { console.log('apply edi'); $editables.add($el); $el.dblclick(function(e) { var $this = $(this); console.log("CLICK OCCUREEDEJSFHSDGKDSJG"); // If we are currently editing a different element, // stop editing it. if ($editing) { stopEditing($editing); } $this.off('dblclick'); startEditing($this); }); }; this.makeEditable = function() { console.log('make edi'); this.applyEditable(app.Page.getContent().find('.editable')); }; this.removeEditable = function() { window.getSelection().collapseToStart(); editor.destroy(); $editing = null; $('.editable').off('dblclick'); $('.editable').off('blur'); }; } app.modules.ContentEditor = ContentEditor; })(window, Math, jQuery, MagTool, {editor: MediumEditor, button: MediumButton});
src/js/Application/ContentEditor.js
(function(window, Math, $, app, Medium) { var parseInt = window.parseInt; var parseFloat = window.parseFloat; var document = window.document; function ContentEditor() { var editing = false; /** * Editor status. */ this.startEdit = function() { editing = true; this.makeDraggable(); this.makeResizable(); this.makeSelectable(); this.makeEditable(); }; this.applyEdit = function($el) { this.applyDraggable($el); this.applyResizable($el); this.applySelectable($el); }; this.stopEdit = function() { this.removeSelectable(); this.removeResizable(); this.removeDraggable(); editing = false; }; this.isEditing = function() { return editing; }; this.getSelection = function() { return app.Page.get().find('.ui-selected'); }; this.getSelectionType = function() { var $selection = this.getSelection(); var types = []; $selection.each(function() { var $this = $(this); if ($this.find('img').length) { types.push('image'); } else if ($this.filter('[class*="creditsWhole"]').length) { types.push('credits'); } else { types.push('text'); } }); types = $.unique(types); if (types.length === 1) { return types[0]; } return 'mixed'; }; /** * Content interactions. */ var $selectable, $selected, $selectables, $draggables, $resizables, $editables; $selected = $selectables = $draggables = $resizables = $editables = $([]); var triggerSelectable = function() { var selectable = $selectable.selectable('instance'); if (selectable) { $selectable.selectable('instance')._mouseStop(null); } }; this.select = function($el) { $el.addClass('ui-selecting'); triggerSelectable(); }; this.deselectAll = function() { $selected.removeClass('ui-selected'); triggerSelectable(); }; var deselect = function($el) { $el.removeClass('ui-selected'); triggerSelectable(); }; var addSelected = function(el) { $selected = $selected.add(el); $(el).addClass('ui-selected'); }; this.applySelectable = function($el) { $selectables.add($el); if ($el.length) { $el.click(function(e) { var $this = $(this); // win ctrl || OS X cmd || shift if (e.ctrlKey || e.metaKey || e.shiftKey) { if ($this.hasClass('ui-selected')) { return deselect($this); } } else { $selectable.find('.ui-selected').removeClass('ui-selected'); $selected = $([]); } app.ContentEditor.select($this); }); } }; this.makeSelectable = function() { var selectableSelector = '.draggable, .editable, .resizable, [class*="creditsWhole"]'; $selectable = app.Page.getContent(); $selectable.selectable({ filter: selectableSelector, cancel: '[class*="creditsHolder"]', selected: function(e, ui) { addSelected(ui.selected); }, unselected: function(e, ui) { $selected = $selected.not(ui.unselected); }, stop: function() { app.resolveAction('updateUI'); } }); this.applySelectable($selectable.find(selectableSelector)); }; this.removeSelectable = function() { deselect($selectables); $selectables.off('click'); if ($selectable.is('.ui-selectable')) { $selectable.selectable('destroy'); } }; this.getSelectedElements = function() { return app.Page.get().find('.ui-selected'); }; var changeXPos = function($this) { var left = parseInt($this.css('left')); if ($this.is('[class*=push-right]')) { var push_right = Math.round(left / 19); $this.removeClass(function(index, css) { return (css.match(/\bpush-right\S+/g) || []).join(' '); }); $this.addClass('push-right-' + push_right); } else { var right = 950 - left - $this.outerWidth(); var pull_left = Math.round(right / 19); $this.removeClass(function(index, css) { return (css.match(/\bpull-left-\S+/g) || []).join(' '); }); $this.addClass('pull-left-' + pull_left); } }; this.applyDraggable = function($el) { $draggables.add($el); if ($el.length) { $el.draggable({ cursor: "move", start: function(e, ui) { var $this = $(this); stopEditing($this); if ($this.hasClass('ui-selected')) { $selected = $selected.filter('.draggable').each(function() { var $this = $(this); $this.data('offset', $this.position()); }); window.$selected = $selected; } else { $selected = $([]); $this.data('offset', $this.position()); app.Page.getContent().find('.ui-selected').removeClass('ui-selected'); } addSelected($this); }, drag: function(e, ui) { var $this = $(this); var drag = { top: ui.position.top - $this.data('offset').top, left: ui.position.left - $this.data('offset').left, }; $selected.not($this).filter('.draggable').each(function() { var $this = $(this); $this.addClass('ui-draggable-dragging').css({top: $this.data('offset').top + drag.top, left: $this.data('offset').left + drag.left}); }); }, stop: function(e, ui) { $selected.each(function() { var $this = $(this); var top = parseInt($this.css('top')); if ($this.is('[class*=push-down]')) { var push_down = Math.round(top / 16); $this.removeClass(function(index, css) { return (css.match(/\bpush-down\S+/g) || []).join(' '); }); $this.addClass('push-down-' + push_down); } else { var bottom = 624 - top - $this.outerHeight(); var pull_up = Math.round(bottom / 16); $this.removeClass(function(index, css) { return (css.match(/\bpull-up\S+/g) || []).join(' '); }); $this.addClass('pull-up-' + pull_up); } changeXPos($this); }).removeClass('ui-draggable-dragging'); }, grid: [19, 16] }); } }; this.makeDraggable = function() { this.applyDraggable(app.Page.getContent().find('.draggable')); }; this.enableDraggable = function($el) { if (typeof $el !== 'undefined') { return $el.draggable('enable'); } $draggables.filter('.ui-draggable').draggable('enable'); }; this.disableDraggable = function($el) { if (typeof $el !== 'undefined') { return $el.draggable('disable'); } $draggables.filter('.ui-draggable').draggable('disable'); }; this.removeDraggable = function($el) { $draggables.filter('.ui-draggable').draggable('destroy'); }; this.move = function(axis, ticks) { var $selection = this.getSelection(); if (typeof ticks === 'undefined') { ticks = .25; } else { ticks = ticks / 4; } $selection.each(function() { var $el = $(this); var dir, current, result, affix, newClass; if (axis === 'y') { dir = $el.attr('class').replace(/.*(?:push|pull)-(up|down)-.*/, '$1'); current = parseFloat( $el.attr('class') .replace(/.*(?:push|pull)-(?:up|down)-(\d+(?:-[a-c])?).*/, '$1') .replace('-a', '.25') .replace('-b', '.5') .replace('-c', '.75') ); if (dir === 'down') { ticks = -ticks; } result = current + ticks; affix = result.toString().replace('.25', '-a').replace('.5', '-b').replace('.75', '-c'); newClass = $el.attr('class').replace(/(push|pull)-(up|down)-\d+(?:-[a-c])?/, '$1-$2-' + affix); $el.attr('class', newClass); } else { dir = $el.attr('class').replace(/.*(?:push|pull)-(left|right)-.*/, '$1'); current = parseFloat( $el.attr('class') .replace(/.*(?:push|pull)-(?:left|right)-(\d+(?:-[a-c])?).*/, '$1') .replace('-a', '.25') .replace('-b', '.5') .replace('-c', '.75') ); if (dir === 'left') { ticks = -ticks; } result = current + ticks; affix = result.toString().replace('.25', '-a').replace('.5', '-b').replace('.75', '-c'); newClass = $el.attr('class').replace(/(push|pull)-(left|right)-\d+(?:-[a-c])?/, '$1-$2-' + affix); $el.attr('class', newClass); } }); }; this.applyResizable = function($el) { $resizables.add($el); if ($el.length) { $el.resizable({ handles: 'e, w', grid: [19, 10], start: function() { stopEditing($(this)); }, stop: function() { var $this = $(this); var width = parseInt($this.css('width')); if ($(this).is('[class*=span]')) { var span = Math.round(width / 19); $this.removeClass(function(index, css) { return (css.match(/\bspan-\S+/g) || []).join(' '); }); $this.addClass('span-' + span); } changeXPos($this); $this.removeAttr("style"); } }); } }; this.makeResizable = function() { this.applyResizable(app.Page.getContent().find('.resizable')); }; this.enableResizable = function($el) { if (typeof $el !== 'undefined') { return $el.resizable('enable'); } $resizables.filter('.ui-resizable').resizable('enable'); }; this.disableResizable = function($el) { if (typeof $el !== 'undefined') { return $el.resizable('disable'); } $resizables.filter('.ui-resizable').resizable('disable'); }; this.removeResizable = function() { $resizables.filter('.ui-resizable').resizable('destroy'); }; var editor, $editing; var makeEditor = function(selector) { return new Medium.editor(selector, { disableExtraSpaces: true, toolbar: { buttons: [ 'b', 'i', 'anchor', 'h2', 'h3', 'h4', 'h5', 'span', 'case' ] }, extensions: { 'b': new Medium.button({ label: '<b>B</b>', start: '<strong>', end: '</strong>' }), 'i': new Medium.button({ label: '<b><i>I</i></b>', start: '<em>', end: '</em>' }), 'span': new Medium.button({ label: '<b>span</b>', start: '<span>', end: '</span>' }), 'case': new Medium.button({ label: '<b>Aa</b>', start: '<span class="upperCase">', end: '</span>' }) } }); }; var startEditing = function($el) { deselect($selectables); app.ContentEditor.select($el); if ($el.find('.dropcap3')) { var $dropcap = $el.find('.dropcap3'); var classes = []; if ($dropcap.data('class')) { classes = $dropcap.data('class').split(' '); } classes.push('dropcap3'); $dropcap.attr('data-class', classes.join(' ')).removeClass('dropcap3'); } app.ContentEditor.disableDraggable($el); app.ContentEditor.disableResizable($el); app.ContentEditor.removeSelectable(); editor = window.editor = makeEditor($el); $el.click(); // trigger a click to make sure it has focus. editor.selectElement(editor.getFocusedElement()); // Now select the element that has focus et voilá! $(document).data('click', function(e) { if (! $editing) { return; } var $target = $(e.target); var $medium = $('[id*=medium-]'); var stop = true; if ($target.is($el) || $.contains($el.get(0), e.target)) { stop = false; } for (var i = 0; i < $medium.length; i++) { if ($.contains($medium.get(i), e.target)) { stop = false; break; } } if (stop) { stopEditing(); } }); $(document).click($(document).data('click')); $editing = $el; }; window.startEdit = startEditing; var stopEditing = function() { if (! $editing) { return; } var $el = $editing; window.getSelection().collapseToStart(); editor.destroy(); $editing = null; $(document).off('click', $(document).data('click')); $el.find('[data-class]').each(function() { var $child = $(this); $child.addClass($child.data('class')); }); app.ContentEditor.enableDraggable($el); app.ContentEditor.enableResizable($el); app.ContentEditor.makeSelectable(); app.ContentEditor.makeEditable(); app.ContentEditor.select($el); }; this.applyEditable = function($el) { console.log('apply edi'); $editables.add($el); $el.dblclick(function(e) { var $this = $(this); console.log("CLICK OCCUREEDEJSFHSDGKDSJG"); // If we are currently editing a different element, // stop editing it. if ($editing) { stopEditing($editing); } $this.off('dblclick'); startEditing($this); }); }; this.makeEditable = function() { console.log('make edi'); this.applyEditable(app.Page.getContent().find('.editable')); }; this.removeEditable = function() { window.getSelection().collapseToStart(); editor.destroy(); $editing = null; $('.editable').off('dblclick'); $('.editable').off('blur'); }; } app.modules.ContentEditor = ContentEditor; })(window, Math, jQuery, MagTool, {editor: MediumEditor, button: MediumButton});
Move fixes
src/js/Application/ContentEditor.js
Move fixes
<ide><path>rc/js/Application/ContentEditor.js <ide> var $selection = this.getSelection(); <ide> var types = []; <ide> <add> if (! $selection.length) { <add> return 'none'; <add> } <add> <ide> $selection.each(function() { <ide> var $this = $(this); <ide> <ide> if ($el.length) { <ide> $el.click(function(e) { <ide> var $this = $(this); <del> <add> <ide> // win ctrl || OS X cmd || shift <ide> if (e.ctrlKey || e.metaKey || e.shiftKey) { <ide> if ($this.hasClass('ui-selected')) { <ide> $selectable.find('.ui-selected').removeClass('ui-selected'); <ide> $selected = $([]); <ide> } <del> <add> <ide> app.ContentEditor.select($this); <ide> }); <ide> } <ide> cursor: "move", <ide> start: function(e, ui) { <ide> var $this = $(this); <del> <add> <ide> stopEditing($this); <del> <add> <ide> if ($this.hasClass('ui-selected')) { <ide> $selected = $selected.filter('.draggable').each(function() { <ide> var $this = $(this); <del> <add> <ide> $this.data('offset', $this.position()); <ide> }); <del> <add> <ide> window.$selected = $selected; <ide> } else { <ide> $selected = $([]); <ide> $this.data('offset', $this.position()); <ide> app.Page.getContent().find('.ui-selected').removeClass('ui-selected'); <ide> } <del> <add> <ide> addSelected($this); <ide> }, <ide> drag: function(e, ui) { <ide> top: ui.position.top - $this.data('offset').top, <ide> left: ui.position.left - $this.data('offset').left, <ide> }; <del> <add> <ide> $selected.not($this).filter('.draggable').each(function() { <ide> var $this = $(this); <del> <add> <ide> $this.addClass('ui-draggable-dragging').css({top: $this.data('offset').top + drag.top, left: $this.data('offset').left + drag.left}); <ide> }); <ide> }, <ide> $selected.each(function() { <ide> var $this = $(this); <ide> var top = parseInt($this.css('top')); <del> <add> <ide> if ($this.is('[class*=push-down]')) { <ide> var push_down = Math.round(top / 16); <del> <add> <ide> $this.removeClass(function(index, css) { <ide> return (css.match(/\bpush-down\S+/g) || []).join(' '); <ide> }); <del> <add> <ide> $this.addClass('push-down-' + push_down); <ide> } else { <ide> var bottom = 624 - top - $this.outerHeight(); <ide> var pull_up = Math.round(bottom / 16); <del> <add> <ide> $this.removeClass(function(index, css) { <ide> return (css.match(/\bpull-up\S+/g) || []).join(' '); <ide> }); <del> <add> <ide> $this.addClass('pull-up-' + pull_up); <ide> } <del> <add> <ide> changeXPos($this); <del> }).removeClass('ui-draggable-dragging'); <add> }).removeClass('ui-draggable-dragging').removeAttr('style'); <ide> }, <ide> grid: [19, 16] <ide> }); <ide> <ide> this.move = function(axis, ticks) { <ide> var $selection = this.getSelection(); <add> var maxCols = 50.75; <add> var maxRows = 39.75; <ide> <ide> if (typeof ticks === 'undefined') { <ide> ticks = .25; <ide> .replace('-c', '.75') <ide> ); <ide> <del> if (dir === 'down') { <del> ticks = -ticks; <del> } <del> <del> result = current + ticks; <add> result = dir === 'down' ? (current - ticks) : (current + ticks); <add> result = Math.min(result, maxRows); <add> result = Math.max(result, 0); <add> <ide> affix = result.toString().replace('.25', '-a').replace('.5', '-b').replace('.75', '-c'); <ide> newClass = $el.attr('class').replace(/(push|pull)-(up|down)-\d+(?:-[a-c])?/, '$1-$2-' + affix); <ide> <ide> dir = $el.attr('class').replace(/.*(?:push|pull)-(left|right)-.*/, '$1'); <ide> current = parseFloat( <ide> $el.attr('class') <del> .replace(/.*(?:push|pull)-(?:left|right)-(\d+(?:-[a-c])?).*/, '$1') <del> .replace('-a', '.25') <del> .replace('-b', '.5') <del> .replace('-c', '.75') <del> ); <del> <del> if (dir === 'left') { <del> ticks = -ticks; <del> } <del> <del> result = current + ticks; <add> .replace(/.*(?:push|pull)-(?:left|right)-(\d+(?:-[a-c])?).*/, '$1') <add> .replace('-a', '.25') <add> .replace('-b', '.5') <add> .replace('-c', '.75') <add> ); <add> <add> result = dir === 'left' ? (current - ticks) : (current + ticks); <add> result = Math.min(result, maxCols); <add> result = Math.max(result, 0); <add> <ide> affix = result.toString().replace('.25', '-a').replace('.5', '-b').replace('.75', '-c'); <ide> newClass = $el.attr('class').replace(/(push|pull)-(left|right)-\d+(?:-[a-c])?/, '$1-$2-' + affix); <ide>
Java
apache-2.0
adb897a09928bc05fccb15fd7f520334f8d70b7d
0
Witerium/stuffEngine,AMaiyndy/employees,AMaiyndy/employees,AMaiyndy/employees,Witerium/stuffEngine
package ru.technoserv.dao; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.criterion.Restrictions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.context.annotation.Bean; import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import java.math.BigDecimal; import java.util.List; @Repository @Transactional public class HibernateEmployeeDao implements EmployeeDao { @Autowired private SessionFactory sessionFactory; private Session getSession(){ return sessionFactory.getCurrentSession(); } @Override public int getID() { return getAllEmployees().size(); } @Override public void create(Employee employee) { Session session = getSession(); try{ session.beginTransaction(); session.save(employee); session.getTransaction().commit(); }catch (RuntimeException e){ session.getTransaction().rollback(); throw e; } } @Override public Employee read(int empID) { Employee dbEmployee; Session session = getSession(); try { session.beginTransaction(); dbEmployee = (Employee) session.get(Employee.class, empID); session.getTransaction().commit(); }catch (RuntimeException e) { session.getTransaction().rollback(); throw e; } return dbEmployee; } @Override public void delete(int empID) { Session session = getSession(); try{ session.beginTransaction(); session.delete( session.get(Employee.class, empID)); session.getTransaction().commit(); }catch (RuntimeException e){ session.getTransaction().rollback(); throw e; } } @Override public List<Employee> getAllFromDept(int deptID) { Session session = getSession(); List<Employee> employees; try{ session.beginTransaction(); employees = session.createQuery("from Employee E where E.department ="+deptID).list(); session.getTransaction().commit(); }catch (RuntimeException e){ session.getTransaction().rollback(); throw e; } return employees; } @Override public Employee updateEmployee(Employee employee) { Session session = getSession(); try{ session.beginTransaction(); session.update(employee); session.getTransaction().commit(); }catch (RuntimeException e){ session.getTransaction().rollback(); throw e; } return read(employee.getEmpID()); } public List<Employee> getAllEmployees(){ Session session = getSession(); List<Employee> employees; try{ session.beginTransaction(); employees = session.createQuery("from Employee").list(); session.getTransaction().commit(); }catch (RuntimeException e){ session.getTransaction().rollback(); throw e; } return employees; } }
src/main/java/ru/technoserv/dao/HibernateEmployeeDao.java
package ru.technoserv.dao; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.criterion.Restrictions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.context.annotation.Bean; import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import java.math.BigDecimal; import java.util.List; @Repository @Transactional public class HibernateEmployeeDao implements EmployeeDao { @Autowired private SessionFactory sessionFactory; private Session getSession(){ return sessionFactory.getCurrentSession(); } @Override public int getID() { return getAllEmployees().size(); } @Override public void create(Employee employee) { Session session = getSession(); try{ session.beginTransaction(); session.save(employee); session.getTransaction().commit(); }catch (RuntimeException e){ session.getTransaction().rollback(); throw e; } } @Override public Employee read(int empID) { Employee dbEmployee; Session session = getSession(); try { session.beginTransaction(); dbEmployee = (Employee) session.get(Employee.class, empID); session.getTransaction().commit(); }catch (RuntimeException e) { session.getTransaction().rollback(); throw e; } return dbEmployee; } @Override public void delete(int empID) { Session session = getSession(); try{ session.beginTransaction(); session.delete( session.get(Employee.class, empID)); session.getTransaction().commit(); }catch (RuntimeException e){ session.getTransaction().rollback(); throw e; } } @Override public List<Employee> getAllFromDept(int deptID) { Session session = getSession(); List<Employee> employees; try{ session.beginTransaction(); employees = session.createQuery("from Employee E where E.department ="+deptID).list(); session.getTransaction().commit(); }catch (RuntimeException e){ session.getTransaction().rollback(); throw e; } return employees; } @Override public Employee updateEmployee(Employee employee) { Session session = getSession(); try{ session.beginTransaction(); session.update(employee); session.getTransaction().commit(); }catch (RuntimeException e){ session.getTransaction().rollback(); throw e; } return read(employee.getEmpID()); } public List<Employee> getAllEmployees(){ Session session = getSession(); return session.createQuery("from Employee").list(); } }
В HibernateEmployeeDao возвращена транзакция для создания сотрудника
src/main/java/ru/technoserv/dao/HibernateEmployeeDao.java
В HibernateEmployeeDao возвращена транзакция для создания сотрудника
<ide><path>rc/main/java/ru/technoserv/dao/HibernateEmployeeDao.java <ide> <ide> public List<Employee> getAllEmployees(){ <ide> Session session = getSession(); <del> return session.createQuery("from Employee").list(); <add> List<Employee> employees; <add> try{ <add> session.beginTransaction(); <add> employees = session.createQuery("from Employee").list(); <add> session.getTransaction().commit(); <add> }catch (RuntimeException e){ <add> session.getTransaction().rollback(); <add> throw e; <add> } <add> return employees; <ide> } <ide> <ide>
JavaScript
mit
03dfc4762d075fa0418d8844586553345c7cfe2c
0
coderaiser/minify
"use strict"; /* Модуль сжатия js-скриптов, css-стилей, html-файлов и * конвертации картинок в css-стилях * в base64 и помещения их в файл стилей */ var Minify = {}; console.log('minify.js loaded...'); /* функция сжимает js-скрипты * и сохраняет их с именем .min.js */ var fs = require('fs'), path = require('path'), crypto = require('crypto'); /* object contains hashes of files*/ var Hashes; var HashesChanged; var html = cloudRequire('./lib/html'); var js = cloudRequire('./lib/js'); var css = cloudRequire('./lib/css'); if(!html || !js || !css) console.log('One of the necessary modules is absent\n' + 're-install the modules\n' + 'npm r minify\n' + 'npm i minify'); else{ Minify._uglifyJS = js._uglifyJS; Minify._cleanCSS = css._cleanCSS; Minify.htmlMinify = html.htmlMinify; } var MinFolder='min/'; /* function clear MinFolder * if we could not create * directory and it is * not exist */ var folderExist = function(pError, pStat){ "use strict"; /*file found and it's directory */ if(!pError && pStat.isDirectory()) console.log('folder exist: ' + MinFolder); else MinFolder='/'; }; /* * function says thet folder created * if everything is OK, or * moves to folderExist function */ var makeFolder = function(pError){ "use strict"; /*folder created successfully*/ if(!pError) console.log('folder created: min'); else fs.stat(MinFolder,folderExist); }; /* Trying to create folder min * where woud be minifyed versions * of files 511(10)=777(8) * rwxrwxrwx */ fs.mkdir(MinFolder, 511, makeFolder); exports.MinFolder = MinFolder; exports.Cache = {}; /** * Функция ищет в имени файла расширение * и если находит возвращает true * @param pName * @param pExt */ Minify._checkExtension = function(pName, pExt) { /* если длина имени больше * длинны расширения - * имеет смысл продолжать */ if (typeof pExt === 'string' && pName.length > pExt.length) { var lLength = pName.length; /* длина имени*/ var lExtNum = pName.lastIndexOf(pExt); /* последнее вхождение расширения*/ var lExtSub = lLength - lExtNum; /* длина расширения*/ /* если pExt - расширение pName */ return lExtSub === pExt.length; }else if(typeof pExt === 'object' && pExt.length){ for(var i=0; i < pName.length; i++) if(this.checkExtension(pName, pExt[i])) return true; }else return false; }; /** * function gets file extension * @param pFileName * @return Ext */ Minify._getExtension = function(pFileName){ /* checking for js/html/css */ var lDot = pFileName.lastIndexOf('.'); return pFileName.substr(lDot); }; /** * function minificate js,css and html files * @param pFiles_a - array of js, css and html file names or string, if name * single, or object if postProcessing neaded * {'client.js': function(pFinalCode){} } * or convertion images to base64 neaded * {'style.css': true} * or {'style.css':{minimize: true, func: function(){}} * * @param pOptions - object contain main options * if cache true files do not writes on disk, just saves * in Minify Cache * Example: * {cache: false, gzip: true, callback: func(){}} */ exports.optimize = function(pFiles_a, pOptions){ 'use strict'; /* if passed string, or object * putting it to array */ if (typeof pFiles_a === 'string' || !pFiles_a[0]) pFiles_a=[pFiles_a]; var lName = ''; var lAllCSS = ''; var lCSS_o = null; /* varible contains all readed file names */ var lReadedFilesCount = 0; /* * Processing of files * @pFileName - name of file * @pData - data of file * @pForce - minify file anyway */ var dataReaded_f = function(pFileName, pData){ ++lReadedFilesCount; var lLastFile_b; /* if leng this not equal * file not last */ if (lReadedFilesCount === pFiles_a.length) lLastFile_b = true; /* * if postProcessing function exist * getting it from pFileName object */ var lMoreProcessing_f; if(typeof pFileName === 'object'){ var lName; for(lName in pFileName){ break; } lMoreProcessing_f = pFileName[lName]; pFileName = lName; } console.log('file ' + pFileName + ' readed'); var lExt = Minify._getExtension(pFileName); var minFileName = pFileName.replace(lExt, '.min' + lExt); minFileName = path.basename(minFileName); minFileName = MinFolder + minFileName; /* functin minimize files */ var lProcessing_f = function(){ var final_code; /* getting optimized version */ switch(lExt){ case '.js': final_code = Minify._uglifyJS(pData); break; case '.html': final_code = Minify.htmlMinify(pData); break; case '.css': final_code = Minify._cleanCSS(pData); lAllCSS += final_code; lCSS_o = lMoreProcessing_f; if (typeof lCSS_o === 'object'){ lMoreProcessing_f = lCSS_o.moreProcessing; } break; default: return console.log('unknow file type ' + lExt + ', only *.js, *.css, *.html'); } /* if it's last file * and base64images setted up * se should convert it */ if (lLastFile_b && (lCSS_o && lCSS_o.img || lCSS_o === true)){ base64_images(lAllCSS); } /* if lMoreProcessing_f seeted up * and function associated with * current file name exists - * run it */ if(lMoreProcessing_f && typeof lMoreProcessing_f === "function"){ final_code = lMoreProcessing_f(final_code); } /* записываем сжатый js-скрипт * в кэш если установлен pCache_b * или на диск, если не установлен */ if(pOptions && pOptions.cache){ exports.Cache[minFileName] = final_code; console.log('file ' + minFileName + ' saved to cache...'); } /* minimized file will be in min file * if it's possible if not - * in root */ fs.writeFile(minFileName, final_code, fileWrited(minFileName)); /* calling callback function if it exist */ if(pOptions && pOptions.callback && typeof pOptions.callback === 'function') pOptions.callback(final_code); }; if(pOptions && pOptions.force || isFileChanged(pFileName, pData, lLastFile_b)) lProcessing_f(); /* if file was not changed */ else{ fs.readFile(minFileName, function(pError, pFinalCode){ /* if could not read file call forse minification */ if(pError) lProcessing_f(); /* if need to save in cache - do it */ else { if(pOptions){ if(pOptions.cache){ exports.Cache[minFileName] = pFinalCode; console.log('file ' + minFileName + ' saved to cache...'); } if(pOptions.callback && typeof pOptions.callback === 'function') pOptions.callback(pFinalCode); } else if(lExt === '.css'){ /* if it's css and last file */ lAllCSS += pFinalCode; if(lLastFile_b && (lMoreProcessing_f.img || lMoreProcessing_f === true)){ base64_images(lAllCSS); } } } }); } }; /* moving thru all elements of js files array */ for(var i=0; pFiles_a[i]; i++){ /* if postProcessing function exist * getting file name and passet next */ var lPostProcessing_o = pFiles_a[i]; if(typeof lPostProcessing_o === 'object'){ for(lName in lPostProcessing_o){ } } else lName = pFiles_a[i]; console.log('reading file ' + lName + '...'); /* if it's last file send true */ fs.readFile(lName, fileReaded(pFiles_a[i], dataReaded_f)); } /* saving the name of last readed file for hash saving function */ return true; }; /** * Функция переводит картинки в base64 и записывает в css-файл * @param pFileContent_s {String} */ function base64_images(pFileContent_s){ 'use strict'; var b64img; try{ b64img = require('css-b64-images'); }catch(error){ console.log('can\'n load clean-css \n' + 'npm install -g css-b64-images\n' + 'https://github.com/Filirom1/css-base64-images'); fs.writeFile(MinFolder + 'all.min.css', pFileContent_s, fileWrited(MinFolder + 'all.min.css')); return pFileContent_s; } b64img.fromString(pFileContent_s, '.','', function(err, css){ console.log('images converted to base64 and saved in css file'); fs.writeFile(MinFolder + 'all.min.css', css, fileWrited(MinFolder + 'all.min.css')); }); } /* Функция создаёт асинхроную версию * для чтения файла * @pFileName - имя считываемого файла * @pProcessFunc - функция обработки файла * @pLastFile_b - последний файл? */ function fileReaded(pFileName,pProcessFunc, pLastFile_b){ "use strict"; return function(pError,pData){ /* функция в которую мы попадаем, * если данные считались * * если ошибка - показываем её * иначе если переданная функция - * функция запускаем её */ if(!pError) if (pProcessFunc && typeof pProcessFunc==="function") pProcessFunc(pFileName,pData.toString(), pLastFile_b); else console.log(pError); }; } /* * Функция вызываеться после записи файла * и выводит ошибку или сообщает, * что файл успешно записан */ function fileWrited(pFileName){ "use strict"; return function(error){ console.log(error?error:('file '+pFileName+' writed...')); }; } /* function do safe require of needed module */ function cloudRequire(pModule){ try{ return require(pModule); } catch(pError){ return false; } } function isFileChanged(pFileName, pFileData, pLastFile_b){ var lReadedHash; /* boolean hashes.json changed or not */ var lThisHashChanged_b = false; if(!Hashes) try { console.log('trying to read hashes.json'); Hashes = require(process.cwd() + '/hashes'); }catch(pError) { console.log('hashes.json not found... \n'); Hashes = {}; } for(var lFileName in Hashes) /* if founded row with * file name - save hash */ if (lFileName === pFileName) { lReadedHash = Hashes[pFileName]; break; } /* create hash of file data */ var lFileHash = crypto.createHash('sha1'); lFileHash = crypto.createHash('sha1'); lFileHash.update(pFileData); lFileHash = lFileHash.digest('hex'); if(lReadedHash !== lFileHash){ Hashes[pFileName] = lFileHash; lThisHashChanged_b = true; HashesChanged = true; } if(pLastFile_b){ /* if hashes file was changes - write it */ if(HashesChanged) fs.writeFile('./hashes.json', JSON.stringify(Hashes), fileWrited('./hashes.json')); else console.log('no one file has been changed'); } /* has file changed? */ return lThisHashChanged_b; }
minify.js
"use strict"; /* Модуль сжатия js-скриптов, css-стилей, html-файлов и * конвертации картинок в css-стилях * в base64 и помещения их в файл стилей */ var Minify = {}; console.log('minify.js loaded...'); /* функция сжимает js-скрипты * и сохраняет их с именем .min.js */ var fs = require('fs'), path = require('path'), crypto = require('crypto'); /* object contains hashes of files*/ var Hashes; var HashesChanged; var html = cloudRequire('./lib/html'); var js = cloudRequire('./lib/js'); var css = cloudRequire('./lib/css'); if(!html || !js || !css) console.log('One of the necessary modules is absent\n' + 're-install the modules\n' + 'npm r minify\n' + 'npm i minify'); else{ Minify._uglifyJS = js._uglifyJS; Minify._cleanCSS = css._cleanCSS; Minify.htmlMinify = html.htmlMinify; } var MinFolder='min/'; /* function clear MinFolder * if we could not create * directory and it is * not exist */ var folderExist = function(pError, pStat){ "use strict"; /*file found and it's directory */ if(!pError && pStat.isDirectory()) console.log('folder exist: ' + MinFolder); else MinFolder='/'; }; /* * function says thet folder created * if everything is OK, or * moves to folderExist function */ var makeFolder = function(pError){ "use strict"; /*folder created successfully*/ if(!pError) console.log('folder created: min'); else fs.stat(MinFolder,folderExist); }; /* Trying to create folder min * where woud be minifyed versions * of files 511(10)=777(8) * rwxrwxrwx */ fs.mkdir(MinFolder, 511, makeFolder); exports.MinFolder = MinFolder; exports.Cache = {}; /** * Функция ищет в имени файла расширение * и если находит возвращает true * @param pName * @param pExt */ Minify._checkExtension = function(pName, pExt) { /* если длина имени больше * длинны расширения - * имеет смысл продолжать */ if (typeof pExt === 'string' && pName.length > pExt.length) { var lLength = pName.length; /* длина имени*/ var lExtNum = pName.lastIndexOf(pExt); /* последнее вхождение расширения*/ var lExtSub = lLength - lExtNum; /* длина расширения*/ /* если pExt - расширение pName */ return lExtSub === pExt.length; }else if(typeof pExt === 'object' && pExt.length){ for(var i=0; i < pName.length; i++) if(this.checkExtension(pName, pExt[i])) return true; }else return false; }; /** * function gets file extension * @param pFileName * @return Ext */ Minify._getExtension = function(pFileName){ /* checking for js/html/css */ var lDot = pFileName.lastIndexOf('.'); return pFileName.substr(lDot); }; /** * function minificate js,css and html files * @param pFiles_a - array of js, css and html file names or string, if name * single, or object if postProcessing neaded * {'client.js': function(pFinalCode){} } * or convertion images to base64 neaded * {'style.css': true} * or {'style.css':{minimize: true, func: function(){}} * * @param pOptions - object contain main options * if cache true files do not writes on disk, just saves * in Minify Cache * Example: * {cache: false, gzip: true, callback: func(){}} */ exports.optimize = function(pFiles_a, pOptions){ 'use strict'; /* if passed string, or object * putting it to array */ if (typeof pFiles_a === 'string' || !pFiles_a[0]) pFiles_a=[pFiles_a]; var lName = ''; var lAllCSS = ''; var lCSS_o = null; /* varible contains all readed file names */ var lReadedFilesCount = 0; /* * Processing of files * @pFileName - name of file * @pData - data of file * @pForce - minify file anyway */ var dataReaded_f = function(pFileName, pData){ ++lReadedFilesCount; var lLastFile_b; /* if leng this not equal * file not last */ if (lReadedFilesCount === pFiles_a.length) lLastFile_b = true; /* * if postProcessing function exist * getting it from pFileName object */ var lMoreProcessing_f; if(typeof pFileName === 'object'){ var lName; for(lName in pFileName){ break; } lMoreProcessing_f = pFileName[lName]; pFileName = lName; } console.log('file ' + pFileName + ' readed'); var lExt = Minify._getExtension(pFileName); var minFileName = pFileName.replace(lExt, '.min' + lExt); minFileName = path.basename(minFileName); minFileName = MinFolder + minFileName; /* functin minimize files */ var lProcessing_f = function(){ var final_code; /* getting optimized version */ switch(lExt){ case '.js': final_code = Minify._uglifyJS(pData); break; case '.html': final_code = Minify.htmlMinify(pData); break; case '.css': final_code = Minify._cleanCSS(pData); lAllCSS += final_code; lCSS_o = lMoreProcessing_f; if (typeof lCSS_o === 'object'){ lMoreProcessing_f = lCSS_o.moreProcessing; } break; default: return console.log('unknow file type ' + lExt + ', only *.js, *.css, *.html'); } /* if it's last file * and base64images setted up * se should convert it */ if (lLastFile_b && (lCSS_o && lCSS_o.img || lCSS_o === true)){ base64_images(lAllCSS); } /* if lMoreProcessing_f seeted up * and function associated with * current file name exists - * run it */ if(lMoreProcessing_f && typeof lMoreProcessing_f === "function"){ final_code = lMoreProcessing_f(final_code); } /* записываем сжатый js-скрипт * в кэш если установлен pCache_b * или на диск, если не установлен */ if(pOptions && pOptions.cache){ exports.Cache[minFileName] = final_code; console.log('file ' + minFileName + ' saved to cache...'); } /* minimized file will be in min file * if it's possible if not - * in root */ fs.writeFile(minFileName, final_code, fileWrited(minFileName)); /* calling callback function if it exist */ if(pOptions && pOptions.callback && typeof pOptions.callback === 'function') pOptions.callback(final_code); }; if(pOptions && pOptions.force || isFileChanged(pFileName, pData, lLastFile_b)) lProcessing_f(); /* if file was not changed */ else{ fs.readFile(minFileName, function(pError, pFinalCode){ /* if could not read file call forse minification */ if(pError) lProcessing_f(); /* if need to save in cache - do it */ else { if(pOptions){ if(pOptions.cache){ exports.Cache[minFileName] = pFinalCode; console.log('file ' + minFileName + ' saved to cache...'); } if(pOptions.callback && typeof pOptions.callback === 'function') pOptions.callback(pFinalCode); } else if(lExt === '.css'){ /* if it's css and last file */ lAllCSS += pFinalCode; if(lLastFile_b && (lMoreProcessing_f.img || lMoreProcessing_f === true)){ base64_images(lAllCSS); } } } }); } }; /* moving thru all elements of js files array */ for(var i=0; pFiles_a[i]; i++){ /* if postProcessing function exist * getting file name and passet next */ var lPostProcessing_o = pFiles_a[i]; if(typeof lPostProcessing_o === 'object'){ for(lName in lPostProcessing_o){ } } else lName = pFiles_a[i]; console.log('reading file ' + lName + '...'); /* if it's last file send true */ fs.readFile(lName, fileReaded(pFiles_a[i], dataReaded_f)); } /* saving the name of last readed file for hash saving function */ return true; }; /** * Функция переводит картинки в base64 и записывает в css-файл * @param pFileContent_s {String} */ function base64_images(pFileContent_s){ 'use strict'; var b64img; try{ b64img = require('css-b64-images'); }catch(error){ console.log('can\'n load clean-css \n' + 'npm install -g css-b64-images\n' + 'https://github.com/Filirom1/css-base64-images'); fs.writeFile(MinFolder + 'all.min.css', pFileContent_s, fileWrited(MinFolder + 'all.min.css')); return pFileContent_s; } b64img.fromString(pFileContent_s, '.','', function(err, css){ console.log('images converted to base64 and saved in css file'); fs.writeFile(MinFolder + 'all.min.css', css, fileWrited(MinFolder + 'all.min.css')); }); } /* Функция создаёт асинхроную версию * для чтения файла * @pFileName - имя считываемого файла * @pProcessFunc - функция обработки файла * @pLastFile_b - последний файл? */ function fileReaded(pFileName,pProcessFunc, pLastFile_b){ "use strict"; return function(pError,pData){ /* функция в которую мы попадаем, * если данные считались * * если ошибка - показываем её * иначе если переданная функция - * функция запускаем её */ if(!pError) if (pProcessFunc && typeof pProcessFunc==="function") pProcessFunc(pFileName,pData.toString(), pLastFile_b); else console.log(pError); }; } /* * Функция вызываеться после записи файла * и выводит ошибку или сообщает, * что файл успешно записан */ function fileWrited(pFileName){ "use strict"; return function(error){ console.log(error?error:('file '+pFileName+' writed...')); }; } /* function do safe require of needed module */ function cloudRequire(pModule){ try{ return require(pModule); } catch(pError){ return false; } } function isFileChanged(pFileName, pFileData, pLastFile_b){ var lReadedHash; /* boolean hashes.json changed or not */ var lThisHashChanged_b = false; if(!Hashes) try { console.log('trying to read hashes.json'); Hashes = require(process.cwd() + '/hashes'); }catch(pError) { console.log('hashes.json not found... \n'); Hashes = {}; } for(var lFileName in Hashes) /* if founded row with * file name - save hash */ if (lFileName === pFileName) { lReadedHash = Hashes[pFileName]; break; } /* create hash of file data */ var lFileHash = crypto.createHash('sha1'); lFileHash = crypto.createHash('sha1'); lFileHash.update(pFileData); lFileHash = lFileHash.digest('hex'); if(lReadedHash !== lFileHash){ Hashes[pFileName] = lFileHash; lThisHashChanged_b = true; HashesChanged = true; } if(pLastFile_b){ /* if hashes file was changes - write it */ if(HashesChanged) fs.writeFile('./hashes.json', JSON.stringify(Hashes), fileWrited('./hashes.json')); else console.log('no one file has been changed'); } /* has file changed? */ return lThisHashChanged_b; }
minor changes
minify.js
minor changes
<ide><path>inify.js <ide> * конвертации картинок в css-стилях <ide> * в base64 и помещения их в файл стилей <ide> */ <add> <ide> var Minify = {}; <ide> console.log('minify.js loaded...'); <ide>
Java
lgpl-2.1
acd72d8f8344c94afff902bd3dfd60ac80eaf68f
0
netarchivesuite/netarchivesuite-svngit-migration,netarchivesuite/netarchivesuite-svngit-migration,netarchivesuite/netarchivesuite-svngit-migration,netarchivesuite/netarchivesuite-svngit-migration,netarchivesuite/netarchivesuite-svngit-migration,netarchivesuite/netarchivesuite-svngit-migration
/* File: $Id$ * Version: $Revision$ * Date: $Date$ * Author: $Author$ * * The Netarchive Suite - Software to harvest and preserve websites * Copyright 2004-2007 Det Kongelige Bibliotek and Statsbiblioteket, Denmark * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package dk.netarkivet; import junit.framework.Test; import junit.framework.TestSuite; import junit.textui.TestRunner; import dk.netarkivet.archive.arcrepository.ArcRepositoryTesterSuite; import dk.netarkivet.archive.arcrepository.bitpreservation.BitPreservationTesterSuite; import dk.netarkivet.archive.arcrepository.distribute.ArcrepositoryDistributeTesterSuite; import dk.netarkivet.archive.arcrepositoryadmin.ArcRepositoryAdminTesterSuite; import dk.netarkivet.archive.bitarchive.BitarchiveTesterSuite; import dk.netarkivet.archive.bitarchive.distribute.BitarchiveDistributeTesterSuite; import dk.netarkivet.archive.distribute.ArchiveDistributeTesterSuite; import dk.netarkivet.archive.indexserver.IndexServerTesterSuite; import dk.netarkivet.archive.indexserver.distribute.IndexserverDistributeTesterSuite; import dk.netarkivet.archive.tools.ArchiveToolsTesterSuite; import dk.netarkivet.common.CommonsTesterSuite; import dk.netarkivet.common.distribute.DistributeTesterSuite; import dk.netarkivet.common.distribute.arcrepository.DistributeArcrepositoryTesterSuite; import dk.netarkivet.common.distribute.indexserver.DistributeIndexserverTesterSuite; import dk.netarkivet.common.exceptions.ExceptionsTesterSuite; import dk.netarkivet.common.management.ManagementTesterSuite; import dk.netarkivet.common.tools.ToolsTesterSuite; import dk.netarkivet.common.utils.UtilsTesterSuite; import dk.netarkivet.common.utils.arc.ArcUtilsTesterSuite; import dk.netarkivet.common.utils.batch.BatchUtilsTesterSuite; import dk.netarkivet.common.utils.cdx.CdxUtilsTesterSuite; import dk.netarkivet.deploy.DeployTesterSuite; import dk.netarkivet.harvester.datamodel.DataModelTesterSuite; import dk.netarkivet.harvester.distribute.HarvesterDistributeTesterSuite; import dk.netarkivet.harvester.harvesting.HarvestingTesterSuite; import dk.netarkivet.harvester.harvesting.distribute.HarvestingDistributeTesterSuite; import dk.netarkivet.harvester.scheduler.SchedulerTesterSuite; import dk.netarkivet.harvester.tools.HarvesterToolsTesterSuite; import dk.netarkivet.harvester.webinterface.WebinterfaceTesterSuite; import dk.netarkivet.monitor.MonitorTesterSuite; import dk.netarkivet.monitor.jmx.MonitorJMXTesterSuite; import dk.netarkivet.monitor.logging.LoggingTesterSuite; import dk.netarkivet.monitor.registry.MonitorRegistryTesterSuite; import dk.netarkivet.monitor.webinterface.MonitorWebinterfaceTesterSuite; import dk.netarkivet.viewerproxy.ViewerProxyTesterSuite; import dk.netarkivet.viewerproxy.distribute.ViewerproxyDistributeTesterSuite; /** * This class runs all the unit tests. */ public class UnitTesterSuite { public static void addToSuite(TestSuite suite) { // Please keep sorted. ArchiveDistributeTesterSuite.addToSuite(suite); ArchiveToolsTesterSuite.addToSuite(suite); ArcRepositoryAdminTesterSuite.addToSuite(suite); ArcrepositoryDistributeTesterSuite.addToSuite(suite); //ArcRepositoryTesterSuite.addToSuite(suite); ArcUtilsTesterSuite.addToSuite(suite); BatchUtilsTesterSuite.addToSuite(suite); BitarchiveDistributeTesterSuite.addToSuite(suite); BitarchiveTesterSuite.addToSuite(suite); BitPreservationTesterSuite.addToSuite(suite); CdxUtilsTesterSuite.addToSuite(suite); CommonsTesterSuite.addToSuite(suite); DataModelTesterSuite.addToSuite(suite); DeployTesterSuite.addToSuite(suite); DistributeArcrepositoryTesterSuite.addToSuite(suite); DistributeIndexserverTesterSuite.addToSuite(suite); DistributeTesterSuite.addToSuite(suite); ExceptionsTesterSuite.addToSuite(suite); HarvesterDistributeTesterSuite.addToSuite(suite); HarvestingDistributeTesterSuite.addToSuite(suite); HarvestingTesterSuite.addToSuite(suite); IndexserverDistributeTesterSuite.addToSuite(suite); IndexServerTesterSuite.addToSuite(suite); LoggingTesterSuite.addToSuite(suite); ManagementTesterSuite.addToSuite(suite); MonitorTesterSuite.addToSuite(suite); MonitorJMXTesterSuite.addToSuite(suite); MonitorRegistryTesterSuite.addToSuite(suite); MonitorWebinterfaceTesterSuite.addToSuite(suite); SchedulerTesterSuite.addToSuite(suite); ToolsTesterSuite.addToSuite(suite); HarvesterToolsTesterSuite.addToSuite(suite); UtilsTesterSuite.addToSuite(suite); ViewerproxyDistributeTesterSuite.addToSuite(suite); ViewerProxyTesterSuite.addToSuite(suite); WebinterfaceTesterSuite.addToSuite(suite); dk.netarkivet.viewerproxy.webinterface.WebinterfaceTesterSuite.addToSuite(suite); } public static Test suite() { TestSuite suite; suite = new TestSuite(UnitTesterSuite.class.getName()); addToSuite(suite); return suite; } public static void main(String[] args) { String[] args2 = {"-noloading", UnitTesterSuite.class.getName()}; TestRunner.main(args2); } }
tests/dk/netarkivet/UnitTesterSuite.java
/* File: $Id$ * Version: $Revision$ * Date: $Date$ * Author: $Author$ * * The Netarchive Suite - Software to harvest and preserve websites * Copyright 2004-2007 Det Kongelige Bibliotek and Statsbiblioteket, Denmark * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package dk.netarkivet; import junit.framework.Test; import junit.framework.TestSuite; import junit.textui.TestRunner; import dk.netarkivet.archive.arcrepository.ArcRepositoryTesterSuite; import dk.netarkivet.archive.arcrepository.bitpreservation.BitPreservationTesterSuite; import dk.netarkivet.archive.arcrepository.distribute.ArcrepositoryDistributeTesterSuite; import dk.netarkivet.archive.arcrepositoryadmin.ArcRepositoryAdminTesterSuite; import dk.netarkivet.archive.bitarchive.BitarchiveTesterSuite; import dk.netarkivet.archive.bitarchive.distribute.BitarchiveDistributeTesterSuite; import dk.netarkivet.archive.distribute.ArchiveDistributeTesterSuite; import dk.netarkivet.archive.indexserver.IndexServerTesterSuite; import dk.netarkivet.archive.indexserver.distribute.IndexserverDistributeTesterSuite; import dk.netarkivet.archive.tools.ArchiveToolsTesterSuite; import dk.netarkivet.common.CommonsTesterSuite; import dk.netarkivet.common.distribute.DistributeTesterSuite; import dk.netarkivet.common.distribute.arcrepository.DistributeArcrepositoryTesterSuite; import dk.netarkivet.common.distribute.indexserver.DistributeIndexserverTesterSuite; import dk.netarkivet.common.exceptions.ExceptionsTesterSuite; import dk.netarkivet.common.management.ManagementTesterSuite; import dk.netarkivet.common.tools.ToolsTesterSuite; import dk.netarkivet.common.utils.UtilsTesterSuite; import dk.netarkivet.common.utils.arc.ArcUtilsTesterSuite; import dk.netarkivet.common.utils.batch.BatchUtilsTesterSuite; import dk.netarkivet.common.utils.cdx.CdxUtilsTesterSuite; import dk.netarkivet.harvester.datamodel.DataModelTesterSuite; import dk.netarkivet.harvester.distribute.HarvesterDistributeTesterSuite; import dk.netarkivet.harvester.harvesting.HarvestingTesterSuite; import dk.netarkivet.harvester.harvesting.distribute.HarvestingDistributeTesterSuite; import dk.netarkivet.harvester.scheduler.SchedulerTesterSuite; import dk.netarkivet.harvester.tools.HarvesterToolsTesterSuite; import dk.netarkivet.harvester.webinterface.WebinterfaceTesterSuite; import dk.netarkivet.monitor.MonitorTesterSuite; import dk.netarkivet.monitor.jmx.MonitorJMXTesterSuite; import dk.netarkivet.monitor.logging.LoggingTesterSuite; import dk.netarkivet.monitor.registry.MonitorRegistryTesterSuite; import dk.netarkivet.monitor.webinterface.MonitorWebinterfaceTesterSuite; import dk.netarkivet.viewerproxy.ViewerProxyTesterSuite; import dk.netarkivet.viewerproxy.distribute.ViewerproxyDistributeTesterSuite; /** * This class runs all the unit tests. */ public class UnitTesterSuite { public static void addToSuite(TestSuite suite) { // Please keep sorted. ArchiveDistributeTesterSuite.addToSuite(suite); ArchiveToolsTesterSuite.addToSuite(suite); ArcRepositoryAdminTesterSuite.addToSuite(suite); ArcrepositoryDistributeTesterSuite.addToSuite(suite); //ArcRepositoryTesterSuite.addToSuite(suite); ArcUtilsTesterSuite.addToSuite(suite); BatchUtilsTesterSuite.addToSuite(suite); BitarchiveDistributeTesterSuite.addToSuite(suite); BitarchiveTesterSuite.addToSuite(suite); BitPreservationTesterSuite.addToSuite(suite); CdxUtilsTesterSuite.addToSuite(suite); CommonsTesterSuite.addToSuite(suite); DataModelTesterSuite.addToSuite(suite); //DeployTesterSuite.addToSuite(suite); dk.netarkivet.deploy2.DeployTesterSuite.addToSuite(suite); DistributeArcrepositoryTesterSuite.addToSuite(suite); DistributeIndexserverTesterSuite.addToSuite(suite); DistributeTesterSuite.addToSuite(suite); ExceptionsTesterSuite.addToSuite(suite); HarvesterDistributeTesterSuite.addToSuite(suite); HarvestingDistributeTesterSuite.addToSuite(suite); HarvestingTesterSuite.addToSuite(suite); IndexserverDistributeTesterSuite.addToSuite(suite); IndexServerTesterSuite.addToSuite(suite); LoggingTesterSuite.addToSuite(suite); ManagementTesterSuite.addToSuite(suite); MonitorTesterSuite.addToSuite(suite); MonitorJMXTesterSuite.addToSuite(suite); MonitorRegistryTesterSuite.addToSuite(suite); MonitorWebinterfaceTesterSuite.addToSuite(suite); SchedulerTesterSuite.addToSuite(suite); ToolsTesterSuite.addToSuite(suite); HarvesterToolsTesterSuite.addToSuite(suite); UtilsTesterSuite.addToSuite(suite); ViewerproxyDistributeTesterSuite.addToSuite(suite); ViewerProxyTesterSuite.addToSuite(suite); WebinterfaceTesterSuite.addToSuite(suite); dk.netarkivet.viewerproxy.webinterface.WebinterfaceTesterSuite.addToSuite(suite); } public static Test suite() { TestSuite suite; suite = new TestSuite(UnitTesterSuite.class.getName()); addToSuite(suite); return suite; } public static void main(String[] args) { String[] args2 = {"-noloading", UnitTesterSuite.class.getName()}; TestRunner.main(args2); } }
Moving the deploy2 test-files to deploy package
tests/dk/netarkivet/UnitTesterSuite.java
Moving the deploy2 test-files to deploy package
<ide><path>ests/dk/netarkivet/UnitTesterSuite.java <ide> import dk.netarkivet.common.utils.arc.ArcUtilsTesterSuite; <ide> import dk.netarkivet.common.utils.batch.BatchUtilsTesterSuite; <ide> import dk.netarkivet.common.utils.cdx.CdxUtilsTesterSuite; <add>import dk.netarkivet.deploy.DeployTesterSuite; <ide> import dk.netarkivet.harvester.datamodel.DataModelTesterSuite; <ide> import dk.netarkivet.harvester.distribute.HarvesterDistributeTesterSuite; <ide> import dk.netarkivet.harvester.harvesting.HarvestingTesterSuite; <ide> CdxUtilsTesterSuite.addToSuite(suite); <ide> CommonsTesterSuite.addToSuite(suite); <ide> DataModelTesterSuite.addToSuite(suite); <del> //DeployTesterSuite.addToSuite(suite); <del> dk.netarkivet.deploy2.DeployTesterSuite.addToSuite(suite); <add> DeployTesterSuite.addToSuite(suite); <ide> DistributeArcrepositoryTesterSuite.addToSuite(suite); <ide> DistributeIndexserverTesterSuite.addToSuite(suite); <ide> DistributeTesterSuite.addToSuite(suite);
Java
apache-2.0
f1f851d038f1d1c87ad5d018b1c946ea314aaf2f
0
ceylon/ceylon-model
package com.redhat.ceylon.model.loader; import static com.redhat.ceylon.model.typechecker.model.ModelUtil.intersection; import static com.redhat.ceylon.model.typechecker.model.ModelUtil.union; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import javax.lang.model.type.TypeKind; import com.redhat.ceylon.common.Backend; import com.redhat.ceylon.common.Backends; import com.redhat.ceylon.common.BooleanUtil; import com.redhat.ceylon.common.JVMModuleUtil; import com.redhat.ceylon.common.ModuleUtil; import com.redhat.ceylon.common.Versions; import com.redhat.ceylon.model.cmr.ArtifactResult; import com.redhat.ceylon.model.cmr.JDKUtils; import com.redhat.ceylon.model.loader.mirror.AccessibleMirror; import com.redhat.ceylon.model.loader.mirror.AnnotatedMirror; import com.redhat.ceylon.model.loader.mirror.AnnotationMirror; import com.redhat.ceylon.model.loader.mirror.ClassMirror; import com.redhat.ceylon.model.loader.mirror.FieldMirror; import com.redhat.ceylon.model.loader.mirror.MethodMirror; import com.redhat.ceylon.model.loader.mirror.PackageMirror; import com.redhat.ceylon.model.loader.mirror.TypeMirror; import com.redhat.ceylon.model.loader.mirror.TypeParameterMirror; import com.redhat.ceylon.model.loader.mirror.VariableMirror; import com.redhat.ceylon.model.loader.model.AnnotationProxyClass; import com.redhat.ceylon.model.loader.model.AnnotationProxyMethod; import com.redhat.ceylon.model.loader.model.FieldValue; import com.redhat.ceylon.model.loader.model.JavaBeanValue; import com.redhat.ceylon.model.loader.model.JavaMethod; import com.redhat.ceylon.model.loader.model.LazyClass; import com.redhat.ceylon.model.loader.model.LazyClassAlias; import com.redhat.ceylon.model.loader.model.LazyContainer; import com.redhat.ceylon.model.loader.model.LazyElement; import com.redhat.ceylon.model.loader.model.LazyFunction; import com.redhat.ceylon.model.loader.model.LazyInterface; import com.redhat.ceylon.model.loader.model.LazyInterfaceAlias; import com.redhat.ceylon.model.loader.model.LazyModule; import com.redhat.ceylon.model.loader.model.LazyPackage; import com.redhat.ceylon.model.loader.model.LazyTypeAlias; import com.redhat.ceylon.model.loader.model.LazyValue; import com.redhat.ceylon.model.loader.model.LocalDeclarationContainer; import com.redhat.ceylon.model.loader.model.OutputElement; import com.redhat.ceylon.model.loader.model.SetterWithLocalDeclarations; import com.redhat.ceylon.model.typechecker.model.Annotated; import com.redhat.ceylon.model.typechecker.model.Annotation; import com.redhat.ceylon.model.typechecker.model.Class; import com.redhat.ceylon.model.typechecker.model.ClassOrInterface; import com.redhat.ceylon.model.typechecker.model.Constructor; import com.redhat.ceylon.model.typechecker.model.Declaration; import com.redhat.ceylon.model.typechecker.model.DeclarationCompleter; import com.redhat.ceylon.model.typechecker.model.Element; import com.redhat.ceylon.model.typechecker.model.Function; import com.redhat.ceylon.model.typechecker.model.FunctionOrValue; import com.redhat.ceylon.model.typechecker.model.Functional; import com.redhat.ceylon.model.typechecker.model.Interface; import com.redhat.ceylon.model.typechecker.model.ModelUtil; import com.redhat.ceylon.model.typechecker.model.Module; import com.redhat.ceylon.model.typechecker.model.ModuleImport; import com.redhat.ceylon.model.typechecker.model.Modules; import com.redhat.ceylon.model.typechecker.model.Package; import com.redhat.ceylon.model.typechecker.model.Parameter; import com.redhat.ceylon.model.typechecker.model.ParameterList; import com.redhat.ceylon.model.typechecker.model.Scope; import com.redhat.ceylon.model.typechecker.model.Setter; import com.redhat.ceylon.model.typechecker.model.SiteVariance; import com.redhat.ceylon.model.typechecker.model.Type; import com.redhat.ceylon.model.typechecker.model.TypeAlias; import com.redhat.ceylon.model.typechecker.model.TypeDeclaration; import com.redhat.ceylon.model.typechecker.model.TypeParameter; import com.redhat.ceylon.model.typechecker.model.TypedDeclaration; import com.redhat.ceylon.model.typechecker.model.Unit; import com.redhat.ceylon.model.typechecker.model.UnknownType; import com.redhat.ceylon.model.typechecker.model.Value; import com.redhat.ceylon.model.typechecker.util.ModuleManager; /** * Abstract class of a model loader that can load a model from a compiled Java representation, * while being agnostic of the reflection API used to load the compiled Java representation. * * @author Stéphane Épardaud <[email protected]> */ public abstract class AbstractModelLoader implements ModelCompleter, ModelLoader, DeclarationCompleter { public static final String JAVA_BASE_MODULE_NAME = "java.base"; public static final String CEYLON_LANGUAGE = "ceylon.language"; public static final String CEYLON_LANGUAGE_MODEL = "ceylon.language.meta.model"; public static final String CEYLON_LANGUAGE_MODEL_DECLARATION = "ceylon.language.meta.declaration"; public static final String CEYLON_LANGUAGE_SERIALIZATION = "ceylon.language.serialization"; private static final String TIMER_MODEL_LOADER_CATEGORY = "model loader"; public static final String CEYLON_CEYLON_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Ceylon"; private static final String CEYLON_MODULE_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Module"; private static final String CEYLON_PACKAGE_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Package"; public static final String CEYLON_IGNORE_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Ignore"; private static final String CEYLON_CLASS_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Class"; private static final String CEYLON_JPA_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Jpa"; private static final String CEYLON_ENUMERATED_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Enumerated"; //private static final String CEYLON_CONSTRUCTOR_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Constructor"; //private static final String CEYLON_PARAMETERLIST_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.ParameterList"; public static final String CEYLON_NAME_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Name"; private static final String CEYLON_SEQUENCED_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Sequenced"; private static final String CEYLON_FUNCTIONAL_PARAMETER_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.FunctionalParameter"; private static final String CEYLON_DEFAULTED_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Defaulted"; private static final String CEYLON_SATISFIED_TYPES_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.SatisfiedTypes"; private static final String CEYLON_CASE_TYPES_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.CaseTypes"; private static final String CEYLON_TYPE_PARAMETERS = "com.redhat.ceylon.compiler.java.metadata.TypeParameters"; private static final String CEYLON_TYPE_INFO_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.TypeInfo"; public static final String CEYLON_ATTRIBUTE_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Attribute"; public static final String CEYLON_SETTER_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Setter"; public static final String CEYLON_OBJECT_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Object"; public static final String CEYLON_METHOD_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Method"; public static final String CEYLON_CONTAINER_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Container"; public static final String CEYLON_LOCAL_CONTAINER_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.LocalContainer"; public static final String CEYLON_LOCAL_DECLARATION_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.LocalDeclaration"; public static final String CEYLON_LOCAL_DECLARATIONS_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.LocalDeclarations"; private static final String CEYLON_MEMBERS_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Members"; private static final String CEYLON_ANNOTATIONS_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Annotations"; public static final String CEYLON_VALUETYPE_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.ValueType"; public static final String CEYLON_ALIAS_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Alias"; public static final String CEYLON_TYPE_ALIAS_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.TypeAlias"; public static final String CEYLON_ANNOTATION_INSTANTIATION_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.AnnotationInstantiation"; public static final String CEYLON_ANNOTATION_INSTANTIATION_ARGUMENTS_MEMBER = "arguments"; public static final String CEYLON_ANNOTATION_INSTANTIATION_ANNOTATION_MEMBER = "primary"; public static final String CEYLON_ANNOTATION_INSTANTIATION_TREE_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.AnnotationInstantiationTree"; public static final String CEYLON_STRING_VALUE_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.StringValue"; public static final String CEYLON_STRING_EXPRS_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.StringExprs"; public static final String CEYLON_BOOLEAN_VALUE_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.BooleanValue"; public static final String CEYLON_BOOLEAN_EXPRS_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.BooleanExprs"; public static final String CEYLON_INTEGER_VALUE_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.IntegerValue"; public static final String CEYLON_INTEGER_EXPRS_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.IntegerExprs"; public static final String CEYLON_CHARACTER_VALUE_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.CharacterValue"; public static final String CEYLON_CHARACTER_EXPRS_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.CharacterExprs"; public static final String CEYLON_FLOAT_VALUE_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.FloatValue"; public static final String CEYLON_FLOAT_EXPRS_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.FloatExprs"; public static final String CEYLON_OBJECT_VALUE_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.ObjectValue"; public static final String CEYLON_OBJECT_EXPRS_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.ObjectExprs"; public static final String CEYLON_DECLARATION_VALUE_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.DeclarationValue"; public static final String CEYLON_DECLARATION_EXPRS_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.DeclarationExprs"; private static final String CEYLON_TRANSIENT_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Transient"; private static final String CEYLON_DYNAMIC_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Dynamic"; private static final String JAVA_DEPRECATED_ANNOTATION = "java.lang.Deprecated"; static final String CEYLON_LANGUAGE_ABSTRACT_ANNOTATION = "ceylon.language.AbstractAnnotation$annotation$"; static final String CEYLON_LANGUAGE_ACTUAL_ANNOTATION = "ceylon.language.ActualAnnotation$annotation$"; static final String CEYLON_LANGUAGE_ANNOTATION_ANNOTATION = "ceylon.language.AnnotationAnnotation$annotation$"; static final String CEYLON_LANGUAGE_DEFAULT_ANNOTATION = "ceylon.language.DefaultAnnotation$annotation$"; static final String CEYLON_LANGUAGE_FORMAL_ANNOTATION = "ceylon.language.FormalAnnotation$annotation$"; static final String CEYLON_LANGUAGE_SHARED_ANNOTATION = "ceylon.language.SharedAnnotation$annotation$"; static final String CEYLON_LANGUAGE_LATE_ANNOTATION = "ceylon.language.LateAnnotation$annotation$"; static final String CEYLON_LANGUAGE_SEALED_ANNOTATION = "ceylon.language.SealedAnnotation$annotation$"; static final String CEYLON_LANGUAGE_VARIABLE_ANNOTATION = "ceylon.language.VariableAnnotation$annotation$"; static final String CEYLON_LANGUAGE_FINAL_ANNOTATION = "ceylon.language.FinalAnnotation$annotation$"; static final String CEYLON_LANGUAGE_NATIVE_ANNOTATION = "ceylon.language.NativeAnnotation$annotation$"; static final String CEYLON_LANGUAGE_OPTIONAL_ANNOTATION = "ceylon.language.OptionalAnnotation$annotation$"; static final String CEYLON_LANGUAGE_SERIALIZABLE_ANNOTATION = "ceylon.language.SerializableAnnotation$annotation$"; static final String CEYLON_LANGUAGE_DOC_ANNOTATION = "ceylon.language.DocAnnotation$annotation$"; static final String CEYLON_LANGUAGE_THROWS_ANNOTATIONS = "ceylon.language.ThrownExceptionAnnotation$annotations$"; static final String CEYLON_LANGUAGE_THROWS_ANNOTATION = "ceylon.language.ThrownExceptionAnnotation$annotation$"; static final String CEYLON_LANGUAGE_AUTHORS_ANNOTATION = "ceylon.language.AuthorsAnnotation$annotation$"; static final String CEYLON_LANGUAGE_SEE_ANNOTATIONS = "ceylon.language.SeeAnnotation$annotations$"; static final String CEYLON_LANGUAGE_SEE_ANNOTATION = "ceylon.language.SeeAnnotation$annotation$"; static final String CEYLON_LANGUAGE_DEPRECATED_ANNOTATION = "ceylon.language.DeprecationAnnotation$annotation$"; static final String CEYLON_LANGUAGE_SUPPRESS_WARNINGS_ANNOTATION = "ceylon.language.SuppressWarningsAnnotation$annotation$"; static final String CEYLON_LANGUAGE_LICENSE_ANNOTATION = "ceylon.language.LicenseAnnotation$annotation$"; static final String CEYLON_LANGUAGE_TAGS_ANNOTATION = "ceylon.language.TagsAnnotation$annotation$"; static final String CEYLON_LANGUAGE_ALIASES_ANNOTATION = "ceylon.language.AliasesAnnotation$annotation$"; // important that these are with :: private static final String CEYLON_LANGUAGE_CALLABLE_TYPE_NAME = "ceylon.language::Callable"; private static final String CEYLON_LANGUAGE_TUPLE_TYPE_NAME = "ceylon.language::Tuple"; private static final String CEYLON_LANGUAGE_SEQUENTIAL_TYPE_NAME = "ceylon.language::Sequential"; private static final String CEYLON_LANGUAGE_SEQUENCE_TYPE_NAME = "ceylon.language::Sequence"; private static final String CEYLON_LANGUAGE_EMPTY_TYPE_NAME = "ceylon.language::Empty"; private static final TypeMirror OBJECT_TYPE = simpleCeylonObjectType("java.lang.Object"); private static final TypeMirror ANNOTATION_TYPE = simpleCeylonObjectType("java.lang.annotation.Annotation"); private static final TypeMirror CEYLON_OBJECT_TYPE = simpleCeylonObjectType("ceylon.language.Object"); private static final TypeMirror CEYLON_ANNOTATION_TYPE = simpleCeylonObjectType("ceylon.language.Annotation"); private static final TypeMirror CEYLON_CONSTRAINED_ANNOTATION_TYPE = simpleCeylonObjectType("ceylon.language.ConstrainedAnnotation"); // private static final TypeMirror CEYLON_FUNCTION_DECLARATION_TYPE = simpleCeylonObjectType("ceylon.language.meta.declaration.FunctionDeclaration"); private static final TypeMirror CEYLON_FUNCTION_OR_VALUE_DECLARATION_TYPE = simpleCeylonObjectType("ceylon.language.meta.declaration.FunctionOrValueDeclaration"); private static final TypeMirror CEYLON_VALUE_DECLARATION_TYPE = simpleCeylonObjectType("ceylon.language.meta.declaration.ValueDeclaration"); private static final TypeMirror CEYLON_ALIAS_DECLARATION_TYPE = simpleCeylonObjectType("ceylon.language.meta.declaration.AliasDeclaration"); private static final TypeMirror CEYLON_CLASS_OR_INTERFACE_DECLARATION_TYPE = simpleCeylonObjectType("ceylon.language.meta.declaration.ClassOrInterfaceDeclaration"); private static final TypeMirror CEYLON_CLASS_WITH_INIT_DECLARATION_TYPE = simpleCeylonObjectType("ceylon.language.meta.declaration.ClassWithInitializerDeclaration"); private static final TypeMirror CEYLON_CLASS_WITH_CTORS_DECLARATION_TYPE = simpleCeylonObjectType("ceylon.language.meta.declaration.ClassWithConstructorsDeclaration"); private static final TypeMirror CEYLON_CONSTRUCTOR_DECLARATION_TYPE = simpleCeylonObjectType("ceylon.language.meta.declaration.ConstructorDeclaration"); private static final TypeMirror CEYLON_CALLABLE_CONSTRUCTOR_DECLARATION_TYPE = simpleCeylonObjectType("ceylon.language.meta.declaration.CallableConstructorDeclaration"); private static final TypeMirror CEYLON_VALUE_CONSTRUCTOR_DECLARATION_TYPE = simpleCeylonObjectType("ceylon.language.meta.declaration.ValueConstructorDeclaration"); private static final TypeMirror CEYLON_ANNOTATED_TYPE = simpleCeylonObjectType("ceylon.language.Annotated"); private static final TypeMirror CEYLON_BASIC_TYPE = simpleCeylonObjectType("ceylon.language.Basic"); private static final TypeMirror CEYLON_REIFIED_TYPE_TYPE = simpleCeylonObjectType("com.redhat.ceylon.compiler.java.runtime.model.ReifiedType"); private static final TypeMirror CEYLON_SERIALIZABLE_TYPE = simpleCeylonObjectType("com.redhat.ceylon.compiler.java.runtime.serialization.Serializable"); private static final TypeMirror CEYLON_TYPE_DESCRIPTOR_TYPE = simpleCeylonObjectType("com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor"); private static final TypeMirror THROWABLE_TYPE = simpleCeylonObjectType("java.lang.Throwable"); // private static final TypeMirror ERROR_TYPE = simpleCeylonObjectType("java.lang.Error"); private static final TypeMirror EXCEPTION_TYPE = simpleCeylonObjectType("java.lang.Exception"); private static final TypeMirror CEYLON_THROWABLE_TYPE = simpleCeylonObjectType("java.lang.Throwable"); private static final TypeMirror CEYLON_EXCEPTION_TYPE = simpleCeylonObjectType("ceylon.language.Exception"); private static final TypeMirror STRING_TYPE = simpleJDKObjectType("java.lang.String"); private static final TypeMirror CEYLON_STRING_TYPE = simpleCeylonObjectType("ceylon.language.String"); private static final TypeMirror PRIM_BOOLEAN_TYPE = simpleJDKObjectType("boolean"); private static final TypeMirror CEYLON_BOOLEAN_TYPE = simpleCeylonObjectType("ceylon.language.Boolean"); private static final TypeMirror PRIM_BYTE_TYPE = simpleJDKObjectType("byte"); private static final TypeMirror CEYLON_BYTE_TYPE = simpleCeylonObjectType("ceylon.language.Byte"); private static final TypeMirror PRIM_SHORT_TYPE = simpleJDKObjectType("short"); private static final TypeMirror PRIM_INT_TYPE = simpleJDKObjectType("int"); private static final TypeMirror PRIM_LONG_TYPE = simpleJDKObjectType("long"); private static final TypeMirror CEYLON_INTEGER_TYPE = simpleCeylonObjectType("ceylon.language.Integer"); private static final TypeMirror PRIM_FLOAT_TYPE = simpleJDKObjectType("float"); private static final TypeMirror PRIM_DOUBLE_TYPE = simpleJDKObjectType("double"); private static final TypeMirror CEYLON_FLOAT_TYPE = simpleCeylonObjectType("ceylon.language.Float"); private static final TypeMirror PRIM_CHAR_TYPE = simpleJDKObjectType("char"); private static final TypeMirror CEYLON_CHARACTER_TYPE = simpleCeylonObjectType("ceylon.language.Character"); // this one has no "_" postfix because that's how we look it up protected static final String JAVA_LANG_BYTE_ARRAY = "java.lang.ByteArray"; protected static final String JAVA_LANG_SHORT_ARRAY = "java.lang.ShortArray"; protected static final String JAVA_LANG_INT_ARRAY = "java.lang.IntArray"; protected static final String JAVA_LANG_LONG_ARRAY = "java.lang.LongArray"; protected static final String JAVA_LANG_FLOAT_ARRAY = "java.lang.FloatArray"; protected static final String JAVA_LANG_DOUBLE_ARRAY = "java.lang.DoubleArray"; protected static final String JAVA_LANG_CHAR_ARRAY = "java.lang.CharArray"; protected static final String JAVA_LANG_BOOLEAN_ARRAY = "java.lang.BooleanArray"; protected static final String JAVA_LANG_OBJECT_ARRAY = "java.lang.ObjectArray"; // this one has the "_" postfix because that's what we translate it to private static final String CEYLON_BYTE_ARRAY = "com.redhat.ceylon.compiler.java.language.ByteArray"; private static final String CEYLON_SHORT_ARRAY = "com.redhat.ceylon.compiler.java.language.ShortArray"; private static final String CEYLON_INT_ARRAY = "com.redhat.ceylon.compiler.java.language.IntArray"; private static final String CEYLON_LONG_ARRAY = "com.redhat.ceylon.compiler.java.language.LongArray"; private static final String CEYLON_FLOAT_ARRAY = "com.redhat.ceylon.compiler.java.language.FloatArray"; private static final String CEYLON_DOUBLE_ARRAY = "com.redhat.ceylon.compiler.java.language.DoubleArray"; private static final String CEYLON_CHAR_ARRAY = "com.redhat.ceylon.compiler.java.language.CharArray"; private static final String CEYLON_BOOLEAN_ARRAY = "com.redhat.ceylon.compiler.java.language.BooleanArray"; private static final String CEYLON_OBJECT_ARRAY = "com.redhat.ceylon.compiler.java.language.ObjectArray"; private static final TypeMirror JAVA_BYTE_ARRAY_TYPE = simpleJDKObjectType("java.lang.ByteArray"); private static final TypeMirror JAVA_SHORT_ARRAY_TYPE = simpleJDKObjectType("java.lang.ShortArray"); private static final TypeMirror JAVA_INT_ARRAY_TYPE = simpleJDKObjectType("java.lang.IntArray"); private static final TypeMirror JAVA_LONG_ARRAY_TYPE = simpleJDKObjectType("java.lang.LongArray"); private static final TypeMirror JAVA_FLOAT_ARRAY_TYPE = simpleJDKObjectType("java.lang.FloatArray"); private static final TypeMirror JAVA_DOUBLE_ARRAY_TYPE = simpleJDKObjectType("java.lang.DoubleArray"); private static final TypeMirror JAVA_CHAR_ARRAY_TYPE = simpleJDKObjectType("java.lang.CharArray"); private static final TypeMirror JAVA_BOOLEAN_ARRAY_TYPE = simpleJDKObjectType("java.lang.BooleanArray"); private static final TypeMirror JAVA_IO_SERIALIZABLE_TYPE_TYPE = simpleJDKObjectType("java.io.Serializable"); private static TypeMirror simpleJDKObjectType(String name) { return new SimpleReflType(name, SimpleReflType.Module.JDK, TypeKind.DECLARED); } private static TypeMirror simpleCeylonObjectType(String name) { return new SimpleReflType(name, SimpleReflType.Module.CEYLON, TypeKind.DECLARED); } protected Map<String, Declaration> valueDeclarationsByName = new HashMap<String, Declaration>(); protected Map<String, Declaration> typeDeclarationsByName = new HashMap<String, Declaration>(); protected Map<Package, Unit> unitsByPackage = new HashMap<Package, Unit>(); protected TypeParser typeParser; /** * The type factory * (<strong>should not be used while completing a declaration</strong>) */ protected Unit typeFactory; protected final Set<String> loadedPackages = new HashSet<String>(); protected final Map<String,LazyPackage> packagesByName = new HashMap<String,LazyPackage>(); protected boolean packageDescriptorsNeedLoading = false; protected boolean isBootstrap; protected ModuleManager moduleManager; protected Modules modules; protected Map<String, ClassMirror> classMirrorCache = new HashMap<String, ClassMirror>(); protected boolean binaryCompatibilityErrorRaised = false; protected Timer timer; private Map<String,LazyPackage> modulelessPackages = new HashMap<String,LazyPackage>(); private ParameterNameParser parameterNameParser = new ParameterNameParser(this); /** * Loads a given package, if required. This is mostly useful for the javac reflection impl. * * @param the module to load the package from * @param packageName the package name to load * @param loadDeclarations true to load all the declarations in this package. * @return */ public abstract boolean loadPackage(Module module, String packageName, boolean loadDeclarations); public final Object getLock(){ return this; } /** * To be redefined by subclasses if they don't need local declarations. */ protected boolean needsLocalDeclarations(){ return true; } /** * For subclassers to skip private members. Defaults to false. */ protected boolean needsPrivateMembers() { return true; } public boolean searchAgain(ClassMirror cachedMirror, Module module, String name) { return false; } public boolean searchAgain(Declaration cachedDeclaration, LazyPackage lazyPackage, String name) { return false; } /** * Looks up a ClassMirror by name. Uses cached results, and caches the result of calling lookupNewClassMirror * on cache misses. * * @param module the module in which we should find the class * @param name the name of the Class to load * @return a ClassMirror for the specified class, or null if not found. */ public final ClassMirror lookupClassMirror(Module module, String name) { synchronized(getLock()){ timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY); try{ // Java array classes are not where we expect them if (JAVA_LANG_OBJECT_ARRAY.equals(name) || JAVA_LANG_BOOLEAN_ARRAY.equals(name) || JAVA_LANG_BYTE_ARRAY.equals(name) || JAVA_LANG_SHORT_ARRAY.equals(name) || JAVA_LANG_INT_ARRAY.equals(name) || JAVA_LANG_LONG_ARRAY.equals(name) || JAVA_LANG_FLOAT_ARRAY.equals(name) || JAVA_LANG_DOUBLE_ARRAY.equals(name) || JAVA_LANG_CHAR_ARRAY.equals(name)) { // turn them into their real class location (get rid of the "java.lang" prefix) name = "com.redhat.ceylon.compiler.java.language" + name.substring(9); module = getLanguageModule(); } String cacheKey = cacheKeyByModule(module, name); // we use containsKey to be able to cache null results if(classMirrorCache.containsKey(cacheKey)) { ClassMirror cachedMirror = classMirrorCache.get(cacheKey); if (! searchAgain(cachedMirror, module, name)) { return cachedMirror; } } ClassMirror mirror = lookupNewClassMirror(module, name); // we even cache null results classMirrorCache.put(cacheKey, mirror); return mirror; }finally{ timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY); } } } protected String cacheKeyByModule(Module module, String name) { return getCacheKeyByModule(module, name); } public static String getCacheKeyByModule(Module module, String name){ String moduleSignature = module.getSignature(); StringBuilder buf = new StringBuilder(moduleSignature.length()+1+name.length()); // '/' is allowed in module version but not in module or class name, so we're good return buf.append(moduleSignature).append('/').append(name).toString(); } protected boolean lastPartHasLowerInitial(String name) { int index = name.lastIndexOf('.'); if (index != -1){ name = name.substring(index+1); } // remove any possibly quoting char name = NamingBase.stripLeadingDollar(name); if(!name.isEmpty()){ int codepoint = name.codePointAt(0); return JvmBackendUtil.isLowerCase(codepoint); } return false; } /** * Looks up a ClassMirror by name. Called by lookupClassMirror on cache misses. * * @param module the module in which we should find the given class * @param name the name of the Class to load * @return a ClassMirror for the specified class, or null if not found. */ protected abstract ClassMirror lookupNewClassMirror(Module module, String name); /** * Adds the given module to the set of modules from which we can load classes. * * @param module the module * @param artifact the module's artifact, if any. Can be null. */ public abstract void addModuleToClassPath(Module module, ArtifactResult artifact); /** * Returns true if the given module has been added to this model loader's classpath. * Defaults to true. */ public boolean isModuleInClassPath(Module module){ return true; } /** * Returns true if the given method is overriding an inherited method (from super class or interfaces). */ protected abstract boolean isOverridingMethod(MethodMirror methodMirror); /** * Returns true if the given method is overloading an inherited method (from super class or interfaces). */ protected abstract boolean isOverloadingMethod(MethodMirror methodMirror); /** * Logs a warning. */ protected abstract void logWarning(String message); /** * Logs a debug message. */ protected abstract void logVerbose(String message); /** * Logs an error */ protected abstract void logError(String message); public void loadStandardModules(){ // set up the type factory Timer nested = timer.nestedTimer(); nested.startTask("load ceylon.language"); Module languageModule = loadLanguageModuleAndPackage(); nested.endTask(); nested.startTask("load JDK"); // make sure the jdk modules are loaded loadJDKModules(); Module jdkModule = findOrCreateModule(JAVA_BASE_MODULE_NAME, JDKUtils.jdk.version); nested.endTask(); /* * We start by loading java.lang and ceylon.language because we will need them no matter what. */ nested.startTask("load standard packages"); loadPackage(jdkModule, "java.lang", false); loadPackage(languageModule, "com.redhat.ceylon.compiler.java.metadata", false); loadPackage(languageModule, "com.redhat.ceylon.compiler.java.language", false); nested.endTask(); } protected Module loadLanguageModuleAndPackage() { Module languageModule = findOrCreateModule(CEYLON_LANGUAGE, null); addModuleToClassPath(languageModule, null); Package languagePackage = findOrCreatePackage(languageModule, CEYLON_LANGUAGE); typeFactory.setPackage(languagePackage); // make sure the language module has its real dependencies added, because we need them in the classpath // otherwise we will get errors on the Util and Metamodel calls we insert // WARNING! Make sure this list is always the same as the one in /ceylon-runtime/dist/repo/ceylon/language/_version_/module.xml languageModule.addImport(new ModuleImport(findOrCreateModule("com.redhat.ceylon.compiler.java", Versions.CEYLON_VERSION_NUMBER), false, false, Backend.Java)); languageModule.addImport(new ModuleImport(findOrCreateModule("com.redhat.ceylon.compiler.js", Versions.CEYLON_VERSION_NUMBER), false, false, Backend.Java)); languageModule.addImport(new ModuleImport(findOrCreateModule("com.redhat.ceylon.common", Versions.CEYLON_VERSION_NUMBER), false, false, Backend.Java)); languageModule.addImport(new ModuleImport(findOrCreateModule("com.redhat.ceylon.model", Versions.CEYLON_VERSION_NUMBER), false, false, Backend.Java)); languageModule.addImport(new ModuleImport(findOrCreateModule("com.redhat.ceylon.module-resolver", Versions.CEYLON_VERSION_NUMBER), false, false, Backend.Java)); languageModule.addImport(new ModuleImport(findOrCreateModule("com.redhat.ceylon.typechecker", Versions.CEYLON_VERSION_NUMBER), false, false, Backend.Java)); languageModule.addImport(new ModuleImport(findOrCreateModule("org.jboss.modules", Versions.DEPENDENCY_JBOSS_MODULES_VERSION), false, false, Backend.Java)); languageModule.addImport(new ModuleImport(findOrCreateModule("org.jboss.jandex", Versions.DEPENDENCY_JANDEX_VERSION), false, false, Backend.Java)); return languageModule; } protected void loadJDKModules() { for(String jdkModule : JDKUtils.getJDKModuleNames()) findOrCreateModule(jdkModule, JDKUtils.jdk.version); for(String jdkOracleModule : JDKUtils.getOracleJDKModuleNames()) findOrCreateModule(jdkOracleModule, JDKUtils.jdk.version); } /** * This is meant to be called if your subclass doesn't call loadStandardModules for whatever reason */ public void setupWithNoStandardModules() { Module languageModule = modules.getLanguageModule(); if(languageModule == null) throw new RuntimeException("Assertion failed: language module is null"); Package languagePackage = languageModule.getPackage(CEYLON_LANGUAGE); if(languagePackage == null) throw new RuntimeException("Assertion failed: language package is null"); typeFactory.setPackage(languagePackage); } enum ClassType { ATTRIBUTE, METHOD, OBJECT, CLASS, INTERFACE; } private ClassMirror loadClass(Module module, String pkgName, String className) { ClassMirror moduleClass = null; try{ loadPackage(module, pkgName, false); moduleClass = lookupClassMirror(module, className); }catch(Exception x){ logVerbose("[Failed to complete class "+className+"]"); } return moduleClass; } private Declaration convertNonPrimitiveTypeToDeclaration(Module moduleScope, TypeMirror type, Scope scope, DeclarationType declarationType) { switch(type.getKind()){ case VOID: return typeFactory.getAnythingDeclaration(); case ARRAY: return ((Class)convertToDeclaration(getLanguageModule(), JAVA_LANG_OBJECT_ARRAY, DeclarationType.TYPE)); case DECLARED: return convertDeclaredTypeToDeclaration(moduleScope, type, declarationType); case TYPEVAR: return safeLookupTypeParameter(scope, type.getQualifiedName()); case WILDCARD: return typeFactory.getNothingDeclaration(); // those can't happen case BOOLEAN: case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT: case DOUBLE: // all the autoboxing should already have been done throw new RuntimeException("Expected non-primitive type: "+type); case ERROR: return null; default: throw new RuntimeException("Failed to handle type "+type); } } private Declaration convertDeclaredTypeToDeclaration(Module moduleScope, TypeMirror type, DeclarationType declarationType) { // SimpleReflType does not do declared class so we make an exception for it String typeName = type.getQualifiedName(); if(type instanceof SimpleReflType){ Module module = null; switch(((SimpleReflType) type).getModule()){ case CEYLON: module = getLanguageModule(); break; case JDK : module = getJDKBaseModule(); break; } return convertToDeclaration(module, typeName, declarationType); } ClassMirror classMirror = type.getDeclaredClass(); Module module = findModuleForClassMirror(classMirror); if(isImported(moduleScope, module)){ return convertToDeclaration(module, typeName, declarationType); }else{ if(module != null && isFlatClasspath() && isMavenModule(moduleScope)) return convertToDeclaration(module, typeName, declarationType); String error = "Declaration '" + typeName + "' could not be found in module '" + moduleScope.getNameAsString() + "' or its imported modules"; if(module != null && !module.isDefault()) error += " but was found in the non-imported module '"+module.getNameAsString()+"'"; return logModelResolutionException(null, moduleScope, error).getDeclaration(); } } public Declaration convertToDeclaration(Module module, ClassMirror classMirror, DeclarationType declarationType) { return convertToDeclaration(module, null, classMirror, declarationType); } private Declaration convertToDeclaration(Module module, Declaration container, ClassMirror classMirror, DeclarationType declarationType) { // find its package String pkgName = getPackageNameForQualifiedClassName(classMirror); if (pkgName.equals("java.lang")) { module = getJDKBaseModule(); } Declaration decl = findCachedDeclaration(module, container, classMirror, declarationType); if (decl != null) { return decl; } // avoid ignored classes if(classMirror.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null) return null; // avoid local interfaces that were pulled to the toplevel if required if(classMirror.getAnnotation(CEYLON_LOCAL_CONTAINER_ANNOTATION) != null && !needsLocalDeclarations()) return null; // avoid Ceylon annotations if(classMirror.getAnnotation(CEYLON_CEYLON_ANNOTATION) != null && classMirror.isAnnotationType()) return null; // avoid module and package descriptors too if(classMirror.getAnnotation(CEYLON_MODULE_ANNOTATION) != null || classMirror.getAnnotation(CEYLON_PACKAGE_ANNOTATION) != null) return null; List<Declaration> decls = new ArrayList<Declaration>(); LazyPackage pkg = findOrCreatePackage(module, pkgName); decl = createDeclaration(module, container, classMirror, declarationType, decls); cacheDeclaration(module, container, classMirror, declarationType, decl, decls); // find/make its Unit Unit unit = getCompiledUnit(pkg, classMirror); // set all the containers for(Declaration d : decls){ // add it to its Unit d.setUnit(unit); unit.addDeclaration(d); setContainer(classMirror, d, pkg); } return decl; } public String getPackageNameForQualifiedClassName(String pkg, String qualifiedName){ // Java array classes we pretend come from java.lang if(qualifiedName.startsWith(CEYLON_OBJECT_ARRAY) || qualifiedName.startsWith(CEYLON_BOOLEAN_ARRAY) || qualifiedName.startsWith(CEYLON_BYTE_ARRAY) || qualifiedName.startsWith(CEYLON_SHORT_ARRAY) || qualifiedName.startsWith(CEYLON_INT_ARRAY) || qualifiedName.startsWith(CEYLON_LONG_ARRAY) || qualifiedName.startsWith(CEYLON_FLOAT_ARRAY) || qualifiedName.startsWith(CEYLON_DOUBLE_ARRAY) || qualifiedName.startsWith(CEYLON_CHAR_ARRAY)) return "java.lang"; else return unquotePackageName(pkg); } protected String getPackageNameForQualifiedClassName(ClassMirror classMirror) { return getPackageNameForQualifiedClassName(classMirror.getPackage().getQualifiedName(), classMirror.getQualifiedName()); } private String unquotePackageName(PackageMirror pkg) { return unquotePackageName(pkg.getQualifiedName()); } private String unquotePackageName(String pkg) { return JvmBackendUtil.removeChar('$', pkg); } private void setContainer(ClassMirror classMirror, Declaration d, LazyPackage pkg) { // add it to its package if it's not an inner class if(!classMirror.isInnerClass() && !classMirror.isLocalClass()){ d.setContainer(pkg); d.setScope(pkg); pkg.addCompiledMember(d); if(d instanceof LazyInterface && ((LazyInterface) d).isCeylon()){ setInterfaceCompanionClass(d, null, pkg); } ModelUtil.setVisibleScope(d); }else if(classMirror.isLocalClass() && !classMirror.isInnerClass()){ // set its container to the package for now, but don't add it to the package as a member because it's not Scope localContainer = getLocalContainer(pkg, classMirror, d); if(localContainer != null){ d.setContainer(localContainer); d.setScope(localContainer); // do not add it as member, it has already been registered by getLocalContainer }else{ d.setContainer(pkg); d.setScope(pkg); } ((LazyElement)d).setLocal(true); }else if(d instanceof ClassOrInterface || d instanceof TypeAlias){ // do overloads later, since their container is their abstract superclass's container and // we have to set that one first if(d instanceof Class == false || !((Class)d).isOverloaded()){ ClassOrInterface container = getContainer(pkg.getModule(), classMirror); if (d.isNativeHeader() && container.isNative()) { container = (ClassOrInterface)ModelUtil.getNativeHeader(container); } d.setContainer(container); d.setScope(container); if(d instanceof LazyInterface && ((LazyInterface) d).isCeylon()){ setInterfaceCompanionClass(d, container, pkg); } // let's not trigger lazy-loading ((LazyContainer)container).addMember(d); ModelUtil.setVisibleScope(d); // now we can do overloads if(d instanceof Class && ((Class)d).getOverloads() != null){ for(Declaration overload : ((Class)d).getOverloads()){ overload.setContainer(container); overload.setScope(container); // let's not trigger lazy-loading ((LazyContainer)container).addMember(overload); ModelUtil.setVisibleScope(overload); } } } } } protected void setInterfaceCompanionClass(Declaration d, ClassOrInterface container, LazyPackage pkg) { // find its companion class in its real container ClassMirror containerMirror = null; if(container instanceof LazyClass){ containerMirror = ((LazyClass) container).classMirror; }else if(container instanceof LazyInterface){ // container must be a LazyInterface, as TypeAlias doesn't contain anything containerMirror = ((LazyInterface)container).companionClass; if(containerMirror == null){ throw new ModelResolutionException("Interface companion class for "+container.getQualifiedNameString()+" not set up"); } } String companionName; if(containerMirror != null) companionName = containerMirror.getFlatName() + "$" + NamingBase.suffixName(NamingBase.Suffix.$impl, d.getName()); else{ // toplevel String p = pkg.getNameAsString(); companionName = ""; if(!p.isEmpty()) companionName = p + "."; companionName += NamingBase.suffixName(NamingBase.Suffix.$impl, d.getName()); } ClassMirror companionClass = lookupClassMirror(pkg.getModule(), companionName); if(companionClass == null){ ((Interface)d).setCompanionClassNeeded(false); } ((LazyInterface)d).companionClass = companionClass; } private Scope getLocalContainer(Package pkg, ClassMirror classMirror, Declaration declaration) { AnnotationMirror localContainerAnnotation = classMirror.getAnnotation(CEYLON_LOCAL_CONTAINER_ANNOTATION); String qualifier = getAnnotationStringValue(classMirror, CEYLON_LOCAL_DECLARATION_ANNOTATION, "qualifier"); // deal with types local to functions in the body of toplevel non-lazy attributes, whose container is ultimately the package Boolean isPackageLocal = getAnnotationBooleanValue(classMirror, CEYLON_LOCAL_DECLARATION_ANNOTATION, "isPackageLocal"); if(BooleanUtil.isTrue(isPackageLocal)){ // make sure it still knows it's a local declaration.setQualifier(qualifier); return null; } LocalDeclarationContainer methodDecl = null; // we get a @LocalContainer annotation for local interfaces if(localContainerAnnotation != null){ methodDecl = (LocalDeclarationContainer) findLocalContainerFromAnnotationAndSetCompanionClass(pkg, (Interface) declaration, localContainerAnnotation); }else{ // all the other cases stay where they belong MethodMirror method = classMirror.getEnclosingMethod(); if(method == null) return null; // see where that method belongs ClassMirror enclosingClass = method.getEnclosingClass(); while(enclosingClass.isAnonymous()){ // this gives us the method in which the anonymous class is, which should be the one we're looking for method = enclosingClass.getEnclosingMethod(); if(method == null) return null; // and the method's containing class enclosingClass = method.getEnclosingClass(); } // if we are in a setter class, the attribute is declared in the getter class, so look for its declaration there TypeMirror getterClass = (TypeMirror) getAnnotationValue(enclosingClass, CEYLON_SETTER_ANNOTATION, "getterClass"); boolean isSetter = false; // we use void.class as default value if(getterClass != null && !getterClass.isPrimitive()){ enclosingClass = getterClass.getDeclaredClass(); isSetter = true; } String javaClassName = enclosingClass.getQualifiedName(); // make sure we don't go looking in companion classes if(javaClassName.endsWith(NamingBase.Suffix.$impl.name())) javaClassName = javaClassName.substring(0, javaClassName.length() - 5); // find the enclosing declaration Declaration enclosingClassDeclaration = convertToDeclaration(pkg.getModule(), javaClassName, DeclarationType.TYPE); if(enclosingClassDeclaration instanceof ClassOrInterface){ ClassOrInterface containerDecl = (ClassOrInterface) enclosingClassDeclaration; // now find the method's declaration // FIXME: find the proper overload if any String name = method.getName(); if(method.isConstructor() || name.startsWith(NamingBase.Prefix.$default$.toString())){ methodDecl = (LocalDeclarationContainer) containerDecl; }else{ // this is only for error messages String type; // lots of special cases if(isStringAttribute(method)){ name = "string"; type = "attribute"; }else if(isHashAttribute(method)){ name = "hash"; type = "attribute"; }else if(isGetter(method)) { // simple attribute name = getJavaAttributeName(method); type = "attribute"; }else if(isSetter(method)) { // simple attribute name = getJavaAttributeName(method); type = "attribute setter"; isSetter = true; }else{ type = "method"; } // strip any escaping or private suffix // it can be foo$priv$canonical so get rid of that one first if (name.endsWith(NamingBase.Suffix.$canonical$.toString())) { name = name.substring(0, name.length()-11); } name = JvmBackendUtil.strip(name, true, method.isPublic() || method.isProtected() || method.isDefaultAccess()); if(name.indexOf('$') > 0){ // may be a default parameter expression? get the method name which is first name = name.substring(0, name.indexOf('$')); } methodDecl = (LocalDeclarationContainer) containerDecl.getDirectMember(name, null, false); if(methodDecl == null) throw new ModelResolutionException("Failed to load outer "+type+" " + name + " for local type " + classMirror.getQualifiedName().toString()); // if it's a setter we wanted, let's get it if(isSetter){ LocalDeclarationContainer setter = (LocalDeclarationContainer) ((Value)methodDecl).getSetter(); if(setter == null) throw new ModelResolutionException("Failed to load outer "+type+" " + name + " for local type " + classMirror.getQualifiedName().toString()); methodDecl = setter; } } }else if(enclosingClassDeclaration instanceof LazyFunction){ // local and toplevel methods methodDecl = (LazyFunction)enclosingClassDeclaration; }else if(enclosingClassDeclaration instanceof LazyValue){ // local and toplevel attributes if(enclosingClassDeclaration.isToplevel() && method.getName().equals(NamingBase.Unfix.set_.name())) isSetter = true; if(isSetter){ LocalDeclarationContainer setter = (LocalDeclarationContainer) ((LazyValue)enclosingClassDeclaration).getSetter(); if(setter == null) throw new ModelResolutionException("Failed to toplevel attribute setter " + enclosingClassDeclaration.getName() + " for local type " + classMirror.getQualifiedName().toString()); methodDecl = setter; }else methodDecl = (LazyValue)enclosingClassDeclaration; }else{ throw new ModelResolutionException("Unknown container type " + enclosingClassDeclaration + " for local type " + classMirror.getQualifiedName().toString()); } } // we have the method, now find the proper local qualifier if any if(qualifier == null) return null; declaration.setQualifier(qualifier); methodDecl.addLocalDeclaration(declaration); return methodDecl; } private Scope findLocalContainerFromAnnotationAndSetCompanionClass(Package pkg, Interface declaration, AnnotationMirror localContainerAnnotation) { @SuppressWarnings("unchecked") List<String> path = (List<String>) localContainerAnnotation.getValue("path"); // we start at the package Scope scope = pkg; for(String name : path){ scope = (Scope) getDirectMember(scope, name); } String companionClassName = (String) localContainerAnnotation.getValue("companionClassName"); if(companionClassName == null || companionClassName.isEmpty()){ declaration.setCompanionClassNeeded(false); return scope; } ClassMirror container; Scope javaClassScope; if(scope instanceof TypedDeclaration && ((TypedDeclaration) scope).isMember()) javaClassScope = scope.getContainer(); else javaClassScope = scope; if(javaClassScope instanceof LazyInterface){ container = ((LazyInterface)javaClassScope).companionClass; }else if(javaClassScope instanceof LazyClass){ container = ((LazyClass) javaClassScope).classMirror; }else if(javaClassScope instanceof LazyValue){ container = ((LazyValue) javaClassScope).classMirror; }else if(javaClassScope instanceof LazyFunction){ container = ((LazyFunction) javaClassScope).classMirror; }else if(javaClassScope instanceof SetterWithLocalDeclarations){ container = ((SetterWithLocalDeclarations) javaClassScope).classMirror; }else{ throw new ModelResolutionException("Unknown scope class: "+javaClassScope); } String qualifiedCompanionClassName = container.getQualifiedName() + "$" + companionClassName; ClassMirror companionClassMirror = lookupClassMirror(pkg.getModule(), qualifiedCompanionClassName); if(companionClassMirror == null) throw new ModelResolutionException("Could not find companion class mirror: "+qualifiedCompanionClassName); ((LazyInterface)declaration).companionClass = companionClassMirror; return scope; } /** * Looks for a direct member of type ClassOrInterface. We're not using Class.getDirectMember() * because it skips object types and we want them. */ public static Declaration getDirectMember(Scope container, String name) { if(name.isEmpty()) return null; boolean wantsSetter = false; if(name.startsWith(NamingBase.Suffix.$setter$.name())){ wantsSetter = true; name = name.substring(8); } if(Character.isDigit(name.charAt(0))){ // this is a local type we have a different accessor for it return ((LocalDeclarationContainer)container).getLocalDeclaration(name); } // don't even try using getDirectMember except on Package, // because it will fail miserably during completion, since we // will for instance have only anonymous types first, before we load their anonymous values, and // when we go looking for them we won't be able to find them until we add their anonymous values, // which is too late if(container instanceof Package){ // don't use Package.getMembers() as it loads the whole package Declaration result = container.getDirectMember(name, null, false); return selectTypeOrSetter(result, wantsSetter); }else{ // must be a Declaration for(Declaration member : container.getMembers()){ // avoid constructors with no name if(member.getName() == null) continue; if(!member.getName().equals(name)) continue; Declaration result = selectTypeOrSetter(member, wantsSetter); if(result != null) return result; } } // not found return null; } private static Declaration selectTypeOrSetter(Declaration member, boolean wantsSetter) { // if we found a type or a method/value we're good to go if (member instanceof ClassOrInterface || member instanceof Constructor || member instanceof Function) { return member; } // if it's a Value return its object type by preference, the member otherwise if (member instanceof Value){ TypeDeclaration typeDeclaration = ((Value) member).getTypeDeclaration(); if(typeDeclaration instanceof Class && typeDeclaration.isAnonymous()) return typeDeclaration; // did we want the setter? if(wantsSetter) return ((Value)member).getSetter(); // must be a non-object value return member; } return null; } private ClassOrInterface getContainer(Module module, ClassMirror classMirror) { AnnotationMirror containerAnnotation = classMirror.getAnnotation(CEYLON_CONTAINER_ANNOTATION); if(containerAnnotation != null){ TypeMirror javaClassMirror = (TypeMirror)containerAnnotation.getValue("klass"); String javaClassName = javaClassMirror.getQualifiedName(); ClassOrInterface containerDecl = (ClassOrInterface) convertToDeclaration(module, javaClassName, DeclarationType.TYPE); if(containerDecl == null) throw new ModelResolutionException("Failed to load outer type " + javaClassName + " for inner type " + classMirror.getQualifiedName().toString()); return containerDecl; }else{ return (ClassOrInterface) convertToDeclaration(module, classMirror.getEnclosingClass(), DeclarationType.TYPE); } } private Declaration findCachedDeclaration(Module module, Declaration container, ClassMirror classMirror, DeclarationType declarationType) { ClassType type = getClassType(classMirror); String key = classMirror.getCacheKey(module); boolean isNativeHeaderMember = container != null && container.isNativeHeader(); if (isNativeHeaderMember) { key = key + "$header"; } // see if we already have it Map<String, Declaration> declarationCache = getCacheByType(type, declarationType); return declarationCache.get(key); } private void cacheDeclaration(Module module, Declaration container, ClassMirror classMirror, DeclarationType declarationType, Declaration decl, List<Declaration> decls) { ClassType type = getClassType(classMirror); String key = classMirror.getCacheKey(module); boolean isNativeHeaderMember = container != null && container.isNativeHeader(); if (isNativeHeaderMember) { key = key + "$header"; } if(type == ClassType.OBJECT){ typeDeclarationsByName.put(key, getByType(decls, Class.class)); valueDeclarationsByName.put(key, getByType(decls, Value.class)); }else { Map<String, Declaration> declarationCache = getCacheByType(type, declarationType); declarationCache.put(key, decl); } } private Map<String, Declaration> getCacheByType(ClassType type, DeclarationType declarationType) { Map<String, Declaration> declarationCache = null; switch(type){ case OBJECT: if(declarationType == DeclarationType.TYPE){ declarationCache = typeDeclarationsByName; break; } // else fall-through to value case ATTRIBUTE: case METHOD: declarationCache = valueDeclarationsByName; break; case CLASS: case INTERFACE: declarationCache = typeDeclarationsByName; } return declarationCache; } private Declaration getByType(List<Declaration> decls, java.lang.Class<?> klass) { for (Declaration decl : decls) { if (klass.isAssignableFrom(decl.getClass())) { return decl; } } return null; } private Declaration createDeclaration(Module module, Declaration container, ClassMirror classMirror, DeclarationType declarationType, List<Declaration> decls) { Declaration decl = null; Declaration hdr = null; checkBinaryCompatibility(classMirror); ClassType type = getClassType(classMirror); boolean isCeylon = classMirror.getAnnotation(CEYLON_CEYLON_ANNOTATION) != null; boolean isNativeHeaderMember = container != null && container.isNativeHeader(); try{ // make it switch(type){ case ATTRIBUTE: decl = makeToplevelAttribute(classMirror, isNativeHeaderMember); setNonLazyDeclarationProperties(decl, classMirror, classMirror, classMirror, true); if (isCeylon && shouldCreateNativeHeader(decl, container)) { hdr = makeToplevelAttribute(classMirror, true); setNonLazyDeclarationProperties(hdr, classMirror, classMirror, classMirror, true); } break; case METHOD: decl = makeToplevelMethod(classMirror, isNativeHeaderMember); setNonLazyDeclarationProperties(decl, classMirror, classMirror, classMirror, true); if (isCeylon && shouldCreateNativeHeader(decl, container)) { hdr = makeToplevelMethod(classMirror, true); setNonLazyDeclarationProperties(hdr, classMirror, classMirror, classMirror, true); } break; case OBJECT: // we first make a class Declaration objectClassDecl = makeLazyClass(classMirror, null, null, isNativeHeaderMember); setNonLazyDeclarationProperties(objectClassDecl, classMirror, classMirror, classMirror, true); decls.add(objectClassDecl); if (isCeylon && shouldCreateNativeHeader(objectClassDecl, container)) { Declaration hdrobj = makeLazyClass(classMirror, null, null, true); setNonLazyDeclarationProperties(hdrobj, classMirror, classMirror, classMirror, true); decls.add(initNativeHeader(hdrobj, objectClassDecl)); } // then we make a value for it, if it's not an inline object expr if(objectClassDecl.isNamed()){ Declaration objectDecl = makeToplevelAttribute(classMirror, isNativeHeaderMember); setNonLazyDeclarationProperties(objectDecl, classMirror, classMirror, classMirror, true); decls.add(objectDecl); if (isCeylon && shouldCreateNativeHeader(objectDecl, container)) { Declaration hdrobj = makeToplevelAttribute(classMirror, true); setNonLazyDeclarationProperties(hdrobj, classMirror, classMirror, classMirror, true); decls.add(initNativeHeader(hdrobj, objectDecl)); } // which one did we want? decl = declarationType == DeclarationType.TYPE ? objectClassDecl : objectDecl; }else{ decl = objectClassDecl; } break; case CLASS: if(classMirror.getAnnotation(CEYLON_ALIAS_ANNOTATION) != null){ decl = makeClassAlias(classMirror); setNonLazyDeclarationProperties(decl, classMirror, classMirror, classMirror, true); }else if(classMirror.getAnnotation(CEYLON_TYPE_ALIAS_ANNOTATION) != null){ decl = makeTypeAlias(classMirror); setNonLazyDeclarationProperties(decl, classMirror, classMirror, classMirror, true); }else{ final List<MethodMirror> constructors = getClassConstructors(classMirror, constructorOnly); if (!constructors.isEmpty()) { Boolean hasConstructors = hasConstructors(classMirror); if (constructors.size() > 1) { if (hasConstructors == null || !hasConstructors) { decl = makeOverloadedConstructor(constructors, classMirror, decls, isCeylon); } else { decl = makeLazyClass(classMirror, null, null, isNativeHeaderMember); setNonLazyDeclarationProperties(decl, classMirror, classMirror, classMirror, isCeylon); if (isCeylon && shouldCreateNativeHeader(decl, container)) { hdr = makeLazyClass(classMirror, null, null, true); setNonLazyDeclarationProperties(hdr, classMirror, classMirror, classMirror, true); } } } else { if (hasConstructors == null || !hasConstructors) { // single constructor MethodMirror constructor = constructors.get(0); // if the class and constructor have different visibility, we pretend there's an overload of one // if it's a ceylon class we don't care that they don't match sometimes, like for inner classes // where the constructor is protected because we want to use an accessor, in this case the class // visibility is to be used if(isCeylon || getJavaVisibility(classMirror) == getJavaVisibility(constructor)){ decl = makeLazyClass(classMirror, null, constructor, isNativeHeaderMember); setNonLazyDeclarationProperties(decl, classMirror, classMirror, classMirror, isCeylon); if (isCeylon && shouldCreateNativeHeader(decl, container)) { hdr = makeLazyClass(classMirror, null, constructor, true); setNonLazyDeclarationProperties(hdr, classMirror, classMirror, classMirror, true); } }else{ decl = makeOverloadedConstructor(constructors, classMirror, decls, isCeylon); } } else { decl = makeLazyClass(classMirror, null, null, isNativeHeaderMember); setNonLazyDeclarationProperties(decl, classMirror, classMirror, classMirror, isCeylon); if (isCeylon && shouldCreateNativeHeader(decl, container)) { hdr = makeLazyClass(classMirror, null, null, true); setNonLazyDeclarationProperties(hdr, classMirror, classMirror, classMirror, true); } } } } else if(isCeylon && classMirror.getAnnotation(CEYLON_OBJECT_ANNOTATION) != null) { // objects don't need overloading stuff decl = makeLazyClass(classMirror, null, null, isNativeHeaderMember); setNonLazyDeclarationProperties(decl, classMirror, classMirror, classMirror, isCeylon); if (isCeylon && shouldCreateNativeHeader(decl, container)) { hdr = makeLazyClass(classMirror, null, null, true); setNonLazyDeclarationProperties(hdr, classMirror, classMirror, classMirror, true); } } else { // no visible constructors decl = makeLazyClass(classMirror, null, null, isNativeHeaderMember); setNonLazyDeclarationProperties(decl, classMirror, classMirror, classMirror, isCeylon); if (isCeylon && shouldCreateNativeHeader(decl, container)) { hdr = makeLazyClass(classMirror, null, null, true); setNonLazyDeclarationProperties(hdr, classMirror, classMirror, classMirror, true); } } if (!isCeylon) { setSealedFromConstructorMods(decl, constructors); } } break; case INTERFACE: boolean isAlias = classMirror.getAnnotation(CEYLON_ALIAS_ANNOTATION) != null; if(isAlias){ decl = makeInterfaceAlias(classMirror); }else{ decl = makeLazyInterface(classMirror, isNativeHeaderMember); } setNonLazyDeclarationProperties(decl, classMirror, classMirror, classMirror, isCeylon); if (!isAlias && isCeylon && shouldCreateNativeHeader(decl, container)) { hdr = makeLazyInterface(classMirror, true); setNonLazyDeclarationProperties(hdr, classMirror, classMirror, classMirror, true); } break; } }catch(ModelResolutionException x){ // FIXME: this may not be the best thing to do, perhaps we should have an erroneous Class,Interface,Function // etc, like javac's model does? decl = logModelResolutionException(x, null, "Failed to load declaration "+classMirror).getDeclaration(); } // objects have special handling above if(type != ClassType.OBJECT){ decls.add(decl); if (hdr != null) { decls.add(initNativeHeader(hdr, decl)); } } return decl; } private ClassType getClassType(ClassMirror classMirror) { ClassType type; if(classMirror.isCeylonToplevelAttribute()){ type = ClassType.ATTRIBUTE; }else if(classMirror.isCeylonToplevelMethod()){ type = ClassType.METHOD; }else if(classMirror.isCeylonToplevelObject()){ type = ClassType.OBJECT; }else if(classMirror.isInterface()){ type = ClassType.INTERFACE; }else{ type = ClassType.CLASS; } return type; } private boolean shouldCreateNativeHeader(Declaration decl, Declaration container) { // TODO instead of checking for "shared" we should add an annotation // to all declarations that have a native header and check that here if (decl.isNativeImplementation() && decl.isShared()) { if (container != null) { if (!decl.isOverloaded()) { return !container.isNative(); } } else { return true; } } return false; } private boolean shouldLinkNatives(Declaration decl) { // TODO instead of checking for "shared" we should add an annotation // to all declarations that have a native header and check that here if (decl.isNative() && decl.isShared()) { Declaration container = (Declaration)decl.getContainer(); return container.isNativeHeader(); } return false; } private Declaration initNativeHeader(Declaration hdr, Declaration impl) { List<Declaration> al = getOverloads(hdr); if (al == null) { al = new ArrayList<Declaration>(1); } al.add(impl); setOverloads(hdr, al); return hdr; } private void initNativeHeaderMember(Declaration hdr) { Declaration impl = ModelUtil.getNativeDeclaration(hdr.getContainer(), hdr.getName(), Backends.JAVA); initNativeHeader(hdr, impl); } /** Returns: * <ul> * <li>true if the class has named constructors ({@code @Class(...constructors=true)}).</li> * <li>false if the class has an initializer constructor.</li> * <li>null if the class lacks {@code @Class} (i.e. is not a Ceylon class).</li> * </ul> * @param classMirror * @return */ private Boolean hasConstructors(ClassMirror classMirror) { AnnotationMirror a = classMirror.getAnnotation(CEYLON_CLASS_ANNOTATION); Boolean hasConstructors; if (a != null) { hasConstructors = (Boolean)a.getValue("constructors"); if (hasConstructors == null) { hasConstructors = false; } } else { hasConstructors = null; } return hasConstructors; } private boolean isDefaultNamedCtor(ClassMirror classMirror, MethodMirror ctor) { return classMirror.getName().equals(getCtorName(ctor)); } private String getCtorName(MethodMirror ctor) { AnnotationMirror nameAnno = ctor.getAnnotation(CEYLON_NAME_ANNOTATION); if (nameAnno != null) { return (String)nameAnno.getValue(); } else { return null; } } private void setSealedFromConstructorMods(Declaration decl, final List<MethodMirror> constructors) { boolean effectivelySealed = true; for (MethodMirror ctor : constructors) { if (ctor.isPublic() || ctor.isProtected()) { effectivelySealed = false; break; } } if (effectivelySealed && decl instanceof Class) { Class type = (Class)decl; type.setSealed(effectivelySealed); if (type.getOverloads() != null) { for (Declaration oload : type.getOverloads()) { ((Class)oload).setSealed(effectivelySealed); } } } } private Declaration makeOverloadedConstructor(List<MethodMirror> constructors, ClassMirror classMirror, List<Declaration> decls, boolean isCeylon) { // If the class has multiple constructors we make a copy of the class // for each one (each with it's own single constructor) and make them // a subclass of the original Class supercls = makeLazyClass(classMirror, null, null, false); // the abstraction class gets the class modifiers setNonLazyDeclarationProperties(supercls, classMirror, classMirror, classMirror, isCeylon); supercls.setAbstraction(true); List<Declaration> overloads = new ArrayList<Declaration>(constructors.size()); // all filtering is done in getClassConstructors for (MethodMirror constructor : constructors) { LazyClass subdecl = makeLazyClass(classMirror, supercls, constructor, false); // the subclasses class get the constructor modifiers setNonLazyDeclarationProperties(subdecl, constructor, constructor, classMirror, isCeylon); subdecl.setOverloaded(true); overloads.add(subdecl); decls.add(subdecl); } supercls.setOverloads(overloads); return supercls; } private void setNonLazyDeclarationProperties(Declaration decl, AccessibleMirror mirror, AnnotatedMirror annotatedMirror, ClassMirror classMirror, boolean isCeylon) { if(isCeylon){ // when we're in a local type somewhere we must turn public declarations into package or protected ones, so // we have to check the shared annotation decl.setShared(mirror.isPublic() || annotatedMirror.getAnnotation(CEYLON_LANGUAGE_SHARED_ANNOTATION) != null); setDeclarationAliases(decl, annotatedMirror); }else{ decl.setShared(mirror.isPublic() || (mirror.isDefaultAccess() && classMirror.isInnerClass()) || mirror.isProtected()); decl.setPackageVisibility(mirror.isDefaultAccess()); decl.setProtectedVisibility(mirror.isProtected()); } decl.setDeprecated(isDeprecated(annotatedMirror)); } private enum JavaVisibility { PRIVATE, PACKAGE, PROTECTED, PUBLIC; } private JavaVisibility getJavaVisibility(AccessibleMirror mirror) { if(mirror.isPublic()) return JavaVisibility.PUBLIC; if(mirror.isProtected()) return JavaVisibility.PROTECTED; if(mirror.isDefaultAccess()) return JavaVisibility.PACKAGE; return JavaVisibility.PRIVATE; } protected Declaration makeClassAlias(ClassMirror classMirror) { return new LazyClassAlias(classMirror, this); } protected Declaration makeTypeAlias(ClassMirror classMirror) { return new LazyTypeAlias(classMirror, this); } protected Declaration makeInterfaceAlias(ClassMirror classMirror) { return new LazyInterfaceAlias(classMirror, this); } private void checkBinaryCompatibility(ClassMirror classMirror) { // let's not report it twice if(binaryCompatibilityErrorRaised) return; AnnotationMirror annotation = classMirror.getAnnotation(CEYLON_CEYLON_ANNOTATION); if(annotation == null) return; // Java class, no check Integer major = (Integer) annotation.getValue("major"); if(major == null) major = 0; Integer minor = (Integer) annotation.getValue("minor"); if(minor == null) minor = 0; if(!Versions.isJvmBinaryVersionSupported(major.intValue(), minor.intValue())){ logError("Ceylon class " + classMirror.getQualifiedName() + " was compiled by an incompatible version of the Ceylon compiler" +"\nThe class was compiled using "+major+"."+minor+"." +"\nThis compiler supports "+Versions.JVM_BINARY_MAJOR_VERSION+"."+Versions.JVM_BINARY_MINOR_VERSION+"." +"\nPlease try to recompile your module using a compatible compiler." +"\nBinary compatibility will only be supported after Ceylon 1.2."); binaryCompatibilityErrorRaised = true; } } interface MethodMirrorFilter { boolean accept(MethodMirror methodMirror); } MethodMirrorFilter constructorOnly = new MethodMirrorFilter() { @Override public boolean accept(MethodMirror methodMirror) { return methodMirror.isConstructor(); } }; class ValueConstructorGetter implements MethodMirrorFilter{ private ClassMirror classMirror; ValueConstructorGetter(ClassMirror classMirror) { this.classMirror = classMirror; } @Override public boolean accept(MethodMirror methodMirror) { return (!methodMirror.isConstructor() && methodMirror.getAnnotation(CEYLON_ENUMERATED_ANNOTATION) != null && methodMirror.getReturnType().getDeclaredClass().toString().equals(classMirror.toString())); } }; private void setHasJpaConstructor(LazyClass c, ClassMirror classMirror) { for(MethodMirror methodMirror : classMirror.getDirectMethods()){ if (methodMirror.isConstructor() && methodMirror.getAnnotation(CEYLON_JPA_ANNOTATION) != null) { c.setHasJpaConstructor(true); break; } } } private List<MethodMirror> getClassConstructors(ClassMirror classMirror, MethodMirrorFilter p) { LinkedList<MethodMirror> constructors = new LinkedList<MethodMirror>(); boolean isFromJDK = isFromJDK(classMirror); for(MethodMirror methodMirror : classMirror.getDirectMethods()){ // We skip members marked with @Ignore, unless they value constructor getters if(methodMirror.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null &&methodMirror.getAnnotation(CEYLON_ENUMERATED_ANNOTATION) == null) continue; if (!p.accept(methodMirror)) continue; // FIXME: tmp hack to skip constructors that have type params as we don't handle them yet if(!methodMirror.getTypeParameters().isEmpty()) continue; // FIXME: temporary, because some private classes from the jdk are // referenced in private methods but not available if(isFromJDK && !methodMirror.isPublic() // allow protected because we can subclass them, but not package-private because we can't define // classes in the jdk packages && !methodMirror.isProtected()) continue; // if we are expecting Ceylon code, check that we have enough reified type parameters if(classMirror.getAnnotation(AbstractModelLoader.CEYLON_CEYLON_ANNOTATION) != null){ List<AnnotationMirror> tpAnnotations = getTypeParametersFromAnnotations(classMirror); int tpCount = tpAnnotations != null ? tpAnnotations.size() : classMirror.getTypeParameters().size(); if(!checkReifiedTypeDescriptors(tpCount, classMirror.getQualifiedName(), methodMirror, true)) continue; } constructors.add(methodMirror); } return constructors; } private boolean checkReifiedTypeDescriptors(int tpCount, String containerName, MethodMirror methodMirror, boolean isConstructor) { List<VariableMirror> params = methodMirror.getParameters(); int actualTypeDescriptorParameters = 0; for(VariableMirror param : params){ if(param.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null && sameType(CEYLON_TYPE_DESCRIPTOR_TYPE, param.getType())){ actualTypeDescriptorParameters++; }else break; } if(tpCount != actualTypeDescriptorParameters){ if(isConstructor) logError("Constructor for '"+containerName+"' should take "+tpCount +" reified type arguments (TypeDescriptor) but has '"+actualTypeDescriptorParameters+"': skipping constructor."); else logError("Function '"+containerName+"."+methodMirror.getName()+"' should take "+tpCount +" reified type arguments (TypeDescriptor) but has '"+actualTypeDescriptorParameters+"': method is invalid."); return false; } return true; } protected Unit getCompiledUnit(LazyPackage pkg, ClassMirror classMirror) { Unit unit = unitsByPackage.get(pkg); if(unit == null){ unit = new Unit(); unit.setPackage(pkg); unitsByPackage.put(pkg, unit); } return unit; } protected LazyValue makeToplevelAttribute(ClassMirror classMirror, boolean isNativeHeader) { LazyValue value = new LazyValue(classMirror, this); AnnotationMirror objectAnnotation = classMirror.getAnnotation(CEYLON_OBJECT_ANNOTATION); if(objectAnnotation == null) { manageNativeBackend(value, classMirror, isNativeHeader); } else { manageNativeBackend(value, getGetterMethodMirror(value, value.classMirror, true), isNativeHeader); } return value; } protected LazyFunction makeToplevelMethod(ClassMirror classMirror, boolean isNativeHeader) { LazyFunction method = new LazyFunction(classMirror, this); manageNativeBackend(method, getFunctionMethodMirror(method), isNativeHeader); return method; } protected LazyClass makeLazyClass(ClassMirror classMirror, Class superClass, MethodMirror initOrDefaultConstructor, boolean isNativeHeader) { LazyClass klass = new LazyClass(classMirror, this, superClass, initOrDefaultConstructor); AnnotationMirror objectAnnotation = classMirror.getAnnotation(CEYLON_OBJECT_ANNOTATION); if(objectAnnotation != null){ klass.setAnonymous(true); // isFalse will only consider non-null arguments, and we default to true if null if(BooleanUtil.isFalse((Boolean) objectAnnotation.getValue("named"))) klass.setNamed(false); } klass.setAnnotation(classMirror.getAnnotation(CEYLON_LANGUAGE_ANNOTATION_ANNOTATION) != null); if(klass.isCeylon()) klass.setAbstract(classMirror.getAnnotation(CEYLON_LANGUAGE_ABSTRACT_ANNOTATION) != null // for toplevel classes if the annotation is missing we respect the java abstract modifier // for member classes that would be ambiguous between formal and abstract so we don't and require // the model annotation || (!classMirror.isInnerClass() && !classMirror.isLocalClass() && classMirror.isAbstract())); else klass.setAbstract(classMirror.isAbstract()); klass.setFormal(classMirror.getAnnotation(CEYLON_LANGUAGE_FORMAL_ANNOTATION) != null); klass.setDefault(classMirror.getAnnotation(CEYLON_LANGUAGE_DEFAULT_ANNOTATION) != null); klass.setSerializable(classMirror.getAnnotation(CEYLON_LANGUAGE_SERIALIZABLE_ANNOTATION) != null || classMirror.getQualifiedName().equals("ceylon.language.Array") || classMirror.getQualifiedName().equals("ceylon.language.Tuple")); // hack to make Throwable sealed until ceylon/ceylon.language#408 is fixed klass.setSealed(classMirror.getAnnotation(CEYLON_LANGUAGE_SEALED_ANNOTATION) != null || CEYLON_LANGUAGE.equals(classMirror.getPackage().getQualifiedName()) && "Throwable".equals(classMirror.getName())); boolean actual = classMirror.getAnnotation(CEYLON_LANGUAGE_ACTUAL_ANNOTATION) != null; klass.setActual(actual); klass.setActualCompleter(this); klass.setFinal(classMirror.isFinal()); klass.setStaticallyImportable(!klass.isCeylon() && classMirror.isStatic()); if(objectAnnotation == null) { manageNativeBackend(klass, classMirror, isNativeHeader); } else { manageNativeBackend(klass, getGetterMethodMirror(klass, klass.classMirror, true), isNativeHeader); } return klass; } protected LazyInterface makeLazyInterface(ClassMirror classMirror, boolean isNativeHeader) { LazyInterface iface = new LazyInterface(classMirror, this); iface.setSealed(classMirror.getAnnotation(CEYLON_LANGUAGE_SEALED_ANNOTATION) != null); iface.setDynamic(classMirror.getAnnotation(CEYLON_DYNAMIC_ANNOTATION) != null); iface.setStaticallyImportable(!iface.isCeylon()); manageNativeBackend(iface, classMirror, isNativeHeader); return iface; } public Declaration convertToDeclaration(Module module, String typeName, DeclarationType declarationType) { return convertToDeclaration(module, null, typeName, declarationType); } private Declaration convertToDeclaration(Module module, Declaration container, String typeName, DeclarationType declarationType) { synchronized(getLock()){ // FIXME: this needs to move to the type parser and report warnings //This should be done where the TypeInfo annotation is parsed //to avoid retarded errors because of a space after a comma typeName = typeName.trim(); timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY); try{ if ("ceylon.language.Nothing".equals(typeName)) { return typeFactory.getNothingDeclaration(); } else if ("java.lang.Throwable".equals(typeName)) { // FIXME: this being here is highly dubious return convertToDeclaration(modules.getLanguageModule(), "ceylon.language.Throwable", declarationType); } else if ("java.lang.Exception".equals(typeName)) { // FIXME: this being here is highly dubious return convertToDeclaration(modules.getLanguageModule(), "ceylon.language.Exception", declarationType); } else if ("java.lang.Annotation".equals(typeName)) { // FIXME: this being here is highly dubious // here we prefer Annotation over ConstrainedAnnotation but that's fine return convertToDeclaration(modules.getLanguageModule(), "ceylon.language.Annotation", declarationType); } ClassMirror classMirror; try{ classMirror = lookupClassMirror(module, typeName); }catch(NoClassDefFoundError x){ // FIXME: this may not be the best thing to do. If the class is not there we don't know what type of declaration // to return, but perhaps if we use annotation scanner rather than reflection we can figure it out, at least // in cases where the supertype is missing, which throws in reflection at class load. return logModelResolutionException(x.getMessage(), module, "Unable to load type "+typeName).getDeclaration(); } if (classMirror == null) { // special case when bootstrapping because we may need to pull the decl from the typechecked model if(isBootstrap && typeName.startsWith(CEYLON_LANGUAGE+".")){ Declaration languageDeclaration = findLanguageModuleDeclarationForBootstrap(typeName); if(languageDeclaration != null) return languageDeclaration; } throw new ModelResolutionException("Failed to resolve "+typeName); } // we only allow source loading when it's java code we're compiling in the same go // (well, technically before the ceylon code) if(classMirror.isLoadedFromSource() && !classMirror.isJavaSource()) return null; return convertToDeclaration(module, container, classMirror, declarationType); }finally{ timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY); } } } private Type newUnknownType() { return new UnknownType(typeFactory).getType(); } protected TypeParameter safeLookupTypeParameter(Scope scope, String name) { TypeParameter param = lookupTypeParameter(scope, name); if(param == null) throw new ModelResolutionException("Type param "+name+" not found in "+scope); return param; } private TypeParameter lookupTypeParameter(Scope scope, String name) { if(scope instanceof Function){ Function m = (Function) scope; for(TypeParameter param : m.getTypeParameters()){ if(param.getName().equals(name)) return param; } if (!m.isToplevel()) { // look it up in its container return lookupTypeParameter(scope.getContainer(), name); } else { // not found return null; } }else if(scope instanceof ClassOrInterface || scope instanceof TypeAlias){ TypeDeclaration decl = (TypeDeclaration) scope; for(TypeParameter param : decl.getTypeParameters()){ if(param.getName().equals(name)) return param; } if (!decl.isToplevel()) { // look it up in its container return lookupTypeParameter(scope.getContainer(), name); } else { // not found return null; } }else if (scope instanceof Constructor) { return lookupTypeParameter(scope.getContainer(), name); }else if(scope instanceof Value || scope instanceof Setter){ Declaration decl = (Declaration) scope; if (!decl.isToplevel()) { // look it up in its container return lookupTypeParameter(scope.getContainer(), name); } else { // not found return null; } }else throw new ModelResolutionException("Type param "+name+" lookup not supported for scope "+scope); } // // Packages public LazyPackage findExistingPackage(Module module, String pkgName) { synchronized(getLock()){ String quotedPkgName = JVMModuleUtil.quoteJavaKeywords(pkgName); LazyPackage pkg = findCachedPackage(module, quotedPkgName); if(pkg != null) return pkg; // special case for the jdk module String moduleName = module.getNameAsString(); if(AbstractModelLoader.isJDKModule(moduleName)){ if(JDKUtils.isJDKPackage(moduleName, pkgName) || JDKUtils.isOracleJDKPackage(moduleName, pkgName)){ return findOrCreatePackage(module, pkgName); } return null; } // only create it if it exists if(((LazyModule)module).containsPackage(pkgName) && loadPackage(module, pkgName, false)){ return findOrCreatePackage(module, pkgName); } return null; } } private LazyPackage findCachedPackage(Module module, String quotedPkgName) { LazyPackage pkg = packagesByName.get(cacheKeyByModule(module, quotedPkgName)); if(pkg != null){ // only return it if it matches the module we're looking for, because if it doesn't we have an issue already logged // for a direct dependency on same module different versions logged, so no need to confuse this further if(module != null && pkg.getModule() != null && !module.equals(pkg.getModule())) return null; return pkg; } return null; } public LazyPackage findOrCreatePackage(Module module, final String pkgName) { synchronized(getLock()){ String quotedPkgName = JVMModuleUtil.quoteJavaKeywords(pkgName); LazyPackage pkg = findCachedPackage(module, quotedPkgName); if(pkg != null) return pkg; // try to find it from the module, perhaps it already got created and we didn't catch it if(module instanceof LazyModule){ pkg = (LazyPackage) ((LazyModule) module).findPackageNoLazyLoading(pkgName); }else if(module != null){ pkg = (LazyPackage) module.getDirectPackage(pkgName); } boolean isNew = pkg == null; if(pkg == null){ pkg = new LazyPackage(this); // FIXME: some refactoring needed pkg.setName(Arrays.asList(pkgName.split("\\."))); } packagesByName.put(cacheKeyByModule(module, quotedPkgName), pkg); // only bind it if we already have a module if(isNew && module != null){ pkg.setModule(module); if(module instanceof LazyModule) ((LazyModule) module).addPackage(pkg); else module.getPackages().add(pkg); } // only load package descriptors for new packages after a certain phase if(packageDescriptorsNeedLoading) loadPackageDescriptor(pkg); return pkg; } } public void loadPackageDescriptors() { synchronized(getLock()){ for(Package pkg : packagesByName.values()){ loadPackageDescriptor(pkg); } packageDescriptorsNeedLoading = true; } } private void loadPackageDescriptor(Package pkg) { // Don't try to load a package descriptor for ceylon.language // if we're bootstrapping if (isBootstrap && pkg.getQualifiedNameString().startsWith(CEYLON_LANGUAGE)) { return; } // let's not load package descriptors for Java modules if(pkg.getModule() != null && ((LazyModule)pkg.getModule()).isJava()){ pkg.setShared(true); return; } String quotedQualifiedName = JVMModuleUtil.quoteJavaKeywords(pkg.getQualifiedNameString()); // FIXME: not sure the toplevel package can have a package declaration String className = quotedQualifiedName.isEmpty() ? NamingBase.PACKAGE_DESCRIPTOR_CLASS_NAME : quotedQualifiedName + "." + NamingBase.PACKAGE_DESCRIPTOR_CLASS_NAME; logVerbose("[Trying to look up package from "+className+"]"); Module module = pkg.getModule(); if(module == null) throw new RuntimeException("Assertion failed: module is null for package "+pkg.getNameAsString()); ClassMirror packageClass = loadClass(module, quotedQualifiedName, className); if(packageClass == null){ logVerbose("[Failed to complete "+className+"]"); // missing: leave it private return; } // did we compile it from source or class? if(packageClass.isLoadedFromSource()){ // must have come from source, in which case we walked it and // loaded its values already logVerbose("[We are compiling the package "+className+"]"); return; } loadCompiledPackage(packageClass, pkg); } private void loadCompiledPackage(ClassMirror packageClass, Package pkg) { String name = getAnnotationStringValue(packageClass, CEYLON_PACKAGE_ANNOTATION, "name"); Boolean shared = getAnnotationBooleanValue(packageClass, CEYLON_PACKAGE_ANNOTATION, "shared"); // FIXME: validate the name? if(name == null || name.isEmpty()){ logWarning("Package class "+pkg.getQualifiedNameString()+" contains no name, ignoring it"); return; } if(shared == null){ logWarning("Package class "+pkg.getQualifiedNameString()+" contains no shared, ignoring it"); return; } pkg.setShared(shared); } public Module lookupModuleByPackageName(String packageName) { for(Module module : modules.getListOfModules()){ // don't try the default module because it will always say yes if(module.isDefault()) continue; // skip modules we're not loading things from if(!ModelUtil.equalModules(module,getLanguageModule()) && !isModuleInClassPath(module)) continue; if(module instanceof LazyModule){ if(((LazyModule)module).containsPackage(packageName)) return module; }else if(isSubPackage(module.getNameAsString(), packageName)){ return module; } } if(JDKUtils.isJDKAnyPackage(packageName) || JDKUtils.isOracleJDKAnyPackage(packageName)){ String moduleName = JDKUtils.getJDKModuleNameForPackage(packageName); return findModule(moduleName, JDKUtils.jdk.version); } if(packageName.startsWith("com.redhat.ceylon.compiler.java.runtime") || packageName.startsWith("com.redhat.ceylon.compiler.java.language") || packageName.startsWith("com.redhat.ceylon.compiler.java.metadata")){ return getLanguageModule(); } return modules.getDefaultModule(); } private boolean isSubPackage(String moduleName, String pkgName) { return pkgName.equals(moduleName) || pkgName.startsWith(moduleName+"."); } // // Modules /** * Finds or creates a new module. This is mostly useful to force creation of modules such as jdk * or ceylon.language modules. */ protected Module findOrCreateModule(String moduleName, String version) { synchronized(getLock()){ boolean isJdk = false; boolean defaultModule = false; // make sure it isn't loaded Module module = getLoadedModule(moduleName, version); if(module != null) return module; if(JDKUtils.isJDKModule(moduleName) || JDKUtils.isOracleJDKModule(moduleName)){ isJdk = true; } java.util.List<String> moduleNameList = Arrays.asList(moduleName.split("\\.")); module = moduleManager.getOrCreateModule(moduleNameList, version); // make sure that when we load the ceylon language module we set it to where // the typechecker will look for it if(moduleName.equals(CEYLON_LANGUAGE) && modules.getLanguageModule() == null){ modules.setLanguageModule(module); } // TRICKY We do this only when isJava is true to prevent resetting // the value to false by mistake. LazyModule get's created with // this attribute to false by default, so it should work if (isJdk && module instanceof LazyModule) { ((LazyModule)module).setJava(true); module.setNativeBackends(Backend.Java.asSet()); } // FIXME: this can't be that easy. if(isJdk) module.setAvailable(true); module.setDefault(defaultModule); return module; } } public boolean loadCompiledModule(Module module) { synchronized(getLock()){ if(module.isDefault()) return false; String pkgName = module.getNameAsString(); if(pkgName.isEmpty()) return false; String moduleClassName = pkgName + "." + NamingBase.MODULE_DESCRIPTOR_CLASS_NAME; logVerbose("[Trying to look up module from "+moduleClassName+"]"); ClassMirror moduleClass = loadClass(module, pkgName, moduleClassName); if(moduleClass == null){ // perhaps we have an old module? String oldModuleClassName = pkgName + "." + NamingBase.OLD_MODULE_DESCRIPTOR_CLASS_NAME; logVerbose("[Trying to look up older module descriptor from "+oldModuleClassName+"]"); ClassMirror oldModuleClass = loadClass(module, pkgName, oldModuleClassName); // keep it only if it has a module annotation, otherwise it could be a normal value if(oldModuleClass != null && oldModuleClass.getAnnotation(CEYLON_MODULE_ANNOTATION) != null) moduleClass = oldModuleClass; } if(moduleClass != null){ // load its module annotation return loadCompiledModule(module, moduleClass, moduleClassName); } // give up return false; } } private boolean loadCompiledModule(Module module, ClassMirror moduleClass, String moduleClassName) { String name = getAnnotationStringValue(moduleClass, CEYLON_MODULE_ANNOTATION, "name"); String version = getAnnotationStringValue(moduleClass, CEYLON_MODULE_ANNOTATION, "version"); if(name == null || name.isEmpty()){ logWarning("Module class "+moduleClassName+" contains no name, ignoring it"); return false; } if(!name.equals(module.getNameAsString())){ logWarning("Module class "+moduleClassName+" declares an invalid name: "+name+". It should be: "+module.getNameAsString()); return false; } if(version == null || version.isEmpty()){ logWarning("Module class "+moduleClassName+" contains no version, ignoring it"); return false; } if(!version.equals(module.getVersion())){ logWarning("Module class "+moduleClassName+" declares an invalid version: "+version+". It should be: "+module.getVersion()); return false; } int major = getAnnotationIntegerValue(moduleClass, CEYLON_CEYLON_ANNOTATION, "major", 0); int minor = getAnnotationIntegerValue(moduleClass, CEYLON_CEYLON_ANNOTATION, "minor", 0); module.setMajor(major); module.setMinor(minor); // no need to load the "nativeBackends" annotation value, it's loaded from annotations setAnnotations(module, moduleClass, false); List<AnnotationMirror> imports = getAnnotationArrayValue(moduleClass, CEYLON_MODULE_ANNOTATION, "dependencies"); if(imports != null){ for (AnnotationMirror importAttribute : imports) { String dependencyName = (String) importAttribute.getValue("name"); if (dependencyName != null) { String dependencyVersion = (String) importAttribute.getValue("version"); Module dependency = moduleManager.getOrCreateModule(ModuleManager.splitModuleName(dependencyName), dependencyVersion); Boolean optionalVal = (Boolean) importAttribute.getValue("optional"); Boolean exportVal = (Boolean) importAttribute.getValue("export"); List<String> nativeBackends = (List<String>) importAttribute.getValue("nativeBackends"); Backends backends = nativeBackends == null ? Backends.ANY : Backends.fromAnnotations(nativeBackends); ModuleImport moduleImport = moduleManager.findImport(module, dependency); if (moduleImport == null) { boolean optional = optionalVal != null && optionalVal; boolean export = exportVal != null && exportVal; moduleImport = new ModuleImport(dependency, optional, export, backends); module.addImport(moduleImport); } } } } module.setAvailable(true); modules.getListOfModules().add(module); Module languageModule = modules.getLanguageModule(); module.setLanguageModule(languageModule); if(!ModelUtil.equalModules(module, languageModule)){ ModuleImport moduleImport = moduleManager.findImport(module, languageModule); if (moduleImport == null) { moduleImport = new ModuleImport(languageModule, false, false); module.addImport(moduleImport); } } return true; } // // Utils for loading type info from the model @SuppressWarnings("unchecked") private <T> List<T> getAnnotationArrayValue(AnnotatedMirror mirror, String type, String field) { return (List<T>) getAnnotationValue(mirror, type, field); } @SuppressWarnings("unchecked") private <T> List<T> getAnnotationArrayValue(AnnotatedMirror mirror, String type) { return (List<T>) getAnnotationValue(mirror, type); } private String getAnnotationStringValue(AnnotatedMirror mirror, String type) { return getAnnotationStringValue(mirror, type, "value"); } private String getAnnotationStringValue(AnnotatedMirror mirror, String type, String field) { return (String) getAnnotationValue(mirror, type, field); } private Boolean getAnnotationBooleanValue(AnnotatedMirror mirror, String type, String field) { return (Boolean) getAnnotationValue(mirror, type, field); } private int getAnnotationIntegerValue(AnnotatedMirror mirror, String type, String field, int defaultValue) { Integer val = (Integer) getAnnotationValue(mirror, type, field); return val != null ? val : defaultValue; } @SuppressWarnings("unchecked") private List<String> getAnnotationStringValues(AnnotationMirror annotation, String field) { return (List<String>)annotation.getValue(field); } private Object getAnnotationValue(AnnotatedMirror mirror, String type) { return getAnnotationValue(mirror, type, "value"); } private Object getAnnotationValue(AnnotatedMirror mirror, String type, String fieldName) { AnnotationMirror annotation = mirror.getAnnotation(type); if(annotation != null){ return annotation.getValue(fieldName); } return null; } // // ModelCompleter @Override public void complete(LazyInterface iface) { synchronized(getLock()){ timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY); complete(iface, iface.classMirror); timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY); } } @Override public void completeTypeParameters(LazyInterface iface) { synchronized(getLock()){ timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY); completeTypeParameters(iface, iface.classMirror); timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY); } } @Override public void complete(LazyClass klass) { synchronized(getLock()){ timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY); complete(klass, klass.classMirror); timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY); } } @Override public void completeTypeParameters(LazyClass klass) { synchronized(getLock()){ timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY); completeTypeParameters(klass, klass.classMirror); timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY); } } @Override public void completeTypeParameters(LazyClassAlias lazyClassAlias) { synchronized(getLock()){ timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY); completeLazyAliasTypeParameters(lazyClassAlias, lazyClassAlias.classMirror); timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY); } } @Override public void completeTypeParameters(LazyInterfaceAlias lazyInterfaceAlias) { synchronized(getLock()){ timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY); completeLazyAliasTypeParameters(lazyInterfaceAlias, lazyInterfaceAlias.classMirror); timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY); } } @Override public void completeTypeParameters(LazyTypeAlias lazyTypeAlias) { synchronized(getLock()){ timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY); completeLazyAliasTypeParameters(lazyTypeAlias, lazyTypeAlias.classMirror); timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY); } } @Override public void complete(LazyInterfaceAlias alias) { synchronized(getLock()){ timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY); completeLazyAlias(alias, alias.classMirror, CEYLON_ALIAS_ANNOTATION); timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY); } } @Override public void complete(LazyClassAlias alias) { synchronized(getLock()){ timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY); completeLazyAlias(alias, alias.classMirror, CEYLON_ALIAS_ANNOTATION); String constructorName = (String)alias.classMirror.getAnnotation(CEYLON_ALIAS_ANNOTATION).getValue("constructor"); if (constructorName != null && !constructorName.isEmpty()) { Declaration constructor = alias.getExtendedType().getDeclaration().getMember(constructorName, null, false); if (constructor instanceof FunctionOrValue && ((FunctionOrValue)constructor).getTypeDeclaration() instanceof Constructor) { alias.setConstructor(((FunctionOrValue)constructor).getTypeDeclaration()); } else { logError("class aliased constructor " + constructorName + " which is no longer a constructor of " + alias.getExtendedType().getDeclaration().getQualifiedNameString()); } } // Find the instantiator method MethodMirror instantiator = null; ClassMirror instantiatorClass = alias.isToplevel() ? alias.classMirror : alias.classMirror.getEnclosingClass(); String aliasName = NamingBase.getAliasInstantiatorMethodName(alias); for (MethodMirror method : instantiatorClass.getDirectMethods()) { if (method.getName().equals(aliasName)) { instantiator = method; break; } } // Read the parameters from the instantiator, rather than the aliased class if (instantiator != null) { setParameters(alias, alias.classMirror, instantiator, true, alias); } timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY); } } @Override public void complete(LazyTypeAlias alias) { synchronized(getLock()){ timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY); completeLazyAlias(alias, alias.classMirror, CEYLON_TYPE_ALIAS_ANNOTATION); timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY); } } private void completeLazyAliasTypeParameters(TypeDeclaration alias, ClassMirror mirror) { // type parameters setTypeParameters(alias, mirror, true); } private void completeLazyAlias(TypeDeclaration alias, ClassMirror mirror, String aliasAnnotationName) { // now resolve the extended type AnnotationMirror aliasAnnotation = mirror.getAnnotation(aliasAnnotationName); String extendedTypeString = (String) aliasAnnotation.getValue(); Type extendedType = decodeType(extendedTypeString, alias, ModelUtil.getModuleContainer(alias), "alias target"); alias.setExtendedType(extendedType); } private void completeTypeParameters(ClassOrInterface klass, ClassMirror classMirror) { boolean isCeylon = classMirror.getAnnotation(CEYLON_CEYLON_ANNOTATION) != null; setTypeParameters(klass, classMirror, isCeylon); } private void complete(ClassOrInterface klass, ClassMirror classMirror) { boolean isFromJDK = isFromJDK(classMirror); boolean isCeylon = (classMirror.getAnnotation(CEYLON_CEYLON_ANNOTATION) != null); // now that everything has containers, do the inner classes if(klass instanceof Class == false || !((Class)klass).isOverloaded()){ // this will not load inner classes of overloads, but that's fine since we want them in the // abstracted super class (the real one) addInnerClasses(klass, classMirror); } // Java classes with multiple constructors get turned into multiple Ceylon classes // Here we get the specific constructor that was assigned to us (if any) MethodMirror constructor = null; if (klass instanceof LazyClass) { constructor = ((LazyClass)klass).getConstructor(); setHasJpaConstructor((LazyClass)klass, classMirror); } // Set up enumerated constructors before looking at getters, // because the type of the getter is the constructor's type Boolean hasConstructors = hasConstructors(classMirror); if (hasConstructors != null && hasConstructors) { HashMap<String, MethodMirror> m = new HashMap<>(); // Get all the java constructors... for (MethodMirror ctorMirror : getClassConstructors(classMirror, constructorOnly)) { m.put(getCtorName(ctorMirror), ctorMirror); } for (MethodMirror ctor : getClassConstructors(classMirror.getEnclosingClass() != null ? classMirror.getEnclosingClass() : classMirror, new ValueConstructorGetter(classMirror))) { Object name = getAnnotationValue(ctor, CEYLON_NAME_ANNOTATION); MethodMirror ctorMirror = m.remove(name); Constructor c; // When for each value constructor getter we can add a Value+Constructor if (ctorMirror == null) { // Only add a Constructor using the getter if we couldn't find a matching java constructor c = addConstructor((Class)klass, classMirror, ctor, false); } else { c = addConstructor((Class)klass, classMirror, ctorMirror, false); } addConstructorMethorOrValue((Class)klass, classMirror, ctor, c, false); if (isCeylon && shouldCreateNativeHeader(c, klass)) { Constructor hdr; if (ctorMirror == null) { hdr = addConstructor((Class)klass, classMirror, ctor, true); } else { hdr = addConstructor((Class)klass, classMirror, ctorMirror, true); } addConstructorMethorOrValue((Class)klass, classMirror, ctorMirror, hdr, true); initNativeHeader(hdr, c); } else if (isCeylon && shouldLinkNatives(c)) { initNativeHeaderMember(c); } } // Everything left must be a callable constructor, so add Function+Constructor for (MethodMirror ctorMirror : m.values()) { Constructor c = addConstructor((Class)klass, classMirror, ctorMirror, false); addConstructorMethorOrValue((Class)klass, classMirror, ctorMirror, c, false); if (isCeylon && shouldCreateNativeHeader(c, klass)) { Constructor hdr = addConstructor((Class)klass, classMirror, ctorMirror, true); addConstructorMethorOrValue((Class)klass, classMirror, ctorMirror, hdr, true); initNativeHeader(hdr, c); } else if (isCeylon && shouldLinkNatives(c)) { initNativeHeaderMember(c); } } } // Turn a list of possibly overloaded methods into a map // of lists that contain methods with the same name Map<String, List<MethodMirror>> methods = new LinkedHashMap<String, List<MethodMirror>>(); collectMethods(classMirror.getDirectMethods(), methods, isCeylon, isFromJDK); if(isCeylon && klass instanceof LazyInterface && JvmBackendUtil.isCompanionClassNeeded(klass)){ ClassMirror companionClass = ((LazyInterface)klass).companionClass; if(companionClass != null) collectMethods(companionClass.getDirectMethods(), methods, isCeylon, isFromJDK); else logWarning("CompanionClass missing for "+klass); } boolean seenStringAttribute = false; boolean seenHashAttribute = false; boolean seenStringGetter = false; boolean seenHashGetter = false; MethodMirror stringSetter = null; MethodMirror hashSetter = null; Map<String, List<MethodMirror>> getters = new HashMap<>(); Map<String, List<MethodMirror>> setters = new HashMap<>(); // Collect attributes for(List<MethodMirror> methodMirrors : methods.values()){ for (MethodMirror methodMirror : methodMirrors) { // same tests as in isMethodOverloaded() if(methodMirror.isConstructor() || isInstantiator(methodMirror)) { break; } else if(isGetter(methodMirror)) { String name = getJavaAttributeName(methodMirror); putMultiMap(getters, name, methodMirror); } else if(isSetter(methodMirror)) { String name = getJavaAttributeName(methodMirror); putMultiMap(setters, name, methodMirror); } else if(isHashAttribute(methodMirror)) { putMultiMap(getters, "hash", methodMirror); seenHashAttribute = true; } else if(isStringAttribute(methodMirror)) { putMultiMap(getters, "string", methodMirror); seenStringAttribute = true; } else { // we never map getString to a property, or generate one if(isStringGetter(methodMirror)) seenStringGetter = true; // same for getHash else if(isHashGetter(methodMirror)) seenHashGetter = true; else if(isStringSetter(methodMirror)){ stringSetter = methodMirror; // we will perhaps add it later continue; }else if(isHashSetter(methodMirror)){ hashSetter = methodMirror; // we will perhaps add it later continue; } } } } // now figure out which properties to add NEXT_PROPERTY: for(Map.Entry<String, List<MethodMirror>> getterEntry : getters.entrySet()){ String propertyName = getterEntry.getKey(); List<MethodMirror> getterList = getterEntry.getValue(); for(MethodMirror getterMethod : getterList){ // if it's hashCode() or toString() they win if(isHashAttribute(getterMethod)) { // ERASURE // Un-erasing 'hash' attribute from 'hashCode' method Declaration decl = addValue(klass, getterMethod, "hash", isCeylon, false); if (isCeylon && shouldCreateNativeHeader(decl, klass)) { Declaration hdr = addValue(klass, getterMethod, "hash", true, true); setNonLazyDeclarationProperties(hdr, classMirror, classMirror, classMirror, true); initNativeHeader(hdr, decl); } else if (isCeylon && shouldLinkNatives(decl)) { initNativeHeaderMember(decl); } // remove it as a method and add all other getters with the same name // as methods removeMultiMap(methods, getterMethod.getName(), getterMethod); // next property continue NEXT_PROPERTY; } if(isStringAttribute(getterMethod)) { // ERASURE // Un-erasing 'string' attribute from 'toString' method Declaration decl = addValue(klass, getterMethod, "string", isCeylon, false); if (isCeylon && shouldCreateNativeHeader(decl, klass)) { Declaration hdr = addValue(klass, getterMethod, "string", true, true); setNonLazyDeclarationProperties(hdr, classMirror, classMirror, classMirror, true); initNativeHeader(hdr, decl); } else if (isCeylon && shouldLinkNatives(decl)) { initNativeHeaderMember(decl); } // remove it as a method and add all other getters with the same name // as methods removeMultiMap(methods, getterMethod.getName(), getterMethod); // next property continue NEXT_PROPERTY; } } // we've weeded out toString/hashCode, now if we have a single property it's easy we just add it if(getterList.size() == 1){ // FTW! MethodMirror getterMethod = getterList.get(0); // simple attribute Declaration decl = addValue(klass, getterMethod, propertyName, isCeylon, false); if (isCeylon && shouldCreateNativeHeader(decl, klass)) { Declaration hdr = addValue(klass, getterMethod, propertyName, true, true); setNonLazyDeclarationProperties(hdr, classMirror, classMirror, classMirror, true); initNativeHeader(hdr, decl); } else if (isCeylon && shouldLinkNatives(decl)) { initNativeHeaderMember(decl); } // remove it as a method removeMultiMap(methods, getterMethod.getName(), getterMethod); // next property continue NEXT_PROPERTY; } // we have more than one // if we have a setter let's favour the one that matches the setter List<MethodMirror> matchingSetters = setters.get(propertyName); if(matchingSetters != null){ if(matchingSetters.size() == 1){ // single setter will tell us what we need MethodMirror matchingSetter = matchingSetters.get(0); MethodMirror bestGetter = null; boolean booleanSetter = matchingSetter.getParameters().get(0).getType().getKind() == TypeKind.BOOLEAN; /* * Getters do not support overloading since they have no parameters, so they can only differ based on * name. For boolean properties we favour "is" getters, otherwise "get" getters. */ for(MethodMirror getterMethod : getterList){ if(propertiesMatch(klass, getterMethod, matchingSetter)){ if(bestGetter == null) bestGetter = getterMethod; else{ // we have two getters, find the best one if(booleanSetter){ // favour the "is" getter if(getterMethod.getName().startsWith("is")) bestGetter = getterMethod; // else keep the current best, it must be an "is" getter }else{ // favour the "get" getter if(getterMethod.getName().startsWith("get")) bestGetter = getterMethod; // else keep the current best, it must be a "get" getter } break; } } } if(bestGetter != null){ // got it! // simple attribute Declaration decl = addValue(klass, bestGetter, propertyName, isCeylon, false); if (isCeylon && shouldCreateNativeHeader(decl, klass)) { Declaration hdr = addValue(klass, bestGetter, propertyName, true, true); setNonLazyDeclarationProperties(hdr, classMirror, classMirror, classMirror, true); initNativeHeader(hdr, decl); } else if (isCeylon && shouldLinkNatives(decl)) { initNativeHeaderMember(decl); } // remove it as a method and add all other getters with the same name // as methods removeMultiMap(methods, bestGetter.getName(), bestGetter); // next property continue NEXT_PROPERTY; }// else we cannot find the right getter thanks to the setter, keep looking } } // setters did not help us, we have more than one getter, one must be "is"/boolean, the other "get" if(getterList.size() == 2){ // if the "get" is also a boolean, prefer the "is" MethodMirror isMethod = null; MethodMirror getMethod = null; for(MethodMirror getterMethod : getterList){ if(getterMethod.getName().startsWith("is")) isMethod = getterMethod; else if(getterMethod.getName().startsWith("get")) getMethod = getterMethod; } if(isMethod != null && getMethod != null){ MethodMirror bestGetter; if(getMethod.getReturnType().getKind() == TypeKind.BOOLEAN){ // pick the is method bestGetter = isMethod; }else{ // just take the getter bestGetter = getMethod; } // simple attribute Declaration decl = addValue(klass, bestGetter, propertyName, isCeylon, false); if (isCeylon && shouldCreateNativeHeader(decl, klass)) { Declaration hdr = addValue(klass, bestGetter, propertyName, true, true); setNonLazyDeclarationProperties(hdr, classMirror, classMirror, classMirror, true); initNativeHeader(hdr, decl); } else if (isCeylon && shouldLinkNatives(decl)) { initNativeHeaderMember(decl); } // remove it as a method and add all other getters with the same name // as methods removeMultiMap(methods, bestGetter.getName(), bestGetter); // next property continue NEXT_PROPERTY; } } } // now handle fields for(FieldMirror fieldMirror : classMirror.getDirectFields()){ // We skip members marked with @Ignore if(fieldMirror.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null) continue; if(skipPrivateMember(fieldMirror)) continue; if(isCeylon && fieldMirror.isStatic()) continue; // FIXME: temporary, because some private classes from the jdk are // referenced in private methods but not available if(isFromJDK && !fieldMirror.isPublic() && !fieldMirror.isProtected()) continue; String name = fieldMirror.getName(); // skip the field if "we've already got one" boolean conflicts = klass.getDirectMember(name, null, false) != null || "equals".equals(name) || "string".equals(name) || "hash".equals(name); if (!conflicts) { Declaration decl = addValue(klass, fieldMirror.getName(), fieldMirror, isCeylon, false); if (isCeylon && shouldCreateNativeHeader(decl, klass)) { Declaration hdr = addValue(klass, fieldMirror.getName(), fieldMirror, true, true); setNonLazyDeclarationProperties(hdr, classMirror, classMirror, classMirror, true); initNativeHeader(hdr, decl); } else if (isCeylon && shouldLinkNatives(decl)) { initNativeHeaderMember(decl); } } } // Now mark all Values for which Setters exist as variable for(List<MethodMirror> variables : setters.values()){ for(MethodMirror setter : variables){ String name = getJavaAttributeName(setter); // make sure we handle private postfixes name = JvmBackendUtil.strip(name, isCeylon, setter.isPublic()); Declaration decl = klass.getMember(name, null, false); // skip Java fields, which we only get if there is no getter method, in that case just add the setter method if (decl instanceof JavaBeanValue) { JavaBeanValue value = (JavaBeanValue)decl; // only add the setter if it has the same visibility as the getter if (setter.isPublic() && value.mirror.isPublic() || setter.isProtected() && value.mirror.isProtected() || setter.isDefaultAccess() && value.mirror.isDefaultAccess() || (!setter.isPublic() && !value.mirror.isPublic() && !setter.isProtected() && !value.mirror.isProtected() && !setter.isDefaultAccess() && !value.mirror.isDefaultAccess())) { VariableMirror setterParam = setter.getParameters().get(0); Type paramType = obtainType(setterParam.getType(), setterParam, klass, ModelUtil.getModuleContainer(klass), VarianceLocation.INVARIANT, "setter '"+setter.getName()+"'", klass); // only add the setter if it has exactly the same type as the getter if(paramType.isExactly(value.getType())){ value.setVariable(true); value.setSetterName(setter.getName()); if(value.isTransient()){ // must be a real setter makeSetter(value, null); } // remove it as a method removeMultiMap(methods, setter.getName(), setter); }else logVerbose("Setter parameter type for "+name+" does not match corresponding getter type, adding setter as a method"); } else { logVerbose("Setter visibility for "+name+" does not match corresponding getter visibility, adding setter as a method"); } } } } // special cases if we have hashCode() setHash() and no getHash() if(hashSetter != null){ if(seenHashAttribute && !seenHashGetter){ Declaration attr = klass.getDirectMember("hash", null, false); if(attr instanceof JavaBeanValue){ ((JavaBeanValue) attr).setVariable(true); ((JavaBeanValue) attr).setSetterName(hashSetter.getName()); // remove it as a method removeMultiMap(methods, hashSetter.getName(), hashSetter); } } } // special cases if we have toString() setString() and no getString() if(stringSetter != null){ if(seenStringAttribute && !seenStringGetter){ Declaration attr = klass.getDirectMember("string", null, false); if(attr instanceof JavaBeanValue){ ((JavaBeanValue) attr).setVariable(true); ((JavaBeanValue) attr).setSetterName(stringSetter.getName()); // remove it as a method removeMultiMap(methods, stringSetter.getName(), stringSetter); } } } // Add the methods, treat remaining getters/setters as methods for(List<MethodMirror> methodMirrors : methods.values()){ boolean isOverloaded = isMethodOverloaded(methodMirrors); List<Declaration> overloads = null; for (MethodMirror methodMirror : methodMirrors) { // normal method Function m = addMethod(klass, methodMirror, classMirror, isCeylon, isOverloaded, false); if (!isOverloaded && isCeylon && shouldCreateNativeHeader(m, klass)) { Declaration hdr = addMethod(klass, methodMirror, classMirror, true, isOverloaded, true); setNonLazyDeclarationProperties(hdr, classMirror, classMirror, classMirror, true); initNativeHeader(hdr, m); } else if (isCeylon && shouldLinkNatives(m)) { initNativeHeaderMember(m); } if (m.isOverloaded()) { overloads = overloads == null ? new ArrayList<Declaration>(methodMirrors.size()) : overloads; overloads.add(m); } } if (overloads != null && !overloads.isEmpty()) { // We create an extra "abstraction" method for overloaded methods Function abstractionMethod = addMethod(klass, methodMirrors.get(0), classMirror, isCeylon, false, false); abstractionMethod.setAbstraction(true); abstractionMethod.setOverloads(overloads); abstractionMethod.setType(newUnknownType()); } } // Having loaded methods and values, we can now set the constructor parameters if(constructor != null && !isDefaultNamedCtor(classMirror, constructor) && (!(klass instanceof LazyClass) || !((LazyClass)klass).isAnonymous())) setParameters((Class)klass, classMirror, constructor, isCeylon, klass); // Now marry-up attributes and parameters) if (klass instanceof Class) { for (Declaration m : klass.getMembers()) { if (JvmBackendUtil.isValue(m)) { Value v = (Value)m; Parameter p = ((Class)klass).getParameter(v.getName()); if (p != null) { p.setHidden(true); } } } } setExtendedType(klass, classMirror); setSatisfiedTypes(klass, classMirror); setCaseTypes(klass, classMirror); setAnnotations(klass, classMirror, klass.isNativeHeader()); // local declarations come last, because they need all members to be completed first if(!klass.isAlias()){ ClassMirror containerMirror = classMirror; if(klass instanceof LazyInterface){ ClassMirror companionClass = ((LazyInterface) klass).companionClass; if(companionClass != null) containerMirror = companionClass; } addLocalDeclarations((LazyContainer) klass, containerMirror, classMirror); } if (!isCeylon) { // In java, a class can inherit a public member from a non-public supertype for (Declaration d : klass.getMembers()) { if (d.isShared()) { d.setVisibleScope(null); } } } } private boolean propertiesMatch(ClassOrInterface klass, MethodMirror getter, MethodMirror setter) { // only add the setter if it has the same visibility as the getter if (setter.isPublic() && getter.isPublic() || setter.isProtected() && getter.isProtected() || setter.isDefaultAccess() && getter.isDefaultAccess() || (!setter.isPublic() && !getter.isPublic() && !setter.isProtected() && !getter.isProtected() && !setter.isDefaultAccess() && !getter.isDefaultAccess())) { Module module = ModelUtil.getModuleContainer(klass); VariableMirror setterParam = setter.getParameters().get(0); Type paramType = obtainType(setterParam.getType(), setterParam, klass, module, VarianceLocation.INVARIANT, "setter '"+setter.getName()+"'", klass); Type returnType = obtainType(getter.getReturnType(), getter, klass, module, VarianceLocation.INVARIANT, "getter '"+getter.getName()+"'", klass); // only add the setter if it has exactly the same type as the getter if(paramType.isExactly(returnType)){ return true; } } return false; } private <Key,Val> void removeMultiMap(Map<Key, List<Val>> map, Key key, Val val) { List<Val> list = map.get(key); if(list != null){ list.remove(val); if(list.isEmpty()) map.remove(key); } } private <Key,Val> void putMultiMap(Map<Key, List<Val>> map, Key key, Val value) { List<Val> list = map.get(key); if(list == null){ list = new LinkedList<>(); map.put(key, list); } list.add(value); } private Constructor addConstructor(Class klass, ClassMirror classMirror, MethodMirror ctor, boolean isNativeHeader) { boolean isCeylon = classMirror.getAnnotation(CEYLON_CEYLON_ANNOTATION) != null; Constructor constructor = new Constructor(); constructor.setName(getCtorName(ctor)); constructor.setContainer(klass); constructor.setScope(klass); constructor.setUnit(klass.getUnit()); constructor.setAbstract(ctor.getAnnotation(CEYLON_LANGUAGE_ABSTRACT_ANNOTATION) != null); constructor.setExtendedType(klass.getType()); setNonLazyDeclarationProperties(constructor, ctor, ctor, classMirror, isCeylon); setAnnotations(constructor, ctor, isNativeHeader); klass.addMember(constructor); return constructor; } protected void addConstructorMethorOrValue(Class klass, ClassMirror classMirror, MethodMirror ctor, Constructor constructor, boolean isNativeHeader) { boolean isCeylon = classMirror.getAnnotation(CEYLON_CEYLON_ANNOTATION) != null; if (ctor.getAnnotation(CEYLON_ENUMERATED_ANNOTATION) != null) { klass.setEnumerated(true); Value v = new Value(); v.setName(constructor.getName()); v.setType(constructor.getType()); v.setContainer(klass); v.setScope(klass); v.setUnit(klass.getUnit()); v.setVisibleScope(constructor.getVisibleScope()); // read annotations from the getter method setNonLazyDeclarationProperties(v, ctor, ctor, classMirror, isCeylon); setAnnotations(v, ctor, isNativeHeader); klass.addMember(v); } else { setParameters(constructor, classMirror, ctor, true, klass); klass.setConstructors(true); Function f = new Function(); f.setName(constructor.getName()); f.setType(constructor.getType()); f.addParameterList(constructor.getParameterList()); f.setContainer(klass); f.setScope(klass); f.setUnit(klass.getUnit()); f.setVisibleScope(constructor.getVisibleScope()); // read annotations from the constructor setNonLazyDeclarationProperties(f, ctor, ctor, classMirror, isCeylon); setAnnotations(f, ctor, isNativeHeader); klass.addMember(f); } } private boolean isMethodOverloaded(List<MethodMirror> methodMirrors) { // it's overloaded if we have more than one method (non constructor/value) boolean one = false; for (MethodMirror methodMirror : methodMirrors) { // same tests as in complete(ClassOrInterface klass, ClassMirror classMirror) if(methodMirror.isConstructor() || isInstantiator(methodMirror) || isGetter(methodMirror) || isSetter(methodMirror) || isHashAttribute(methodMirror) || isStringAttribute(methodMirror) || methodMirror.getName().equals("hash") || methodMirror.getName().equals("string")){ break; } if(one) return true; one = true; } return false; } private void collectMethods(List<MethodMirror> methodMirrors, Map<String,List<MethodMirror>> methods, boolean isCeylon, boolean isFromJDK) { for(MethodMirror methodMirror : methodMirrors){ // We skip members marked with @Ignore if(methodMirror.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null) continue; if(skipPrivateMember(methodMirror)) continue; if(methodMirror.isStaticInit()) continue; if(isCeylon && methodMirror.isStatic() && methodMirror.getAnnotation(CEYLON_ENUMERATED_ANNOTATION) == null) continue; // these are not relevant for our caller if(methodMirror.isConstructor() || isInstantiator(methodMirror)) { continue; } // FIXME: temporary, because some private classes from the jdk are // referenced in private methods but not available if(isFromJDK && !methodMirror.isPublic() && !methodMirror.isProtected()) continue; String methodName = methodMirror.getName(); List<MethodMirror> homonyms = methods.get(methodName); if (homonyms == null) { homonyms = new LinkedList<MethodMirror>(); methods.put(methodName, homonyms); } homonyms.add(methodMirror); } } private boolean skipPrivateMember(AccessibleMirror mirror) { return !mirror.isPublic() && !mirror.isProtected() && !mirror.isDefaultAccess() && !needsPrivateMembers(); } private void addLocalDeclarations(LocalDeclarationContainer container, ClassMirror classContainerMirror, AnnotatedMirror annotatedMirror) { if(!needsLocalDeclarations()) return; AnnotationMirror annotation = annotatedMirror.getAnnotation(CEYLON_LOCAL_DECLARATIONS_ANNOTATION); if(annotation == null) return; List<String> values = getAnnotationStringValues(annotation, "value"); String parentClassName = classContainerMirror.getQualifiedName(); Package pkg = ModelUtil.getPackageContainer(container); Module module = pkg.getModule(); for(String scope : values){ // assemble the name with the parent String name; if(scope.startsWith("::")){ // interface pulled to toplevel name = pkg.getNameAsString() + "." + scope.substring(2); }else{ name = parentClassName; name += "$" + scope; } Declaration innerDecl = convertToDeclaration(module, (Declaration)container, name, DeclarationType.TYPE); if(innerDecl == null) throw new ModelResolutionException("Failed to load local type " + name + " for outer type " + container.getQualifiedNameString()); } } private boolean isInstantiator(MethodMirror methodMirror) { return methodMirror.getName().endsWith("$aliased$"); } private boolean isFromJDK(ClassMirror classMirror) { String pkgName = unquotePackageName(classMirror.getPackage()); return JDKUtils.isJDKAnyPackage(pkgName) || JDKUtils.isOracleJDKAnyPackage(pkgName); } private void setAnnotations(Annotated annotated, AnnotatedMirror classMirror, boolean isNativeHeader) { if (classMirror.getAnnotation(CEYLON_ANNOTATIONS_ANNOTATION) != null) { // If the class has @Annotations then use it (in >=1.2 only ceylon.language does) Long mods = (Long)getAnnotationValue(classMirror, CEYLON_ANNOTATIONS_ANNOTATION, "modifiers"); if (mods != null) { // If there is a modifiers value then use it to load the modifiers for (LanguageAnnotation mod : LanguageAnnotation.values()) { if (mod.isModifier()) { if ((mod.mask & mods) != 0) { annotated.getAnnotations().addAll(mod.makeFromCeylonAnnotation(null)); } } } } // Load anything else the long way, reading the @Annotation(name=...) List<AnnotationMirror> annotations = getAnnotationArrayValue(classMirror, CEYLON_ANNOTATIONS_ANNOTATION); if(annotations != null) { for(AnnotationMirror annotation : annotations){ annotated.getAnnotations().add(readModelAnnotation(annotation)); } } } else { // If the class lacks @Annotations then set the modifier annotations // according to the presence of @Shared$annotation etc for (LanguageAnnotation mod : LanguageAnnotation.values()) { if (classMirror.getAnnotation(mod.annotationType) != null) { annotated.getAnnotations().addAll(mod.makeFromCeylonAnnotation(classMirror.getAnnotation(mod.annotationType))); } } // Hack for anonymous classes where the getter method has the annotations, // but the typechecker wants them on the Class model. if ((annotated instanceof Class) && ((Class)annotated).isAnonymous()) { Class clazz = (Class)annotated; Declaration objectValue = clazz.getContainer().getDirectMember(clazz.getName(), null, false); if (objectValue != null) { annotated.getAnnotations().addAll(objectValue.getAnnotations()); } } } boolean hasCeylonDeprecated = false; for(Annotation a : annotated.getAnnotations()) { if (a.getName().equals("deprecated")) { hasCeylonDeprecated = true; break; } } // Add a ceylon deprecated("") if it's annotated with java.lang.Deprecated // and doesn't already have the ceylon annotation if (classMirror.getAnnotation(JAVA_DEPRECATED_ANNOTATION) != null) { if (!hasCeylonDeprecated) { Annotation modelAnnotation = new Annotation(); modelAnnotation.setName("deprecated"); modelAnnotation.getPositionalArguments().add(""); annotated.getAnnotations().add(modelAnnotation); hasCeylonDeprecated = true; } } if (annotated instanceof Declaration && !((Declaration)annotated).getNativeBackends().none()) { // Do nothing : // it has already been managed when in the makeLazyXXX() function } else { manageNativeBackend(annotated, classMirror, isNativeHeader); } } private void manageNativeBackend(Annotated annotated, AnnotatedMirror mirror, boolean isNativeHeader) { if (mirror == null) return; // Set "native" annotation @SuppressWarnings("unchecked") List<String> nativeBackends = (List<String>)getAnnotationValue(mirror, CEYLON_LANGUAGE_NATIVE_ANNOTATION, "backends"); if (nativeBackends != null) { Backends backends = Backends.fromAnnotations(nativeBackends); if (isNativeHeader) { backends = Backends.HEADER; } else if (backends.header()) { // Elements in the class file marked `native("")` are actually // default implementations taken from the header that were // copied to the output, so here we reset them to `native("jvm")` backends = Backends.JAVA; } if (annotated instanceof Declaration) { Declaration decl = (Declaration)annotated; decl.setNativeBackends(backends); if (isNativeHeader) { List<Declaration> al = new ArrayList<Declaration>(1); setOverloads(decl, al); } } else if (annotated instanceof Module) { ((Module)annotated).setNativeBackends(backends); } } else { // Mark native Classes and Interfaces as well, but don't deal with overloads and such if (annotated instanceof LazyClass && !((LazyClass)annotated).isCeylon() || annotated instanceof LazyInterface && !((LazyInterface)annotated).isCeylon()) { ((Declaration)annotated).setNativeBackends(Backend.Java.asSet()); } } } protected boolean isDeprecated(AnnotatedMirror classMirror){ if (classMirror.getAnnotation(JAVA_DEPRECATED_ANNOTATION) != null) return true; if (classMirror.getAnnotation(CEYLON_ANNOTATIONS_ANNOTATION) != null) { // Load anything else the long way, reading the @Annotation(name=...) List<AnnotationMirror> annotations = getAnnotationArrayValue(classMirror, CEYLON_ANNOTATIONS_ANNOTATION); if(annotations != null) { for(AnnotationMirror annotation : annotations){ String name = (String) annotation.getValue(); if(name != null && name.equals("deprecated")) return true; } } return false; } else { // If the class lacks @Annotations then set the modifier annotations // according to the presence of @Shared$annotation etc return classMirror.getAnnotation(LanguageAnnotation.DEPRECATED.annotationType) != null; } } public static List<Declaration> getOverloads(Declaration decl) { if (decl instanceof Function) { return ((Function)decl).getOverloads(); } else if (decl instanceof Value) { return ((Value)decl).getOverloads(); } else if (decl instanceof Class) { return ((Class)decl).getOverloads(); } return Collections.emptyList(); } public static void setOverloads(Declaration decl, List<Declaration> overloads) { if (decl instanceof Function) { ((Function)decl).setOverloads(overloads); } else if (decl instanceof Value) { ((Value)decl).setOverloads(overloads); } else if (decl instanceof Class) { ((Class)decl).setOverloads(overloads); } } private Annotation readModelAnnotation(AnnotationMirror annotation) { Annotation modelAnnotation = new Annotation(); modelAnnotation.setName((String) annotation.getValue()); @SuppressWarnings("unchecked") List<String> arguments = (List<String>) annotation.getValue("arguments"); if(arguments != null){ modelAnnotation.getPositionalArguments().addAll(arguments); }else{ @SuppressWarnings("unchecked") List<AnnotationMirror> namedArguments = (List<AnnotationMirror>) annotation.getValue("namedArguments"); if(namedArguments != null){ for(AnnotationMirror namedArgument : namedArguments){ String argName = (String) namedArgument.getValue("name"); String argValue = (String) namedArgument.getValue("value"); modelAnnotation.getNamedArguments().put(argName, argValue); } } } return modelAnnotation; } private void addInnerClasses(ClassOrInterface klass, ClassMirror classMirror) { AnnotationMirror membersAnnotation = classMirror.getAnnotation(CEYLON_MEMBERS_ANNOTATION); if(membersAnnotation == null) addInnerClassesFromMirror(klass, classMirror); else addInnerClassesFromAnnotation(klass, membersAnnotation); } private void addInnerClassesFromAnnotation(ClassOrInterface klass, AnnotationMirror membersAnnotation) { @SuppressWarnings("unchecked") List<AnnotationMirror> members = (List<AnnotationMirror>) membersAnnotation.getValue(); for(AnnotationMirror member : members){ TypeMirror javaClassMirror = (TypeMirror)member.getValue("klass"); String javaClassName; // void.class is the default value, I guess it's a primitive? if(javaClassMirror != null && !javaClassMirror.isPrimitive()){ javaClassName = javaClassMirror.getQualifiedName(); }else{ // we get the class name as a string String name = (String)member.getValue("javaClassName"); ClassMirror container = null; if(klass instanceof LazyClass){ container = ((LazyClass) klass).classMirror; }else if(klass instanceof LazyInterface){ if(((LazyInterface) klass).isCeylon()) container = ((LazyInterface) klass).companionClass; else container = ((LazyInterface) klass).classMirror; } if(container == null) throw new ModelResolutionException("Unknown container type: " + klass + " when trying to load inner class " + name); javaClassName = container.getQualifiedName()+"$"+name; } Declaration innerDecl = convertToDeclaration(ModelUtil.getModuleContainer(klass), klass, javaClassName, DeclarationType.TYPE); if(innerDecl == null) throw new ModelResolutionException("Failed to load inner type " + javaClassName + " for outer type " + klass.getQualifiedNameString()); if(shouldLinkNatives(innerDecl)) { initNativeHeaderMember(innerDecl); } } } /** * Allows subclasses to do something to the class name */ protected String assembleJavaClass(String javaClass, String packageName) { return javaClass; } private void addInnerClassesFromMirror(ClassOrInterface klass, ClassMirror classMirror) { boolean isJDK = isFromJDK(classMirror); Module module = ModelUtil.getModule(klass); for(ClassMirror innerClass : classMirror.getDirectInnerClasses()){ // We skip members marked with @Ignore if(innerClass.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null) continue; // We skip anonymous inner classes if(innerClass.isAnonymous()) continue; // We skip private classes, otherwise the JDK has a ton of unresolved things if(isJDK && !innerClass.isPublic()) continue; // convert it convertToDeclaration(module, klass, innerClass, DeclarationType.TYPE); // no need to set its container as that's now handled by convertToDeclaration } } private Function addMethod(ClassOrInterface klass, MethodMirror methodMirror, ClassMirror classMirror, boolean isCeylon, boolean isOverloaded, boolean isNativeHeader) { JavaMethod method = new JavaMethod(methodMirror); String methodName = methodMirror.getName(); method.setContainer(klass); method.setScope(klass); method.setRealName(methodName); method.setUnit(klass.getUnit()); method.setOverloaded(isOverloaded || isOverloadingMethod(methodMirror)); Type type = null; try{ setMethodOrValueFlags(klass, methodMirror, method, isCeylon); }catch(ModelResolutionException x){ // collect an error in its type type = logModelResolutionException(x, klass, "method '"+methodMirror.getName()+"' (checking if it is an overriding method)"); } if(methodName.equals("hash") || methodName.equals("string")) method.setName(methodName+"_method"); else method.setName(JvmBackendUtil.strip(methodName, isCeylon, method.isShared())); method.setDefaultedAnnotation(methodMirror.isDefault()); // type params first try{ setTypeParameters(method, methodMirror, isCeylon); }catch(ModelResolutionException x){ if(type == null){ type = logModelResolutionException(x, klass, "method '"+methodMirror.getName()+"' (loading type parameters)"); } } // and its return type // do not log an additional error if we had one from checking if it was overriding if(type == null) type = obtainType(methodMirror.getReturnType(), methodMirror, method, ModelUtil.getModuleContainer(method), VarianceLocation.COVARIANT, "method '"+methodMirror.getName()+"'", klass); method.setType(type); // now its parameters if(isEqualsMethod(methodMirror)) setEqualsParameters(method, methodMirror); else setParameters(method, classMirror, methodMirror, isCeylon, klass); method.setUncheckedNullType((!isCeylon && !methodMirror.getReturnType().isPrimitive()) || isUncheckedNull(methodMirror)); type.setRaw(isRaw(ModelUtil.getModuleContainer(klass), methodMirror.getReturnType())); markDeclaredVoid(method, methodMirror); markUnboxed(method, methodMirror, methodMirror.getReturnType()); markTypeErased(method, methodMirror, methodMirror.getReturnType()); markUntrustedType(method, methodMirror, methodMirror.getReturnType()); method.setDeprecated(isDeprecated(methodMirror)); setAnnotations(method, methodMirror, isNativeHeader); klass.addMember(method); ModelUtil.setVisibleScope(method); addLocalDeclarations(method, classMirror, methodMirror); return method; } private List<Type> getSignature(Declaration decl) { List<Type> result = null; if (decl instanceof Functional) { Functional func = (Functional)decl; if (func.getParameterLists().size() > 0) { List<Parameter> params = func.getFirstParameterList().getParameters(); result = new ArrayList<Type>(params.size()); for (Parameter p : params) { result.add(p.getType()); } } } return result; } private boolean isStartOfJavaBeanPropertyName(int codepoint){ return (codepoint == Character.toUpperCase(codepoint)) || codepoint == '_'; } private boolean isNonGenericMethod(MethodMirror methodMirror){ return !methodMirror.isConstructor() && methodMirror.getTypeParameters().isEmpty(); } private boolean isGetter(MethodMirror methodMirror) { if(!isNonGenericMethod(methodMirror)) return false; String name = methodMirror.getName(); boolean matchesGet = name.length() > 3 && name.startsWith("get") && isStartOfJavaBeanPropertyName(name.codePointAt(3)) && !"getString".equals(name) && !"getHash".equals(name) && !"getEquals".equals(name); boolean matchesIs = name.length() > 2 && name.startsWith("is") && isStartOfJavaBeanPropertyName(name.codePointAt(2)) && !"isString".equals(name) && !"isHash".equals(name) && !"isEquals".equals(name); boolean hasNoParams = methodMirror.getParameters().size() == 0; boolean hasNonVoidReturn = (methodMirror.getReturnType().getKind() != TypeKind.VOID); boolean hasBooleanReturn = (methodMirror.getReturnType().getKind() == TypeKind.BOOLEAN); return (matchesGet && hasNonVoidReturn || matchesIs && hasBooleanReturn) && hasNoParams; } private boolean isStringGetter(MethodMirror methodMirror) { if(!isNonGenericMethod(methodMirror)) return false; String name = methodMirror.getName(); boolean matchesGet = "getString".equals(name); boolean matchesIs = "isString".equals(name); boolean hasNoParams = methodMirror.getParameters().size() == 0; boolean hasNonVoidReturn = (methodMirror.getReturnType().getKind() != TypeKind.VOID); boolean hasBooleanReturn = (methodMirror.getReturnType().getKind() == TypeKind.BOOLEAN); return (matchesGet && hasNonVoidReturn || matchesIs && hasBooleanReturn) && hasNoParams; } private boolean isHashGetter(MethodMirror methodMirror) { if(!isNonGenericMethod(methodMirror)) return false; String name = methodMirror.getName(); boolean matchesGet = "getHash".equals(name); boolean matchesIs = "isHash".equals(name); boolean hasNoParams = methodMirror.getParameters().size() == 0; boolean hasNonVoidReturn = (methodMirror.getReturnType().getKind() != TypeKind.VOID); boolean hasBooleanReturn = (methodMirror.getReturnType().getKind() == TypeKind.BOOLEAN); return (matchesGet && hasNonVoidReturn || matchesIs && hasBooleanReturn) && hasNoParams; } private boolean isSetter(MethodMirror methodMirror) { if(!isNonGenericMethod(methodMirror)) return false; String name = methodMirror.getName(); boolean matchesSet = name.length() > 3 && name.startsWith("set") && isStartOfJavaBeanPropertyName(name.codePointAt(3)) && !"setString".equals(name) && !"setHash".equals(name) && !"setEquals".equals(name); boolean hasOneParam = methodMirror.getParameters().size() == 1; boolean hasVoidReturn = (methodMirror.getReturnType().getKind() == TypeKind.VOID); return matchesSet && hasOneParam && hasVoidReturn; } private boolean isStringSetter(MethodMirror methodMirror) { if(!isNonGenericMethod(methodMirror)) return false; String name = methodMirror.getName(); boolean matchesSet = name.equals("setString"); boolean hasOneParam = methodMirror.getParameters().size() == 1; boolean hasVoidReturn = (methodMirror.getReturnType().getKind() == TypeKind.VOID); return matchesSet && hasOneParam && hasVoidReturn; } private boolean isHashSetter(MethodMirror methodMirror) { if(!isNonGenericMethod(methodMirror)) return false; String name = methodMirror.getName(); boolean matchesSet = name.equals("setHash"); boolean hasOneParam = methodMirror.getParameters().size() == 1; boolean hasVoidReturn = (methodMirror.getReturnType().getKind() == TypeKind.VOID); return matchesSet && hasOneParam && hasVoidReturn; } private boolean isHashAttribute(MethodMirror methodMirror) { if(!isNonGenericMethod(methodMirror) || methodMirror.isStatic()) return false; String name = methodMirror.getName(); boolean matchesName = "hashCode".equals(name); boolean hasNoParams = methodMirror.getParameters().size() == 0; return matchesName && hasNoParams; } private boolean isStringAttribute(MethodMirror methodMirror) { if(!isNonGenericMethod(methodMirror) || methodMirror.isStatic()) return false; String name = methodMirror.getName(); boolean matchesName = "toString".equals(name); boolean hasNoParams = methodMirror.getParameters().size() == 0; return matchesName && hasNoParams; } private boolean isEqualsMethod(MethodMirror methodMirror) { if(!isNonGenericMethod(methodMirror) || methodMirror.isStatic()) return false; String name = methodMirror.getName(); if(!"equals".equals(name) || methodMirror.getParameters().size() != 1) return false; VariableMirror param = methodMirror.getParameters().get(0); return sameType(param.getType(), OBJECT_TYPE); } private void setEqualsParameters(Function decl, MethodMirror methodMirror) { ParameterList parameters = new ParameterList(); decl.addParameterList(parameters); Parameter parameter = new Parameter(); Value value = new Value(); parameter.setModel(value); value.setInitializerParameter(parameter); value.setUnit(decl.getUnit()); value.setContainer((Scope) decl); value.setScope((Scope) decl); parameter.setName("that"); value.setName("that"); value.setType(getNonPrimitiveType(getLanguageModule(), CEYLON_OBJECT_TYPE, decl, VarianceLocation.INVARIANT)); parameter.setDeclaration((Declaration) decl); parameters.getParameters().add(parameter); decl.addMember(value); } private String getJavaAttributeName(MethodMirror methodMirror) { String name = getAnnotationStringValue(methodMirror, CEYLON_NAME_ANNOTATION); if(name != null) return name; return getJavaAttributeName(methodMirror.getName()); } private String getJavaAttributeName(String getterName) { if (getterName.startsWith("get") || getterName.startsWith("set")) { return NamingBase.getJavaBeanName(getterName.substring(3)); } else if (getterName.startsWith("is")) { // Starts with "is" return NamingBase.getJavaBeanName(getterName.substring(2)); } else { throw new RuntimeException("Illegal java getter/setter name"); } } private Value addValue(ClassOrInterface klass, String ceylonName, FieldMirror fieldMirror, boolean isCeylon, boolean isNativeHeader) { // make sure it's a FieldValue so we can figure it out in the backend Value value = new FieldValue(fieldMirror.getName()); value.setContainer(klass); value.setScope(klass); // use the name annotation if present (used by Java arrays) String nameAnnotation = getAnnotationStringValue(fieldMirror, CEYLON_NAME_ANNOTATION); value.setName(nameAnnotation != null ? nameAnnotation : ceylonName); value.setUnit(klass.getUnit()); value.setShared(fieldMirror.isPublic() || fieldMirror.isProtected() || fieldMirror.isDefaultAccess()); value.setProtectedVisibility(fieldMirror.isProtected()); value.setPackageVisibility(fieldMirror.isDefaultAccess()); value.setStaticallyImportable(fieldMirror.isStatic()); setDeclarationAliases(value, fieldMirror); // field can't be abstract or interface, so not formal // can we override fields? good question. Not really, but from an external point of view? // FIXME: figure this out: (default) // FIXME: for the same reason, can it be an overriding field? (actual) value.setVariable(!fieldMirror.isFinal()); // figure out if it's an enum subtype in a final static field if(fieldMirror.getType().getKind() == TypeKind.DECLARED && fieldMirror.getType().getDeclaredClass() != null && fieldMirror.getType().getDeclaredClass().isEnum() && fieldMirror.isFinal() && fieldMirror.isStatic()) value.setEnumValue(true); Type type = obtainType(fieldMirror.getType(), fieldMirror, klass, ModelUtil.getModuleContainer(klass), VarianceLocation.INVARIANT, "field '"+value.getName()+"'", klass); if (value.isEnumValue()) { Class enumValueType = new Class(); enumValueType.setValueConstructor(true); enumValueType.setJavaEnum(true); enumValueType.setAnonymous(true); enumValueType.setExtendedType(type); enumValueType.setContainer(value.getContainer()); enumValueType.setScope(value.getContainer()); enumValueType.setDeprecated(value.isDeprecated()); enumValueType.setName(value.getName()); enumValueType.setFinal(true); enumValueType.setUnit(value.getUnit()); enumValueType.setStaticallyImportable(value.isStaticallyImportable()); value.setType(enumValueType.getType()); value.setUncheckedNullType(false); } else { value.setType(type); value.setUncheckedNullType((!isCeylon && !fieldMirror.getType().isPrimitive()) || isUncheckedNull(fieldMirror)); } type.setRaw(isRaw(ModelUtil.getModuleContainer(klass), fieldMirror.getType())); markUnboxed(value, null, fieldMirror.getType()); markTypeErased(value, fieldMirror, fieldMirror.getType()); markUntrustedType(value, fieldMirror, fieldMirror.getType()); value.setDeprecated(isDeprecated(fieldMirror)); setAnnotations(value, fieldMirror, isNativeHeader); klass.addMember(value); ModelUtil.setVisibleScope(value); return value; } private boolean isRaw(Module module, TypeMirror type) { // dirty hack to get rid of bug where calling type.isRaw() on a ceylon type we are going to compile would complete() it, which // would try to parse its file. For ceylon types we don't need the class file info we can query it // See https://github.com/ceylon/ceylon-compiler/issues/1085 switch(type.getKind()){ case ARRAY: // arrays are never raw case BOOLEAN: case BYTE: case CHAR: case DOUBLE: case ERROR: case FLOAT: case INT: case LONG: case NULL: case SHORT: case TYPEVAR: case VOID: case WILDCARD: return false; case DECLARED: ClassMirror klass = type.getDeclaredClass(); if(klass.isJavaSource()){ // I suppose this should work return type.isRaw(); } List<String> path = new LinkedList<String>(); String pkgName = klass.getPackage().getQualifiedName(); String unquotedPkgName = unquotePackageName(klass.getPackage()); String qualifiedName = klass.getQualifiedName(); String relativeName = pkgName.isEmpty() ? qualifiedName : qualifiedName.substring(pkgName.length()+1); for(String name : relativeName.split("[\\$\\.]")){ if(!name.isEmpty()){ path.add(name); } } if(path.size() > 1){ // find the proper class mirror for the container klass = loadClass(module, pkgName, new StringBuilder(pkgName) .append('.') .append(path.get(0)).toString()); if(klass == null) return false; } if(!path.isEmpty() && klass.isLoadedFromSource()){ // we need to find its model Scope scope = packagesByName.get(cacheKeyByModule(module, unquotedPkgName)); if(scope == null) return false; for(String name : path){ Declaration decl = scope.getDirectMember(name, null, false); if(decl == null) return false; // if we get a value, we want its type if(JvmBackendUtil.isValue(decl) && ((Value)decl).getTypeDeclaration().getName().equals(name)) decl = ((Value)decl).getTypeDeclaration(); if(decl instanceof TypeDeclaration == false) return false; scope = (TypeDeclaration)decl; } TypeDeclaration typeDecl = (TypeDeclaration) scope; return !typeDecl.getTypeParameters().isEmpty() && type.getTypeArguments().isEmpty(); } try{ return type.isRaw(); }catch(Exception x){ // ignore this exception, it's likely to be due to missing module imports and an unknown type and // it will be logged somewhere else return false; } default: return false; } } private JavaBeanValue addValue(ClassOrInterface klass, MethodMirror methodMirror, String methodName, boolean isCeylon, boolean isNativeHeader) { JavaBeanValue value = new JavaBeanValue(methodMirror); value.setGetterName(methodMirror.getName()); value.setContainer(klass); value.setScope(klass); value.setUnit(klass.getUnit()); Type type = null; try{ setMethodOrValueFlags(klass, methodMirror, value, isCeylon); }catch(ModelResolutionException x){ // collect an error in its type type = logModelResolutionException(x, klass, "getter '"+methodName+"' (checking if it is an overriding method"); } value.setName(JvmBackendUtil.strip(methodName, isCeylon, value.isShared())); // do not log an additional error if we had one from checking if it was overriding if(type == null) type = obtainType(methodMirror.getReturnType(), methodMirror, klass, ModelUtil.getModuleContainer(klass), VarianceLocation.INVARIANT, "getter '"+methodName+"'", klass); value.setType(type); // special case for hash attributes which we want to pretend are of type long internally if(value.isShared() && methodName.equals("hash")) type.setUnderlyingType("long"); value.setUncheckedNullType((!isCeylon && !methodMirror.getReturnType().isPrimitive()) || isUncheckedNull(methodMirror)); type.setRaw(isRaw(ModelUtil.getModuleContainer(klass), methodMirror.getReturnType())); markUnboxed(value, methodMirror, methodMirror.getReturnType()); markTypeErased(value, methodMirror, methodMirror.getReturnType()); markUntrustedType(value, methodMirror, methodMirror.getReturnType()); value.setDeprecated(isDeprecated(methodMirror)); setAnnotations(value, methodMirror, isNativeHeader); klass.addMember(value); ModelUtil.setVisibleScope(value); return value; } private boolean isUncheckedNull(AnnotatedMirror methodMirror) { Boolean unchecked = getAnnotationBooleanValue(methodMirror, CEYLON_TYPE_INFO_ANNOTATION, "uncheckedNull"); return unchecked != null && unchecked.booleanValue(); } private void setMethodOrValueFlags(final ClassOrInterface klass, final MethodMirror methodMirror, final FunctionOrValue decl, boolean isCeylon) { decl.setShared(methodMirror.isPublic() || methodMirror.isProtected() || methodMirror.isDefaultAccess()); decl.setProtectedVisibility(methodMirror.isProtected()); decl.setPackageVisibility(methodMirror.isDefaultAccess()); setDeclarationAliases(decl, methodMirror); if(decl instanceof Value){ setValueTransientLateFlags((Value)decl, methodMirror, isCeylon); } if(// for class members we rely on abstract bit (klass instanceof Class && methodMirror.isAbstract()) // Trust the abstract bit for Java interfaces, but not for Ceylon ones || (klass instanceof Interface && !((LazyInterface)klass).isCeylon() && methodMirror.isAbstract()) // For Ceylon interfaces we rely on annotation || methodMirror.getAnnotation(CEYLON_LANGUAGE_FORMAL_ANNOTATION) != null) { decl.setFormal(true); } else { if (// for class members we rely on final/static bits (klass instanceof Class && !klass.isFinal() // a final class necessarily has final members && !methodMirror.isFinal() && !methodMirror.isStatic()) // Java interfaces are never final || (klass instanceof Interface && !((LazyInterface)klass).isCeylon()) // For Ceylon interfaces we rely on annotation || methodMirror.getAnnotation(CEYLON_LANGUAGE_DEFAULT_ANNOTATION) != null){ decl.setDefault(true); } } decl.setStaticallyImportable(methodMirror.isStatic() && methodMirror.getAnnotation(CEYLON_ENUMERATED_ANNOTATION) == null); decl.setActualCompleter(this); } @Override public void completeActual(Declaration decl){ Scope container = decl.getContainer(); if(container instanceof ClassOrInterface){ ClassOrInterface klass = (ClassOrInterface) container; decl.setRefinedDeclaration(decl); // we never consider Interface and other stuff, since we never register the actualCompleter for them if(decl instanceof Class){ // Java member classes are never actual if(!JvmBackendUtil.isCeylon((Class)decl)) return; // we already set the actual bit for member classes, we just need the refined decl if(decl.isActual()){ Declaration refined = klass.getRefinedMember(decl.getName(), getSignature(decl), false); decl.setRefinedDeclaration(refined); } }else{ // Function or Value MethodMirror methodMirror; if(decl instanceof JavaBeanValue) methodMirror = ((JavaBeanValue) decl).mirror; else if(decl instanceof JavaMethod) methodMirror = ((JavaMethod) decl).mirror; else throw new ModelResolutionException("Unknown type of declaration: "+decl+": "+decl.getClass().getName()); decl.setRefinedDeclaration(decl); // For Ceylon interfaces we rely on annotation if(klass instanceof LazyInterface && ((LazyInterface)klass).isCeylon()){ boolean actual = methodMirror.getAnnotation(CEYLON_LANGUAGE_ACTUAL_ANNOTATION) != null; decl.setActual(actual); if(actual){ Declaration refined = klass.getRefinedMember(decl.getName(), getSignature(decl), false); decl.setRefinedDeclaration(refined); } }else{ if(isOverridingMethod(methodMirror)){ decl.setActual(true); Declaration refined = klass.getRefinedMember(decl.getName(), getSignature(decl), false); decl.setRefinedDeclaration(refined); } } // now that we know the refined declaration, we can check for reified type param support // for Ceylon methods if(decl instanceof JavaMethod && JvmBackendUtil.isCeylon(klass)){ if(!methodMirror.getTypeParameters().isEmpty() // because this requires the refined decl, we defer this check until we've set it, to not trigger // lazy loading just to check. && JvmBackendUtil.supportsReified(decl)){ checkReifiedTypeDescriptors(methodMirror.getTypeParameters().size(), container.getQualifiedNameString(), methodMirror, false); } } } } } private void setValueTransientLateFlags(Value decl, MethodMirror methodMirror, boolean isCeylon) { if(isCeylon) decl.setTransient(methodMirror.getAnnotation(CEYLON_TRANSIENT_ANNOTATION) != null); else // all Java getters are transient, fields are not decl.setTransient(decl instanceof FieldValue == false); decl.setLate(methodMirror.getAnnotation(CEYLON_LANGUAGE_LATE_ANNOTATION) != null); } private void setExtendedType(ClassOrInterface klass, ClassMirror classMirror) { // look at its super type TypeMirror superClass = classMirror.getSuperclass(); Type extendedType; if(klass instanceof Interface){ // interfaces need to have their superclass set to Object if(superClass == null || superClass.getKind() == TypeKind.NONE) extendedType = getNonPrimitiveType(getLanguageModule(), CEYLON_OBJECT_TYPE, klass, VarianceLocation.INVARIANT); else extendedType = getNonPrimitiveType(ModelUtil.getModule(klass), superClass, klass, VarianceLocation.INVARIANT); }else if(klass instanceof Class && ((Class) klass).isOverloaded()){ // if the class is overloaded we already have it stored extendedType = klass.getExtendedType(); }else{ String className = classMirror.getQualifiedName(); String superClassName = superClass == null ? null : superClass.getQualifiedName(); if(className.equals("ceylon.language.Anything")){ // ceylon.language.Anything has no super type extendedType = null; }else if(className.equals("java.lang.Object")){ // we pretend its superclass is something else, but note that in theory we shouldn't // be seeing j.l.Object at all due to unerasure extendedType = getNonPrimitiveType(getLanguageModule(), CEYLON_BASIC_TYPE, klass, VarianceLocation.INVARIANT); }else{ // read it from annotation first String annotationSuperClassName = getAnnotationStringValue(classMirror, CEYLON_CLASS_ANNOTATION, "extendsType"); if(annotationSuperClassName != null && !annotationSuperClassName.isEmpty()){ extendedType = decodeType(annotationSuperClassName, klass, ModelUtil.getModuleContainer(klass), "extended type"); }else{ // read it from the Java super type // now deal with type erasure, avoid having Object as superclass if("java.lang.Object".equals(superClassName)){ extendedType = getNonPrimitiveType(getLanguageModule(), CEYLON_BASIC_TYPE, klass, VarianceLocation.INVARIANT); } else if(superClass != null){ try{ extendedType = getNonPrimitiveType(ModelUtil.getModule(klass), superClass, klass, VarianceLocation.INVARIANT); }catch(ModelResolutionException x){ extendedType = logModelResolutionException(x, klass, "Error while resolving extended type of "+klass.getQualifiedNameString()); } }else{ // FIXME: should this be UnknownType? extendedType = null; } } } } if(extendedType != null) klass.setExtendedType(extendedType); } private Type getJavaAnnotationExtendedType(ClassOrInterface klass, ClassMirror classMirror) { TypeDeclaration constrainedAnnotation = (TypeDeclaration) convertNonPrimitiveTypeToDeclaration(getLanguageModule(), CEYLON_CONSTRAINED_ANNOTATION_TYPE, klass, DeclarationType.TYPE); AnnotationMirror target = classMirror.getAnnotation("java.lang.annotation.Target"); Set<Type> types = new HashSet<Type>(); if(target != null){ @SuppressWarnings("unchecked") List<String> values = (List<String>) target.getValue(); for(String value : values){ switch(value){ case "TYPE": TypeDeclaration decl = (TypeDeclaration) convertNonPrimitiveTypeToDeclaration(getLanguageModule(), CEYLON_CLASS_OR_INTERFACE_DECLARATION_TYPE, klass, DeclarationType.TYPE); types.add(decl.getType()); decl = (TypeDeclaration) convertNonPrimitiveTypeToDeclaration(getLanguageModule(), CEYLON_ALIAS_DECLARATION_TYPE, klass, DeclarationType.TYPE); types.add(decl.getType()); break; case "ANNOTATION_TYPE": decl = (TypeDeclaration) convertNonPrimitiveTypeToDeclaration(getLanguageModule(), CEYLON_CLASS_OR_INTERFACE_DECLARATION_TYPE, klass, DeclarationType.TYPE); types.add(decl.getType()); break; case "CONSTRUCTOR": decl = (TypeDeclaration) convertNonPrimitiveTypeToDeclaration(getLanguageModule(), CEYLON_CONSTRUCTOR_DECLARATION_TYPE, klass, DeclarationType.TYPE); types.add(decl.getType()); if (!values.contains("TYPE")) { decl = (TypeDeclaration) convertNonPrimitiveTypeToDeclaration(getLanguageModule(), CEYLON_CLASS_WITH_INIT_DECLARATION_TYPE, klass, DeclarationType.TYPE); types.add(decl.getType()); } break; case "METHOD": // method annotations may be applied to shared members which are turned into getter methods case "PARAMETER": decl = (TypeDeclaration) convertNonPrimitiveTypeToDeclaration(getLanguageModule(), CEYLON_FUNCTION_OR_VALUE_DECLARATION_TYPE, klass, DeclarationType.TYPE); types.add(decl.getType()); break; case "FIELD": case "LOCAL_VARIABLE": decl = (TypeDeclaration) convertNonPrimitiveTypeToDeclaration(getLanguageModule(), CEYLON_VALUE_DECLARATION_TYPE, klass, DeclarationType.TYPE); types.add(decl.getType()); break; default: // all other values are ambiguous or have no mapping } } } Module module = ModelUtil.getModuleContainer(klass); Type annotatedType; if(types.size() == 1) annotatedType = types.iterator().next(); else if(types.isEmpty()){ TypeDeclaration decl; if(target == null){ // default is anything decl = (TypeDeclaration) convertNonPrimitiveTypeToDeclaration(getLanguageModule(), CEYLON_ANNOTATED_TYPE, klass, DeclarationType.TYPE); }else{ // we either had an empty set which means cannot be used as annotation in Java (only as annotation member) // or that we only had unmappable targets decl = typeFactory.getNothingDeclaration(); } annotatedType = decl.getType(); }else{ List<Type> list = new ArrayList<Type>(types.size()); list.addAll(types); annotatedType = union(list, getUnitForModule(module)); } Type constrainedType = constrainedAnnotation.appliedType(null, Arrays.asList(klass.getType(), getOptionalType(klass.getType(), module), annotatedType)); return constrainedType; } private void setParameters(Functional decl, ClassMirror classMirror, MethodMirror methodMirror, boolean isCeylon, Scope container) { ParameterList parameters = new ParameterList(); parameters.setNamedParametersSupported(isCeylon); decl.addParameterList(parameters); int parameterCount = methodMirror.getParameters().size(); int parameterIndex = 0; for(VariableMirror paramMirror : methodMirror.getParameters()){ // ignore some parameters if(paramMirror.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null) continue; boolean isLastParameter = parameterIndex == parameterCount - 1; boolean isVariadic = isLastParameter && methodMirror.isVariadic(); String paramName = getAnnotationStringValue(paramMirror, CEYLON_NAME_ANNOTATION); // use whatever param name we find as default if(paramName == null) paramName = paramMirror.getName(); Parameter parameter = new Parameter(); parameter.setName(paramName); TypeMirror typeMirror = paramMirror.getType(); Module module = ModelUtil.getModuleContainer((Scope) decl); Type type; if(isVariadic){ // possibly make it optional TypeMirror variadicType = typeMirror.getComponentType(); // we pretend it's toplevel because we want to get magic string conversion for variadic methods type = obtainType(ModelUtil.getModuleContainer((Scope)decl), variadicType, (Scope)decl, TypeLocation.TOPLEVEL, VarianceLocation.CONTRAVARIANT); if(!isCeylon && !variadicType.isPrimitive()){ // Java parameters are all optional unless primitives Type optionalType = getOptionalType(type, module); optionalType.setUnderlyingType(type.getUnderlyingType()); type = optionalType; } // turn it into a Sequential<T> type = typeFactory.getSequentialType(type); }else{ type = obtainType(typeMirror, paramMirror, (Scope) decl, module, VarianceLocation.CONTRAVARIANT, "parameter '"+paramName+"' of method '"+methodMirror.getName()+"'", (Declaration)decl); // variadic params may technically be null in Java, but it Ceylon sequenced params may not // so it breaks the typechecker logic for handling them, and it will always be a case of bugs // in the java side so let's not allow this if(!isCeylon && !typeMirror.isPrimitive()){ // Java parameters are all optional unless primitives Type optionalType = getOptionalType(type, module); optionalType.setUnderlyingType(type.getUnderlyingType()); type = optionalType; } } type.setRaw(isRaw(ModelUtil.getModuleContainer(container), typeMirror)); FunctionOrValue value = null; boolean lookedup = false; if (isCeylon && decl instanceof Class){ // For a functional parameter to a class, we can just lookup the member value = (FunctionOrValue)((Class)decl).getDirectMember(paramName, null, false); lookedup = value != null; } if (value == null) { // So either decl is not a Class, // or the method or value member of decl is not shared AnnotationMirror functionalParameterAnnotation = paramMirror.getAnnotation(CEYLON_FUNCTIONAL_PARAMETER_ANNOTATION); if (functionalParameterAnnotation != null) { // A functional parameter to a method Function method = loadFunctionalParameter((Declaration)decl, paramName, type, (String)functionalParameterAnnotation.getValue()); value = method; parameter.setDeclaredAnything(method.isDeclaredVoid()); } else { // A value parameter to a method value = new Value(); value.setType(type); } value.setContainer((Scope) decl); value.setScope((Scope) decl); ModelUtil.setVisibleScope(value); value.setUnit(((Element)decl).getUnit()); value.setName(paramName); }else{ // Ceylon 1.1 had a bug where TypeInfo for functional parameters included the full CallableType on the method // rather than just the method return type, so we try to detect this and fix it if(value instanceof Function && isCeylon1Dot1(classMirror)){ Type newType = getSimpleCallableReturnType(value.getType()); if(!newType.isUnknown()) value.setType(newType); } } value.setInitializerParameter(parameter); parameter.setModel(value); if(paramMirror.getAnnotation(CEYLON_SEQUENCED_ANNOTATION) != null || isVariadic) parameter.setSequenced(true); if(paramMirror.getAnnotation(CEYLON_DEFAULTED_ANNOTATION) != null) parameter.setDefaulted(true); if (parameter.isSequenced() && // FIXME: store info in Sequenced typeFactory.isNonemptyIterableType(parameter.getType())) { parameter.setAtLeastOne(true); } // unboxed is already set if it's a real method if(!lookedup){ // if it's variadic, consider the array element type (T[] == T...) for boxing rules markUnboxed(value, null, isVariadic ? paramMirror.getType().getComponentType() : paramMirror.getType()); } parameter.setDeclaration((Declaration) decl); value.setDeprecated(value.isDeprecated() || isDeprecated(paramMirror)); setAnnotations(value, paramMirror, false); parameters.getParameters().add(parameter); if (!lookedup) { parameter.getDeclaration().getMembers().add(parameter.getModel()); } parameterIndex++; } if (decl instanceof Function) { // Multiple parameter lists AnnotationMirror functionalParameterAnnotation = methodMirror.getAnnotation(CEYLON_FUNCTIONAL_PARAMETER_ANNOTATION); if (functionalParameterAnnotation != null) { parameterNameParser.parseMpl((String)functionalParameterAnnotation.getValue(), ((Function)decl).getType().getFullType(), (Function)decl); } } } private boolean isCeylon1Dot1(ClassMirror classMirror) { AnnotationMirror annotation = classMirror.getAnnotation(CEYLON_CEYLON_ANNOTATION); if(annotation == null) return false; Integer major = (Integer) annotation.getValue("major"); if(major == null) major = 0; Integer minor = (Integer) annotation.getValue("minor"); if(minor == null) minor = 0; return major == Versions.V1_1_BINARY_MAJOR_VERSION && minor == Versions.V1_1_BINARY_MINOR_VERSION; } private Function loadFunctionalParameter(Declaration decl, String paramName, Type type, String parameterNames) { Function method = new Function(); method.setName(paramName); method.setUnit(decl.getUnit()); if (parameterNames == null || parameterNames.isEmpty()) { // This branch is broken, but it deals with old code which lacked // the encoding of parameter names of functional parameters, so we'll keep it until 1.2 method.setType(getSimpleCallableReturnType(type)); ParameterList pl = new ParameterList(); int count = 0; for (Type pt : getSimpleCallableArgumentTypes(type)) { Parameter p = new Parameter(); Value v = new Value(); String name = "arg" + count++; p.setName(name); v.setName(name); v.setType(pt); v.setContainer(method); v.setScope(method); p.setModel(v); v.setInitializerParameter(p); pl.getParameters().add(p); method.addMember(v); } method.addParameterList(pl); } else { try { parameterNameParser.parse(parameterNames, type, method); } catch(Exception x){ logError(x.getClass().getSimpleName() + " while parsing parameter names of "+decl+": " + x.getMessage()); return method; } } return method; } List<Type> getSimpleCallableArgumentTypes(Type type) { if(type != null && type.isClassOrInterface() && type.getDeclaration().getQualifiedNameString().equals(CEYLON_LANGUAGE_CALLABLE_TYPE_NAME) && type.getTypeArgumentList().size() >= 2) return flattenCallableTupleType(type.getTypeArgumentList().get(1)); return Collections.emptyList(); } List<Type> flattenCallableTupleType(Type tupleType) { if(tupleType != null && tupleType.isClassOrInterface()){ String declName = tupleType.getDeclaration().getQualifiedNameString(); if(declName.equals(CEYLON_LANGUAGE_TUPLE_TYPE_NAME)){ List<Type> tal = tupleType.getTypeArgumentList(); if(tal.size() >= 3){ List<Type> ret = flattenCallableTupleType(tal.get(2)); ret.add(0, tal.get(1)); return ret; } }else if(declName.equals(CEYLON_LANGUAGE_EMPTY_TYPE_NAME)){ return new LinkedList<Type>(); }else if(declName.equals(CEYLON_LANGUAGE_SEQUENTIAL_TYPE_NAME)){ LinkedList<Type> ret = new LinkedList<Type>(); ret.add(tupleType); return ret; }else if(declName.equals(CEYLON_LANGUAGE_SEQUENCE_TYPE_NAME)){ LinkedList<Type> ret = new LinkedList<Type>(); ret.add(tupleType); return ret; } } return Collections.emptyList(); } Type getSimpleCallableReturnType(Type type) { if(type != null && type.isClassOrInterface() && type.getDeclaration().getQualifiedNameString().equals(CEYLON_LANGUAGE_CALLABLE_TYPE_NAME) && !type.getTypeArgumentList().isEmpty()) return type.getTypeArgumentList().get(0); return newUnknownType(); } private Type getOptionalType(Type type, Module moduleScope) { if(type.isUnknown()) return type; // we do not use Unit.getOptionalType because it causes lots of lazy loading that ultimately triggers the typechecker's // infinite recursion loop List<Type> list = new ArrayList<Type>(2); list.add(typeFactory.getNullType()); list.add(type); return union(list, getUnitForModule(moduleScope)); } private Type logModelResolutionError(Scope container, String message) { return logModelResolutionException((String)null, container, message); } private Type logModelResolutionException(ModelResolutionException x, Scope container, String message) { return logModelResolutionException(x.getMessage(), container, message); } private Type logModelResolutionException(final String exceptionMessage, Scope container, final String message) { final Module module = ModelUtil.getModuleContainer(container); return logModelResolutionException(exceptionMessage, module, message); } private Type logModelResolutionException(final String exceptionMessage, Module module, final String message) { UnknownType.ErrorReporter errorReporter; if(module != null && !module.isDefault()){ final StringBuilder sb = new StringBuilder(); sb.append("Error while loading the ").append(module.getNameAsString()).append("/").append(module.getVersion()); sb.append(" module:\n "); sb.append(message); if(exceptionMessage != null) sb.append(":\n ").append(exceptionMessage); errorReporter = makeModelErrorReporter(module, sb.toString()); }else if(exceptionMessage == null){ errorReporter = makeModelErrorReporter(message); }else{ errorReporter = makeModelErrorReporter(message+": "+exceptionMessage); } UnknownType ret = new UnknownType(typeFactory); ret.setErrorReporter(errorReporter); return ret.getType(); } /** * To be overridden by subclasses */ protected UnknownType.ErrorReporter makeModelErrorReporter(String message) { return new LogErrorRunnable(this, message); } /** * To be overridden by subclasses */ protected abstract UnknownType.ErrorReporter makeModelErrorReporter(Module module, String message); private static class LogErrorRunnable extends UnknownType.ErrorReporter { private AbstractModelLoader modelLoader; public LogErrorRunnable(AbstractModelLoader modelLoader, String message) { super(message); this.modelLoader = modelLoader; } @Override public void reportError() { modelLoader.logError(getMessage()); } } private void markTypeErased(TypedDeclaration decl, AnnotatedMirror typedMirror, TypeMirror type) { if (BooleanUtil.isTrue(getAnnotationBooleanValue(typedMirror, CEYLON_TYPE_INFO_ANNOTATION, "erased"))) { decl.setTypeErased(true); } else { decl.setTypeErased(sameType(type, OBJECT_TYPE)); } } private void markUntrustedType(TypedDeclaration decl, AnnotatedMirror typedMirror, TypeMirror type) { if (BooleanUtil.isTrue(getAnnotationBooleanValue(typedMirror, CEYLON_TYPE_INFO_ANNOTATION, "untrusted"))) { decl.setUntrustedType(true); } } private void markDeclaredVoid(Function decl, MethodMirror methodMirror) { if (methodMirror.isDeclaredVoid() || BooleanUtil.isTrue(getAnnotationBooleanValue(methodMirror, CEYLON_TYPE_INFO_ANNOTATION, "declaredVoid"))) { decl.setDeclaredVoid(true); } } /*private boolean hasTypeParameterWithConstraints(TypeMirror type) { switch(type.getKind()){ case BOOLEAN: case BYTE: case CHAR: case DOUBLE: case FLOAT: case INT: case LONG: case SHORT: case VOID: case WILDCARD: return false; case ARRAY: return hasTypeParameterWithConstraints(type.getComponentType()); case DECLARED: for(TypeMirror ta : type.getTypeArguments()){ if(hasTypeParameterWithConstraints(ta)) return true; } return false; case TYPEVAR: TypeParameterMirror typeParameter = type.getTypeParameter(); return typeParameter != null && hasNonErasedBounds(typeParameter); default: return false; } }*/ private void markUnboxed(TypedDeclaration decl, MethodMirror methodMirror, TypeMirror type) { boolean unboxed = false; if(type.isPrimitive() || type.getKind() == TypeKind.ARRAY || sameType(type, STRING_TYPE) || (methodMirror != null && methodMirror.isDeclaredVoid())) { unboxed = true; } decl.setUnboxed(unboxed); } @Override public void complete(LazyValue value) { synchronized(getLock()){ timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY); try{ MethodMirror meth = getGetterMethodMirror(value, value.classMirror, value.isToplevel()); if(meth == null || meth.getReturnType() == null){ value.setType(logModelResolutionError(value.getContainer(), "Error while resolving toplevel attribute "+value.getQualifiedNameString()+": getter method missing")); return; } value.setDeprecated(value.isDeprecated() | isDeprecated(meth)); value.setType(obtainType(meth.getReturnType(), meth, null, ModelUtil.getModuleContainer(value.getContainer()), VarianceLocation.INVARIANT, "toplevel attribute", value)); markVariable(value); setValueTransientLateFlags(value, meth, true); setAnnotations(value, meth, value.isNativeHeader()); markUnboxed(value, meth, meth.getReturnType()); markTypeErased(value, meth, meth.getReturnType()); TypeMirror setterClass = (TypeMirror) getAnnotationValue(value.classMirror, CEYLON_ATTRIBUTE_ANNOTATION, "setterClass"); // void.class is the default value, I guess it's a primitive? if(setterClass != null && !setterClass.isPrimitive()){ ClassMirror setterClassMirror = setterClass.getDeclaredClass(); value.setVariable(true); SetterWithLocalDeclarations setter = makeSetter(value, setterClassMirror); // adding local scopes should be done last, when we have the setter, because it may be needed by container chain addLocalDeclarations(value, value.classMirror, value.classMirror); addLocalDeclarations(setter, setterClassMirror, setterClassMirror); }else if(value.isToplevel() && value.isTransient() && value.isVariable()){ makeSetter(value, value.classMirror); // all local scopes for getter/setter are declared in the same class // adding local scopes should be done last, when we have the setter, because it may be needed by container chain addLocalDeclarations(value, value.classMirror, value.classMirror); }else{ // adding local scopes should be done last, when we have the setter, because it may be needed by container chain addLocalDeclarations(value, value.classMirror, value.classMirror); } }finally{ timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY); } } } private MethodMirror getGetterMethodMirror(Declaration value, ClassMirror classMirror, boolean toplevel) { MethodMirror meth = null; String getterName; if (toplevel) { // We do this to prevent calling complete() unnecessarily getterName = NamingBase.Unfix.get_.name(); } else { getterName = NamingBase.getGetterName(value); } for (MethodMirror m : classMirror.getDirectMethods()) { // Do not skip members marked with @Ignore, because the getter is supposed to be ignored if (m.getName().equals(getterName) && (!toplevel || m.isStatic()) && m.getParameters().size() == 0) { meth = m; break; } } return meth; } private void markVariable(LazyValue value) { String setterName = NamingBase.getSetterName(value); boolean toplevel = value.isToplevel(); for (MethodMirror m : value.classMirror.getDirectMethods()) { // Do not skip members marked with @Ignore, because the getter is supposed to be ignored if (m.getName().equals(setterName) && (!toplevel || m.isStatic()) && m.getParameters().size() == 1) { value.setVariable(true); } } } private SetterWithLocalDeclarations makeSetter(Value value, ClassMirror classMirror) { SetterWithLocalDeclarations setter = new SetterWithLocalDeclarations(classMirror); setter.setContainer(value.getContainer()); setter.setScope(value.getContainer()); setter.setType(value.getType()); setter.setName(value.getName()); Parameter p = new Parameter(); p.setHidden(true); Value v = new Value(); v.setType(value.getType()); v.setUnboxed(value.getUnboxed()); v.setInitializerParameter(p); v.setContainer(setter); p.setModel(v); v.setName(setter.getName()); p.setName(setter.getName()); p.setDeclaration(setter); setter.setParameter(p); value.setSetter(setter); setter.setGetter(value); return setter; } @Override public void complete(LazyFunction method) { synchronized(getLock()){ timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY); try{ MethodMirror meth = getFunctionMethodMirror(method); if(meth == null || meth.getReturnType() == null){ method.setType(logModelResolutionError(method.getContainer(), "Error while resolving toplevel method "+method.getQualifiedNameString()+": static method missing")); return; } // only check the static mod for toplevel classes if(!method.classMirror.isLocalClass() && !meth.isStatic()){ method.setType(logModelResolutionError(method.getContainer(), "Error while resolving toplevel method "+method.getQualifiedNameString()+": method is not static")); return; } method.setDeprecated(method.isDeprecated() | isDeprecated(meth)); // save the method name method.setRealMethodName(meth.getName()); // save the method method.setMethodMirror(meth); // type params first setTypeParameters(method, meth, true); method.setType(obtainType(meth.getReturnType(), meth, method, ModelUtil.getModuleContainer(method), VarianceLocation.COVARIANT, "toplevel method", method)); method.setDeclaredVoid(meth.isDeclaredVoid()); markDeclaredVoid(method, meth); markUnboxed(method, meth, meth.getReturnType()); markTypeErased(method, meth, meth.getReturnType()); markUntrustedType(method, meth, meth.getReturnType()); // now its parameters setParameters(method, method.classMirror, meth, true /* toplevel methods are always Ceylon */, method); method.setAnnotation(meth.getAnnotation(CEYLON_LANGUAGE_ANNOTATION_ANNOTATION) != null); setAnnotations(method, meth, method.isNativeHeader()); setAnnotationConstructor(method, meth); addLocalDeclarations(method, method.classMirror, method.classMirror); }finally{ timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY); } } } private MethodMirror getFunctionMethodMirror(LazyFunction method) { MethodMirror meth = null; String lookupName = method.getName(); for(MethodMirror m : method.classMirror.getDirectMethods()){ // We skip members marked with @Ignore if(m.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null) continue; if(NamingBase.stripLeadingDollar(m.getName()).equals(lookupName)){ meth = m; break; } } return meth; } // for subclasses protected abstract void setAnnotationConstructor(LazyFunction method, MethodMirror meth); public AnnotationProxyMethod makeInteropAnnotationConstructor(LazyInterface iface, AnnotationProxyClass klass, OutputElement oe, Package pkg){ String ctorName = oe == null ? NamingBase.getJavaBeanName(iface.getName()) : NamingBase.getDisambigAnnoCtorName(iface, oe); AnnotationProxyMethod ctor = new AnnotationProxyMethod(); ctor.setAnnotationTarget(oe); ctor.setProxyClass(klass); ctor.setContainer(pkg); ctor.setAnnotation(true); ctor.setName(ctorName); ctor.setShared(iface.isShared()); Annotation annotationAnnotation2 = new Annotation(); annotationAnnotation2.setName("annotation"); ctor.getAnnotations().add(annotationAnnotation2); ctor.setType(((TypeDeclaration)iface).getType()); ctor.setUnit(iface.getUnit()); ParameterList ctorpl = new ParameterList(); ctorpl.setPositionalParametersSupported(false); ctor.addParameterList(ctorpl); List<Parameter> ctorParams = new ArrayList<Parameter>(); for (Declaration member : iface.getMembers()) { boolean isValue = member.getName().equals("value"); if (member instanceof JavaMethod) { JavaMethod m = (JavaMethod)member; Parameter ctorParam = new Parameter(); ctorParams.add(ctorParam); Value value = new Value(); ctorParam.setModel(value); value.setInitializerParameter(ctorParam); ctorParam.setDeclaration(ctor); value.setContainer(klass); value.setScope(klass); ctorParam.setDefaulted(m.isDefaultedAnnotation()); value.setName(member.getName()); ctorParam.setName(member.getName()); value.setType(annotationParameterType(iface.getUnit(), m)); value.setUnboxed(true); value.setUnit(iface.getUnit()); if(isValue) ctorpl.getParameters().add(0, ctorParam); else ctorpl.getParameters().add(ctorParam); ctor.addMember(value); } } makeInteropAnnotationConstructorInvocation(ctor, klass, ctorParams); return ctor; } /** * For subclasses that provide compilation to Java annotations. */ protected abstract void makeInteropAnnotationConstructorInvocation(AnnotationProxyMethod ctor, AnnotationProxyClass klass, List<Parameter> ctorParams); /** * <pre> * annotation class Annotation$Proxy(...) satisfies Annotation { * // a `shared` class parameter for each method of Annotation * } * </pre> * @param iface The model of the annotation @interface * @return The annotation class for the given interface */ public AnnotationProxyClass makeInteropAnnotationClass( LazyInterface iface, Package pkg) { AnnotationProxyClass klass = new AnnotationProxyClass(iface); klass.setContainer(pkg); klass.setScope(pkg); klass.setName(iface.getName()+"$Proxy"); klass.setShared(iface.isShared()); klass.setAnnotation(true); Annotation annotationAnnotation = new Annotation(); annotationAnnotation.setName("annotation"); klass.getAnnotations().add(annotationAnnotation); klass.getSatisfiedTypes().add(iface.getType()); klass.setUnit(iface.getUnit()); ParameterList classpl = new ParameterList(); klass.addParameterList(classpl); klass.setScope(pkg); for (Declaration member : iface.getMembers()) { boolean isValue = member.getName().equals("value"); if (member instanceof JavaMethod) { JavaMethod m = (JavaMethod)member; Parameter klassParam = new Parameter(); Value value = new Value(); klassParam.setModel(value); value.setInitializerParameter(klassParam); klassParam.setDeclaration(klass); value.setContainer(klass); value.setScope(klass); value.setName(member.getName()); klassParam.setName(member.getName()); value.setType(annotationParameterType(iface.getUnit(), m)); value.setUnboxed(true); value.setUnit(iface.getUnit()); if(isValue) classpl.getParameters().add(0, klassParam); else classpl.getParameters().add(klassParam); klass.addMember(value); } } return klass; } private Type annotationParameterType(Unit unit, JavaMethod m) { Type type = m.getType(); if (JvmBackendUtil.isJavaArray(type.getDeclaration())) { String name = type.getDeclaration().getQualifiedNameString(); final Type elementType; String underlyingType = null; if(name.equals("java.lang::ObjectArray")){ Type eType = type.getTypeArgumentList().get(0); String elementTypeName = eType.getDeclaration().getQualifiedNameString(); if ("java.lang::String".equals(elementTypeName)) { elementType = unit.getStringType(); } else if ("java.lang::Class".equals(elementTypeName) || "java.lang.Class".equals(eType.getUnderlyingType())) { // Two cases because the types // Class[] and Class<?>[] are treated differently by // AbstractModelLoader.obtainType() // TODO Replace with metamodel ClassOrInterface type // once we have support for metamodel references elementType = unit.getAnythingType(); underlyingType = "java.lang.Class"; } else { elementType = eType; } // TODO Enum elements } else if(name.equals("java.lang::LongArray")) { elementType = unit.getIntegerType(); } else if (name.equals("java.lang::ByteArray")) { elementType = unit.getByteType(); } else if (name.equals("java.lang::ShortArray")) { elementType = unit.getIntegerType(); underlyingType = "short"; } else if (name.equals("java.lang::IntArray")){ elementType = unit.getIntegerType(); underlyingType = "int"; } else if(name.equals("java.lang::BooleanArray")){ elementType = unit.getBooleanType(); } else if(name.equals("java.lang::CharArray")){ elementType = unit.getCharacterType(); underlyingType = "char"; } else if(name.equals("java.lang::DoubleArray")) { elementType = unit.getFloatType(); } else if (name.equals("java.lang::FloatArray")){ elementType = unit.getFloatType(); underlyingType = "float"; } else { throw new RuntimeException(); } elementType.setUnderlyingType(underlyingType); Type iterableType = unit.getIterableType(elementType); return iterableType; } else if ("java.lang::Class".equals(type.getDeclaration().getQualifiedNameString())) { // TODO Replace with metamodel ClassOrInterface type // once we have support for metamodel references return unit.getAnythingType(); } else { return type; } } // // Satisfied Types private List<String> getSatisfiedTypesFromAnnotations(AnnotatedMirror symbol) { return getAnnotationArrayValue(symbol, CEYLON_SATISFIED_TYPES_ANNOTATION); } private void setSatisfiedTypes(ClassOrInterface klass, ClassMirror classMirror) { List<String> satisfiedTypes = getSatisfiedTypesFromAnnotations(classMirror); if(satisfiedTypes != null){ klass.getSatisfiedTypes().addAll(getTypesList(satisfiedTypes, klass, ModelUtil.getModuleContainer(klass), "satisfied types", klass.getQualifiedNameString())); }else{ if(classMirror.isAnnotationType()) // this only happens for Java annotations since Ceylon annotations are ignored // turn @Target into a subtype of ConstrainedAnnotation klass.getSatisfiedTypes().add(getJavaAnnotationExtendedType(klass, classMirror)); for(TypeMirror iface : classMirror.getInterfaces()){ // ignore generated interfaces if(sameType(iface, CEYLON_REIFIED_TYPE_TYPE) || sameType(iface, CEYLON_SERIALIZABLE_TYPE) || (classMirror.getAnnotation(CEYLON_CEYLON_ANNOTATION) != null && sameType(iface, JAVA_IO_SERIALIZABLE_TYPE_TYPE))) continue; try{ klass.getSatisfiedTypes().add(getNonPrimitiveType(ModelUtil.getModule(klass), iface, klass, VarianceLocation.INVARIANT)); }catch(ModelResolutionException x){ String classPackageName = unquotePackageName(classMirror.getPackage()); if(JDKUtils.isJDKAnyPackage(classPackageName)){ if(iface.getKind() == TypeKind.DECLARED){ // check if it's a JDK thing ClassMirror ifaceClass = iface.getDeclaredClass(); String ifacePackageName = unquotePackageName(ifaceClass.getPackage()); if(JDKUtils.isOracleJDKAnyPackage(ifacePackageName)){ // just log and ignore it logMissingOracleType(iface.getQualifiedName()); continue; } } } } } } } // // Case Types private List<String> getCaseTypesFromAnnotations(AnnotatedMirror symbol) { return getAnnotationArrayValue(symbol, CEYLON_CASE_TYPES_ANNOTATION); } private String getSelfTypeFromAnnotations(AnnotatedMirror symbol) { return getAnnotationStringValue(symbol, CEYLON_CASE_TYPES_ANNOTATION, "of"); } private void setCaseTypes(ClassOrInterface klass, ClassMirror classMirror) { if (classMirror.isEnum()) { ArrayList<Type> caseTypes = new ArrayList<Type>(); for (Declaration member : klass.getMembers()) { if (member instanceof FieldValue && ((FieldValue) member).isEnumValue()) { caseTypes.add(((FieldValue)member).getType()); } } klass.setCaseTypes(caseTypes); } else { String selfType = getSelfTypeFromAnnotations(classMirror); Module moduleScope = ModelUtil.getModuleContainer(klass); if(selfType != null && !selfType.isEmpty()){ Type type = decodeType(selfType, klass, moduleScope, "self type"); if(!type.isTypeParameter()){ logError("Invalid type signature for self type of "+klass.getQualifiedNameString()+": "+selfType+" is not a type parameter"); }else{ klass.setSelfType(type); List<Type> caseTypes = new LinkedList<Type>(); caseTypes.add(type); klass.setCaseTypes(caseTypes); } } else { List<String> caseTypes = getCaseTypesFromAnnotations(classMirror); if(caseTypes != null && !caseTypes.isEmpty()){ klass.setCaseTypes(getTypesList(caseTypes, klass, moduleScope, "case types", klass.getQualifiedNameString())); } } } } private List<Type> getTypesList(List<String> caseTypes, Scope scope, Module moduleScope, String targetType, String targetName) { List<Type> producedTypes = new LinkedList<Type>(); for(String type : caseTypes){ producedTypes.add(decodeType(type, scope, moduleScope, targetType)); } return producedTypes; } // // Type parameters loading @SuppressWarnings("unchecked") private List<AnnotationMirror> getTypeParametersFromAnnotations(AnnotatedMirror symbol) { return (List<AnnotationMirror>) getAnnotationValue(symbol, CEYLON_TYPE_PARAMETERS); } // from our annotation private void setTypeParametersFromAnnotations(Scope scope, List<TypeParameter> params, AnnotatedMirror mirror, List<AnnotationMirror> typeParameterAnnotations, List<TypeParameterMirror> typeParameterMirrors) { // We must first add every type param, before we resolve the bounds, which can // refer to type params. String selfTypeName = getSelfTypeFromAnnotations(mirror); int i=0; for(AnnotationMirror typeParamAnnotation : typeParameterAnnotations){ TypeParameter param = new TypeParameter(); param.setUnit(((Element)scope).getUnit()); param.setContainer(scope); param.setScope(scope); ModelUtil.setVisibleScope(param); param.setDeclaration((Declaration) scope); // let's not trigger the lazy-loading if we're completing a LazyClass/LazyInterface if(scope instanceof LazyContainer) ((LazyContainer)scope).addMember(param); else // must be a method scope.addMember(param); param.setName((String)typeParamAnnotation.getValue("value")); param.setExtendedType(typeFactory.getAnythingType()); if(i < typeParameterMirrors.size()){ TypeParameterMirror typeParameterMirror = typeParameterMirrors.get(i); param.setNonErasedBounds(hasNonErasedBounds(typeParameterMirror)); } String varianceName = (String) typeParamAnnotation.getValue("variance"); if(varianceName != null){ if(varianceName.equals("IN")){ param.setContravariant(true); }else if(varianceName.equals("OUT")) param.setCovariant(true); } // If this is a self type param then link it to its type's declaration if (param.getName().equals(selfTypeName)) { param.setSelfTypedDeclaration((TypeDeclaration)scope); } params.add(param); i++; } Module moduleScope = ModelUtil.getModuleContainer(scope); // Now all type params have been set, we can resolve the references parts Iterator<TypeParameter> paramsIterator = params.iterator(); for(AnnotationMirror typeParamAnnotation : typeParameterAnnotations){ TypeParameter param = paramsIterator.next(); @SuppressWarnings("unchecked") List<String> satisfiesAttribute = (List<String>)typeParamAnnotation.getValue("satisfies"); setListOfTypes(param.getSatisfiedTypes(), satisfiesAttribute, scope, moduleScope, "type parameter '"+param.getName()+"' satisfied types"); @SuppressWarnings("unchecked") List<String> caseTypesAttribute = (List<String>)typeParamAnnotation.getValue("caseTypes"); if(caseTypesAttribute != null && !caseTypesAttribute.isEmpty()) param.setCaseTypes(new LinkedList<Type>()); setListOfTypes(param.getCaseTypes(), caseTypesAttribute, scope, moduleScope, "type parameter '"+param.getName()+"' case types"); String defaultValueAttribute = (String)typeParamAnnotation.getValue("defaultValue"); if(defaultValueAttribute != null && !defaultValueAttribute.isEmpty()){ Type decodedType = decodeType(defaultValueAttribute, scope, moduleScope, "type parameter '"+param.getName()+"' defaultValue"); param.setDefaultTypeArgument(decodedType); param.setDefaulted(true); } } } private boolean hasNonErasedBounds(TypeParameterMirror typeParameterMirror) { List<TypeMirror> bounds = typeParameterMirror.getBounds(); // if we have at least one bound and not a single Object one return bounds.size() > 0 && (bounds.size() != 1 || !sameType(bounds.get(0), OBJECT_TYPE)); } private void setListOfTypes(List<Type> destinationTypeList, List<String> serialisedTypes, Scope scope, Module moduleScope, String targetType) { if(serialisedTypes != null){ for (String serialisedType : serialisedTypes) { Type decodedType = decodeType(serialisedType, scope, moduleScope, targetType); destinationTypeList.add(decodedType); } } } // from java type info private void setTypeParameters(Scope scope, List<TypeParameter> params, List<TypeParameterMirror> typeParameters, boolean isCeylon) { // We must first add every type param, before we resolve the bounds, which can // refer to type params. for(TypeParameterMirror typeParam : typeParameters){ TypeParameter param = new TypeParameter(); param.setUnit(((Element)scope).getUnit()); param.setContainer(scope); param.setScope(scope); ModelUtil.setVisibleScope(param); param.setDeclaration((Declaration) scope); // let's not trigger the lazy-loading if we're completing a LazyClass/LazyInterface if(scope instanceof LazyContainer) ((LazyContainer)scope).addMember(param); else // must be a method scope.addMember(param); param.setName(typeParam.getName()); param.setExtendedType(typeFactory.getAnythingType()); params.add(param); } boolean needsObjectBounds = !isCeylon && scope instanceof Function; // Now all type params have been set, we can resolve the references parts Iterator<TypeParameter> paramsIterator = params.iterator(); for(TypeParameterMirror typeParam : typeParameters){ TypeParameter param = paramsIterator.next(); List<TypeMirror> bounds = typeParam.getBounds(); for(TypeMirror bound : bounds){ Type boundType; // we turn java's default upper bound java.lang.Object into ceylon.language.Object if(sameType(bound, OBJECT_TYPE)){ // avoid adding java's default upper bound if it's just there with no meaning, // especially since we do not want it for types if(bounds.size() == 1) break; boundType = getNonPrimitiveType(getLanguageModule(), CEYLON_OBJECT_TYPE, scope, VarianceLocation.INVARIANT); }else boundType = getNonPrimitiveType(ModelUtil.getModuleContainer(scope), bound, scope, VarianceLocation.INVARIANT); param.getSatisfiedTypes().add(boundType); } if(needsObjectBounds && param.getSatisfiedTypes().isEmpty()){ Type boundType = getNonPrimitiveType(getLanguageModule(), CEYLON_OBJECT_TYPE, scope, VarianceLocation.INVARIANT); param.getSatisfiedTypes().add(boundType); } } } // method private void setTypeParameters(Function method, MethodMirror methodMirror, boolean isCeylon) { List<TypeParameter> params = new LinkedList<TypeParameter>(); method.setTypeParameters(params); List<AnnotationMirror> typeParameters = getTypeParametersFromAnnotations(methodMirror); if(typeParameters != null) { setTypeParametersFromAnnotations(method, params, methodMirror, typeParameters, methodMirror.getTypeParameters()); } else { setTypeParameters(method, params, methodMirror.getTypeParameters(), isCeylon); } } // class private void setTypeParameters(TypeDeclaration klass, ClassMirror classMirror, boolean isCeylon) { List<AnnotationMirror> typeParameters = getTypeParametersFromAnnotations(classMirror); List<TypeParameterMirror> mirrorTypeParameters = classMirror.getTypeParameters(); if(typeParameters != null) { if(typeParameters.isEmpty()) return; List<TypeParameter> params = new ArrayList<TypeParameter>(typeParameters.size()); klass.setTypeParameters(params); setTypeParametersFromAnnotations(klass, params, classMirror, typeParameters, mirrorTypeParameters); } else { if(mirrorTypeParameters.isEmpty()) return; List<TypeParameter> params = new ArrayList<TypeParameter>(mirrorTypeParameters.size()); klass.setTypeParameters(params); setTypeParameters(klass, params, mirrorTypeParameters, isCeylon); } } // // TypeParsing and ModelLoader private Type decodeType(String value, Scope scope, Module moduleScope, String targetType) { return decodeType(value, scope, moduleScope, targetType, null); } private Type decodeType(String value, Scope scope, Module moduleScope, String targetType, Declaration target) { try{ return typeParser.decodeType(value, scope, moduleScope, getUnitForModule(moduleScope)); }catch(TypeParserException x){ String text = formatTypeErrorMessage("Error while parsing type of", targetType, target, scope); return logModelResolutionException(x.getMessage(), scope, text); }catch(ModelResolutionException x){ String text = formatTypeErrorMessage("Error while resolving type of", targetType, target, scope); return logModelResolutionException(x, scope, text); } } private Unit getUnitForModule(Module module) { List<Package> packages = module.getPackages(); if(packages.isEmpty()){ System.err.println("No package for module "+module.getNameAsString()); return null; } Package pkg = packages.get(0); if(pkg instanceof LazyPackage == false){ System.err.println("No lazy package for module "+module.getNameAsString()); return null; } Unit unit = getCompiledUnit((LazyPackage) pkg, null); if(unit == null){ System.err.println("No unit for module "+module.getNameAsString()); return null; } return unit; } private String formatTypeErrorMessage(String prefix, String targetType, Declaration target, Scope scope) { String forTarget; if(target != null) forTarget = " for "+target.getQualifiedNameString(); else if(scope != null) forTarget = " for "+scope.getQualifiedNameString(); else forTarget = ""; return prefix+" "+targetType+forTarget; } /** Warning: only valid for toplevel types, not for type parameters */ private Type obtainType(TypeMirror type, AnnotatedMirror symbol, Scope scope, Module moduleScope, VarianceLocation variance, String targetType, Declaration target) { String typeName = getAnnotationStringValue(symbol, CEYLON_TYPE_INFO_ANNOTATION); if (typeName != null) { Type ret = decodeType(typeName, scope, moduleScope, targetType, target); // even decoded types need to fit with the reality of the underlying type ret.setUnderlyingType(getUnderlyingType(type, TypeLocation.TOPLEVEL)); return ret; } else { try{ return obtainType(moduleScope, type, scope, TypeLocation.TOPLEVEL, variance); }catch(ModelResolutionException x){ String text = formatTypeErrorMessage("Error while resolving type of", targetType, target, scope); return logModelResolutionException(x, scope, text); } } } private enum TypeLocation { TOPLEVEL, TYPE_PARAM; } private enum VarianceLocation { /** * Used in parameter */ CONTRAVARIANT, /** * Used in method return value */ COVARIANT, /** * For field */ INVARIANT; } private String getUnderlyingType(TypeMirror type, TypeLocation location){ // don't erase to c.l.String if in a type param location if ((sameType(type, STRING_TYPE) && location != TypeLocation.TYPE_PARAM) || sameType(type, PRIM_BYTE_TYPE) || sameType(type, PRIM_SHORT_TYPE) || sameType(type, PRIM_INT_TYPE) || sameType(type, PRIM_FLOAT_TYPE) || sameType(type, PRIM_CHAR_TYPE)) { return type.getQualifiedName(); } return null; } public Type obtainType(Module moduleScope, TypeMirror type, Scope scope, TypeLocation location, VarianceLocation variance) { TypeMirror originalType = type; // ERASURE type = applyTypeMapping(type, location); Type ret = getNonPrimitiveType(moduleScope, type, scope, variance); if (ret.getUnderlyingType() == null) { ret.setUnderlyingType(getUnderlyingType(originalType, location)); } return ret; } private TypeMirror applyTypeMapping(TypeMirror type, TypeLocation location) { // don't erase to c.l.String if in a type param location if (sameType(type, STRING_TYPE) && location != TypeLocation.TYPE_PARAM) { return CEYLON_STRING_TYPE; } else if (sameType(type, PRIM_BOOLEAN_TYPE)) { return CEYLON_BOOLEAN_TYPE; } else if (sameType(type, PRIM_BYTE_TYPE)) { return CEYLON_BYTE_TYPE; } else if (sameType(type, PRIM_SHORT_TYPE)) { return CEYLON_INTEGER_TYPE; } else if (sameType(type, PRIM_INT_TYPE)) { return CEYLON_INTEGER_TYPE; } else if (sameType(type, PRIM_LONG_TYPE)) { return CEYLON_INTEGER_TYPE; } else if (sameType(type, PRIM_FLOAT_TYPE)) { return CEYLON_FLOAT_TYPE; } else if (sameType(type, PRIM_DOUBLE_TYPE)) { return CEYLON_FLOAT_TYPE; } else if (sameType(type, PRIM_CHAR_TYPE)) { return CEYLON_CHARACTER_TYPE; } else if (sameType(type, OBJECT_TYPE)) { return CEYLON_OBJECT_TYPE; } else if (sameType(type, THROWABLE_TYPE)) { return CEYLON_THROWABLE_TYPE; } else if (sameType(type, EXCEPTION_TYPE)) { return CEYLON_EXCEPTION_TYPE; } else if (sameType(type, ANNOTATION_TYPE)) { // here we prefer Annotation over ConstrainedAnnotation but that's fine return CEYLON_ANNOTATION_TYPE; } else if (type.getKind() == TypeKind.ARRAY) { TypeMirror ct = type.getComponentType(); if (sameType(ct, PRIM_BOOLEAN_TYPE)) { return JAVA_BOOLEAN_ARRAY_TYPE; } else if (sameType(ct, PRIM_BYTE_TYPE)) { return JAVA_BYTE_ARRAY_TYPE; } else if (sameType(ct, PRIM_SHORT_TYPE)) { return JAVA_SHORT_ARRAY_TYPE; } else if (sameType(ct, PRIM_INT_TYPE)) { return JAVA_INT_ARRAY_TYPE; } else if (sameType(ct, PRIM_LONG_TYPE)) { return JAVA_LONG_ARRAY_TYPE; } else if (sameType(ct, PRIM_FLOAT_TYPE)) { return JAVA_FLOAT_ARRAY_TYPE; } else if (sameType(ct, PRIM_DOUBLE_TYPE)) { return JAVA_DOUBLE_ARRAY_TYPE; } else if (sameType(ct, PRIM_CHAR_TYPE)) { return JAVA_CHAR_ARRAY_TYPE; } else { // object array return new SimpleReflType(JAVA_LANG_OBJECT_ARRAY, SimpleReflType.Module.JDK, TypeKind.DECLARED, ct); } } return type; } private boolean sameType(TypeMirror t1, TypeMirror t2) { // make sure we deal with arrays which can't have a qualified name if(t1.getKind() == TypeKind.ARRAY){ if(t2.getKind() != TypeKind.ARRAY) return false; return sameType(t1.getComponentType(), t2.getComponentType()); } if(t2.getKind() == TypeKind.ARRAY) return false; // the rest should be OK return t1.getQualifiedName().equals(t2.getQualifiedName()); } @Override public Declaration getDeclaration(Module module, String typeName, DeclarationType declarationType) { return convertToDeclaration(module, typeName, declarationType); } private Type getNonPrimitiveType(Module moduleScope, TypeMirror type, Scope scope, VarianceLocation variance) { TypeDeclaration declaration = (TypeDeclaration) convertNonPrimitiveTypeToDeclaration(moduleScope, type, scope, DeclarationType.TYPE); if(declaration == null){ throw new ModelResolutionException("Failed to find declaration for "+type.getQualifiedName()); } return applyTypeArguments(moduleScope, declaration, type, scope, variance, TypeMappingMode.NORMAL, null); } private enum TypeMappingMode { NORMAL, GENERATOR } @SuppressWarnings("serial") private static class RecursiveTypeParameterBoundException extends RuntimeException {} private Type applyTypeArguments(Module moduleScope, TypeDeclaration declaration, TypeMirror type, Scope scope, VarianceLocation variance, TypeMappingMode mode, Set<TypeDeclaration> rawDeclarationsSeen) { List<TypeMirror> javacTypeArguments = type.getTypeArguments(); boolean hasTypeParameters = !declaration.getTypeParameters().isEmpty(); boolean hasTypeArguments = !javacTypeArguments.isEmpty(); boolean isRaw = !hasTypeArguments && hasTypeParameters; // if we have type arguments or type parameters (raw) if(hasTypeArguments || isRaw){ // if it's raw we will need the map anyways if(rawDeclarationsSeen == null) rawDeclarationsSeen = new HashSet<TypeDeclaration>(); // detect recursive bounds that we can't possibly satisfy, such as Foo<T extends Foo<T>> if(rawDeclarationsSeen != null && !rawDeclarationsSeen.add(declaration)) throw new RecursiveTypeParameterBoundException(); try{ List<Type> typeArguments = new ArrayList<Type>(javacTypeArguments.size()); List<TypeParameter> typeParameters = declaration.getTypeParameters(); List<TypeParameterMirror> typeParameterMirrors = null; // SimpleReflType for Object and friends don't have a type, but don't need one if(type.getDeclaredClass() != null) typeParameterMirrors = type.getDeclaredClass().getTypeParameters(); Map<TypeParameter,SiteVariance> siteVarianceMap = null; int len = hasTypeArguments ? javacTypeArguments.size() : typeParameters.size(); for(int i=0 ; i<len ; i++){ TypeParameter typeParameter = null; if(i < typeParameters.size()) typeParameter = typeParameters.get(i); Type producedTypeArgument = null; // do we have a type argument? TypeMirror typeArgument = null; SiteVariance siteVariance = null; if(hasTypeArguments){ typeArgument = javacTypeArguments.get(i); // if a single type argument is a wildcard and we are in a covariant location, we erase to Object if(typeArgument.getKind() == TypeKind.WILDCARD){ TypeMirror bound = typeArgument.getUpperBound(); if(bound != null){ siteVariance = SiteVariance.OUT; } else { bound = typeArgument.getLowerBound(); if(bound != null){ // it has a lower bound siteVariance = SiteVariance.IN; } } // use the bound in any case typeArgument = bound; } } // if we have no type argument, or if it's a wildcard with no bound, use the type parameter bounds if we can if(typeArgument == null && typeParameterMirrors != null && i < typeParameterMirrors.size()){ TypeParameterMirror typeParameterMirror = typeParameterMirrors.get(i); // FIXME: multiple bounds? if(typeParameterMirror.getBounds().size() == 1){ // make sure we don't go overboard if(rawDeclarationsSeen == null){ rawDeclarationsSeen = new HashSet<TypeDeclaration>(); // detect recursive bounds that we can't possibly satisfy, such as Foo<T extends Foo<T>> if(!rawDeclarationsSeen.add(declaration)) throw new RecursiveTypeParameterBoundException(); } TypeMirror bound = typeParameterMirror.getBounds().get(0); try{ producedTypeArgument = obtainTypeParameterBound(moduleScope, bound, declaration, rawDeclarationsSeen); siteVariance = SiteVariance.OUT; }catch(RecursiveTypeParameterBoundException x){ // damnit, go for Object later } } } // if we have no type argument, or it was a wildcard with no bounds and we could not use the type parameter bounds, // let's fall back to "out Object" if(typeArgument == null && producedTypeArgument == null){ producedTypeArgument = typeFactory.getObjectType(); siteVariance = SiteVariance.OUT; } // record use-site variance if required if(!JvmBackendUtil.isCeylon(declaration) && siteVariance != null){ // lazy alloc if(siteVarianceMap == null) siteVarianceMap = new HashMap<TypeParameter,SiteVariance>(); siteVarianceMap.put(typeParameter, siteVariance); } // in some cases we may already have a produced type argument we can use. if not let's fetch it if(producedTypeArgument == null){ if(mode == TypeMappingMode.NORMAL) producedTypeArgument = obtainType(moduleScope, typeArgument, scope, TypeLocation.TYPE_PARAM, variance); else producedTypeArgument = obtainTypeParameterBound(moduleScope, typeArgument, scope, rawDeclarationsSeen); } typeArguments.add(producedTypeArgument); } Type qualifyingType = null; if(type.getQualifyingType() != null){ qualifyingType = getNonPrimitiveType(moduleScope, type.getQualifyingType(), scope, variance); } Type ret = declaration.appliedType(qualifyingType, typeArguments); if(siteVarianceMap != null){ ret.setVarianceOverrides(siteVarianceMap); } ret.setUnderlyingType(type.getQualifiedName()); ret.setRaw(isRaw); return ret; }finally{ if(rawDeclarationsSeen != null) rawDeclarationsSeen.remove(declaration); } } // we have no type args, but perhaps we have a qualifying type which has some? if(type.getQualifyingType() != null){ // that one may have type arguments Type qualifyingType = getNonPrimitiveType(moduleScope, type.getQualifyingType(), scope, variance); Type ret = declaration.appliedType(qualifyingType, Collections.<Type>emptyList()); ret.setUnderlyingType(type.getQualifiedName()); ret.setRaw(isRaw); return ret; } // no type arg and no qualifying type return declaration.getType(); } private Type obtainTypeParameterBound(Module moduleScope, TypeMirror type, Scope scope, Set<TypeDeclaration> rawDeclarationsSeen) { // type variables are never mapped if(type.getKind() == TypeKind.TYPEVAR){ TypeParameterMirror typeParameter = type.getTypeParameter(); if(!typeParameter.getBounds().isEmpty()){ List<Type> bounds = new ArrayList<Type>(typeParameter.getBounds().size()); for(TypeMirror bound : typeParameter.getBounds()){ Type boundModel = obtainTypeParameterBound(moduleScope, bound, scope, rawDeclarationsSeen); bounds.add(boundModel); } return intersection(bounds, getUnitForModule(moduleScope)); }else // no bound is Object return typeFactory.getObjectType(); }else{ TypeMirror mappedType = applyTypeMapping(type, TypeLocation.TYPE_PARAM); TypeDeclaration declaration = (TypeDeclaration) convertNonPrimitiveTypeToDeclaration(moduleScope, mappedType, scope, DeclarationType.TYPE); if(declaration == null){ throw new RuntimeException("Failed to find declaration for "+type); } if(declaration instanceof UnknownType) return declaration.getType(); Type ret = applyTypeArguments(moduleScope, declaration, type, scope, VarianceLocation.CONTRAVARIANT, TypeMappingMode.GENERATOR, rawDeclarationsSeen); if (ret.getUnderlyingType() == null) { ret.setUnderlyingType(getUnderlyingType(type, TypeLocation.TYPE_PARAM)); } return ret; } } /*private Type getQualifyingType(TypeDeclaration declaration) { // As taken from Type.getType(): if (declaration.isMember()) { return((ClassOrInterface) declaration.getContainer()).getType(); } return null; }*/ @Override public Type getType(Module module, String pkgName, String name, Scope scope) { Declaration decl = getDeclaration(module, pkgName, name, scope); if(decl == null) return null; if(decl instanceof TypeDeclaration) return ((TypeDeclaration) decl).getType(); // it's a method or non-object value, but it's not a type return null; } @Override public Declaration getDeclaration(Module module, String pkgName, String name, Scope scope) { synchronized(getLock()){ if(scope != null){ TypeParameter typeParameter = lookupTypeParameter(scope, name); if(typeParameter != null) return typeParameter; } if(!isBootstrap || !name.startsWith(CEYLON_LANGUAGE)) { if(scope != null && pkgName != null){ Package containingPackage = ModelUtil.getPackageContainer(scope); Package pkg = containingPackage.getModule().getPackage(pkgName); String relativeName = null; String unquotedName = name.replace("$", ""); if(!pkgName.isEmpty()){ if(unquotedName.startsWith(pkgName+".")) relativeName = unquotedName.substring(pkgName.length()+1); // else we don't try it's not in this package }else relativeName = unquotedName; if(relativeName != null && pkg != null){ Declaration declaration = pkg.getDirectMember(relativeName, null, false); // if we get a value, we want its type if(JvmBackendUtil.isValue(declaration) && ((Value)declaration).getTypeDeclaration().getName().equals(relativeName)) declaration = ((Value)declaration).getTypeDeclaration(); if(declaration != null) return declaration; } } return convertToDeclaration(module, name, DeclarationType.TYPE); } return findLanguageModuleDeclarationForBootstrap(name); } } private Declaration findLanguageModuleDeclarationForBootstrap(String name) { // make sure we don't return anything for ceylon.language if(name.equals(CEYLON_LANGUAGE)) return null; // we're bootstrapping ceylon.language so we need to return the ProducedTypes straight from the model we're compiling Module languageModule = modules.getLanguageModule(); int lastDot = name.lastIndexOf("."); if(lastDot == -1) return null; String pkgName = name.substring(0, lastDot); String simpleName = name.substring(lastDot+1); // Nothing is a special case with no real decl if(name.equals("ceylon.language.Nothing")) return typeFactory.getNothingDeclaration(); // find the right package Package pkg = languageModule.getDirectPackage(pkgName); if(pkg != null){ Declaration member = pkg.getDirectMember(simpleName, null, false); // if we get a value, we want its type if(JvmBackendUtil.isValue(member) && ((Value)member).getTypeDeclaration().getName().equals(simpleName)){ member = ((Value)member).getTypeDeclaration(); } if(member != null) return member; } throw new ModelResolutionException("Failed to look up given type in language module while bootstrapping: "+name); } public ClassMirror[] getClassMirrorsToRemove(com.redhat.ceylon.model.typechecker.model.Declaration declaration) { if(declaration instanceof LazyClass){ return new ClassMirror[] { ((LazyClass) declaration).classMirror }; } if(declaration instanceof LazyInterface){ LazyInterface lazyInterface = (LazyInterface) declaration; if (lazyInterface.companionClass != null) { return new ClassMirror[] { lazyInterface.classMirror, lazyInterface.companionClass }; } else { return new ClassMirror[] { lazyInterface.classMirror }; } } if(declaration instanceof LazyFunction){ return new ClassMirror[] { ((LazyFunction) declaration).classMirror }; } if(declaration instanceof LazyValue){ return new ClassMirror[] { ((LazyValue) declaration).classMirror }; } if (declaration instanceof LazyClassAlias) { return new ClassMirror[] { ((LazyClassAlias) declaration).classMirror }; } if (declaration instanceof LazyInterfaceAlias) { return new ClassMirror[] { ((LazyInterfaceAlias) declaration).classMirror }; } if (declaration instanceof LazyTypeAlias) { return new ClassMirror[] { ((LazyTypeAlias) declaration).classMirror }; } return new ClassMirror[0]; } public void removeDeclarations(List<Declaration> declarations) { synchronized(getLock()){ Set<String> qualifiedNames = new HashSet<>(declarations.size() * 2); // keep in sync with getOrCreateDeclaration for (Declaration decl : declarations) { try { ClassMirror[] classMirrors = getClassMirrorsToRemove(decl); if (classMirrors == null || classMirrors.length == 0) { continue; } Map<String, Declaration> firstCache = null; Map<String, Declaration> secondCache = null; // String firstCacheName = null; // String secondCacheName = null; if(decl.isToplevel()){ if(JvmBackendUtil.isValue(decl)){ firstCache = valueDeclarationsByName; // firstCacheName = "value declarations cache"; TypeDeclaration typeDeclaration = ((Value)decl).getTypeDeclaration(); if (typeDeclaration != null) { if(typeDeclaration.isAnonymous()) { secondCache = typeDeclarationsByName; // secondCacheName = "type declarations cache"; } } else { // The value declaration has probably not been fully loaded yet. // => still try to clean the second cache also, just in case it is an anonymous object secondCache = typeDeclarationsByName; // secondCacheName = "type declarations cache"; } }else if(JvmBackendUtil.isMethod(decl)) { firstCache = valueDeclarationsByName; // firstCacheName = "value declarations cache"; } } if(decl instanceof ClassOrInterface){ firstCache = typeDeclarationsByName; // firstCacheName = "type declarations cache"; } Module module = ModelUtil.getModuleContainer(decl.getContainer()); // ignore declarations which we do not cache, like member method/attributes for (ClassMirror classMirror : classMirrors) { qualifiedNames.add(classMirror.getQualifiedName()); String key = classMirror.getCacheKey(module); // String notRemovedMessageFromFirstCache = "No non-null declaration removed from the " + firstCacheName + " for key :" + key; // String notRemovedMessageFromSecondCache = "No non-null declaration removed from the " + secondCacheName + " for key :" + key; if(firstCache != null) { if (firstCache.remove(key) == null) { // System.out.println(notRemovedMessageFromFirstCache); } if(secondCache != null) { if (secondCache.remove(key) == null) { // System.out.println(notRemovedMessageFromSecondCache); } } } } } catch(Exception e) { e.printStackTrace(); } } List<String> keysToRemove = new ArrayList<>(qualifiedNames.size()); for (Map.Entry<String, ClassMirror> entry : classMirrorCache.entrySet()) { ClassMirror mirror = entry.getValue(); if (mirror == null || qualifiedNames.contains(mirror.getQualifiedName())) { keysToRemove.add(entry.getKey()); } } for (String keyToRemove : keysToRemove) { classMirrorCache.remove(keyToRemove); } } } private static class Stats{ int loaded, total; } private int inspectForStats(Map<String,Declaration> cache, Map<Package, Stats> loadedByPackage){ int loaded = 0; for(Declaration decl : cache.values()){ if(decl instanceof LazyElement){ Package pkg = getPackage(decl); if(pkg == null){ logVerbose("[Model loader stats: declaration "+decl.getName()+" has no package. Skipping.]"); continue; } Stats stats = loadedByPackage.get(pkg); if(stats == null){ stats = new Stats(); loadedByPackage.put(pkg, stats); } stats.total++; if(((LazyElement)decl).isLoaded()){ loaded++; stats.loaded++; } } } return loaded; } public void printStats() { synchronized(getLock()){ Map<Package, Stats> loadedByPackage = new HashMap<Package, Stats>(); int loaded = inspectForStats(typeDeclarationsByName, loadedByPackage) + inspectForStats(valueDeclarationsByName, loadedByPackage); logVerbose("[Model loader: "+loaded+"(loaded)/"+(typeDeclarationsByName.size()+valueDeclarationsByName.size())+"(total) declarations]"); for(Entry<Package, Stats> packageEntry : loadedByPackage.entrySet()){ logVerbose("[ Package "+packageEntry.getKey().getNameAsString()+": " +packageEntry.getValue().loaded+"(loaded)/"+packageEntry.getValue().total+"(total) declarations]"); } } } private static Package getPackage(Object decl) { if(decl == null) return null; if(decl instanceof Package) return (Package) decl; return getPackage(((Declaration)decl).getContainer()); } protected void logMissingOracleType(String type) { logVerbose("Hopefully harmless completion failure in model loader: "+type +". This is most likely when the JDK depends on Oracle private classes that we can't find." +" As a result some model information will be incomplete."); } public void setupSourceFileObjects(List<?> treeHolders) { } public static boolean isJDKModule(String name) { return JDKUtils.isJDKModule(name) || JDKUtils.isOracleJDKModule(name); } @Override public Module getLoadedModule(String moduleName, String version) { return findModule(moduleName, version); } public Module getLanguageModule() { return modules.getLanguageModule(); } public Module findModule(String name, String version){ return moduleManager.findLoadedModule(name, version); } public Module getJDKBaseModule() { return findModule(JAVA_BASE_MODULE_NAME, JDKUtils.jdk.version); } public Module findModuleForFile(File file){ File path = file.getParentFile(); while (path != null) { String name = path.getPath().replaceAll("[\\\\/]", "."); // FIXME: this would load any version of this module Module m = getLoadedModule(name, null); if (m != null) { return m; } path = path.getParentFile(); } return modules.getDefaultModule(); } public abstract Module findModuleForClassMirror(ClassMirror classMirror); protected boolean isTypeHidden(Module module, String qualifiedName){ return module.getNameAsString().equals(JAVA_BASE_MODULE_NAME) && qualifiedName.equals("java.lang.Object"); } public Package findPackage(String quotedPkgName) { synchronized(getLock()){ String pkgName = quotedPkgName.replace("$", ""); // in theory we only have one package with the same name per module in javac for(Package pkg : packagesByName.values()){ if(pkg.getNameAsString().equals(pkgName)) return pkg; } return null; } } /** * See explanation in cacheModulelessPackages() below. This is called by LanguageCompiler during loadCompiledModules(). */ public LazyPackage findOrCreateModulelessPackage(String pkgName) { synchronized(getLock()){ LazyPackage pkg = modulelessPackages.get(pkgName); if(pkg != null) return pkg; pkg = new LazyPackage(this); // FIXME: some refactoring needed pkg.setName(pkgName == null ? Collections.<String>emptyList() : Arrays.asList(pkgName.split("\\."))); modulelessPackages.put(pkgName, pkg); return pkg; } } /** * Stef: this sucks balls, but the typechecker wants Packages created before we have any Module set up, including for parsing a module * file, and because the model loader looks up packages and caches them using their modules, we can't really have packages before we * have modules. Rather than rewrite the typechecker, we create moduleless packages during parsing, which means they are not cached with * their modules, and after the loadCompiledModules step above, we fix the package modules. Remains to be done is to move the packages * created from their cache to the right per-module cache. */ public void cacheModulelessPackages() { synchronized(getLock()){ for(LazyPackage pkg : modulelessPackages.values()){ String quotedPkgName = JVMModuleUtil.quoteJavaKeywords(pkg.getQualifiedNameString()); if (pkg.getModule() != null) { packagesByName.put(cacheKeyByModule(pkg.getModule(), quotedPkgName), pkg); } } modulelessPackages.clear(); } } /** * Stef: after a lot of attempting, I failed to make the CompilerModuleManager produce a LazyPackage when the ModuleManager.initCoreModules * is called for the default package. Because it is called by the PhasedUnits constructor, which is called by the ModelLoader constructor, * which means the model loader is not yet in the context, so the CompilerModuleManager can't obtain it to pass it to the LazyPackage * constructor. A rewrite of the logic of the typechecker scanning would fix this, but at this point it's just faster to let it create * the wrong default package and fix it before we start parsing anything. */ public void fixDefaultPackage() { synchronized(getLock()){ Module defaultModule = modules.getDefaultModule(); Package defaultPackage = defaultModule.getDirectPackage(""); if(defaultPackage instanceof LazyPackage == false){ LazyPackage newPkg = findOrCreateModulelessPackage(""); List<Package> defaultModulePackages = defaultModule.getPackages(); if(defaultModulePackages.size() != 1) throw new RuntimeException("Assertion failed: default module has more than the default package: "+defaultModulePackages.size()); defaultModulePackages.clear(); defaultModulePackages.add(newPkg); newPkg.setModule(defaultModule); defaultPackage.setModule(null); } } } public boolean isImported(Module moduleScope, Module importedModule) { if(ModelUtil.equalModules(moduleScope, importedModule)) return true; if(isImportedSpecialRules(moduleScope, importedModule)) return true; boolean isMaven = isAutoExportMavenDependencies() && isMavenModule(moduleScope); if(isMaven && isMavenModule(importedModule)) return true; Set<Module> visited = new HashSet<Module>(); visited.add(moduleScope); for(ModuleImport imp : moduleScope.getImports()){ if(ModelUtil.equalModules(imp.getModule(), importedModule)) return true; if((imp.isExport() || isMaven) && isImportedTransitively(imp.getModule(), importedModule, visited)) return true; } return false; } private boolean isMavenModule(Module moduleScope) { return moduleScope.isJava() && ModuleUtil.isMavenModule(moduleScope.getNameAsString()); } private boolean isImportedSpecialRules(Module moduleScope, Module importedModule) { String importedModuleName = importedModule.getNameAsString(); // every Java module imports the JDK // ceylon.language imports the JDK if((moduleScope.isJava() || ModelUtil.equalModules(moduleScope, getLanguageModule())) && (JDKUtils.isJDKModule(importedModuleName) || JDKUtils.isOracleJDKModule(importedModuleName))) return true; // everyone imports the language module if(ModelUtil.equalModules(importedModule, getLanguageModule())) return true; if(ModelUtil.equalModules(moduleScope, getLanguageModule())){ // this really sucks, I suppose we should set that up better somewhere else if((importedModuleName.equals("com.redhat.ceylon.compiler.java") || importedModuleName.equals("com.redhat.ceylon.typechecker") || importedModuleName.equals("com.redhat.ceylon.common") || importedModuleName.equals("com.redhat.ceylon.model") || importedModuleName.equals("com.redhat.ceylon.module-resolver")) && importedModule.getVersion().equals(Versions.CEYLON_VERSION_NUMBER)) return true; if(importedModuleName.equals("org.jboss.modules") && importedModule.getVersion().equals("1.3.3.Final")) return true; } return false; } private boolean isImportedTransitively(Module moduleScope, Module importedModule, Set<Module> visited) { if(!visited.add(moduleScope)) return false; boolean isMaven = isAutoExportMavenDependencies() && isMavenModule(moduleScope); for(ModuleImport imp : moduleScope.getImports()){ // only consider exported transitive deps if(!imp.isExport() && !isMaven) continue; if(ModelUtil.equalModules(imp.getModule(), importedModule)) return true; if(isImportedSpecialRules(imp.getModule(), importedModule)) return true; if(isImportedTransitively(imp.getModule(), importedModule, visited)) return true; } return false; } protected boolean isModuleOrPackageDescriptorName(String name) { return name.equals(NamingBase.MODULE_DESCRIPTOR_CLASS_NAME) || name.equals(NamingBase.PACKAGE_DESCRIPTOR_CLASS_NAME); } protected void loadJavaBaseArrays(){ convertToDeclaration(getJDKBaseModule(), JAVA_LANG_OBJECT_ARRAY, DeclarationType.TYPE); convertToDeclaration(getJDKBaseModule(), JAVA_LANG_BOOLEAN_ARRAY, DeclarationType.TYPE); convertToDeclaration(getJDKBaseModule(), JAVA_LANG_BYTE_ARRAY, DeclarationType.TYPE); convertToDeclaration(getJDKBaseModule(), JAVA_LANG_SHORT_ARRAY, DeclarationType.TYPE); convertToDeclaration(getJDKBaseModule(), JAVA_LANG_INT_ARRAY, DeclarationType.TYPE); convertToDeclaration(getJDKBaseModule(), JAVA_LANG_LONG_ARRAY, DeclarationType.TYPE); convertToDeclaration(getJDKBaseModule(), JAVA_LANG_FLOAT_ARRAY, DeclarationType.TYPE); convertToDeclaration(getJDKBaseModule(), JAVA_LANG_DOUBLE_ARRAY, DeclarationType.TYPE); convertToDeclaration(getJDKBaseModule(), JAVA_LANG_CHAR_ARRAY, DeclarationType.TYPE); } /** * To be overridden by subclasses, defaults to false. */ protected boolean isAutoExportMavenDependencies(){ return false; } /** * To be overridden by subclasses, defaults to false. */ protected boolean isFlatClasspath(){ return false; } private static void setDeclarationAliases(Declaration decl, AnnotatedMirror mirror){ AnnotationMirror annot = mirror.getAnnotation(AbstractModelLoader.CEYLON_LANGUAGE_ALIASES_ANNOTATION); if (annot != null) { @SuppressWarnings("unchecked") List<String> value = (List<String>) annot.getValue("aliases"); if(value != null && !value.isEmpty()) decl.setAliases(value); } } }
src/com/redhat/ceylon/model/loader/AbstractModelLoader.java
package com.redhat.ceylon.model.loader; import static com.redhat.ceylon.model.typechecker.model.ModelUtil.intersection; import static com.redhat.ceylon.model.typechecker.model.ModelUtil.union; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import javax.lang.model.type.TypeKind; import com.redhat.ceylon.common.Backend; import com.redhat.ceylon.common.Backends; import com.redhat.ceylon.common.BooleanUtil; import com.redhat.ceylon.common.JVMModuleUtil; import com.redhat.ceylon.common.ModuleUtil; import com.redhat.ceylon.common.Versions; import com.redhat.ceylon.model.cmr.ArtifactResult; import com.redhat.ceylon.model.cmr.JDKUtils; import com.redhat.ceylon.model.loader.mirror.AccessibleMirror; import com.redhat.ceylon.model.loader.mirror.AnnotatedMirror; import com.redhat.ceylon.model.loader.mirror.AnnotationMirror; import com.redhat.ceylon.model.loader.mirror.ClassMirror; import com.redhat.ceylon.model.loader.mirror.FieldMirror; import com.redhat.ceylon.model.loader.mirror.MethodMirror; import com.redhat.ceylon.model.loader.mirror.PackageMirror; import com.redhat.ceylon.model.loader.mirror.TypeMirror; import com.redhat.ceylon.model.loader.mirror.TypeParameterMirror; import com.redhat.ceylon.model.loader.mirror.VariableMirror; import com.redhat.ceylon.model.loader.model.AnnotationProxyClass; import com.redhat.ceylon.model.loader.model.AnnotationProxyMethod; import com.redhat.ceylon.model.loader.model.FieldValue; import com.redhat.ceylon.model.loader.model.JavaBeanValue; import com.redhat.ceylon.model.loader.model.JavaMethod; import com.redhat.ceylon.model.loader.model.LazyClass; import com.redhat.ceylon.model.loader.model.LazyClassAlias; import com.redhat.ceylon.model.loader.model.LazyContainer; import com.redhat.ceylon.model.loader.model.LazyElement; import com.redhat.ceylon.model.loader.model.LazyFunction; import com.redhat.ceylon.model.loader.model.LazyInterface; import com.redhat.ceylon.model.loader.model.LazyInterfaceAlias; import com.redhat.ceylon.model.loader.model.LazyModule; import com.redhat.ceylon.model.loader.model.LazyPackage; import com.redhat.ceylon.model.loader.model.LazyTypeAlias; import com.redhat.ceylon.model.loader.model.LazyValue; import com.redhat.ceylon.model.loader.model.LocalDeclarationContainer; import com.redhat.ceylon.model.loader.model.OutputElement; import com.redhat.ceylon.model.loader.model.SetterWithLocalDeclarations; import com.redhat.ceylon.model.typechecker.model.Annotated; import com.redhat.ceylon.model.typechecker.model.Annotation; import com.redhat.ceylon.model.typechecker.model.Class; import com.redhat.ceylon.model.typechecker.model.ClassOrInterface; import com.redhat.ceylon.model.typechecker.model.Constructor; import com.redhat.ceylon.model.typechecker.model.Declaration; import com.redhat.ceylon.model.typechecker.model.DeclarationCompleter; import com.redhat.ceylon.model.typechecker.model.Element; import com.redhat.ceylon.model.typechecker.model.Function; import com.redhat.ceylon.model.typechecker.model.FunctionOrValue; import com.redhat.ceylon.model.typechecker.model.Functional; import com.redhat.ceylon.model.typechecker.model.Interface; import com.redhat.ceylon.model.typechecker.model.ModelUtil; import com.redhat.ceylon.model.typechecker.model.Module; import com.redhat.ceylon.model.typechecker.model.ModuleImport; import com.redhat.ceylon.model.typechecker.model.Modules; import com.redhat.ceylon.model.typechecker.model.Package; import com.redhat.ceylon.model.typechecker.model.Parameter; import com.redhat.ceylon.model.typechecker.model.ParameterList; import com.redhat.ceylon.model.typechecker.model.Scope; import com.redhat.ceylon.model.typechecker.model.Setter; import com.redhat.ceylon.model.typechecker.model.SiteVariance; import com.redhat.ceylon.model.typechecker.model.Type; import com.redhat.ceylon.model.typechecker.model.TypeAlias; import com.redhat.ceylon.model.typechecker.model.TypeDeclaration; import com.redhat.ceylon.model.typechecker.model.TypeParameter; import com.redhat.ceylon.model.typechecker.model.TypedDeclaration; import com.redhat.ceylon.model.typechecker.model.Unit; import com.redhat.ceylon.model.typechecker.model.UnknownType; import com.redhat.ceylon.model.typechecker.model.Value; import com.redhat.ceylon.model.typechecker.util.ModuleManager; /** * Abstract class of a model loader that can load a model from a compiled Java representation, * while being agnostic of the reflection API used to load the compiled Java representation. * * @author Stéphane Épardaud <[email protected]> */ public abstract class AbstractModelLoader implements ModelCompleter, ModelLoader, DeclarationCompleter { public static final String JAVA_BASE_MODULE_NAME = "java.base"; public static final String CEYLON_LANGUAGE = "ceylon.language"; public static final String CEYLON_LANGUAGE_MODEL = "ceylon.language.meta.model"; public static final String CEYLON_LANGUAGE_MODEL_DECLARATION = "ceylon.language.meta.declaration"; public static final String CEYLON_LANGUAGE_SERIALIZATION = "ceylon.language.serialization"; private static final String TIMER_MODEL_LOADER_CATEGORY = "model loader"; public static final String CEYLON_CEYLON_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Ceylon"; private static final String CEYLON_MODULE_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Module"; private static final String CEYLON_PACKAGE_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Package"; public static final String CEYLON_IGNORE_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Ignore"; private static final String CEYLON_CLASS_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Class"; private static final String CEYLON_JPA_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Jpa"; private static final String CEYLON_ENUMERATED_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Enumerated"; //private static final String CEYLON_CONSTRUCTOR_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Constructor"; //private static final String CEYLON_PARAMETERLIST_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.ParameterList"; public static final String CEYLON_NAME_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Name"; private static final String CEYLON_SEQUENCED_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Sequenced"; private static final String CEYLON_FUNCTIONAL_PARAMETER_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.FunctionalParameter"; private static final String CEYLON_DEFAULTED_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Defaulted"; private static final String CEYLON_SATISFIED_TYPES_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.SatisfiedTypes"; private static final String CEYLON_CASE_TYPES_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.CaseTypes"; private static final String CEYLON_TYPE_PARAMETERS = "com.redhat.ceylon.compiler.java.metadata.TypeParameters"; private static final String CEYLON_TYPE_INFO_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.TypeInfo"; public static final String CEYLON_ATTRIBUTE_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Attribute"; public static final String CEYLON_SETTER_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Setter"; public static final String CEYLON_OBJECT_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Object"; public static final String CEYLON_METHOD_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Method"; public static final String CEYLON_CONTAINER_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Container"; public static final String CEYLON_LOCAL_CONTAINER_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.LocalContainer"; public static final String CEYLON_LOCAL_DECLARATION_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.LocalDeclaration"; public static final String CEYLON_LOCAL_DECLARATIONS_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.LocalDeclarations"; private static final String CEYLON_MEMBERS_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Members"; private static final String CEYLON_ANNOTATIONS_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Annotations"; public static final String CEYLON_VALUETYPE_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.ValueType"; public static final String CEYLON_ALIAS_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Alias"; public static final String CEYLON_TYPE_ALIAS_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.TypeAlias"; public static final String CEYLON_ANNOTATION_INSTANTIATION_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.AnnotationInstantiation"; public static final String CEYLON_ANNOTATION_INSTANTIATION_ARGUMENTS_MEMBER = "arguments"; public static final String CEYLON_ANNOTATION_INSTANTIATION_ANNOTATION_MEMBER = "primary"; public static final String CEYLON_ANNOTATION_INSTANTIATION_TREE_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.AnnotationInstantiationTree"; public static final String CEYLON_STRING_VALUE_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.StringValue"; public static final String CEYLON_STRING_EXPRS_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.StringExprs"; public static final String CEYLON_BOOLEAN_VALUE_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.BooleanValue"; public static final String CEYLON_BOOLEAN_EXPRS_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.BooleanExprs"; public static final String CEYLON_INTEGER_VALUE_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.IntegerValue"; public static final String CEYLON_INTEGER_EXPRS_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.IntegerExprs"; public static final String CEYLON_CHARACTER_VALUE_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.CharacterValue"; public static final String CEYLON_CHARACTER_EXPRS_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.CharacterExprs"; public static final String CEYLON_FLOAT_VALUE_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.FloatValue"; public static final String CEYLON_FLOAT_EXPRS_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.FloatExprs"; public static final String CEYLON_OBJECT_VALUE_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.ObjectValue"; public static final String CEYLON_OBJECT_EXPRS_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.ObjectExprs"; public static final String CEYLON_DECLARATION_VALUE_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.DeclarationValue"; public static final String CEYLON_DECLARATION_EXPRS_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.DeclarationExprs"; private static final String CEYLON_TRANSIENT_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Transient"; private static final String CEYLON_DYNAMIC_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Dynamic"; private static final String JAVA_DEPRECATED_ANNOTATION = "java.lang.Deprecated"; static final String CEYLON_LANGUAGE_ABSTRACT_ANNOTATION = "ceylon.language.AbstractAnnotation$annotation$"; static final String CEYLON_LANGUAGE_ACTUAL_ANNOTATION = "ceylon.language.ActualAnnotation$annotation$"; static final String CEYLON_LANGUAGE_ANNOTATION_ANNOTATION = "ceylon.language.AnnotationAnnotation$annotation$"; static final String CEYLON_LANGUAGE_DEFAULT_ANNOTATION = "ceylon.language.DefaultAnnotation$annotation$"; static final String CEYLON_LANGUAGE_FORMAL_ANNOTATION = "ceylon.language.FormalAnnotation$annotation$"; static final String CEYLON_LANGUAGE_SHARED_ANNOTATION = "ceylon.language.SharedAnnotation$annotation$"; static final String CEYLON_LANGUAGE_LATE_ANNOTATION = "ceylon.language.LateAnnotation$annotation$"; static final String CEYLON_LANGUAGE_SEALED_ANNOTATION = "ceylon.language.SealedAnnotation$annotation$"; static final String CEYLON_LANGUAGE_VARIABLE_ANNOTATION = "ceylon.language.VariableAnnotation$annotation$"; static final String CEYLON_LANGUAGE_FINAL_ANNOTATION = "ceylon.language.FinalAnnotation$annotation$"; static final String CEYLON_LANGUAGE_NATIVE_ANNOTATION = "ceylon.language.NativeAnnotation$annotation$"; static final String CEYLON_LANGUAGE_OPTIONAL_ANNOTATION = "ceylon.language.OptionalAnnotation$annotation$"; static final String CEYLON_LANGUAGE_SERIALIZABLE_ANNOTATION = "ceylon.language.SerializableAnnotation$annotation$"; static final String CEYLON_LANGUAGE_DOC_ANNOTATION = "ceylon.language.DocAnnotation$annotation$"; static final String CEYLON_LANGUAGE_THROWS_ANNOTATIONS = "ceylon.language.ThrownExceptionAnnotation$annotations$"; static final String CEYLON_LANGUAGE_THROWS_ANNOTATION = "ceylon.language.ThrownExceptionAnnotation$annotation$"; static final String CEYLON_LANGUAGE_AUTHORS_ANNOTATION = "ceylon.language.AuthorsAnnotation$annotation$"; static final String CEYLON_LANGUAGE_SEE_ANNOTATIONS = "ceylon.language.SeeAnnotation$annotations$"; static final String CEYLON_LANGUAGE_SEE_ANNOTATION = "ceylon.language.SeeAnnotation$annotation$"; static final String CEYLON_LANGUAGE_DEPRECATED_ANNOTATION = "ceylon.language.DeprecationAnnotation$annotation$"; static final String CEYLON_LANGUAGE_SUPPRESS_WARNINGS_ANNOTATION = "ceylon.language.SuppressWarningsAnnotation$annotation$"; static final String CEYLON_LANGUAGE_LICENSE_ANNOTATION = "ceylon.language.LicenseAnnotation$annotation$"; static final String CEYLON_LANGUAGE_TAGS_ANNOTATION = "ceylon.language.TagsAnnotation$annotation$"; static final String CEYLON_LANGUAGE_ALIASES_ANNOTATION = "ceylon.language.AliasesAnnotation$annotation$"; // important that these are with :: private static final String CEYLON_LANGUAGE_CALLABLE_TYPE_NAME = "ceylon.language::Callable"; private static final String CEYLON_LANGUAGE_TUPLE_TYPE_NAME = "ceylon.language::Tuple"; private static final String CEYLON_LANGUAGE_SEQUENTIAL_TYPE_NAME = "ceylon.language::Sequential"; private static final String CEYLON_LANGUAGE_SEQUENCE_TYPE_NAME = "ceylon.language::Sequence"; private static final String CEYLON_LANGUAGE_EMPTY_TYPE_NAME = "ceylon.language::Empty"; private static final TypeMirror OBJECT_TYPE = simpleCeylonObjectType("java.lang.Object"); private static final TypeMirror ANNOTATION_TYPE = simpleCeylonObjectType("java.lang.annotation.Annotation"); private static final TypeMirror CEYLON_OBJECT_TYPE = simpleCeylonObjectType("ceylon.language.Object"); private static final TypeMirror CEYLON_ANNOTATION_TYPE = simpleCeylonObjectType("ceylon.language.Annotation"); private static final TypeMirror CEYLON_CONSTRAINED_ANNOTATION_TYPE = simpleCeylonObjectType("ceylon.language.ConstrainedAnnotation"); // private static final TypeMirror CEYLON_FUNCTION_DECLARATION_TYPE = simpleCeylonObjectType("ceylon.language.meta.declaration.FunctionDeclaration"); private static final TypeMirror CEYLON_FUNCTION_OR_VALUE_DECLARATION_TYPE = simpleCeylonObjectType("ceylon.language.meta.declaration.FunctionOrValueDeclaration"); private static final TypeMirror CEYLON_VALUE_DECLARATION_TYPE = simpleCeylonObjectType("ceylon.language.meta.declaration.ValueDeclaration"); private static final TypeMirror CEYLON_ALIAS_DECLARATION_TYPE = simpleCeylonObjectType("ceylon.language.meta.declaration.AliasDeclaration"); private static final TypeMirror CEYLON_CLASS_OR_INTERFACE_DECLARATION_TYPE = simpleCeylonObjectType("ceylon.language.meta.declaration.ClassOrInterfaceDeclaration"); private static final TypeMirror CEYLON_CLASS_WITH_INIT_DECLARATION_TYPE = simpleCeylonObjectType("ceylon.language.meta.declaration.ClassWithInitializerDeclaration"); private static final TypeMirror CEYLON_CLASS_WITH_CTORS_DECLARATION_TYPE = simpleCeylonObjectType("ceylon.language.meta.declaration.ClassWithConstructorsDeclaration"); private static final TypeMirror CEYLON_CONSTRUCTOR_DECLARATION_TYPE = simpleCeylonObjectType("ceylon.language.meta.declaration.ConstructorDeclaration"); private static final TypeMirror CEYLON_CALLABLE_CONSTRUCTOR_DECLARATION_TYPE = simpleCeylonObjectType("ceylon.language.meta.declaration.CallableConstructorDeclaration"); private static final TypeMirror CEYLON_VALUE_CONSTRUCTOR_DECLARATION_TYPE = simpleCeylonObjectType("ceylon.language.meta.declaration.ValueConstructorDeclaration"); private static final TypeMirror CEYLON_ANNOTATED_TYPE = simpleCeylonObjectType("ceylon.language.Annotated"); private static final TypeMirror CEYLON_BASIC_TYPE = simpleCeylonObjectType("ceylon.language.Basic"); private static final TypeMirror CEYLON_REIFIED_TYPE_TYPE = simpleCeylonObjectType("com.redhat.ceylon.compiler.java.runtime.model.ReifiedType"); private static final TypeMirror CEYLON_SERIALIZABLE_TYPE = simpleCeylonObjectType("com.redhat.ceylon.compiler.java.runtime.serialization.Serializable"); private static final TypeMirror CEYLON_TYPE_DESCRIPTOR_TYPE = simpleCeylonObjectType("com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor"); private static final TypeMirror THROWABLE_TYPE = simpleCeylonObjectType("java.lang.Throwable"); // private static final TypeMirror ERROR_TYPE = simpleCeylonObjectType("java.lang.Error"); private static final TypeMirror EXCEPTION_TYPE = simpleCeylonObjectType("java.lang.Exception"); private static final TypeMirror CEYLON_THROWABLE_TYPE = simpleCeylonObjectType("java.lang.Throwable"); private static final TypeMirror CEYLON_EXCEPTION_TYPE = simpleCeylonObjectType("ceylon.language.Exception"); private static final TypeMirror STRING_TYPE = simpleJDKObjectType("java.lang.String"); private static final TypeMirror CEYLON_STRING_TYPE = simpleCeylonObjectType("ceylon.language.String"); private static final TypeMirror PRIM_BOOLEAN_TYPE = simpleJDKObjectType("boolean"); private static final TypeMirror CEYLON_BOOLEAN_TYPE = simpleCeylonObjectType("ceylon.language.Boolean"); private static final TypeMirror PRIM_BYTE_TYPE = simpleJDKObjectType("byte"); private static final TypeMirror CEYLON_BYTE_TYPE = simpleCeylonObjectType("ceylon.language.Byte"); private static final TypeMirror PRIM_SHORT_TYPE = simpleJDKObjectType("short"); private static final TypeMirror PRIM_INT_TYPE = simpleJDKObjectType("int"); private static final TypeMirror PRIM_LONG_TYPE = simpleJDKObjectType("long"); private static final TypeMirror CEYLON_INTEGER_TYPE = simpleCeylonObjectType("ceylon.language.Integer"); private static final TypeMirror PRIM_FLOAT_TYPE = simpleJDKObjectType("float"); private static final TypeMirror PRIM_DOUBLE_TYPE = simpleJDKObjectType("double"); private static final TypeMirror CEYLON_FLOAT_TYPE = simpleCeylonObjectType("ceylon.language.Float"); private static final TypeMirror PRIM_CHAR_TYPE = simpleJDKObjectType("char"); private static final TypeMirror CEYLON_CHARACTER_TYPE = simpleCeylonObjectType("ceylon.language.Character"); // this one has no "_" postfix because that's how we look it up protected static final String JAVA_LANG_BYTE_ARRAY = "java.lang.ByteArray"; protected static final String JAVA_LANG_SHORT_ARRAY = "java.lang.ShortArray"; protected static final String JAVA_LANG_INT_ARRAY = "java.lang.IntArray"; protected static final String JAVA_LANG_LONG_ARRAY = "java.lang.LongArray"; protected static final String JAVA_LANG_FLOAT_ARRAY = "java.lang.FloatArray"; protected static final String JAVA_LANG_DOUBLE_ARRAY = "java.lang.DoubleArray"; protected static final String JAVA_LANG_CHAR_ARRAY = "java.lang.CharArray"; protected static final String JAVA_LANG_BOOLEAN_ARRAY = "java.lang.BooleanArray"; protected static final String JAVA_LANG_OBJECT_ARRAY = "java.lang.ObjectArray"; // this one has the "_" postfix because that's what we translate it to private static final String CEYLON_BYTE_ARRAY = "com.redhat.ceylon.compiler.java.language.ByteArray"; private static final String CEYLON_SHORT_ARRAY = "com.redhat.ceylon.compiler.java.language.ShortArray"; private static final String CEYLON_INT_ARRAY = "com.redhat.ceylon.compiler.java.language.IntArray"; private static final String CEYLON_LONG_ARRAY = "com.redhat.ceylon.compiler.java.language.LongArray"; private static final String CEYLON_FLOAT_ARRAY = "com.redhat.ceylon.compiler.java.language.FloatArray"; private static final String CEYLON_DOUBLE_ARRAY = "com.redhat.ceylon.compiler.java.language.DoubleArray"; private static final String CEYLON_CHAR_ARRAY = "com.redhat.ceylon.compiler.java.language.CharArray"; private static final String CEYLON_BOOLEAN_ARRAY = "com.redhat.ceylon.compiler.java.language.BooleanArray"; private static final String CEYLON_OBJECT_ARRAY = "com.redhat.ceylon.compiler.java.language.ObjectArray"; private static final TypeMirror JAVA_BYTE_ARRAY_TYPE = simpleJDKObjectType("java.lang.ByteArray"); private static final TypeMirror JAVA_SHORT_ARRAY_TYPE = simpleJDKObjectType("java.lang.ShortArray"); private static final TypeMirror JAVA_INT_ARRAY_TYPE = simpleJDKObjectType("java.lang.IntArray"); private static final TypeMirror JAVA_LONG_ARRAY_TYPE = simpleJDKObjectType("java.lang.LongArray"); private static final TypeMirror JAVA_FLOAT_ARRAY_TYPE = simpleJDKObjectType("java.lang.FloatArray"); private static final TypeMirror JAVA_DOUBLE_ARRAY_TYPE = simpleJDKObjectType("java.lang.DoubleArray"); private static final TypeMirror JAVA_CHAR_ARRAY_TYPE = simpleJDKObjectType("java.lang.CharArray"); private static final TypeMirror JAVA_BOOLEAN_ARRAY_TYPE = simpleJDKObjectType("java.lang.BooleanArray"); private static final TypeMirror JAVA_IO_SERIALIZABLE_TYPE_TYPE = simpleJDKObjectType("java.io.Serializable"); private static TypeMirror simpleJDKObjectType(String name) { return new SimpleReflType(name, SimpleReflType.Module.JDK, TypeKind.DECLARED); } private static TypeMirror simpleCeylonObjectType(String name) { return new SimpleReflType(name, SimpleReflType.Module.CEYLON, TypeKind.DECLARED); } protected Map<String, Declaration> valueDeclarationsByName = new HashMap<String, Declaration>(); protected Map<String, Declaration> typeDeclarationsByName = new HashMap<String, Declaration>(); protected Map<Package, Unit> unitsByPackage = new HashMap<Package, Unit>(); protected TypeParser typeParser; /** * The type factory * (<strong>should not be used while completing a declaration</strong>) */ protected Unit typeFactory; protected final Set<String> loadedPackages = new HashSet<String>(); protected final Map<String,LazyPackage> packagesByName = new HashMap<String,LazyPackage>(); protected boolean packageDescriptorsNeedLoading = false; protected boolean isBootstrap; protected ModuleManager moduleManager; protected Modules modules; protected Map<String, ClassMirror> classMirrorCache = new HashMap<String, ClassMirror>(); protected boolean binaryCompatibilityErrorRaised = false; protected Timer timer; private Map<String,LazyPackage> modulelessPackages = new HashMap<String,LazyPackage>(); private ParameterNameParser parameterNameParser = new ParameterNameParser(this); /** * Loads a given package, if required. This is mostly useful for the javac reflection impl. * * @param the module to load the package from * @param packageName the package name to load * @param loadDeclarations true to load all the declarations in this package. * @return */ public abstract boolean loadPackage(Module module, String packageName, boolean loadDeclarations); public final Object getLock(){ return this; } /** * To be redefined by subclasses if they don't need local declarations. */ protected boolean needsLocalDeclarations(){ return true; } /** * For subclassers to skip private members. Defaults to false. */ protected boolean needsPrivateMembers() { return true; } public boolean searchAgain(ClassMirror cachedMirror, Module module, String name) { return false; } public boolean searchAgain(Declaration cachedDeclaration, LazyPackage lazyPackage, String name) { return false; } /** * Looks up a ClassMirror by name. Uses cached results, and caches the result of calling lookupNewClassMirror * on cache misses. * * @param module the module in which we should find the class * @param name the name of the Class to load * @return a ClassMirror for the specified class, or null if not found. */ public final ClassMirror lookupClassMirror(Module module, String name) { synchronized(getLock()){ timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY); try{ // Java array classes are not where we expect them if (JAVA_LANG_OBJECT_ARRAY.equals(name) || JAVA_LANG_BOOLEAN_ARRAY.equals(name) || JAVA_LANG_BYTE_ARRAY.equals(name) || JAVA_LANG_SHORT_ARRAY.equals(name) || JAVA_LANG_INT_ARRAY.equals(name) || JAVA_LANG_LONG_ARRAY.equals(name) || JAVA_LANG_FLOAT_ARRAY.equals(name) || JAVA_LANG_DOUBLE_ARRAY.equals(name) || JAVA_LANG_CHAR_ARRAY.equals(name)) { // turn them into their real class location (get rid of the "java.lang" prefix) name = "com.redhat.ceylon.compiler.java.language" + name.substring(9); module = getLanguageModule(); } String cacheKey = cacheKeyByModule(module, name); // we use containsKey to be able to cache null results if(classMirrorCache.containsKey(cacheKey)) { ClassMirror cachedMirror = classMirrorCache.get(cacheKey); if (! searchAgain(cachedMirror, module, name)) { return cachedMirror; } } ClassMirror mirror = lookupNewClassMirror(module, name); // we even cache null results classMirrorCache.put(cacheKey, mirror); return mirror; }finally{ timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY); } } } protected String cacheKeyByModule(Module module, String name) { return getCacheKeyByModule(module, name); } public static String getCacheKeyByModule(Module module, String name){ String moduleSignature = module.getSignature(); StringBuilder buf = new StringBuilder(moduleSignature.length()+1+name.length()); // '/' is allowed in module version but not in module or class name, so we're good return buf.append(moduleSignature).append('/').append(name).toString(); } protected boolean lastPartHasLowerInitial(String name) { int index = name.lastIndexOf('.'); if (index != -1){ name = name.substring(index+1); } // remove any possibly quoting char name = NamingBase.stripLeadingDollar(name); if(!name.isEmpty()){ int codepoint = name.codePointAt(0); return JvmBackendUtil.isLowerCase(codepoint); } return false; } /** * Looks up a ClassMirror by name. Called by lookupClassMirror on cache misses. * * @param module the module in which we should find the given class * @param name the name of the Class to load * @return a ClassMirror for the specified class, or null if not found. */ protected abstract ClassMirror lookupNewClassMirror(Module module, String name); /** * Adds the given module to the set of modules from which we can load classes. * * @param module the module * @param artifact the module's artifact, if any. Can be null. */ public abstract void addModuleToClassPath(Module module, ArtifactResult artifact); /** * Returns true if the given module has been added to this model loader's classpath. * Defaults to true. */ public boolean isModuleInClassPath(Module module){ return true; } /** * Returns true if the given method is overriding an inherited method (from super class or interfaces). */ protected abstract boolean isOverridingMethod(MethodMirror methodMirror); /** * Returns true if the given method is overloading an inherited method (from super class or interfaces). */ protected abstract boolean isOverloadingMethod(MethodMirror methodMirror); /** * Logs a warning. */ protected abstract void logWarning(String message); /** * Logs a debug message. */ protected abstract void logVerbose(String message); /** * Logs an error */ protected abstract void logError(String message); public void loadStandardModules(){ // set up the type factory Timer nested = timer.nestedTimer(); nested.startTask("load ceylon.language"); Module languageModule = loadLanguageModuleAndPackage(); nested.endTask(); nested.startTask("load JDK"); // make sure the jdk modules are loaded loadJDKModules(); Module jdkModule = findOrCreateModule(JAVA_BASE_MODULE_NAME, JDKUtils.jdk.version); nested.endTask(); /* * We start by loading java.lang and ceylon.language because we will need them no matter what. */ nested.startTask("load standard packages"); loadPackage(jdkModule, "java.lang", false); loadPackage(languageModule, "com.redhat.ceylon.compiler.java.metadata", false); loadPackage(languageModule, "com.redhat.ceylon.compiler.java.language", false); nested.endTask(); } protected Module loadLanguageModuleAndPackage() { Module languageModule = findOrCreateModule(CEYLON_LANGUAGE, null); addModuleToClassPath(languageModule, null); Package languagePackage = findOrCreatePackage(languageModule, CEYLON_LANGUAGE); typeFactory.setPackage(languagePackage); // make sure the language module has its real dependencies added, because we need them in the classpath // otherwise we will get errors on the Util and Metamodel calls we insert // WARNING! Make sure this list is always the same as the one in /ceylon-runtime/dist/repo/ceylon/language/_version_/module.xml languageModule.addImport(new ModuleImport(findOrCreateModule("com.redhat.ceylon.compiler.java", Versions.CEYLON_VERSION_NUMBER), false, false, Backend.Java)); languageModule.addImport(new ModuleImport(findOrCreateModule("com.redhat.ceylon.compiler.js", Versions.CEYLON_VERSION_NUMBER), false, false, Backend.Java)); languageModule.addImport(new ModuleImport(findOrCreateModule("com.redhat.ceylon.common", Versions.CEYLON_VERSION_NUMBER), false, false, Backend.Java)); languageModule.addImport(new ModuleImport(findOrCreateModule("com.redhat.ceylon.model", Versions.CEYLON_VERSION_NUMBER), false, false, Backend.Java)); languageModule.addImport(new ModuleImport(findOrCreateModule("com.redhat.ceylon.module-resolver", Versions.CEYLON_VERSION_NUMBER), false, false, Backend.Java)); languageModule.addImport(new ModuleImport(findOrCreateModule("com.redhat.ceylon.typechecker", Versions.CEYLON_VERSION_NUMBER), false, false, Backend.Java)); languageModule.addImport(new ModuleImport(findOrCreateModule("org.jboss.modules", Versions.DEPENDENCY_JBOSS_MODULES_VERSION), false, false, Backend.Java)); languageModule.addImport(new ModuleImport(findOrCreateModule("org.jboss.jandex", Versions.DEPENDENCY_JANDEX_VERSION), false, false, Backend.Java)); return languageModule; } protected void loadJDKModules() { for(String jdkModule : JDKUtils.getJDKModuleNames()) findOrCreateModule(jdkModule, JDKUtils.jdk.version); for(String jdkOracleModule : JDKUtils.getOracleJDKModuleNames()) findOrCreateModule(jdkOracleModule, JDKUtils.jdk.version); } /** * This is meant to be called if your subclass doesn't call loadStandardModules for whatever reason */ public void setupWithNoStandardModules() { Module languageModule = modules.getLanguageModule(); if(languageModule == null) throw new RuntimeException("Assertion failed: language module is null"); Package languagePackage = languageModule.getPackage(CEYLON_LANGUAGE); if(languagePackage == null) throw new RuntimeException("Assertion failed: language package is null"); typeFactory.setPackage(languagePackage); } enum ClassType { ATTRIBUTE, METHOD, OBJECT, CLASS, INTERFACE; } private ClassMirror loadClass(Module module, String pkgName, String className) { ClassMirror moduleClass = null; try{ loadPackage(module, pkgName, false); moduleClass = lookupClassMirror(module, className); }catch(Exception x){ logVerbose("[Failed to complete class "+className+"]"); } return moduleClass; } private Declaration convertNonPrimitiveTypeToDeclaration(Module moduleScope, TypeMirror type, Scope scope, DeclarationType declarationType) { switch(type.getKind()){ case VOID: return typeFactory.getAnythingDeclaration(); case ARRAY: return ((Class)convertToDeclaration(getLanguageModule(), JAVA_LANG_OBJECT_ARRAY, DeclarationType.TYPE)); case DECLARED: return convertDeclaredTypeToDeclaration(moduleScope, type, declarationType); case TYPEVAR: return safeLookupTypeParameter(scope, type.getQualifiedName()); case WILDCARD: return typeFactory.getNothingDeclaration(); // those can't happen case BOOLEAN: case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT: case DOUBLE: // all the autoboxing should already have been done throw new RuntimeException("Expected non-primitive type: "+type); case ERROR: return null; default: throw new RuntimeException("Failed to handle type "+type); } } private Declaration convertDeclaredTypeToDeclaration(Module moduleScope, TypeMirror type, DeclarationType declarationType) { // SimpleReflType does not do declared class so we make an exception for it String typeName = type.getQualifiedName(); if(type instanceof SimpleReflType){ Module module = null; switch(((SimpleReflType) type).getModule()){ case CEYLON: module = getLanguageModule(); break; case JDK : module = getJDKBaseModule(); break; } return convertToDeclaration(module, typeName, declarationType); } ClassMirror classMirror = type.getDeclaredClass(); Module module = findModuleForClassMirror(classMirror); if(isImported(moduleScope, module)){ return convertToDeclaration(module, typeName, declarationType); }else{ if(module != null && isFlatClasspath() && isMavenModule(moduleScope)) return convertToDeclaration(module, typeName, declarationType); String error = "Declaration '" + typeName + "' could not be found in module '" + moduleScope.getNameAsString() + "' or its imported modules"; if(module != null && !module.isDefault()) error += " but was found in the non-imported module '"+module.getNameAsString()+"'"; return logModelResolutionException(null, moduleScope, error).getDeclaration(); } } public Declaration convertToDeclaration(Module module, ClassMirror classMirror, DeclarationType declarationType) { return convertToDeclaration(module, null, classMirror, declarationType); } private Declaration convertToDeclaration(Module module, Declaration container, ClassMirror classMirror, DeclarationType declarationType) { // find its package String pkgName = getPackageNameForQualifiedClassName(classMirror); if (pkgName.equals("java.lang")) { module = getJDKBaseModule(); } Declaration decl = findCachedDeclaration(module, classMirror, declarationType); if (decl != null) { return decl; } // avoid ignored classes if(classMirror.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null) return null; // avoid local interfaces that were pulled to the toplevel if required if(classMirror.getAnnotation(CEYLON_LOCAL_CONTAINER_ANNOTATION) != null && !needsLocalDeclarations()) return null; // avoid Ceylon annotations if(classMirror.getAnnotation(CEYLON_CEYLON_ANNOTATION) != null && classMirror.isAnnotationType()) return null; // avoid module and package descriptors too if(classMirror.getAnnotation(CEYLON_MODULE_ANNOTATION) != null || classMirror.getAnnotation(CEYLON_PACKAGE_ANNOTATION) != null) return null; List<Declaration> decls = new ArrayList<Declaration>(); LazyPackage pkg = findOrCreatePackage(module, pkgName); decl = createDeclaration(module, container, classMirror, declarationType, decls); cacheDeclaration(module, classMirror, declarationType, decl, decls); // find/make its Unit Unit unit = getCompiledUnit(pkg, classMirror); // set all the containers for(Declaration d : decls){ // add it to its Unit d.setUnit(unit); unit.addDeclaration(d); setContainer(classMirror, d, pkg); } return decl; } public String getPackageNameForQualifiedClassName(String pkg, String qualifiedName){ // Java array classes we pretend come from java.lang if(qualifiedName.startsWith(CEYLON_OBJECT_ARRAY) || qualifiedName.startsWith(CEYLON_BOOLEAN_ARRAY) || qualifiedName.startsWith(CEYLON_BYTE_ARRAY) || qualifiedName.startsWith(CEYLON_SHORT_ARRAY) || qualifiedName.startsWith(CEYLON_INT_ARRAY) || qualifiedName.startsWith(CEYLON_LONG_ARRAY) || qualifiedName.startsWith(CEYLON_FLOAT_ARRAY) || qualifiedName.startsWith(CEYLON_DOUBLE_ARRAY) || qualifiedName.startsWith(CEYLON_CHAR_ARRAY)) return "java.lang"; else return unquotePackageName(pkg); } protected String getPackageNameForQualifiedClassName(ClassMirror classMirror) { return getPackageNameForQualifiedClassName(classMirror.getPackage().getQualifiedName(), classMirror.getQualifiedName()); } private String unquotePackageName(PackageMirror pkg) { return unquotePackageName(pkg.getQualifiedName()); } private String unquotePackageName(String pkg) { return JvmBackendUtil.removeChar('$', pkg); } private void setContainer(ClassMirror classMirror, Declaration d, LazyPackage pkg) { // add it to its package if it's not an inner class if(!classMirror.isInnerClass() && !classMirror.isLocalClass()){ d.setContainer(pkg); d.setScope(pkg); pkg.addCompiledMember(d); if(d instanceof LazyInterface && ((LazyInterface) d).isCeylon()){ setInterfaceCompanionClass(d, null, pkg); } ModelUtil.setVisibleScope(d); }else if(classMirror.isLocalClass() && !classMirror.isInnerClass()){ // set its container to the package for now, but don't add it to the package as a member because it's not Scope localContainer = getLocalContainer(pkg, classMirror, d); if(localContainer != null){ d.setContainer(localContainer); d.setScope(localContainer); // do not add it as member, it has already been registered by getLocalContainer }else{ d.setContainer(pkg); d.setScope(pkg); } ((LazyElement)d).setLocal(true); }else if(d instanceof ClassOrInterface || d instanceof TypeAlias){ // do overloads later, since their container is their abstract superclass's container and // we have to set that one first if(d instanceof Class == false || !((Class)d).isOverloaded()){ ClassOrInterface container = getContainer(pkg.getModule(), classMirror); if (d.isNativeHeader() && container.isNative()) { container = (ClassOrInterface)ModelUtil.getNativeHeader(container); } d.setContainer(container); d.setScope(container); if(d instanceof LazyInterface && ((LazyInterface) d).isCeylon()){ setInterfaceCompanionClass(d, container, pkg); } // let's not trigger lazy-loading ((LazyContainer)container).addMember(d); ModelUtil.setVisibleScope(d); // now we can do overloads if(d instanceof Class && ((Class)d).getOverloads() != null){ for(Declaration overload : ((Class)d).getOverloads()){ overload.setContainer(container); overload.setScope(container); // let's not trigger lazy-loading ((LazyContainer)container).addMember(overload); ModelUtil.setVisibleScope(overload); } } } } } protected void setInterfaceCompanionClass(Declaration d, ClassOrInterface container, LazyPackage pkg) { // find its companion class in its real container ClassMirror containerMirror = null; if(container instanceof LazyClass){ containerMirror = ((LazyClass) container).classMirror; }else if(container instanceof LazyInterface){ // container must be a LazyInterface, as TypeAlias doesn't contain anything containerMirror = ((LazyInterface)container).companionClass; if(containerMirror == null){ throw new ModelResolutionException("Interface companion class for "+container.getQualifiedNameString()+" not set up"); } } String companionName; if(containerMirror != null) companionName = containerMirror.getFlatName() + "$" + NamingBase.suffixName(NamingBase.Suffix.$impl, d.getName()); else{ // toplevel String p = pkg.getNameAsString(); companionName = ""; if(!p.isEmpty()) companionName = p + "."; companionName += NamingBase.suffixName(NamingBase.Suffix.$impl, d.getName()); } ClassMirror companionClass = lookupClassMirror(pkg.getModule(), companionName); if(companionClass == null){ ((Interface)d).setCompanionClassNeeded(false); } ((LazyInterface)d).companionClass = companionClass; } private Scope getLocalContainer(Package pkg, ClassMirror classMirror, Declaration declaration) { AnnotationMirror localContainerAnnotation = classMirror.getAnnotation(CEYLON_LOCAL_CONTAINER_ANNOTATION); String qualifier = getAnnotationStringValue(classMirror, CEYLON_LOCAL_DECLARATION_ANNOTATION, "qualifier"); // deal with types local to functions in the body of toplevel non-lazy attributes, whose container is ultimately the package Boolean isPackageLocal = getAnnotationBooleanValue(classMirror, CEYLON_LOCAL_DECLARATION_ANNOTATION, "isPackageLocal"); if(BooleanUtil.isTrue(isPackageLocal)){ // make sure it still knows it's a local declaration.setQualifier(qualifier); return null; } LocalDeclarationContainer methodDecl = null; // we get a @LocalContainer annotation for local interfaces if(localContainerAnnotation != null){ methodDecl = (LocalDeclarationContainer) findLocalContainerFromAnnotationAndSetCompanionClass(pkg, (Interface) declaration, localContainerAnnotation); }else{ // all the other cases stay where they belong MethodMirror method = classMirror.getEnclosingMethod(); if(method == null) return null; // see where that method belongs ClassMirror enclosingClass = method.getEnclosingClass(); while(enclosingClass.isAnonymous()){ // this gives us the method in which the anonymous class is, which should be the one we're looking for method = enclosingClass.getEnclosingMethod(); if(method == null) return null; // and the method's containing class enclosingClass = method.getEnclosingClass(); } // if we are in a setter class, the attribute is declared in the getter class, so look for its declaration there TypeMirror getterClass = (TypeMirror) getAnnotationValue(enclosingClass, CEYLON_SETTER_ANNOTATION, "getterClass"); boolean isSetter = false; // we use void.class as default value if(getterClass != null && !getterClass.isPrimitive()){ enclosingClass = getterClass.getDeclaredClass(); isSetter = true; } String javaClassName = enclosingClass.getQualifiedName(); // make sure we don't go looking in companion classes if(javaClassName.endsWith(NamingBase.Suffix.$impl.name())) javaClassName = javaClassName.substring(0, javaClassName.length() - 5); // find the enclosing declaration Declaration enclosingClassDeclaration = convertToDeclaration(pkg.getModule(), javaClassName, DeclarationType.TYPE); if(enclosingClassDeclaration instanceof ClassOrInterface){ ClassOrInterface containerDecl = (ClassOrInterface) enclosingClassDeclaration; // now find the method's declaration // FIXME: find the proper overload if any String name = method.getName(); if(method.isConstructor() || name.startsWith(NamingBase.Prefix.$default$.toString())){ methodDecl = (LocalDeclarationContainer) containerDecl; }else{ // this is only for error messages String type; // lots of special cases if(isStringAttribute(method)){ name = "string"; type = "attribute"; }else if(isHashAttribute(method)){ name = "hash"; type = "attribute"; }else if(isGetter(method)) { // simple attribute name = getJavaAttributeName(method); type = "attribute"; }else if(isSetter(method)) { // simple attribute name = getJavaAttributeName(method); type = "attribute setter"; isSetter = true; }else{ type = "method"; } // strip any escaping or private suffix // it can be foo$priv$canonical so get rid of that one first if (name.endsWith(NamingBase.Suffix.$canonical$.toString())) { name = name.substring(0, name.length()-11); } name = JvmBackendUtil.strip(name, true, method.isPublic() || method.isProtected() || method.isDefaultAccess()); if(name.indexOf('$') > 0){ // may be a default parameter expression? get the method name which is first name = name.substring(0, name.indexOf('$')); } methodDecl = (LocalDeclarationContainer) containerDecl.getDirectMember(name, null, false); if(methodDecl == null) throw new ModelResolutionException("Failed to load outer "+type+" " + name + " for local type " + classMirror.getQualifiedName().toString()); // if it's a setter we wanted, let's get it if(isSetter){ LocalDeclarationContainer setter = (LocalDeclarationContainer) ((Value)methodDecl).getSetter(); if(setter == null) throw new ModelResolutionException("Failed to load outer "+type+" " + name + " for local type " + classMirror.getQualifiedName().toString()); methodDecl = setter; } } }else if(enclosingClassDeclaration instanceof LazyFunction){ // local and toplevel methods methodDecl = (LazyFunction)enclosingClassDeclaration; }else if(enclosingClassDeclaration instanceof LazyValue){ // local and toplevel attributes if(enclosingClassDeclaration.isToplevel() && method.getName().equals(NamingBase.Unfix.set_.name())) isSetter = true; if(isSetter){ LocalDeclarationContainer setter = (LocalDeclarationContainer) ((LazyValue)enclosingClassDeclaration).getSetter(); if(setter == null) throw new ModelResolutionException("Failed to toplevel attribute setter " + enclosingClassDeclaration.getName() + " for local type " + classMirror.getQualifiedName().toString()); methodDecl = setter; }else methodDecl = (LazyValue)enclosingClassDeclaration; }else{ throw new ModelResolutionException("Unknown container type " + enclosingClassDeclaration + " for local type " + classMirror.getQualifiedName().toString()); } } // we have the method, now find the proper local qualifier if any if(qualifier == null) return null; declaration.setQualifier(qualifier); methodDecl.addLocalDeclaration(declaration); return methodDecl; } private Scope findLocalContainerFromAnnotationAndSetCompanionClass(Package pkg, Interface declaration, AnnotationMirror localContainerAnnotation) { @SuppressWarnings("unchecked") List<String> path = (List<String>) localContainerAnnotation.getValue("path"); // we start at the package Scope scope = pkg; for(String name : path){ scope = (Scope) getDirectMember(scope, name); } String companionClassName = (String) localContainerAnnotation.getValue("companionClassName"); if(companionClassName == null || companionClassName.isEmpty()){ declaration.setCompanionClassNeeded(false); return scope; } ClassMirror container; Scope javaClassScope; if(scope instanceof TypedDeclaration && ((TypedDeclaration) scope).isMember()) javaClassScope = scope.getContainer(); else javaClassScope = scope; if(javaClassScope instanceof LazyInterface){ container = ((LazyInterface)javaClassScope).companionClass; }else if(javaClassScope instanceof LazyClass){ container = ((LazyClass) javaClassScope).classMirror; }else if(javaClassScope instanceof LazyValue){ container = ((LazyValue) javaClassScope).classMirror; }else if(javaClassScope instanceof LazyFunction){ container = ((LazyFunction) javaClassScope).classMirror; }else if(javaClassScope instanceof SetterWithLocalDeclarations){ container = ((SetterWithLocalDeclarations) javaClassScope).classMirror; }else{ throw new ModelResolutionException("Unknown scope class: "+javaClassScope); } String qualifiedCompanionClassName = container.getQualifiedName() + "$" + companionClassName; ClassMirror companionClassMirror = lookupClassMirror(pkg.getModule(), qualifiedCompanionClassName); if(companionClassMirror == null) throw new ModelResolutionException("Could not find companion class mirror: "+qualifiedCompanionClassName); ((LazyInterface)declaration).companionClass = companionClassMirror; return scope; } /** * Looks for a direct member of type ClassOrInterface. We're not using Class.getDirectMember() * because it skips object types and we want them. */ public static Declaration getDirectMember(Scope container, String name) { if(name.isEmpty()) return null; boolean wantsSetter = false; if(name.startsWith(NamingBase.Suffix.$setter$.name())){ wantsSetter = true; name = name.substring(8); } if(Character.isDigit(name.charAt(0))){ // this is a local type we have a different accessor for it return ((LocalDeclarationContainer)container).getLocalDeclaration(name); } // don't even try using getDirectMember except on Package, // because it will fail miserably during completion, since we // will for instance have only anonymous types first, before we load their anonymous values, and // when we go looking for them we won't be able to find them until we add their anonymous values, // which is too late if(container instanceof Package){ // don't use Package.getMembers() as it loads the whole package Declaration result = container.getDirectMember(name, null, false); return selectTypeOrSetter(result, wantsSetter); }else{ // must be a Declaration for(Declaration member : container.getMembers()){ // avoid constructors with no name if(member.getName() == null) continue; if(!member.getName().equals(name)) continue; Declaration result = selectTypeOrSetter(member, wantsSetter); if(result != null) return result; } } // not found return null; } private static Declaration selectTypeOrSetter(Declaration member, boolean wantsSetter) { // if we found a type or a method/value we're good to go if (member instanceof ClassOrInterface || member instanceof Constructor || member instanceof Function) { return member; } // if it's a Value return its object type by preference, the member otherwise if (member instanceof Value){ TypeDeclaration typeDeclaration = ((Value) member).getTypeDeclaration(); if(typeDeclaration instanceof Class && typeDeclaration.isAnonymous()) return typeDeclaration; // did we want the setter? if(wantsSetter) return ((Value)member).getSetter(); // must be a non-object value return member; } return null; } private ClassOrInterface getContainer(Module module, ClassMirror classMirror) { AnnotationMirror containerAnnotation = classMirror.getAnnotation(CEYLON_CONTAINER_ANNOTATION); if(containerAnnotation != null){ TypeMirror javaClassMirror = (TypeMirror)containerAnnotation.getValue("klass"); String javaClassName = javaClassMirror.getQualifiedName(); ClassOrInterface containerDecl = (ClassOrInterface) convertToDeclaration(module, javaClassName, DeclarationType.TYPE); if(containerDecl == null) throw new ModelResolutionException("Failed to load outer type " + javaClassName + " for inner type " + classMirror.getQualifiedName().toString()); return containerDecl; }else{ return (ClassOrInterface) convertToDeclaration(module, classMirror.getEnclosingClass(), DeclarationType.TYPE); } } private Declaration findCachedDeclaration(Module module, ClassMirror classMirror, DeclarationType declarationType) { ClassType type = getClassType(classMirror); String key = classMirror.getCacheKey(module); // see if we already have it Map<String, Declaration> declarationCache = getCacheByType(type, declarationType); return declarationCache.get(key); } private void cacheDeclaration(Module module, ClassMirror classMirror, DeclarationType declarationType, Declaration decl, List<Declaration> decls) { ClassType type = getClassType(classMirror); String key = classMirror.getCacheKey(module); if(type == ClassType.OBJECT){ typeDeclarationsByName.put(key, getByType(decls, Class.class)); valueDeclarationsByName.put(key, getByType(decls, Value.class)); }else { Map<String, Declaration> declarationCache = getCacheByType(type, declarationType); declarationCache.put(key, decl); } } private Map<String, Declaration> getCacheByType(ClassType type, DeclarationType declarationType) { Map<String, Declaration> declarationCache = null; switch(type){ case OBJECT: if(declarationType == DeclarationType.TYPE){ declarationCache = typeDeclarationsByName; break; } // else fall-through to value case ATTRIBUTE: case METHOD: declarationCache = valueDeclarationsByName; break; case CLASS: case INTERFACE: declarationCache = typeDeclarationsByName; } return declarationCache; } private Declaration getByType(List<Declaration> decls, java.lang.Class<?> klass) { for (Declaration decl : decls) { if (klass.isAssignableFrom(decl.getClass())) { return decl; } } return null; } private Declaration createDeclaration(Module module, Declaration container, ClassMirror classMirror, DeclarationType declarationType, List<Declaration> decls) { Declaration decl = null; Declaration hdr = null; checkBinaryCompatibility(classMirror); ClassType type = getClassType(classMirror); boolean isCeylon = classMirror.getAnnotation(CEYLON_CEYLON_ANNOTATION) != null; boolean isNativeHeaderMember = container != null && container.isNativeHeader(); try{ // make it switch(type){ case ATTRIBUTE: decl = makeToplevelAttribute(classMirror, isNativeHeaderMember); setNonLazyDeclarationProperties(decl, classMirror, classMirror, classMirror, true); if (isCeylon && shouldCreateNativeHeader(decl, container)) { hdr = makeToplevelAttribute(classMirror, true); setNonLazyDeclarationProperties(hdr, classMirror, classMirror, classMirror, true); } break; case METHOD: decl = makeToplevelMethod(classMirror, isNativeHeaderMember); setNonLazyDeclarationProperties(decl, classMirror, classMirror, classMirror, true); if (isCeylon && shouldCreateNativeHeader(decl, container)) { hdr = makeToplevelMethod(classMirror, true); setNonLazyDeclarationProperties(hdr, classMirror, classMirror, classMirror, true); } break; case OBJECT: // we first make a class Declaration objectClassDecl = makeLazyClass(classMirror, null, null, isNativeHeaderMember); setNonLazyDeclarationProperties(objectClassDecl, classMirror, classMirror, classMirror, true); decls.add(objectClassDecl); if (isCeylon && shouldCreateNativeHeader(objectClassDecl, container)) { Declaration hdrobj = makeLazyClass(classMirror, null, null, true); setNonLazyDeclarationProperties(hdrobj, classMirror, classMirror, classMirror, true); decls.add(initNativeHeader(hdrobj, objectClassDecl)); } // then we make a value for it, if it's not an inline object expr if(objectClassDecl.isNamed()){ Declaration objectDecl = makeToplevelAttribute(classMirror, isNativeHeaderMember); setNonLazyDeclarationProperties(objectDecl, classMirror, classMirror, classMirror, true); decls.add(objectDecl); if (isCeylon && shouldCreateNativeHeader(objectDecl, container)) { Declaration hdrobj = makeToplevelAttribute(classMirror, true); setNonLazyDeclarationProperties(hdrobj, classMirror, classMirror, classMirror, true); decls.add(initNativeHeader(hdrobj, objectDecl)); } // which one did we want? decl = declarationType == DeclarationType.TYPE ? objectClassDecl : objectDecl; }else{ decl = objectClassDecl; } break; case CLASS: if(classMirror.getAnnotation(CEYLON_ALIAS_ANNOTATION) != null){ decl = makeClassAlias(classMirror); setNonLazyDeclarationProperties(decl, classMirror, classMirror, classMirror, true); }else if(classMirror.getAnnotation(CEYLON_TYPE_ALIAS_ANNOTATION) != null){ decl = makeTypeAlias(classMirror); setNonLazyDeclarationProperties(decl, classMirror, classMirror, classMirror, true); }else{ final List<MethodMirror> constructors = getClassConstructors(classMirror, constructorOnly); if (!constructors.isEmpty()) { Boolean hasConstructors = hasConstructors(classMirror); if (constructors.size() > 1) { if (hasConstructors == null || !hasConstructors) { decl = makeOverloadedConstructor(constructors, classMirror, decls, isCeylon); } else { decl = makeLazyClass(classMirror, null, null, isNativeHeaderMember); setNonLazyDeclarationProperties(decl, classMirror, classMirror, classMirror, isCeylon); if (isCeylon && shouldCreateNativeHeader(decl, container)) { hdr = makeLazyClass(classMirror, null, null, true); setNonLazyDeclarationProperties(hdr, classMirror, classMirror, classMirror, true); } } } else { if (hasConstructors == null || !hasConstructors) { // single constructor MethodMirror constructor = constructors.get(0); // if the class and constructor have different visibility, we pretend there's an overload of one // if it's a ceylon class we don't care that they don't match sometimes, like for inner classes // where the constructor is protected because we want to use an accessor, in this case the class // visibility is to be used if(isCeylon || getJavaVisibility(classMirror) == getJavaVisibility(constructor)){ decl = makeLazyClass(classMirror, null, constructor, isNativeHeaderMember); setNonLazyDeclarationProperties(decl, classMirror, classMirror, classMirror, isCeylon); if (isCeylon && shouldCreateNativeHeader(decl, container)) { hdr = makeLazyClass(classMirror, null, constructor, true); setNonLazyDeclarationProperties(hdr, classMirror, classMirror, classMirror, true); } }else{ decl = makeOverloadedConstructor(constructors, classMirror, decls, isCeylon); } } else { decl = makeLazyClass(classMirror, null, null, isNativeHeaderMember); setNonLazyDeclarationProperties(decl, classMirror, classMirror, classMirror, isCeylon); if (isCeylon && shouldCreateNativeHeader(decl, container)) { hdr = makeLazyClass(classMirror, null, null, true); setNonLazyDeclarationProperties(hdr, classMirror, classMirror, classMirror, true); } } } } else if(isCeylon && classMirror.getAnnotation(CEYLON_OBJECT_ANNOTATION) != null) { // objects don't need overloading stuff decl = makeLazyClass(classMirror, null, null, isNativeHeaderMember); setNonLazyDeclarationProperties(decl, classMirror, classMirror, classMirror, isCeylon); if (isCeylon && shouldCreateNativeHeader(decl, container)) { hdr = makeLazyClass(classMirror, null, null, true); setNonLazyDeclarationProperties(hdr, classMirror, classMirror, classMirror, true); } } else { // no visible constructors decl = makeLazyClass(classMirror, null, null, isNativeHeaderMember); setNonLazyDeclarationProperties(decl, classMirror, classMirror, classMirror, isCeylon); if (isCeylon && shouldCreateNativeHeader(decl, container)) { hdr = makeLazyClass(classMirror, null, null, true); setNonLazyDeclarationProperties(hdr, classMirror, classMirror, classMirror, true); } } if (!isCeylon) { setSealedFromConstructorMods(decl, constructors); } } break; case INTERFACE: boolean isAlias = classMirror.getAnnotation(CEYLON_ALIAS_ANNOTATION) != null; if(isAlias){ decl = makeInterfaceAlias(classMirror); }else{ decl = makeLazyInterface(classMirror, isNativeHeaderMember); } setNonLazyDeclarationProperties(decl, classMirror, classMirror, classMirror, isCeylon); if (!isAlias && isCeylon && shouldCreateNativeHeader(decl, container)) { hdr = makeLazyInterface(classMirror, true); setNonLazyDeclarationProperties(hdr, classMirror, classMirror, classMirror, true); } break; } }catch(ModelResolutionException x){ // FIXME: this may not be the best thing to do, perhaps we should have an erroneous Class,Interface,Function // etc, like javac's model does? decl = logModelResolutionException(x, null, "Failed to load declaration "+classMirror).getDeclaration(); } // objects have special handling above if(type != ClassType.OBJECT){ decls.add(decl); if (hdr != null) { decls.add(initNativeHeader(hdr, decl)); } } return decl; } private ClassType getClassType(ClassMirror classMirror) { ClassType type; if(classMirror.isCeylonToplevelAttribute()){ type = ClassType.ATTRIBUTE; }else if(classMirror.isCeylonToplevelMethod()){ type = ClassType.METHOD; }else if(classMirror.isCeylonToplevelObject()){ type = ClassType.OBJECT; }else if(classMirror.isInterface()){ type = ClassType.INTERFACE; }else{ type = ClassType.CLASS; } return type; } private boolean shouldCreateNativeHeader(Declaration decl, Declaration container) { // TODO instead of checking for "shared" we should add an annotation // to all declarations that have a native header and check that here if (decl.isNativeImplementation() && decl.isShared()) { if (container != null) { if (!decl.isOverloaded()) { return !container.isNative(); } } else { return true; } } return false; } private boolean shouldLinkNatives(Declaration decl) { // TODO instead of checking for "shared" we should add an annotation // to all declarations that have a native header and check that here if (decl.isNative() && decl.isShared()) { Declaration container = (Declaration)decl.getContainer(); return container.isNativeHeader(); } return false; } private Declaration initNativeHeader(Declaration hdr, Declaration impl) { List<Declaration> al = getOverloads(hdr); if (al == null) { al = new ArrayList<Declaration>(1); } al.add(impl); setOverloads(hdr, al); return hdr; } private void initNativeHeaderMember(Declaration hdr) { Declaration impl = ModelUtil.getNativeDeclaration(hdr, Backend.Java); initNativeHeader(hdr, impl); } /** Returns: * <ul> * <li>true if the class has named constructors ({@code @Class(...constructors=true)}).</li> * <li>false if the class has an initializer constructor.</li> * <li>null if the class lacks {@code @Class} (i.e. is not a Ceylon class).</li> * </ul> * @param classMirror * @return */ private Boolean hasConstructors(ClassMirror classMirror) { AnnotationMirror a = classMirror.getAnnotation(CEYLON_CLASS_ANNOTATION); Boolean hasConstructors; if (a != null) { hasConstructors = (Boolean)a.getValue("constructors"); if (hasConstructors == null) { hasConstructors = false; } } else { hasConstructors = null; } return hasConstructors; } private boolean isDefaultNamedCtor(ClassMirror classMirror, MethodMirror ctor) { return classMirror.getName().equals(getCtorName(ctor)); } private String getCtorName(MethodMirror ctor) { AnnotationMirror nameAnno = ctor.getAnnotation(CEYLON_NAME_ANNOTATION); if (nameAnno != null) { return (String)nameAnno.getValue(); } else { return null; } } private void setSealedFromConstructorMods(Declaration decl, final List<MethodMirror> constructors) { boolean effectivelySealed = true; for (MethodMirror ctor : constructors) { if (ctor.isPublic() || ctor.isProtected()) { effectivelySealed = false; break; } } if (effectivelySealed && decl instanceof Class) { Class type = (Class)decl; type.setSealed(effectivelySealed); if (type.getOverloads() != null) { for (Declaration oload : type.getOverloads()) { ((Class)oload).setSealed(effectivelySealed); } } } } private Declaration makeOverloadedConstructor(List<MethodMirror> constructors, ClassMirror classMirror, List<Declaration> decls, boolean isCeylon) { // If the class has multiple constructors we make a copy of the class // for each one (each with it's own single constructor) and make them // a subclass of the original Class supercls = makeLazyClass(classMirror, null, null, false); // the abstraction class gets the class modifiers setNonLazyDeclarationProperties(supercls, classMirror, classMirror, classMirror, isCeylon); supercls.setAbstraction(true); List<Declaration> overloads = new ArrayList<Declaration>(constructors.size()); // all filtering is done in getClassConstructors for (MethodMirror constructor : constructors) { LazyClass subdecl = makeLazyClass(classMirror, supercls, constructor, false); // the subclasses class get the constructor modifiers setNonLazyDeclarationProperties(subdecl, constructor, constructor, classMirror, isCeylon); subdecl.setOverloaded(true); overloads.add(subdecl); decls.add(subdecl); } supercls.setOverloads(overloads); return supercls; } private void setNonLazyDeclarationProperties(Declaration decl, AccessibleMirror mirror, AnnotatedMirror annotatedMirror, ClassMirror classMirror, boolean isCeylon) { if(isCeylon){ // when we're in a local type somewhere we must turn public declarations into package or protected ones, so // we have to check the shared annotation decl.setShared(mirror.isPublic() || annotatedMirror.getAnnotation(CEYLON_LANGUAGE_SHARED_ANNOTATION) != null); setDeclarationAliases(decl, annotatedMirror); }else{ decl.setShared(mirror.isPublic() || (mirror.isDefaultAccess() && classMirror.isInnerClass()) || mirror.isProtected()); decl.setPackageVisibility(mirror.isDefaultAccess()); decl.setProtectedVisibility(mirror.isProtected()); } decl.setDeprecated(isDeprecated(annotatedMirror)); } private enum JavaVisibility { PRIVATE, PACKAGE, PROTECTED, PUBLIC; } private JavaVisibility getJavaVisibility(AccessibleMirror mirror) { if(mirror.isPublic()) return JavaVisibility.PUBLIC; if(mirror.isProtected()) return JavaVisibility.PROTECTED; if(mirror.isDefaultAccess()) return JavaVisibility.PACKAGE; return JavaVisibility.PRIVATE; } protected Declaration makeClassAlias(ClassMirror classMirror) { return new LazyClassAlias(classMirror, this); } protected Declaration makeTypeAlias(ClassMirror classMirror) { return new LazyTypeAlias(classMirror, this); } protected Declaration makeInterfaceAlias(ClassMirror classMirror) { return new LazyInterfaceAlias(classMirror, this); } private void checkBinaryCompatibility(ClassMirror classMirror) { // let's not report it twice if(binaryCompatibilityErrorRaised) return; AnnotationMirror annotation = classMirror.getAnnotation(CEYLON_CEYLON_ANNOTATION); if(annotation == null) return; // Java class, no check Integer major = (Integer) annotation.getValue("major"); if(major == null) major = 0; Integer minor = (Integer) annotation.getValue("minor"); if(minor == null) minor = 0; if(!Versions.isJvmBinaryVersionSupported(major.intValue(), minor.intValue())){ logError("Ceylon class " + classMirror.getQualifiedName() + " was compiled by an incompatible version of the Ceylon compiler" +"\nThe class was compiled using "+major+"."+minor+"." +"\nThis compiler supports "+Versions.JVM_BINARY_MAJOR_VERSION+"."+Versions.JVM_BINARY_MINOR_VERSION+"." +"\nPlease try to recompile your module using a compatible compiler." +"\nBinary compatibility will only be supported after Ceylon 1.2."); binaryCompatibilityErrorRaised = true; } } interface MethodMirrorFilter { boolean accept(MethodMirror methodMirror); } MethodMirrorFilter constructorOnly = new MethodMirrorFilter() { @Override public boolean accept(MethodMirror methodMirror) { return methodMirror.isConstructor(); } }; class ValueConstructorGetter implements MethodMirrorFilter{ private ClassMirror classMirror; ValueConstructorGetter(ClassMirror classMirror) { this.classMirror = classMirror; } @Override public boolean accept(MethodMirror methodMirror) { return (!methodMirror.isConstructor() && methodMirror.getAnnotation(CEYLON_ENUMERATED_ANNOTATION) != null && methodMirror.getReturnType().getDeclaredClass().toString().equals(classMirror.toString())); } }; private void setHasJpaConstructor(LazyClass c, ClassMirror classMirror) { for(MethodMirror methodMirror : classMirror.getDirectMethods()){ if (methodMirror.isConstructor() && methodMirror.getAnnotation(CEYLON_JPA_ANNOTATION) != null) { c.setHasJpaConstructor(true); break; } } } private List<MethodMirror> getClassConstructors(ClassMirror classMirror, MethodMirrorFilter p) { LinkedList<MethodMirror> constructors = new LinkedList<MethodMirror>(); boolean isFromJDK = isFromJDK(classMirror); for(MethodMirror methodMirror : classMirror.getDirectMethods()){ // We skip members marked with @Ignore, unless they value constructor getters if(methodMirror.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null &&methodMirror.getAnnotation(CEYLON_ENUMERATED_ANNOTATION) == null) continue; if (!p.accept(methodMirror)) continue; // FIXME: tmp hack to skip constructors that have type params as we don't handle them yet if(!methodMirror.getTypeParameters().isEmpty()) continue; // FIXME: temporary, because some private classes from the jdk are // referenced in private methods but not available if(isFromJDK && !methodMirror.isPublic() // allow protected because we can subclass them, but not package-private because we can't define // classes in the jdk packages && !methodMirror.isProtected()) continue; // if we are expecting Ceylon code, check that we have enough reified type parameters if(classMirror.getAnnotation(AbstractModelLoader.CEYLON_CEYLON_ANNOTATION) != null){ List<AnnotationMirror> tpAnnotations = getTypeParametersFromAnnotations(classMirror); int tpCount = tpAnnotations != null ? tpAnnotations.size() : classMirror.getTypeParameters().size(); if(!checkReifiedTypeDescriptors(tpCount, classMirror.getQualifiedName(), methodMirror, true)) continue; } constructors.add(methodMirror); } return constructors; } private boolean checkReifiedTypeDescriptors(int tpCount, String containerName, MethodMirror methodMirror, boolean isConstructor) { List<VariableMirror> params = methodMirror.getParameters(); int actualTypeDescriptorParameters = 0; for(VariableMirror param : params){ if(param.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null && sameType(CEYLON_TYPE_DESCRIPTOR_TYPE, param.getType())){ actualTypeDescriptorParameters++; }else break; } if(tpCount != actualTypeDescriptorParameters){ if(isConstructor) logError("Constructor for '"+containerName+"' should take "+tpCount +" reified type arguments (TypeDescriptor) but has '"+actualTypeDescriptorParameters+"': skipping constructor."); else logError("Function '"+containerName+"."+methodMirror.getName()+"' should take "+tpCount +" reified type arguments (TypeDescriptor) but has '"+actualTypeDescriptorParameters+"': method is invalid."); return false; } return true; } protected Unit getCompiledUnit(LazyPackage pkg, ClassMirror classMirror) { Unit unit = unitsByPackage.get(pkg); if(unit == null){ unit = new Unit(); unit.setPackage(pkg); unitsByPackage.put(pkg, unit); } return unit; } protected LazyValue makeToplevelAttribute(ClassMirror classMirror, boolean isNativeHeader) { LazyValue value = new LazyValue(classMirror, this); AnnotationMirror objectAnnotation = classMirror.getAnnotation(CEYLON_OBJECT_ANNOTATION); if(objectAnnotation == null) { manageNativeBackend(value, classMirror, isNativeHeader); } else { manageNativeBackend(value, getGetterMethodMirror(value, value.classMirror, true), isNativeHeader); } return value; } protected LazyFunction makeToplevelMethod(ClassMirror classMirror, boolean isNativeHeader) { LazyFunction method = new LazyFunction(classMirror, this); manageNativeBackend(method, getFunctionMethodMirror(method), isNativeHeader); return method; } protected LazyClass makeLazyClass(ClassMirror classMirror, Class superClass, MethodMirror initOrDefaultConstructor, boolean isNativeHeader) { LazyClass klass = new LazyClass(classMirror, this, superClass, initOrDefaultConstructor); AnnotationMirror objectAnnotation = classMirror.getAnnotation(CEYLON_OBJECT_ANNOTATION); if(objectAnnotation != null){ klass.setAnonymous(true); // isFalse will only consider non-null arguments, and we default to true if null if(BooleanUtil.isFalse((Boolean) objectAnnotation.getValue("named"))) klass.setNamed(false); } klass.setAnnotation(classMirror.getAnnotation(CEYLON_LANGUAGE_ANNOTATION_ANNOTATION) != null); if(klass.isCeylon()) klass.setAbstract(classMirror.getAnnotation(CEYLON_LANGUAGE_ABSTRACT_ANNOTATION) != null // for toplevel classes if the annotation is missing we respect the java abstract modifier // for member classes that would be ambiguous between formal and abstract so we don't and require // the model annotation || (!classMirror.isInnerClass() && !classMirror.isLocalClass() && classMirror.isAbstract())); else klass.setAbstract(classMirror.isAbstract()); klass.setFormal(classMirror.getAnnotation(CEYLON_LANGUAGE_FORMAL_ANNOTATION) != null); klass.setDefault(classMirror.getAnnotation(CEYLON_LANGUAGE_DEFAULT_ANNOTATION) != null); klass.setSerializable(classMirror.getAnnotation(CEYLON_LANGUAGE_SERIALIZABLE_ANNOTATION) != null || classMirror.getQualifiedName().equals("ceylon.language.Array") || classMirror.getQualifiedName().equals("ceylon.language.Tuple")); // hack to make Throwable sealed until ceylon/ceylon.language#408 is fixed klass.setSealed(classMirror.getAnnotation(CEYLON_LANGUAGE_SEALED_ANNOTATION) != null || CEYLON_LANGUAGE.equals(classMirror.getPackage().getQualifiedName()) && "Throwable".equals(classMirror.getName())); boolean actual = classMirror.getAnnotation(CEYLON_LANGUAGE_ACTUAL_ANNOTATION) != null; klass.setActual(actual); klass.setActualCompleter(this); klass.setFinal(classMirror.isFinal()); klass.setStaticallyImportable(!klass.isCeylon() && classMirror.isStatic()); if(objectAnnotation == null) { manageNativeBackend(klass, classMirror, isNativeHeader); } else { manageNativeBackend(klass, getGetterMethodMirror(klass, klass.classMirror, true), isNativeHeader); } return klass; } protected LazyInterface makeLazyInterface(ClassMirror classMirror, boolean isNativeHeader) { LazyInterface iface = new LazyInterface(classMirror, this); iface.setSealed(classMirror.getAnnotation(CEYLON_LANGUAGE_SEALED_ANNOTATION) != null); iface.setDynamic(classMirror.getAnnotation(CEYLON_DYNAMIC_ANNOTATION) != null); iface.setStaticallyImportable(!iface.isCeylon()); manageNativeBackend(iface, classMirror, isNativeHeader); return iface; } public Declaration convertToDeclaration(Module module, String typeName, DeclarationType declarationType) { return convertToDeclaration(module, null, typeName, declarationType); } private Declaration convertToDeclaration(Module module, Declaration container, String typeName, DeclarationType declarationType) { synchronized(getLock()){ // FIXME: this needs to move to the type parser and report warnings //This should be done where the TypeInfo annotation is parsed //to avoid retarded errors because of a space after a comma typeName = typeName.trim(); timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY); try{ if ("ceylon.language.Nothing".equals(typeName)) { return typeFactory.getNothingDeclaration(); } else if ("java.lang.Throwable".equals(typeName)) { // FIXME: this being here is highly dubious return convertToDeclaration(modules.getLanguageModule(), "ceylon.language.Throwable", declarationType); } else if ("java.lang.Exception".equals(typeName)) { // FIXME: this being here is highly dubious return convertToDeclaration(modules.getLanguageModule(), "ceylon.language.Exception", declarationType); } else if ("java.lang.Annotation".equals(typeName)) { // FIXME: this being here is highly dubious // here we prefer Annotation over ConstrainedAnnotation but that's fine return convertToDeclaration(modules.getLanguageModule(), "ceylon.language.Annotation", declarationType); } ClassMirror classMirror; try{ classMirror = lookupClassMirror(module, typeName); }catch(NoClassDefFoundError x){ // FIXME: this may not be the best thing to do. If the class is not there we don't know what type of declaration // to return, but perhaps if we use annotation scanner rather than reflection we can figure it out, at least // in cases where the supertype is missing, which throws in reflection at class load. return logModelResolutionException(x.getMessage(), module, "Unable to load type "+typeName).getDeclaration(); } if (classMirror == null) { // special case when bootstrapping because we may need to pull the decl from the typechecked model if(isBootstrap && typeName.startsWith(CEYLON_LANGUAGE+".")){ Declaration languageDeclaration = findLanguageModuleDeclarationForBootstrap(typeName); if(languageDeclaration != null) return languageDeclaration; } throw new ModelResolutionException("Failed to resolve "+typeName); } // we only allow source loading when it's java code we're compiling in the same go // (well, technically before the ceylon code) if(classMirror.isLoadedFromSource() && !classMirror.isJavaSource()) return null; return convertToDeclaration(module, container, classMirror, declarationType); }finally{ timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY); } } } private Type newUnknownType() { return new UnknownType(typeFactory).getType(); } protected TypeParameter safeLookupTypeParameter(Scope scope, String name) { TypeParameter param = lookupTypeParameter(scope, name); if(param == null) throw new ModelResolutionException("Type param "+name+" not found in "+scope); return param; } private TypeParameter lookupTypeParameter(Scope scope, String name) { if(scope instanceof Function){ Function m = (Function) scope; for(TypeParameter param : m.getTypeParameters()){ if(param.getName().equals(name)) return param; } if (!m.isToplevel()) { // look it up in its container return lookupTypeParameter(scope.getContainer(), name); } else { // not found return null; } }else if(scope instanceof ClassOrInterface || scope instanceof TypeAlias){ TypeDeclaration decl = (TypeDeclaration) scope; for(TypeParameter param : decl.getTypeParameters()){ if(param.getName().equals(name)) return param; } if (!decl.isToplevel()) { // look it up in its container return lookupTypeParameter(scope.getContainer(), name); } else { // not found return null; } }else if (scope instanceof Constructor) { return lookupTypeParameter(scope.getContainer(), name); }else if(scope instanceof Value || scope instanceof Setter){ Declaration decl = (Declaration) scope; if (!decl.isToplevel()) { // look it up in its container return lookupTypeParameter(scope.getContainer(), name); } else { // not found return null; } }else throw new ModelResolutionException("Type param "+name+" lookup not supported for scope "+scope); } // // Packages public LazyPackage findExistingPackage(Module module, String pkgName) { synchronized(getLock()){ String quotedPkgName = JVMModuleUtil.quoteJavaKeywords(pkgName); LazyPackage pkg = findCachedPackage(module, quotedPkgName); if(pkg != null) return pkg; // special case for the jdk module String moduleName = module.getNameAsString(); if(AbstractModelLoader.isJDKModule(moduleName)){ if(JDKUtils.isJDKPackage(moduleName, pkgName) || JDKUtils.isOracleJDKPackage(moduleName, pkgName)){ return findOrCreatePackage(module, pkgName); } return null; } // only create it if it exists if(((LazyModule)module).containsPackage(pkgName) && loadPackage(module, pkgName, false)){ return findOrCreatePackage(module, pkgName); } return null; } } private LazyPackage findCachedPackage(Module module, String quotedPkgName) { LazyPackage pkg = packagesByName.get(cacheKeyByModule(module, quotedPkgName)); if(pkg != null){ // only return it if it matches the module we're looking for, because if it doesn't we have an issue already logged // for a direct dependency on same module different versions logged, so no need to confuse this further if(module != null && pkg.getModule() != null && !module.equals(pkg.getModule())) return null; return pkg; } return null; } public LazyPackage findOrCreatePackage(Module module, final String pkgName) { synchronized(getLock()){ String quotedPkgName = JVMModuleUtil.quoteJavaKeywords(pkgName); LazyPackage pkg = findCachedPackage(module, quotedPkgName); if(pkg != null) return pkg; // try to find it from the module, perhaps it already got created and we didn't catch it if(module instanceof LazyModule){ pkg = (LazyPackage) ((LazyModule) module).findPackageNoLazyLoading(pkgName); }else if(module != null){ pkg = (LazyPackage) module.getDirectPackage(pkgName); } boolean isNew = pkg == null; if(pkg == null){ pkg = new LazyPackage(this); // FIXME: some refactoring needed pkg.setName(Arrays.asList(pkgName.split("\\."))); } packagesByName.put(cacheKeyByModule(module, quotedPkgName), pkg); // only bind it if we already have a module if(isNew && module != null){ pkg.setModule(module); if(module instanceof LazyModule) ((LazyModule) module).addPackage(pkg); else module.getPackages().add(pkg); } // only load package descriptors for new packages after a certain phase if(packageDescriptorsNeedLoading) loadPackageDescriptor(pkg); return pkg; } } public void loadPackageDescriptors() { synchronized(getLock()){ for(Package pkg : packagesByName.values()){ loadPackageDescriptor(pkg); } packageDescriptorsNeedLoading = true; } } private void loadPackageDescriptor(Package pkg) { // Don't try to load a package descriptor for ceylon.language // if we're bootstrapping if (isBootstrap && pkg.getQualifiedNameString().startsWith(CEYLON_LANGUAGE)) { return; } // let's not load package descriptors for Java modules if(pkg.getModule() != null && ((LazyModule)pkg.getModule()).isJava()){ pkg.setShared(true); return; } String quotedQualifiedName = JVMModuleUtil.quoteJavaKeywords(pkg.getQualifiedNameString()); // FIXME: not sure the toplevel package can have a package declaration String className = quotedQualifiedName.isEmpty() ? NamingBase.PACKAGE_DESCRIPTOR_CLASS_NAME : quotedQualifiedName + "." + NamingBase.PACKAGE_DESCRIPTOR_CLASS_NAME; logVerbose("[Trying to look up package from "+className+"]"); Module module = pkg.getModule(); if(module == null) throw new RuntimeException("Assertion failed: module is null for package "+pkg.getNameAsString()); ClassMirror packageClass = loadClass(module, quotedQualifiedName, className); if(packageClass == null){ logVerbose("[Failed to complete "+className+"]"); // missing: leave it private return; } // did we compile it from source or class? if(packageClass.isLoadedFromSource()){ // must have come from source, in which case we walked it and // loaded its values already logVerbose("[We are compiling the package "+className+"]"); return; } loadCompiledPackage(packageClass, pkg); } private void loadCompiledPackage(ClassMirror packageClass, Package pkg) { String name = getAnnotationStringValue(packageClass, CEYLON_PACKAGE_ANNOTATION, "name"); Boolean shared = getAnnotationBooleanValue(packageClass, CEYLON_PACKAGE_ANNOTATION, "shared"); // FIXME: validate the name? if(name == null || name.isEmpty()){ logWarning("Package class "+pkg.getQualifiedNameString()+" contains no name, ignoring it"); return; } if(shared == null){ logWarning("Package class "+pkg.getQualifiedNameString()+" contains no shared, ignoring it"); return; } pkg.setShared(shared); } public Module lookupModuleByPackageName(String packageName) { for(Module module : modules.getListOfModules()){ // don't try the default module because it will always say yes if(module.isDefault()) continue; // skip modules we're not loading things from if(!ModelUtil.equalModules(module,getLanguageModule()) && !isModuleInClassPath(module)) continue; if(module instanceof LazyModule){ if(((LazyModule)module).containsPackage(packageName)) return module; }else if(isSubPackage(module.getNameAsString(), packageName)){ return module; } } if(JDKUtils.isJDKAnyPackage(packageName) || JDKUtils.isOracleJDKAnyPackage(packageName)){ String moduleName = JDKUtils.getJDKModuleNameForPackage(packageName); return findModule(moduleName, JDKUtils.jdk.version); } if(packageName.startsWith("com.redhat.ceylon.compiler.java.runtime") || packageName.startsWith("com.redhat.ceylon.compiler.java.language") || packageName.startsWith("com.redhat.ceylon.compiler.java.metadata")){ return getLanguageModule(); } return modules.getDefaultModule(); } private boolean isSubPackage(String moduleName, String pkgName) { return pkgName.equals(moduleName) || pkgName.startsWith(moduleName+"."); } // // Modules /** * Finds or creates a new module. This is mostly useful to force creation of modules such as jdk * or ceylon.language modules. */ protected Module findOrCreateModule(String moduleName, String version) { synchronized(getLock()){ boolean isJdk = false; boolean defaultModule = false; // make sure it isn't loaded Module module = getLoadedModule(moduleName, version); if(module != null) return module; if(JDKUtils.isJDKModule(moduleName) || JDKUtils.isOracleJDKModule(moduleName)){ isJdk = true; } java.util.List<String> moduleNameList = Arrays.asList(moduleName.split("\\.")); module = moduleManager.getOrCreateModule(moduleNameList, version); // make sure that when we load the ceylon language module we set it to where // the typechecker will look for it if(moduleName.equals(CEYLON_LANGUAGE) && modules.getLanguageModule() == null){ modules.setLanguageModule(module); } // TRICKY We do this only when isJava is true to prevent resetting // the value to false by mistake. LazyModule get's created with // this attribute to false by default, so it should work if (isJdk && module instanceof LazyModule) { ((LazyModule)module).setJava(true); module.setNativeBackends(Backend.Java.asSet()); } // FIXME: this can't be that easy. if(isJdk) module.setAvailable(true); module.setDefault(defaultModule); return module; } } public boolean loadCompiledModule(Module module) { synchronized(getLock()){ if(module.isDefault()) return false; String pkgName = module.getNameAsString(); if(pkgName.isEmpty()) return false; String moduleClassName = pkgName + "." + NamingBase.MODULE_DESCRIPTOR_CLASS_NAME; logVerbose("[Trying to look up module from "+moduleClassName+"]"); ClassMirror moduleClass = loadClass(module, pkgName, moduleClassName); if(moduleClass == null){ // perhaps we have an old module? String oldModuleClassName = pkgName + "." + NamingBase.OLD_MODULE_DESCRIPTOR_CLASS_NAME; logVerbose("[Trying to look up older module descriptor from "+oldModuleClassName+"]"); ClassMirror oldModuleClass = loadClass(module, pkgName, oldModuleClassName); // keep it only if it has a module annotation, otherwise it could be a normal value if(oldModuleClass != null && oldModuleClass.getAnnotation(CEYLON_MODULE_ANNOTATION) != null) moduleClass = oldModuleClass; } if(moduleClass != null){ // load its module annotation return loadCompiledModule(module, moduleClass, moduleClassName); } // give up return false; } } private boolean loadCompiledModule(Module module, ClassMirror moduleClass, String moduleClassName) { String name = getAnnotationStringValue(moduleClass, CEYLON_MODULE_ANNOTATION, "name"); String version = getAnnotationStringValue(moduleClass, CEYLON_MODULE_ANNOTATION, "version"); if(name == null || name.isEmpty()){ logWarning("Module class "+moduleClassName+" contains no name, ignoring it"); return false; } if(!name.equals(module.getNameAsString())){ logWarning("Module class "+moduleClassName+" declares an invalid name: "+name+". It should be: "+module.getNameAsString()); return false; } if(version == null || version.isEmpty()){ logWarning("Module class "+moduleClassName+" contains no version, ignoring it"); return false; } if(!version.equals(module.getVersion())){ logWarning("Module class "+moduleClassName+" declares an invalid version: "+version+". It should be: "+module.getVersion()); return false; } int major = getAnnotationIntegerValue(moduleClass, CEYLON_CEYLON_ANNOTATION, "major", 0); int minor = getAnnotationIntegerValue(moduleClass, CEYLON_CEYLON_ANNOTATION, "minor", 0); module.setMajor(major); module.setMinor(minor); // no need to load the "nativeBackends" annotation value, it's loaded from annotations setAnnotations(module, moduleClass, false); List<AnnotationMirror> imports = getAnnotationArrayValue(moduleClass, CEYLON_MODULE_ANNOTATION, "dependencies"); if(imports != null){ for (AnnotationMirror importAttribute : imports) { String dependencyName = (String) importAttribute.getValue("name"); if (dependencyName != null) { String dependencyVersion = (String) importAttribute.getValue("version"); Module dependency = moduleManager.getOrCreateModule(ModuleManager.splitModuleName(dependencyName), dependencyVersion); Boolean optionalVal = (Boolean) importAttribute.getValue("optional"); Boolean exportVal = (Boolean) importAttribute.getValue("export"); List<String> nativeBackends = (List<String>) importAttribute.getValue("nativeBackends"); Backends backends = nativeBackends == null ? Backends.ANY : Backends.fromAnnotations(nativeBackends); ModuleImport moduleImport = moduleManager.findImport(module, dependency); if (moduleImport == null) { boolean optional = optionalVal != null && optionalVal; boolean export = exportVal != null && exportVal; moduleImport = new ModuleImport(dependency, optional, export, backends); module.addImport(moduleImport); } } } } module.setAvailable(true); modules.getListOfModules().add(module); Module languageModule = modules.getLanguageModule(); module.setLanguageModule(languageModule); if(!ModelUtil.equalModules(module, languageModule)){ ModuleImport moduleImport = moduleManager.findImport(module, languageModule); if (moduleImport == null) { moduleImport = new ModuleImport(languageModule, false, false); module.addImport(moduleImport); } } return true; } // // Utils for loading type info from the model @SuppressWarnings("unchecked") private <T> List<T> getAnnotationArrayValue(AnnotatedMirror mirror, String type, String field) { return (List<T>) getAnnotationValue(mirror, type, field); } @SuppressWarnings("unchecked") private <T> List<T> getAnnotationArrayValue(AnnotatedMirror mirror, String type) { return (List<T>) getAnnotationValue(mirror, type); } private String getAnnotationStringValue(AnnotatedMirror mirror, String type) { return getAnnotationStringValue(mirror, type, "value"); } private String getAnnotationStringValue(AnnotatedMirror mirror, String type, String field) { return (String) getAnnotationValue(mirror, type, field); } private Boolean getAnnotationBooleanValue(AnnotatedMirror mirror, String type, String field) { return (Boolean) getAnnotationValue(mirror, type, field); } private int getAnnotationIntegerValue(AnnotatedMirror mirror, String type, String field, int defaultValue) { Integer val = (Integer) getAnnotationValue(mirror, type, field); return val != null ? val : defaultValue; } @SuppressWarnings("unchecked") private List<String> getAnnotationStringValues(AnnotationMirror annotation, String field) { return (List<String>)annotation.getValue(field); } private Object getAnnotationValue(AnnotatedMirror mirror, String type) { return getAnnotationValue(mirror, type, "value"); } private Object getAnnotationValue(AnnotatedMirror mirror, String type, String fieldName) { AnnotationMirror annotation = mirror.getAnnotation(type); if(annotation != null){ return annotation.getValue(fieldName); } return null; } // // ModelCompleter @Override public void complete(LazyInterface iface) { synchronized(getLock()){ timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY); complete(iface, iface.classMirror); timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY); } } @Override public void completeTypeParameters(LazyInterface iface) { synchronized(getLock()){ timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY); completeTypeParameters(iface, iface.classMirror); timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY); } } @Override public void complete(LazyClass klass) { synchronized(getLock()){ timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY); complete(klass, klass.classMirror); timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY); } } @Override public void completeTypeParameters(LazyClass klass) { synchronized(getLock()){ timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY); completeTypeParameters(klass, klass.classMirror); timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY); } } @Override public void completeTypeParameters(LazyClassAlias lazyClassAlias) { synchronized(getLock()){ timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY); completeLazyAliasTypeParameters(lazyClassAlias, lazyClassAlias.classMirror); timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY); } } @Override public void completeTypeParameters(LazyInterfaceAlias lazyInterfaceAlias) { synchronized(getLock()){ timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY); completeLazyAliasTypeParameters(lazyInterfaceAlias, lazyInterfaceAlias.classMirror); timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY); } } @Override public void completeTypeParameters(LazyTypeAlias lazyTypeAlias) { synchronized(getLock()){ timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY); completeLazyAliasTypeParameters(lazyTypeAlias, lazyTypeAlias.classMirror); timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY); } } @Override public void complete(LazyInterfaceAlias alias) { synchronized(getLock()){ timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY); completeLazyAlias(alias, alias.classMirror, CEYLON_ALIAS_ANNOTATION); timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY); } } @Override public void complete(LazyClassAlias alias) { synchronized(getLock()){ timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY); completeLazyAlias(alias, alias.classMirror, CEYLON_ALIAS_ANNOTATION); String constructorName = (String)alias.classMirror.getAnnotation(CEYLON_ALIAS_ANNOTATION).getValue("constructor"); if (constructorName != null && !constructorName.isEmpty()) { Declaration constructor = alias.getExtendedType().getDeclaration().getMember(constructorName, null, false); if (constructor instanceof FunctionOrValue && ((FunctionOrValue)constructor).getTypeDeclaration() instanceof Constructor) { alias.setConstructor(((FunctionOrValue)constructor).getTypeDeclaration()); } else { logError("class aliased constructor " + constructorName + " which is no longer a constructor of " + alias.getExtendedType().getDeclaration().getQualifiedNameString()); } } // Find the instantiator method MethodMirror instantiator = null; ClassMirror instantiatorClass = alias.isToplevel() ? alias.classMirror : alias.classMirror.getEnclosingClass(); String aliasName = NamingBase.getAliasInstantiatorMethodName(alias); for (MethodMirror method : instantiatorClass.getDirectMethods()) { if (method.getName().equals(aliasName)) { instantiator = method; break; } } // Read the parameters from the instantiator, rather than the aliased class if (instantiator != null) { setParameters(alias, alias.classMirror, instantiator, true, alias); } timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY); } } @Override public void complete(LazyTypeAlias alias) { synchronized(getLock()){ timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY); completeLazyAlias(alias, alias.classMirror, CEYLON_TYPE_ALIAS_ANNOTATION); timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY); } } private void completeLazyAliasTypeParameters(TypeDeclaration alias, ClassMirror mirror) { // type parameters setTypeParameters(alias, mirror, true); } private void completeLazyAlias(TypeDeclaration alias, ClassMirror mirror, String aliasAnnotationName) { // now resolve the extended type AnnotationMirror aliasAnnotation = mirror.getAnnotation(aliasAnnotationName); String extendedTypeString = (String) aliasAnnotation.getValue(); Type extendedType = decodeType(extendedTypeString, alias, ModelUtil.getModuleContainer(alias), "alias target"); alias.setExtendedType(extendedType); } private void completeTypeParameters(ClassOrInterface klass, ClassMirror classMirror) { boolean isCeylon = classMirror.getAnnotation(CEYLON_CEYLON_ANNOTATION) != null; setTypeParameters(klass, classMirror, isCeylon); } private void complete(ClassOrInterface klass, ClassMirror classMirror) { boolean isFromJDK = isFromJDK(classMirror); boolean isCeylon = (classMirror.getAnnotation(CEYLON_CEYLON_ANNOTATION) != null); // now that everything has containers, do the inner classes if(klass instanceof Class == false || !((Class)klass).isOverloaded()){ // this will not load inner classes of overloads, but that's fine since we want them in the // abstracted super class (the real one) addInnerClasses(klass, classMirror); } // Java classes with multiple constructors get turned into multiple Ceylon classes // Here we get the specific constructor that was assigned to us (if any) MethodMirror constructor = null; if (klass instanceof LazyClass) { constructor = ((LazyClass)klass).getConstructor(); setHasJpaConstructor((LazyClass)klass, classMirror); } // Set up enumerated constructors before looking at getters, // because the type of the getter is the constructor's type Boolean hasConstructors = hasConstructors(classMirror); if (hasConstructors != null && hasConstructors) { HashMap<String, MethodMirror> m = new HashMap<>(); // Get all the java constructors... for (MethodMirror ctorMirror : getClassConstructors(classMirror, constructorOnly)) { m.put(getCtorName(ctorMirror), ctorMirror); } for (MethodMirror ctor : getClassConstructors(classMirror.getEnclosingClass() != null ? classMirror.getEnclosingClass() : classMirror, new ValueConstructorGetter(classMirror))) { Object name = getAnnotationValue(ctor, CEYLON_NAME_ANNOTATION); MethodMirror ctorMirror = m.remove(name); Constructor c; // When for each value constructor getter we can add a Value+Constructor if (ctorMirror == null) { // Only add a Constructor using the getter if we couldn't find a matching java constructor c = addConstructor((Class)klass, classMirror, ctor, false); } else { c = addConstructor((Class)klass, classMirror, ctorMirror, false); } addConstructorMethorOrValue((Class)klass, classMirror, ctor, c, false); if (isCeylon && shouldCreateNativeHeader(c, klass)) { Constructor hdr; if (ctorMirror == null) { hdr = addConstructor((Class)klass, classMirror, ctor, true); } else { hdr = addConstructor((Class)klass, classMirror, ctorMirror, true); } addConstructorMethorOrValue((Class)klass, classMirror, ctorMirror, hdr, true); initNativeHeader(hdr, c); } else if (isCeylon && shouldLinkNatives(c)) { initNativeHeaderMember(c); } } // Everything left must be a callable constructor, so add Function+Constructor for (MethodMirror ctorMirror : m.values()) { Constructor c = addConstructor((Class)klass, classMirror, ctorMirror, false); addConstructorMethorOrValue((Class)klass, classMirror, ctorMirror, c, false); if (isCeylon && shouldCreateNativeHeader(c, klass)) { Constructor hdr = addConstructor((Class)klass, classMirror, ctorMirror, true); addConstructorMethorOrValue((Class)klass, classMirror, ctorMirror, hdr, true); initNativeHeader(hdr, c); } else if (isCeylon && shouldLinkNatives(c)) { initNativeHeaderMember(c); } } } // Turn a list of possibly overloaded methods into a map // of lists that contain methods with the same name Map<String, List<MethodMirror>> methods = new LinkedHashMap<String, List<MethodMirror>>(); collectMethods(classMirror.getDirectMethods(), methods, isCeylon, isFromJDK); if(isCeylon && klass instanceof LazyInterface && JvmBackendUtil.isCompanionClassNeeded(klass)){ ClassMirror companionClass = ((LazyInterface)klass).companionClass; if(companionClass != null) collectMethods(companionClass.getDirectMethods(), methods, isCeylon, isFromJDK); else logWarning("CompanionClass missing for "+klass); } boolean seenStringAttribute = false; boolean seenHashAttribute = false; boolean seenStringGetter = false; boolean seenHashGetter = false; MethodMirror stringSetter = null; MethodMirror hashSetter = null; Map<String, List<MethodMirror>> getters = new HashMap<>(); Map<String, List<MethodMirror>> setters = new HashMap<>(); // Collect attributes for(List<MethodMirror> methodMirrors : methods.values()){ for (MethodMirror methodMirror : methodMirrors) { // same tests as in isMethodOverloaded() if(methodMirror.isConstructor() || isInstantiator(methodMirror)) { break; } else if(isGetter(methodMirror)) { String name = getJavaAttributeName(methodMirror); putMultiMap(getters, name, methodMirror); } else if(isSetter(methodMirror)) { String name = getJavaAttributeName(methodMirror); putMultiMap(setters, name, methodMirror); } else if(isHashAttribute(methodMirror)) { putMultiMap(getters, "hash", methodMirror); seenHashAttribute = true; } else if(isStringAttribute(methodMirror)) { putMultiMap(getters, "string", methodMirror); seenStringAttribute = true; } else { // we never map getString to a property, or generate one if(isStringGetter(methodMirror)) seenStringGetter = true; // same for getHash else if(isHashGetter(methodMirror)) seenHashGetter = true; else if(isStringSetter(methodMirror)){ stringSetter = methodMirror; // we will perhaps add it later continue; }else if(isHashSetter(methodMirror)){ hashSetter = methodMirror; // we will perhaps add it later continue; } } } } // now figure out which properties to add NEXT_PROPERTY: for(Map.Entry<String, List<MethodMirror>> getterEntry : getters.entrySet()){ String propertyName = getterEntry.getKey(); List<MethodMirror> getterList = getterEntry.getValue(); for(MethodMirror getterMethod : getterList){ // if it's hashCode() or toString() they win if(isHashAttribute(getterMethod)) { // ERASURE // Un-erasing 'hash' attribute from 'hashCode' method Declaration decl = addValue(klass, getterMethod, "hash", isCeylon, false); if (isCeylon && shouldCreateNativeHeader(decl, klass)) { Declaration hdr = addValue(klass, getterMethod, "hash", true, true); setNonLazyDeclarationProperties(hdr, classMirror, classMirror, classMirror, true); initNativeHeader(hdr, decl); } else if (isCeylon && shouldLinkNatives(decl)) { initNativeHeaderMember(decl); } // remove it as a method and add all other getters with the same name // as methods removeMultiMap(methods, getterMethod.getName(), getterMethod); // next property continue NEXT_PROPERTY; } if(isStringAttribute(getterMethod)) { // ERASURE // Un-erasing 'string' attribute from 'toString' method Declaration decl = addValue(klass, getterMethod, "string", isCeylon, false); if (isCeylon && shouldCreateNativeHeader(decl, klass)) { Declaration hdr = addValue(klass, getterMethod, "string", true, true); setNonLazyDeclarationProperties(hdr, classMirror, classMirror, classMirror, true); initNativeHeader(hdr, decl); } else if (isCeylon && shouldLinkNatives(decl)) { initNativeHeaderMember(decl); } // remove it as a method and add all other getters with the same name // as methods removeMultiMap(methods, getterMethod.getName(), getterMethod); // next property continue NEXT_PROPERTY; } } // we've weeded out toString/hashCode, now if we have a single property it's easy we just add it if(getterList.size() == 1){ // FTW! MethodMirror getterMethod = getterList.get(0); // simple attribute Declaration decl = addValue(klass, getterMethod, propertyName, isCeylon, false); if (isCeylon && shouldCreateNativeHeader(decl, klass)) { Declaration hdr = addValue(klass, getterMethod, propertyName, true, true); setNonLazyDeclarationProperties(hdr, classMirror, classMirror, classMirror, true); initNativeHeader(hdr, decl); } else if (isCeylon && shouldLinkNatives(decl)) { initNativeHeaderMember(decl); } // remove it as a method removeMultiMap(methods, getterMethod.getName(), getterMethod); // next property continue NEXT_PROPERTY; } // we have more than one // if we have a setter let's favour the one that matches the setter List<MethodMirror> matchingSetters = setters.get(propertyName); if(matchingSetters != null){ if(matchingSetters.size() == 1){ // single setter will tell us what we need MethodMirror matchingSetter = matchingSetters.get(0); MethodMirror bestGetter = null; boolean booleanSetter = matchingSetter.getParameters().get(0).getType().getKind() == TypeKind.BOOLEAN; /* * Getters do not support overloading since they have no parameters, so they can only differ based on * name. For boolean properties we favour "is" getters, otherwise "get" getters. */ for(MethodMirror getterMethod : getterList){ if(propertiesMatch(klass, getterMethod, matchingSetter)){ if(bestGetter == null) bestGetter = getterMethod; else{ // we have two getters, find the best one if(booleanSetter){ // favour the "is" getter if(getterMethod.getName().startsWith("is")) bestGetter = getterMethod; // else keep the current best, it must be an "is" getter }else{ // favour the "get" getter if(getterMethod.getName().startsWith("get")) bestGetter = getterMethod; // else keep the current best, it must be a "get" getter } break; } } } if(bestGetter != null){ // got it! // simple attribute Declaration decl = addValue(klass, bestGetter, propertyName, isCeylon, false); if (isCeylon && shouldCreateNativeHeader(decl, klass)) { Declaration hdr = addValue(klass, bestGetter, propertyName, true, true); setNonLazyDeclarationProperties(hdr, classMirror, classMirror, classMirror, true); initNativeHeader(hdr, decl); } else if (isCeylon && shouldLinkNatives(decl)) { initNativeHeaderMember(decl); } // remove it as a method and add all other getters with the same name // as methods removeMultiMap(methods, bestGetter.getName(), bestGetter); // next property continue NEXT_PROPERTY; }// else we cannot find the right getter thanks to the setter, keep looking } } // setters did not help us, we have more than one getter, one must be "is"/boolean, the other "get" if(getterList.size() == 2){ // if the "get" is also a boolean, prefer the "is" MethodMirror isMethod = null; MethodMirror getMethod = null; for(MethodMirror getterMethod : getterList){ if(getterMethod.getName().startsWith("is")) isMethod = getterMethod; else if(getterMethod.getName().startsWith("get")) getMethod = getterMethod; } if(isMethod != null && getMethod != null){ MethodMirror bestGetter; if(getMethod.getReturnType().getKind() == TypeKind.BOOLEAN){ // pick the is method bestGetter = isMethod; }else{ // just take the getter bestGetter = getMethod; } // simple attribute Declaration decl = addValue(klass, bestGetter, propertyName, isCeylon, false); if (isCeylon && shouldCreateNativeHeader(decl, klass)) { Declaration hdr = addValue(klass, bestGetter, propertyName, true, true); setNonLazyDeclarationProperties(hdr, classMirror, classMirror, classMirror, true); initNativeHeader(hdr, decl); } else if (isCeylon && shouldLinkNatives(decl)) { initNativeHeaderMember(decl); } // remove it as a method and add all other getters with the same name // as methods removeMultiMap(methods, bestGetter.getName(), bestGetter); // next property continue NEXT_PROPERTY; } } } // now handle fields for(FieldMirror fieldMirror : classMirror.getDirectFields()){ // We skip members marked with @Ignore if(fieldMirror.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null) continue; if(skipPrivateMember(fieldMirror)) continue; if(isCeylon && fieldMirror.isStatic()) continue; // FIXME: temporary, because some private classes from the jdk are // referenced in private methods but not available if(isFromJDK && !fieldMirror.isPublic() && !fieldMirror.isProtected()) continue; String name = fieldMirror.getName(); // skip the field if "we've already got one" boolean conflicts = klass.getDirectMember(name, null, false) != null || "equals".equals(name) || "string".equals(name) || "hash".equals(name); if (!conflicts) { Declaration decl = addValue(klass, fieldMirror.getName(), fieldMirror, isCeylon, false); if (isCeylon && shouldCreateNativeHeader(decl, klass)) { Declaration hdr = addValue(klass, fieldMirror.getName(), fieldMirror, true, true); setNonLazyDeclarationProperties(hdr, classMirror, classMirror, classMirror, true); initNativeHeader(hdr, decl); } else if (isCeylon && shouldLinkNatives(decl)) { initNativeHeaderMember(decl); } } } // Now mark all Values for which Setters exist as variable for(List<MethodMirror> variables : setters.values()){ for(MethodMirror setter : variables){ String name = getJavaAttributeName(setter); // make sure we handle private postfixes name = JvmBackendUtil.strip(name, isCeylon, setter.isPublic()); Declaration decl = klass.getMember(name, null, false); // skip Java fields, which we only get if there is no getter method, in that case just add the setter method if (decl instanceof JavaBeanValue) { JavaBeanValue value = (JavaBeanValue)decl; // only add the setter if it has the same visibility as the getter if (setter.isPublic() && value.mirror.isPublic() || setter.isProtected() && value.mirror.isProtected() || setter.isDefaultAccess() && value.mirror.isDefaultAccess() || (!setter.isPublic() && !value.mirror.isPublic() && !setter.isProtected() && !value.mirror.isProtected() && !setter.isDefaultAccess() && !value.mirror.isDefaultAccess())) { VariableMirror setterParam = setter.getParameters().get(0); Type paramType = obtainType(setterParam.getType(), setterParam, klass, ModelUtil.getModuleContainer(klass), VarianceLocation.INVARIANT, "setter '"+setter.getName()+"'", klass); // only add the setter if it has exactly the same type as the getter if(paramType.isExactly(value.getType())){ value.setVariable(true); value.setSetterName(setter.getName()); if(value.isTransient()){ // must be a real setter makeSetter(value, null); } // remove it as a method removeMultiMap(methods, setter.getName(), setter); }else logVerbose("Setter parameter type for "+name+" does not match corresponding getter type, adding setter as a method"); } else { logVerbose("Setter visibility for "+name+" does not match corresponding getter visibility, adding setter as a method"); } } } } // special cases if we have hashCode() setHash() and no getHash() if(hashSetter != null){ if(seenHashAttribute && !seenHashGetter){ Declaration attr = klass.getDirectMember("hash", null, false); if(attr instanceof JavaBeanValue){ ((JavaBeanValue) attr).setVariable(true); ((JavaBeanValue) attr).setSetterName(hashSetter.getName()); // remove it as a method removeMultiMap(methods, hashSetter.getName(), hashSetter); } } } // special cases if we have toString() setString() and no getString() if(stringSetter != null){ if(seenStringAttribute && !seenStringGetter){ Declaration attr = klass.getDirectMember("string", null, false); if(attr instanceof JavaBeanValue){ ((JavaBeanValue) attr).setVariable(true); ((JavaBeanValue) attr).setSetterName(stringSetter.getName()); // remove it as a method removeMultiMap(methods, stringSetter.getName(), stringSetter); } } } // Add the methods, treat remaining getters/setters as methods for(List<MethodMirror> methodMirrors : methods.values()){ boolean isOverloaded = isMethodOverloaded(methodMirrors); List<Declaration> overloads = null; for (MethodMirror methodMirror : methodMirrors) { // normal method Function m = addMethod(klass, methodMirror, classMirror, isCeylon, isOverloaded, false); if (!isOverloaded && isCeylon && shouldCreateNativeHeader(m, klass)) { Declaration hdr = addMethod(klass, methodMirror, classMirror, true, isOverloaded, true); setNonLazyDeclarationProperties(hdr, classMirror, classMirror, classMirror, true); initNativeHeader(hdr, m); } else if (isCeylon && shouldLinkNatives(m)) { initNativeHeaderMember(m); } if (m.isOverloaded()) { overloads = overloads == null ? new ArrayList<Declaration>(methodMirrors.size()) : overloads; overloads.add(m); } } if (overloads != null && !overloads.isEmpty()) { // We create an extra "abstraction" method for overloaded methods Function abstractionMethod = addMethod(klass, methodMirrors.get(0), classMirror, isCeylon, false, false); abstractionMethod.setAbstraction(true); abstractionMethod.setOverloads(overloads); abstractionMethod.setType(newUnknownType()); } } // Having loaded methods and values, we can now set the constructor parameters if(constructor != null && !isDefaultNamedCtor(classMirror, constructor) && (!(klass instanceof LazyClass) || !((LazyClass)klass).isAnonymous())) setParameters((Class)klass, classMirror, constructor, isCeylon, klass); // Now marry-up attributes and parameters) if (klass instanceof Class) { for (Declaration m : klass.getMembers()) { if (JvmBackendUtil.isValue(m)) { Value v = (Value)m; Parameter p = ((Class)klass).getParameter(v.getName()); if (p != null) { p.setHidden(true); } } } } setExtendedType(klass, classMirror); setSatisfiedTypes(klass, classMirror); setCaseTypes(klass, classMirror); setAnnotations(klass, classMirror, klass.isNativeHeader()); // local declarations come last, because they need all members to be completed first if(!klass.isAlias()){ ClassMirror containerMirror = classMirror; if(klass instanceof LazyInterface){ ClassMirror companionClass = ((LazyInterface) klass).companionClass; if(companionClass != null) containerMirror = companionClass; } addLocalDeclarations((LazyContainer) klass, containerMirror, classMirror); } if (!isCeylon) { // In java, a class can inherit a public member from a non-public supertype for (Declaration d : klass.getMembers()) { if (d.isShared()) { d.setVisibleScope(null); } } } } private boolean propertiesMatch(ClassOrInterface klass, MethodMirror getter, MethodMirror setter) { // only add the setter if it has the same visibility as the getter if (setter.isPublic() && getter.isPublic() || setter.isProtected() && getter.isProtected() || setter.isDefaultAccess() && getter.isDefaultAccess() || (!setter.isPublic() && !getter.isPublic() && !setter.isProtected() && !getter.isProtected() && !setter.isDefaultAccess() && !getter.isDefaultAccess())) { Module module = ModelUtil.getModuleContainer(klass); VariableMirror setterParam = setter.getParameters().get(0); Type paramType = obtainType(setterParam.getType(), setterParam, klass, module, VarianceLocation.INVARIANT, "setter '"+setter.getName()+"'", klass); Type returnType = obtainType(getter.getReturnType(), getter, klass, module, VarianceLocation.INVARIANT, "getter '"+getter.getName()+"'", klass); // only add the setter if it has exactly the same type as the getter if(paramType.isExactly(returnType)){ return true; } } return false; } private <Key,Val> void removeMultiMap(Map<Key, List<Val>> map, Key key, Val val) { List<Val> list = map.get(key); if(list != null){ list.remove(val); if(list.isEmpty()) map.remove(key); } } private <Key,Val> void putMultiMap(Map<Key, List<Val>> map, Key key, Val value) { List<Val> list = map.get(key); if(list == null){ list = new LinkedList<>(); map.put(key, list); } list.add(value); } private Constructor addConstructor(Class klass, ClassMirror classMirror, MethodMirror ctor, boolean isNativeHeader) { boolean isCeylon = classMirror.getAnnotation(CEYLON_CEYLON_ANNOTATION) != null; Constructor constructor = new Constructor(); constructor.setName(getCtorName(ctor)); constructor.setContainer(klass); constructor.setScope(klass); constructor.setUnit(klass.getUnit()); constructor.setAbstract(ctor.getAnnotation(CEYLON_LANGUAGE_ABSTRACT_ANNOTATION) != null); constructor.setExtendedType(klass.getType()); setNonLazyDeclarationProperties(constructor, ctor, ctor, classMirror, isCeylon); setAnnotations(constructor, ctor, isNativeHeader); klass.addMember(constructor); return constructor; } protected void addConstructorMethorOrValue(Class klass, ClassMirror classMirror, MethodMirror ctor, Constructor constructor, boolean isNativeHeader) { boolean isCeylon = classMirror.getAnnotation(CEYLON_CEYLON_ANNOTATION) != null; if (ctor.getAnnotation(CEYLON_ENUMERATED_ANNOTATION) != null) { klass.setEnumerated(true); Value v = new Value(); v.setName(constructor.getName()); v.setType(constructor.getType()); v.setContainer(klass); v.setScope(klass); v.setUnit(klass.getUnit()); v.setVisibleScope(constructor.getVisibleScope()); // read annotations from the getter method setNonLazyDeclarationProperties(v, ctor, ctor, classMirror, isCeylon); setAnnotations(v, ctor, isNativeHeader); klass.addMember(v); } else { setParameters(constructor, classMirror, ctor, true, klass); klass.setConstructors(true); Function f = new Function(); f.setName(constructor.getName()); f.setType(constructor.getType()); f.addParameterList(constructor.getParameterList()); f.setContainer(klass); f.setScope(klass); f.setUnit(klass.getUnit()); f.setVisibleScope(constructor.getVisibleScope()); // read annotations from the constructor setNonLazyDeclarationProperties(f, ctor, ctor, classMirror, isCeylon); setAnnotations(f, ctor, isNativeHeader); klass.addMember(f); } } private boolean isMethodOverloaded(List<MethodMirror> methodMirrors) { // it's overloaded if we have more than one method (non constructor/value) boolean one = false; for (MethodMirror methodMirror : methodMirrors) { // same tests as in complete(ClassOrInterface klass, ClassMirror classMirror) if(methodMirror.isConstructor() || isInstantiator(methodMirror) || isGetter(methodMirror) || isSetter(methodMirror) || isHashAttribute(methodMirror) || isStringAttribute(methodMirror) || methodMirror.getName().equals("hash") || methodMirror.getName().equals("string")){ break; } if(one) return true; one = true; } return false; } private void collectMethods(List<MethodMirror> methodMirrors, Map<String,List<MethodMirror>> methods, boolean isCeylon, boolean isFromJDK) { for(MethodMirror methodMirror : methodMirrors){ // We skip members marked with @Ignore if(methodMirror.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null) continue; if(skipPrivateMember(methodMirror)) continue; if(methodMirror.isStaticInit()) continue; if(isCeylon && methodMirror.isStatic() && methodMirror.getAnnotation(CEYLON_ENUMERATED_ANNOTATION) == null) continue; // these are not relevant for our caller if(methodMirror.isConstructor() || isInstantiator(methodMirror)) { continue; } // FIXME: temporary, because some private classes from the jdk are // referenced in private methods but not available if(isFromJDK && !methodMirror.isPublic() && !methodMirror.isProtected()) continue; String methodName = methodMirror.getName(); List<MethodMirror> homonyms = methods.get(methodName); if (homonyms == null) { homonyms = new LinkedList<MethodMirror>(); methods.put(methodName, homonyms); } homonyms.add(methodMirror); } } private boolean skipPrivateMember(AccessibleMirror mirror) { return !mirror.isPublic() && !mirror.isProtected() && !mirror.isDefaultAccess() && !needsPrivateMembers(); } private void addLocalDeclarations(LocalDeclarationContainer container, ClassMirror classContainerMirror, AnnotatedMirror annotatedMirror) { if(!needsLocalDeclarations()) return; AnnotationMirror annotation = annotatedMirror.getAnnotation(CEYLON_LOCAL_DECLARATIONS_ANNOTATION); if(annotation == null) return; List<String> values = getAnnotationStringValues(annotation, "value"); String parentClassName = classContainerMirror.getQualifiedName(); Package pkg = ModelUtil.getPackageContainer(container); Module module = pkg.getModule(); for(String scope : values){ // assemble the name with the parent String name; if(scope.startsWith("::")){ // interface pulled to toplevel name = pkg.getNameAsString() + "." + scope.substring(2); }else{ name = parentClassName; name += "$" + scope; } Declaration innerDecl = convertToDeclaration(module, (Declaration)container, name, DeclarationType.TYPE); if(innerDecl == null) throw new ModelResolutionException("Failed to load local type " + name + " for outer type " + container.getQualifiedNameString()); } } private boolean isInstantiator(MethodMirror methodMirror) { return methodMirror.getName().endsWith("$aliased$"); } private boolean isFromJDK(ClassMirror classMirror) { String pkgName = unquotePackageName(classMirror.getPackage()); return JDKUtils.isJDKAnyPackage(pkgName) || JDKUtils.isOracleJDKAnyPackage(pkgName); } private void setAnnotations(Annotated annotated, AnnotatedMirror classMirror, boolean isNativeHeader) { if (classMirror.getAnnotation(CEYLON_ANNOTATIONS_ANNOTATION) != null) { // If the class has @Annotations then use it (in >=1.2 only ceylon.language does) Long mods = (Long)getAnnotationValue(classMirror, CEYLON_ANNOTATIONS_ANNOTATION, "modifiers"); if (mods != null) { // If there is a modifiers value then use it to load the modifiers for (LanguageAnnotation mod : LanguageAnnotation.values()) { if (mod.isModifier()) { if ((mod.mask & mods) != 0) { annotated.getAnnotations().addAll(mod.makeFromCeylonAnnotation(null)); } } } } // Load anything else the long way, reading the @Annotation(name=...) List<AnnotationMirror> annotations = getAnnotationArrayValue(classMirror, CEYLON_ANNOTATIONS_ANNOTATION); if(annotations != null) { for(AnnotationMirror annotation : annotations){ annotated.getAnnotations().add(readModelAnnotation(annotation)); } } } else { // If the class lacks @Annotations then set the modifier annotations // according to the presence of @Shared$annotation etc for (LanguageAnnotation mod : LanguageAnnotation.values()) { if (classMirror.getAnnotation(mod.annotationType) != null) { annotated.getAnnotations().addAll(mod.makeFromCeylonAnnotation(classMirror.getAnnotation(mod.annotationType))); } } // Hack for anonymous classes where the getter method has the annotations, // but the typechecker wants them on the Class model. if ((annotated instanceof Class) && ((Class)annotated).isAnonymous()) { Class clazz = (Class)annotated; Declaration objectValue = clazz.getContainer().getDirectMember(clazz.getName(), null, false); if (objectValue != null) { annotated.getAnnotations().addAll(objectValue.getAnnotations()); } } } boolean hasCeylonDeprecated = false; for(Annotation a : annotated.getAnnotations()) { if (a.getName().equals("deprecated")) { hasCeylonDeprecated = true; break; } } // Add a ceylon deprecated("") if it's annotated with java.lang.Deprecated // and doesn't already have the ceylon annotation if (classMirror.getAnnotation(JAVA_DEPRECATED_ANNOTATION) != null) { if (!hasCeylonDeprecated) { Annotation modelAnnotation = new Annotation(); modelAnnotation.setName("deprecated"); modelAnnotation.getPositionalArguments().add(""); annotated.getAnnotations().add(modelAnnotation); hasCeylonDeprecated = true; } } if (annotated instanceof Declaration && !((Declaration)annotated).getNativeBackends().none()) { // Do nothing : // it has already been managed when in the makeLazyXXX() function } else { manageNativeBackend(annotated, classMirror, isNativeHeader); } } private void manageNativeBackend(Annotated annotated, AnnotatedMirror mirror, boolean isNativeHeader) { if (mirror == null) return; // Set "native" annotation @SuppressWarnings("unchecked") List<String> nativeBackends = (List<String>)getAnnotationValue(mirror, CEYLON_LANGUAGE_NATIVE_ANNOTATION, "backends"); if (nativeBackends != null) { Backends backends = Backends.fromAnnotations(nativeBackends); if (isNativeHeader) { backends = Backends.HEADER; } else if (backends.header()) { // Elements in the class file marked `native("")` are actually // default implementations taken from the header that were // copied to the output, so here we reset them to `native("jvm")` backends = Backends.JAVA; } if (annotated instanceof Declaration) { Declaration decl = (Declaration)annotated; decl.setNativeBackends(backends); if (isNativeHeader) { List<Declaration> al = new ArrayList<Declaration>(1); setOverloads(decl, al); } } else if (annotated instanceof Module) { ((Module)annotated).setNativeBackends(backends); } } else { // Mark native Classes and Interfaces as well, but don't deal with overloads and such if (annotated instanceof LazyClass && !((LazyClass)annotated).isCeylon() || annotated instanceof LazyInterface && !((LazyInterface)annotated).isCeylon()) { ((Declaration)annotated).setNativeBackends(Backend.Java.asSet()); } } } protected boolean isDeprecated(AnnotatedMirror classMirror){ if (classMirror.getAnnotation(JAVA_DEPRECATED_ANNOTATION) != null) return true; if (classMirror.getAnnotation(CEYLON_ANNOTATIONS_ANNOTATION) != null) { // Load anything else the long way, reading the @Annotation(name=...) List<AnnotationMirror> annotations = getAnnotationArrayValue(classMirror, CEYLON_ANNOTATIONS_ANNOTATION); if(annotations != null) { for(AnnotationMirror annotation : annotations){ String name = (String) annotation.getValue(); if(name != null && name.equals("deprecated")) return true; } } return false; } else { // If the class lacks @Annotations then set the modifier annotations // according to the presence of @Shared$annotation etc return classMirror.getAnnotation(LanguageAnnotation.DEPRECATED.annotationType) != null; } } public static List<Declaration> getOverloads(Declaration decl) { if (decl instanceof Function) { return ((Function)decl).getOverloads(); } else if (decl instanceof Value) { return ((Value)decl).getOverloads(); } else if (decl instanceof Class) { return ((Class)decl).getOverloads(); } return Collections.emptyList(); } public static void setOverloads(Declaration decl, List<Declaration> overloads) { if (decl instanceof Function) { ((Function)decl).setOverloads(overloads); } else if (decl instanceof Value) { ((Value)decl).setOverloads(overloads); } else if (decl instanceof Class) { ((Class)decl).setOverloads(overloads); } } private Annotation readModelAnnotation(AnnotationMirror annotation) { Annotation modelAnnotation = new Annotation(); modelAnnotation.setName((String) annotation.getValue()); @SuppressWarnings("unchecked") List<String> arguments = (List<String>) annotation.getValue("arguments"); if(arguments != null){ modelAnnotation.getPositionalArguments().addAll(arguments); }else{ @SuppressWarnings("unchecked") List<AnnotationMirror> namedArguments = (List<AnnotationMirror>) annotation.getValue("namedArguments"); if(namedArguments != null){ for(AnnotationMirror namedArgument : namedArguments){ String argName = (String) namedArgument.getValue("name"); String argValue = (String) namedArgument.getValue("value"); modelAnnotation.getNamedArguments().put(argName, argValue); } } } return modelAnnotation; } private void addInnerClasses(ClassOrInterface klass, ClassMirror classMirror) { AnnotationMirror membersAnnotation = classMirror.getAnnotation(CEYLON_MEMBERS_ANNOTATION); if(membersAnnotation == null) addInnerClassesFromMirror(klass, classMirror); else addInnerClassesFromAnnotation(klass, membersAnnotation); } private void addInnerClassesFromAnnotation(ClassOrInterface klass, AnnotationMirror membersAnnotation) { @SuppressWarnings("unchecked") List<AnnotationMirror> members = (List<AnnotationMirror>) membersAnnotation.getValue(); for(AnnotationMirror member : members){ TypeMirror javaClassMirror = (TypeMirror)member.getValue("klass"); String javaClassName; // void.class is the default value, I guess it's a primitive? if(javaClassMirror != null && !javaClassMirror.isPrimitive()){ javaClassName = javaClassMirror.getQualifiedName(); }else{ // we get the class name as a string String name = (String)member.getValue("javaClassName"); ClassMirror container = null; if(klass instanceof LazyClass){ container = ((LazyClass) klass).classMirror; }else if(klass instanceof LazyInterface){ if(((LazyInterface) klass).isCeylon()) container = ((LazyInterface) klass).companionClass; else container = ((LazyInterface) klass).classMirror; } if(container == null) throw new ModelResolutionException("Unknown container type: " + klass + " when trying to load inner class " + name); javaClassName = container.getQualifiedName()+"$"+name; } Declaration innerDecl = convertToDeclaration(ModelUtil.getModuleContainer(klass), klass, javaClassName, DeclarationType.TYPE); if(innerDecl == null) throw new ModelResolutionException("Failed to load inner type " + javaClassName + " for outer type " + klass.getQualifiedNameString()); if(shouldLinkNatives(innerDecl)) { initNativeHeaderMember(innerDecl); } } } /** * Allows subclasses to do something to the class name */ protected String assembleJavaClass(String javaClass, String packageName) { return javaClass; } private void addInnerClassesFromMirror(ClassOrInterface klass, ClassMirror classMirror) { boolean isJDK = isFromJDK(classMirror); Module module = ModelUtil.getModule(klass); for(ClassMirror innerClass : classMirror.getDirectInnerClasses()){ // We skip members marked with @Ignore if(innerClass.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null) continue; // We skip anonymous inner classes if(innerClass.isAnonymous()) continue; // We skip private classes, otherwise the JDK has a ton of unresolved things if(isJDK && !innerClass.isPublic()) continue; // convert it convertToDeclaration(module, klass, innerClass, DeclarationType.TYPE); // no need to set its container as that's now handled by convertToDeclaration } } private Function addMethod(ClassOrInterface klass, MethodMirror methodMirror, ClassMirror classMirror, boolean isCeylon, boolean isOverloaded, boolean isNativeHeader) { JavaMethod method = new JavaMethod(methodMirror); String methodName = methodMirror.getName(); method.setContainer(klass); method.setScope(klass); method.setRealName(methodName); method.setUnit(klass.getUnit()); method.setOverloaded(isOverloaded || isOverloadingMethod(methodMirror)); Type type = null; try{ setMethodOrValueFlags(klass, methodMirror, method, isCeylon); }catch(ModelResolutionException x){ // collect an error in its type type = logModelResolutionException(x, klass, "method '"+methodMirror.getName()+"' (checking if it is an overriding method)"); } if(methodName.equals("hash") || methodName.equals("string")) method.setName(methodName+"_method"); else method.setName(JvmBackendUtil.strip(methodName, isCeylon, method.isShared())); method.setDefaultedAnnotation(methodMirror.isDefault()); // type params first try{ setTypeParameters(method, methodMirror, isCeylon); }catch(ModelResolutionException x){ if(type == null){ type = logModelResolutionException(x, klass, "method '"+methodMirror.getName()+"' (loading type parameters)"); } } // and its return type // do not log an additional error if we had one from checking if it was overriding if(type == null) type = obtainType(methodMirror.getReturnType(), methodMirror, method, ModelUtil.getModuleContainer(method), VarianceLocation.COVARIANT, "method '"+methodMirror.getName()+"'", klass); method.setType(type); // now its parameters if(isEqualsMethod(methodMirror)) setEqualsParameters(method, methodMirror); else setParameters(method, classMirror, methodMirror, isCeylon, klass); method.setUncheckedNullType((!isCeylon && !methodMirror.getReturnType().isPrimitive()) || isUncheckedNull(methodMirror)); type.setRaw(isRaw(ModelUtil.getModuleContainer(klass), methodMirror.getReturnType())); markDeclaredVoid(method, methodMirror); markUnboxed(method, methodMirror, methodMirror.getReturnType()); markTypeErased(method, methodMirror, methodMirror.getReturnType()); markUntrustedType(method, methodMirror, methodMirror.getReturnType()); method.setDeprecated(isDeprecated(methodMirror)); setAnnotations(method, methodMirror, isNativeHeader); klass.addMember(method); ModelUtil.setVisibleScope(method); addLocalDeclarations(method, classMirror, methodMirror); return method; } private List<Type> getSignature(Declaration decl) { List<Type> result = null; if (decl instanceof Functional) { Functional func = (Functional)decl; if (func.getParameterLists().size() > 0) { List<Parameter> params = func.getFirstParameterList().getParameters(); result = new ArrayList<Type>(params.size()); for (Parameter p : params) { result.add(p.getType()); } } } return result; } private boolean isStartOfJavaBeanPropertyName(int codepoint){ return (codepoint == Character.toUpperCase(codepoint)) || codepoint == '_'; } private boolean isNonGenericMethod(MethodMirror methodMirror){ return !methodMirror.isConstructor() && methodMirror.getTypeParameters().isEmpty(); } private boolean isGetter(MethodMirror methodMirror) { if(!isNonGenericMethod(methodMirror)) return false; String name = methodMirror.getName(); boolean matchesGet = name.length() > 3 && name.startsWith("get") && isStartOfJavaBeanPropertyName(name.codePointAt(3)) && !"getString".equals(name) && !"getHash".equals(name) && !"getEquals".equals(name); boolean matchesIs = name.length() > 2 && name.startsWith("is") && isStartOfJavaBeanPropertyName(name.codePointAt(2)) && !"isString".equals(name) && !"isHash".equals(name) && !"isEquals".equals(name); boolean hasNoParams = methodMirror.getParameters().size() == 0; boolean hasNonVoidReturn = (methodMirror.getReturnType().getKind() != TypeKind.VOID); boolean hasBooleanReturn = (methodMirror.getReturnType().getKind() == TypeKind.BOOLEAN); return (matchesGet && hasNonVoidReturn || matchesIs && hasBooleanReturn) && hasNoParams; } private boolean isStringGetter(MethodMirror methodMirror) { if(!isNonGenericMethod(methodMirror)) return false; String name = methodMirror.getName(); boolean matchesGet = "getString".equals(name); boolean matchesIs = "isString".equals(name); boolean hasNoParams = methodMirror.getParameters().size() == 0; boolean hasNonVoidReturn = (methodMirror.getReturnType().getKind() != TypeKind.VOID); boolean hasBooleanReturn = (methodMirror.getReturnType().getKind() == TypeKind.BOOLEAN); return (matchesGet && hasNonVoidReturn || matchesIs && hasBooleanReturn) && hasNoParams; } private boolean isHashGetter(MethodMirror methodMirror) { if(!isNonGenericMethod(methodMirror)) return false; String name = methodMirror.getName(); boolean matchesGet = "getHash".equals(name); boolean matchesIs = "isHash".equals(name); boolean hasNoParams = methodMirror.getParameters().size() == 0; boolean hasNonVoidReturn = (methodMirror.getReturnType().getKind() != TypeKind.VOID); boolean hasBooleanReturn = (methodMirror.getReturnType().getKind() == TypeKind.BOOLEAN); return (matchesGet && hasNonVoidReturn || matchesIs && hasBooleanReturn) && hasNoParams; } private boolean isSetter(MethodMirror methodMirror) { if(!isNonGenericMethod(methodMirror)) return false; String name = methodMirror.getName(); boolean matchesSet = name.length() > 3 && name.startsWith("set") && isStartOfJavaBeanPropertyName(name.codePointAt(3)) && !"setString".equals(name) && !"setHash".equals(name) && !"setEquals".equals(name); boolean hasOneParam = methodMirror.getParameters().size() == 1; boolean hasVoidReturn = (methodMirror.getReturnType().getKind() == TypeKind.VOID); return matchesSet && hasOneParam && hasVoidReturn; } private boolean isStringSetter(MethodMirror methodMirror) { if(!isNonGenericMethod(methodMirror)) return false; String name = methodMirror.getName(); boolean matchesSet = name.equals("setString"); boolean hasOneParam = methodMirror.getParameters().size() == 1; boolean hasVoidReturn = (methodMirror.getReturnType().getKind() == TypeKind.VOID); return matchesSet && hasOneParam && hasVoidReturn; } private boolean isHashSetter(MethodMirror methodMirror) { if(!isNonGenericMethod(methodMirror)) return false; String name = methodMirror.getName(); boolean matchesSet = name.equals("setHash"); boolean hasOneParam = methodMirror.getParameters().size() == 1; boolean hasVoidReturn = (methodMirror.getReturnType().getKind() == TypeKind.VOID); return matchesSet && hasOneParam && hasVoidReturn; } private boolean isHashAttribute(MethodMirror methodMirror) { if(!isNonGenericMethod(methodMirror) || methodMirror.isStatic()) return false; String name = methodMirror.getName(); boolean matchesName = "hashCode".equals(name); boolean hasNoParams = methodMirror.getParameters().size() == 0; return matchesName && hasNoParams; } private boolean isStringAttribute(MethodMirror methodMirror) { if(!isNonGenericMethod(methodMirror) || methodMirror.isStatic()) return false; String name = methodMirror.getName(); boolean matchesName = "toString".equals(name); boolean hasNoParams = methodMirror.getParameters().size() == 0; return matchesName && hasNoParams; } private boolean isEqualsMethod(MethodMirror methodMirror) { if(!isNonGenericMethod(methodMirror) || methodMirror.isStatic()) return false; String name = methodMirror.getName(); if(!"equals".equals(name) || methodMirror.getParameters().size() != 1) return false; VariableMirror param = methodMirror.getParameters().get(0); return sameType(param.getType(), OBJECT_TYPE); } private void setEqualsParameters(Function decl, MethodMirror methodMirror) { ParameterList parameters = new ParameterList(); decl.addParameterList(parameters); Parameter parameter = new Parameter(); Value value = new Value(); parameter.setModel(value); value.setInitializerParameter(parameter); value.setUnit(decl.getUnit()); value.setContainer((Scope) decl); value.setScope((Scope) decl); parameter.setName("that"); value.setName("that"); value.setType(getNonPrimitiveType(getLanguageModule(), CEYLON_OBJECT_TYPE, decl, VarianceLocation.INVARIANT)); parameter.setDeclaration((Declaration) decl); parameters.getParameters().add(parameter); decl.addMember(value); } private String getJavaAttributeName(MethodMirror methodMirror) { String name = getAnnotationStringValue(methodMirror, CEYLON_NAME_ANNOTATION); if(name != null) return name; return getJavaAttributeName(methodMirror.getName()); } private String getJavaAttributeName(String getterName) { if (getterName.startsWith("get") || getterName.startsWith("set")) { return NamingBase.getJavaBeanName(getterName.substring(3)); } else if (getterName.startsWith("is")) { // Starts with "is" return NamingBase.getJavaBeanName(getterName.substring(2)); } else { throw new RuntimeException("Illegal java getter/setter name"); } } private Value addValue(ClassOrInterface klass, String ceylonName, FieldMirror fieldMirror, boolean isCeylon, boolean isNativeHeader) { // make sure it's a FieldValue so we can figure it out in the backend Value value = new FieldValue(fieldMirror.getName()); value.setContainer(klass); value.setScope(klass); // use the name annotation if present (used by Java arrays) String nameAnnotation = getAnnotationStringValue(fieldMirror, CEYLON_NAME_ANNOTATION); value.setName(nameAnnotation != null ? nameAnnotation : ceylonName); value.setUnit(klass.getUnit()); value.setShared(fieldMirror.isPublic() || fieldMirror.isProtected() || fieldMirror.isDefaultAccess()); value.setProtectedVisibility(fieldMirror.isProtected()); value.setPackageVisibility(fieldMirror.isDefaultAccess()); value.setStaticallyImportable(fieldMirror.isStatic()); setDeclarationAliases(value, fieldMirror); // field can't be abstract or interface, so not formal // can we override fields? good question. Not really, but from an external point of view? // FIXME: figure this out: (default) // FIXME: for the same reason, can it be an overriding field? (actual) value.setVariable(!fieldMirror.isFinal()); // figure out if it's an enum subtype in a final static field if(fieldMirror.getType().getKind() == TypeKind.DECLARED && fieldMirror.getType().getDeclaredClass() != null && fieldMirror.getType().getDeclaredClass().isEnum() && fieldMirror.isFinal() && fieldMirror.isStatic()) value.setEnumValue(true); Type type = obtainType(fieldMirror.getType(), fieldMirror, klass, ModelUtil.getModuleContainer(klass), VarianceLocation.INVARIANT, "field '"+value.getName()+"'", klass); if (value.isEnumValue()) { Class enumValueType = new Class(); enumValueType.setValueConstructor(true); enumValueType.setJavaEnum(true); enumValueType.setAnonymous(true); enumValueType.setExtendedType(type); enumValueType.setContainer(value.getContainer()); enumValueType.setScope(value.getContainer()); enumValueType.setDeprecated(value.isDeprecated()); enumValueType.setName(value.getName()); enumValueType.setFinal(true); enumValueType.setUnit(value.getUnit()); enumValueType.setStaticallyImportable(value.isStaticallyImportable()); value.setType(enumValueType.getType()); value.setUncheckedNullType(false); } else { value.setType(type); value.setUncheckedNullType((!isCeylon && !fieldMirror.getType().isPrimitive()) || isUncheckedNull(fieldMirror)); } type.setRaw(isRaw(ModelUtil.getModuleContainer(klass), fieldMirror.getType())); markUnboxed(value, null, fieldMirror.getType()); markTypeErased(value, fieldMirror, fieldMirror.getType()); markUntrustedType(value, fieldMirror, fieldMirror.getType()); value.setDeprecated(isDeprecated(fieldMirror)); setAnnotations(value, fieldMirror, isNativeHeader); klass.addMember(value); ModelUtil.setVisibleScope(value); return value; } private boolean isRaw(Module module, TypeMirror type) { // dirty hack to get rid of bug where calling type.isRaw() on a ceylon type we are going to compile would complete() it, which // would try to parse its file. For ceylon types we don't need the class file info we can query it // See https://github.com/ceylon/ceylon-compiler/issues/1085 switch(type.getKind()){ case ARRAY: // arrays are never raw case BOOLEAN: case BYTE: case CHAR: case DOUBLE: case ERROR: case FLOAT: case INT: case LONG: case NULL: case SHORT: case TYPEVAR: case VOID: case WILDCARD: return false; case DECLARED: ClassMirror klass = type.getDeclaredClass(); if(klass.isJavaSource()){ // I suppose this should work return type.isRaw(); } List<String> path = new LinkedList<String>(); String pkgName = klass.getPackage().getQualifiedName(); String unquotedPkgName = unquotePackageName(klass.getPackage()); String qualifiedName = klass.getQualifiedName(); String relativeName = pkgName.isEmpty() ? qualifiedName : qualifiedName.substring(pkgName.length()+1); for(String name : relativeName.split("[\\$\\.]")){ if(!name.isEmpty()){ path.add(name); } } if(path.size() > 1){ // find the proper class mirror for the container klass = loadClass(module, pkgName, new StringBuilder(pkgName) .append('.') .append(path.get(0)).toString()); if(klass == null) return false; } if(!path.isEmpty() && klass.isLoadedFromSource()){ // we need to find its model Scope scope = packagesByName.get(cacheKeyByModule(module, unquotedPkgName)); if(scope == null) return false; for(String name : path){ Declaration decl = scope.getDirectMember(name, null, false); if(decl == null) return false; // if we get a value, we want its type if(JvmBackendUtil.isValue(decl) && ((Value)decl).getTypeDeclaration().getName().equals(name)) decl = ((Value)decl).getTypeDeclaration(); if(decl instanceof TypeDeclaration == false) return false; scope = (TypeDeclaration)decl; } TypeDeclaration typeDecl = (TypeDeclaration) scope; return !typeDecl.getTypeParameters().isEmpty() && type.getTypeArguments().isEmpty(); } try{ return type.isRaw(); }catch(Exception x){ // ignore this exception, it's likely to be due to missing module imports and an unknown type and // it will be logged somewhere else return false; } default: return false; } } private JavaBeanValue addValue(ClassOrInterface klass, MethodMirror methodMirror, String methodName, boolean isCeylon, boolean isNativeHeader) { JavaBeanValue value = new JavaBeanValue(methodMirror); value.setGetterName(methodMirror.getName()); value.setContainer(klass); value.setScope(klass); value.setUnit(klass.getUnit()); Type type = null; try{ setMethodOrValueFlags(klass, methodMirror, value, isCeylon); }catch(ModelResolutionException x){ // collect an error in its type type = logModelResolutionException(x, klass, "getter '"+methodName+"' (checking if it is an overriding method"); } value.setName(JvmBackendUtil.strip(methodName, isCeylon, value.isShared())); // do not log an additional error if we had one from checking if it was overriding if(type == null) type = obtainType(methodMirror.getReturnType(), methodMirror, klass, ModelUtil.getModuleContainer(klass), VarianceLocation.INVARIANT, "getter '"+methodName+"'", klass); value.setType(type); // special case for hash attributes which we want to pretend are of type long internally if(value.isShared() && methodName.equals("hash")) type.setUnderlyingType("long"); value.setUncheckedNullType((!isCeylon && !methodMirror.getReturnType().isPrimitive()) || isUncheckedNull(methodMirror)); type.setRaw(isRaw(ModelUtil.getModuleContainer(klass), methodMirror.getReturnType())); markUnboxed(value, methodMirror, methodMirror.getReturnType()); markTypeErased(value, methodMirror, methodMirror.getReturnType()); markUntrustedType(value, methodMirror, methodMirror.getReturnType()); value.setDeprecated(isDeprecated(methodMirror)); setAnnotations(value, methodMirror, isNativeHeader); klass.addMember(value); ModelUtil.setVisibleScope(value); return value; } private boolean isUncheckedNull(AnnotatedMirror methodMirror) { Boolean unchecked = getAnnotationBooleanValue(methodMirror, CEYLON_TYPE_INFO_ANNOTATION, "uncheckedNull"); return unchecked != null && unchecked.booleanValue(); } private void setMethodOrValueFlags(final ClassOrInterface klass, final MethodMirror methodMirror, final FunctionOrValue decl, boolean isCeylon) { decl.setShared(methodMirror.isPublic() || methodMirror.isProtected() || methodMirror.isDefaultAccess()); decl.setProtectedVisibility(methodMirror.isProtected()); decl.setPackageVisibility(methodMirror.isDefaultAccess()); setDeclarationAliases(decl, methodMirror); if(decl instanceof Value){ setValueTransientLateFlags((Value)decl, methodMirror, isCeylon); } if(// for class members we rely on abstract bit (klass instanceof Class && methodMirror.isAbstract()) // Trust the abstract bit for Java interfaces, but not for Ceylon ones || (klass instanceof Interface && !((LazyInterface)klass).isCeylon() && methodMirror.isAbstract()) // For Ceylon interfaces we rely on annotation || methodMirror.getAnnotation(CEYLON_LANGUAGE_FORMAL_ANNOTATION) != null) { decl.setFormal(true); } else { if (// for class members we rely on final/static bits (klass instanceof Class && !klass.isFinal() // a final class necessarily has final members && !methodMirror.isFinal() && !methodMirror.isStatic()) // Java interfaces are never final || (klass instanceof Interface && !((LazyInterface)klass).isCeylon()) // For Ceylon interfaces we rely on annotation || methodMirror.getAnnotation(CEYLON_LANGUAGE_DEFAULT_ANNOTATION) != null){ decl.setDefault(true); } } decl.setStaticallyImportable(methodMirror.isStatic() && methodMirror.getAnnotation(CEYLON_ENUMERATED_ANNOTATION) == null); decl.setActualCompleter(this); } @Override public void completeActual(Declaration decl){ Scope container = decl.getContainer(); if(container instanceof ClassOrInterface){ ClassOrInterface klass = (ClassOrInterface) container; decl.setRefinedDeclaration(decl); // we never consider Interface and other stuff, since we never register the actualCompleter for them if(decl instanceof Class){ // Java member classes are never actual if(!JvmBackendUtil.isCeylon((Class)decl)) return; // we already set the actual bit for member classes, we just need the refined decl if(decl.isActual()){ Declaration refined = klass.getRefinedMember(decl.getName(), getSignature(decl), false); decl.setRefinedDeclaration(refined); } }else{ // Function or Value MethodMirror methodMirror; if(decl instanceof JavaBeanValue) methodMirror = ((JavaBeanValue) decl).mirror; else if(decl instanceof JavaMethod) methodMirror = ((JavaMethod) decl).mirror; else throw new ModelResolutionException("Unknown type of declaration: "+decl+": "+decl.getClass().getName()); decl.setRefinedDeclaration(decl); // For Ceylon interfaces we rely on annotation if(klass instanceof LazyInterface && ((LazyInterface)klass).isCeylon()){ boolean actual = methodMirror.getAnnotation(CEYLON_LANGUAGE_ACTUAL_ANNOTATION) != null; decl.setActual(actual); if(actual){ Declaration refined = klass.getRefinedMember(decl.getName(), getSignature(decl), false); decl.setRefinedDeclaration(refined); } }else{ if(isOverridingMethod(methodMirror)){ decl.setActual(true); Declaration refined = klass.getRefinedMember(decl.getName(), getSignature(decl), false); decl.setRefinedDeclaration(refined); } } // now that we know the refined declaration, we can check for reified type param support // for Ceylon methods if(decl instanceof JavaMethod && JvmBackendUtil.isCeylon(klass)){ if(!methodMirror.getTypeParameters().isEmpty() // because this requires the refined decl, we defer this check until we've set it, to not trigger // lazy loading just to check. && JvmBackendUtil.supportsReified(decl)){ checkReifiedTypeDescriptors(methodMirror.getTypeParameters().size(), container.getQualifiedNameString(), methodMirror, false); } } } } } private void setValueTransientLateFlags(Value decl, MethodMirror methodMirror, boolean isCeylon) { if(isCeylon) decl.setTransient(methodMirror.getAnnotation(CEYLON_TRANSIENT_ANNOTATION) != null); else // all Java getters are transient, fields are not decl.setTransient(decl instanceof FieldValue == false); decl.setLate(methodMirror.getAnnotation(CEYLON_LANGUAGE_LATE_ANNOTATION) != null); } private void setExtendedType(ClassOrInterface klass, ClassMirror classMirror) { // look at its super type TypeMirror superClass = classMirror.getSuperclass(); Type extendedType; if(klass instanceof Interface){ // interfaces need to have their superclass set to Object if(superClass == null || superClass.getKind() == TypeKind.NONE) extendedType = getNonPrimitiveType(getLanguageModule(), CEYLON_OBJECT_TYPE, klass, VarianceLocation.INVARIANT); else extendedType = getNonPrimitiveType(ModelUtil.getModule(klass), superClass, klass, VarianceLocation.INVARIANT); }else if(klass instanceof Class && ((Class) klass).isOverloaded()){ // if the class is overloaded we already have it stored extendedType = klass.getExtendedType(); }else{ String className = classMirror.getQualifiedName(); String superClassName = superClass == null ? null : superClass.getQualifiedName(); if(className.equals("ceylon.language.Anything")){ // ceylon.language.Anything has no super type extendedType = null; }else if(className.equals("java.lang.Object")){ // we pretend its superclass is something else, but note that in theory we shouldn't // be seeing j.l.Object at all due to unerasure extendedType = getNonPrimitiveType(getLanguageModule(), CEYLON_BASIC_TYPE, klass, VarianceLocation.INVARIANT); }else{ // read it from annotation first String annotationSuperClassName = getAnnotationStringValue(classMirror, CEYLON_CLASS_ANNOTATION, "extendsType"); if(annotationSuperClassName != null && !annotationSuperClassName.isEmpty()){ extendedType = decodeType(annotationSuperClassName, klass, ModelUtil.getModuleContainer(klass), "extended type"); }else{ // read it from the Java super type // now deal with type erasure, avoid having Object as superclass if("java.lang.Object".equals(superClassName)){ extendedType = getNonPrimitiveType(getLanguageModule(), CEYLON_BASIC_TYPE, klass, VarianceLocation.INVARIANT); } else if(superClass != null){ try{ extendedType = getNonPrimitiveType(ModelUtil.getModule(klass), superClass, klass, VarianceLocation.INVARIANT); }catch(ModelResolutionException x){ extendedType = logModelResolutionException(x, klass, "Error while resolving extended type of "+klass.getQualifiedNameString()); } }else{ // FIXME: should this be UnknownType? extendedType = null; } } } } if(extendedType != null) klass.setExtendedType(extendedType); } private Type getJavaAnnotationExtendedType(ClassOrInterface klass, ClassMirror classMirror) { TypeDeclaration constrainedAnnotation = (TypeDeclaration) convertNonPrimitiveTypeToDeclaration(getLanguageModule(), CEYLON_CONSTRAINED_ANNOTATION_TYPE, klass, DeclarationType.TYPE); AnnotationMirror target = classMirror.getAnnotation("java.lang.annotation.Target"); Set<Type> types = new HashSet<Type>(); if(target != null){ @SuppressWarnings("unchecked") List<String> values = (List<String>) target.getValue(); for(String value : values){ switch(value){ case "TYPE": TypeDeclaration decl = (TypeDeclaration) convertNonPrimitiveTypeToDeclaration(getLanguageModule(), CEYLON_CLASS_OR_INTERFACE_DECLARATION_TYPE, klass, DeclarationType.TYPE); types.add(decl.getType()); decl = (TypeDeclaration) convertNonPrimitiveTypeToDeclaration(getLanguageModule(), CEYLON_ALIAS_DECLARATION_TYPE, klass, DeclarationType.TYPE); types.add(decl.getType()); break; case "ANNOTATION_TYPE": decl = (TypeDeclaration) convertNonPrimitiveTypeToDeclaration(getLanguageModule(), CEYLON_CLASS_OR_INTERFACE_DECLARATION_TYPE, klass, DeclarationType.TYPE); types.add(decl.getType()); break; case "CONSTRUCTOR": decl = (TypeDeclaration) convertNonPrimitiveTypeToDeclaration(getLanguageModule(), CEYLON_CONSTRUCTOR_DECLARATION_TYPE, klass, DeclarationType.TYPE); types.add(decl.getType()); if (!values.contains("TYPE")) { decl = (TypeDeclaration) convertNonPrimitiveTypeToDeclaration(getLanguageModule(), CEYLON_CLASS_WITH_INIT_DECLARATION_TYPE, klass, DeclarationType.TYPE); types.add(decl.getType()); } break; case "METHOD": // method annotations may be applied to shared members which are turned into getter methods case "PARAMETER": decl = (TypeDeclaration) convertNonPrimitiveTypeToDeclaration(getLanguageModule(), CEYLON_FUNCTION_OR_VALUE_DECLARATION_TYPE, klass, DeclarationType.TYPE); types.add(decl.getType()); break; case "FIELD": case "LOCAL_VARIABLE": decl = (TypeDeclaration) convertNonPrimitiveTypeToDeclaration(getLanguageModule(), CEYLON_VALUE_DECLARATION_TYPE, klass, DeclarationType.TYPE); types.add(decl.getType()); break; default: // all other values are ambiguous or have no mapping } } } Module module = ModelUtil.getModuleContainer(klass); Type annotatedType; if(types.size() == 1) annotatedType = types.iterator().next(); else if(types.isEmpty()){ TypeDeclaration decl; if(target == null){ // default is anything decl = (TypeDeclaration) convertNonPrimitiveTypeToDeclaration(getLanguageModule(), CEYLON_ANNOTATED_TYPE, klass, DeclarationType.TYPE); }else{ // we either had an empty set which means cannot be used as annotation in Java (only as annotation member) // or that we only had unmappable targets decl = typeFactory.getNothingDeclaration(); } annotatedType = decl.getType(); }else{ List<Type> list = new ArrayList<Type>(types.size()); list.addAll(types); annotatedType = union(list, getUnitForModule(module)); } Type constrainedType = constrainedAnnotation.appliedType(null, Arrays.asList(klass.getType(), getOptionalType(klass.getType(), module), annotatedType)); return constrainedType; } private void setParameters(Functional decl, ClassMirror classMirror, MethodMirror methodMirror, boolean isCeylon, Scope container) { ParameterList parameters = new ParameterList(); parameters.setNamedParametersSupported(isCeylon); decl.addParameterList(parameters); int parameterCount = methodMirror.getParameters().size(); int parameterIndex = 0; for(VariableMirror paramMirror : methodMirror.getParameters()){ // ignore some parameters if(paramMirror.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null) continue; boolean isLastParameter = parameterIndex == parameterCount - 1; boolean isVariadic = isLastParameter && methodMirror.isVariadic(); String paramName = getAnnotationStringValue(paramMirror, CEYLON_NAME_ANNOTATION); // use whatever param name we find as default if(paramName == null) paramName = paramMirror.getName(); Parameter parameter = new Parameter(); parameter.setName(paramName); TypeMirror typeMirror = paramMirror.getType(); Module module = ModelUtil.getModuleContainer((Scope) decl); Type type; if(isVariadic){ // possibly make it optional TypeMirror variadicType = typeMirror.getComponentType(); // we pretend it's toplevel because we want to get magic string conversion for variadic methods type = obtainType(ModelUtil.getModuleContainer((Scope)decl), variadicType, (Scope)decl, TypeLocation.TOPLEVEL, VarianceLocation.CONTRAVARIANT); if(!isCeylon && !variadicType.isPrimitive()){ // Java parameters are all optional unless primitives Type optionalType = getOptionalType(type, module); optionalType.setUnderlyingType(type.getUnderlyingType()); type = optionalType; } // turn it into a Sequential<T> type = typeFactory.getSequentialType(type); }else{ type = obtainType(typeMirror, paramMirror, (Scope) decl, module, VarianceLocation.CONTRAVARIANT, "parameter '"+paramName+"' of method '"+methodMirror.getName()+"'", (Declaration)decl); // variadic params may technically be null in Java, but it Ceylon sequenced params may not // so it breaks the typechecker logic for handling them, and it will always be a case of bugs // in the java side so let's not allow this if(!isCeylon && !typeMirror.isPrimitive()){ // Java parameters are all optional unless primitives Type optionalType = getOptionalType(type, module); optionalType.setUnderlyingType(type.getUnderlyingType()); type = optionalType; } } type.setRaw(isRaw(ModelUtil.getModuleContainer(container), typeMirror)); FunctionOrValue value = null; boolean lookedup = false; if (isCeylon && decl instanceof Class){ // For a functional parameter to a class, we can just lookup the member value = (FunctionOrValue)((Class)decl).getDirectMember(paramName, null, false); lookedup = value != null; } if (value == null) { // So either decl is not a Class, // or the method or value member of decl is not shared AnnotationMirror functionalParameterAnnotation = paramMirror.getAnnotation(CEYLON_FUNCTIONAL_PARAMETER_ANNOTATION); if (functionalParameterAnnotation != null) { // A functional parameter to a method Function method = loadFunctionalParameter((Declaration)decl, paramName, type, (String)functionalParameterAnnotation.getValue()); value = method; parameter.setDeclaredAnything(method.isDeclaredVoid()); } else { // A value parameter to a method value = new Value(); value.setType(type); } value.setContainer((Scope) decl); value.setScope((Scope) decl); ModelUtil.setVisibleScope(value); value.setUnit(((Element)decl).getUnit()); value.setName(paramName); }else{ // Ceylon 1.1 had a bug where TypeInfo for functional parameters included the full CallableType on the method // rather than just the method return type, so we try to detect this and fix it if(value instanceof Function && isCeylon1Dot1(classMirror)){ Type newType = getSimpleCallableReturnType(value.getType()); if(!newType.isUnknown()) value.setType(newType); } } value.setInitializerParameter(parameter); parameter.setModel(value); if(paramMirror.getAnnotation(CEYLON_SEQUENCED_ANNOTATION) != null || isVariadic) parameter.setSequenced(true); if(paramMirror.getAnnotation(CEYLON_DEFAULTED_ANNOTATION) != null) parameter.setDefaulted(true); if (parameter.isSequenced() && // FIXME: store info in Sequenced typeFactory.isNonemptyIterableType(parameter.getType())) { parameter.setAtLeastOne(true); } // unboxed is already set if it's a real method if(!lookedup){ // if it's variadic, consider the array element type (T[] == T...) for boxing rules markUnboxed(value, null, isVariadic ? paramMirror.getType().getComponentType() : paramMirror.getType()); } parameter.setDeclaration((Declaration) decl); value.setDeprecated(value.isDeprecated() || isDeprecated(paramMirror)); setAnnotations(value, paramMirror, false); parameters.getParameters().add(parameter); if (!lookedup) { parameter.getDeclaration().getMembers().add(parameter.getModel()); } parameterIndex++; } if (decl instanceof Function) { // Multiple parameter lists AnnotationMirror functionalParameterAnnotation = methodMirror.getAnnotation(CEYLON_FUNCTIONAL_PARAMETER_ANNOTATION); if (functionalParameterAnnotation != null) { parameterNameParser.parseMpl((String)functionalParameterAnnotation.getValue(), ((Function)decl).getType().getFullType(), (Function)decl); } } } private boolean isCeylon1Dot1(ClassMirror classMirror) { AnnotationMirror annotation = classMirror.getAnnotation(CEYLON_CEYLON_ANNOTATION); if(annotation == null) return false; Integer major = (Integer) annotation.getValue("major"); if(major == null) major = 0; Integer minor = (Integer) annotation.getValue("minor"); if(minor == null) minor = 0; return major == Versions.V1_1_BINARY_MAJOR_VERSION && minor == Versions.V1_1_BINARY_MINOR_VERSION; } private Function loadFunctionalParameter(Declaration decl, String paramName, Type type, String parameterNames) { Function method = new Function(); method.setName(paramName); method.setUnit(decl.getUnit()); if (parameterNames == null || parameterNames.isEmpty()) { // This branch is broken, but it deals with old code which lacked // the encoding of parameter names of functional parameters, so we'll keep it until 1.2 method.setType(getSimpleCallableReturnType(type)); ParameterList pl = new ParameterList(); int count = 0; for (Type pt : getSimpleCallableArgumentTypes(type)) { Parameter p = new Parameter(); Value v = new Value(); String name = "arg" + count++; p.setName(name); v.setName(name); v.setType(pt); v.setContainer(method); v.setScope(method); p.setModel(v); v.setInitializerParameter(p); pl.getParameters().add(p); method.addMember(v); } method.addParameterList(pl); } else { try { parameterNameParser.parse(parameterNames, type, method); } catch(Exception x){ logError(x.getClass().getSimpleName() + " while parsing parameter names of "+decl+": " + x.getMessage()); return method; } } return method; } List<Type> getSimpleCallableArgumentTypes(Type type) { if(type != null && type.isClassOrInterface() && type.getDeclaration().getQualifiedNameString().equals(CEYLON_LANGUAGE_CALLABLE_TYPE_NAME) && type.getTypeArgumentList().size() >= 2) return flattenCallableTupleType(type.getTypeArgumentList().get(1)); return Collections.emptyList(); } List<Type> flattenCallableTupleType(Type tupleType) { if(tupleType != null && tupleType.isClassOrInterface()){ String declName = tupleType.getDeclaration().getQualifiedNameString(); if(declName.equals(CEYLON_LANGUAGE_TUPLE_TYPE_NAME)){ List<Type> tal = tupleType.getTypeArgumentList(); if(tal.size() >= 3){ List<Type> ret = flattenCallableTupleType(tal.get(2)); ret.add(0, tal.get(1)); return ret; } }else if(declName.equals(CEYLON_LANGUAGE_EMPTY_TYPE_NAME)){ return new LinkedList<Type>(); }else if(declName.equals(CEYLON_LANGUAGE_SEQUENTIAL_TYPE_NAME)){ LinkedList<Type> ret = new LinkedList<Type>(); ret.add(tupleType); return ret; }else if(declName.equals(CEYLON_LANGUAGE_SEQUENCE_TYPE_NAME)){ LinkedList<Type> ret = new LinkedList<Type>(); ret.add(tupleType); return ret; } } return Collections.emptyList(); } Type getSimpleCallableReturnType(Type type) { if(type != null && type.isClassOrInterface() && type.getDeclaration().getQualifiedNameString().equals(CEYLON_LANGUAGE_CALLABLE_TYPE_NAME) && !type.getTypeArgumentList().isEmpty()) return type.getTypeArgumentList().get(0); return newUnknownType(); } private Type getOptionalType(Type type, Module moduleScope) { if(type.isUnknown()) return type; // we do not use Unit.getOptionalType because it causes lots of lazy loading that ultimately triggers the typechecker's // infinite recursion loop List<Type> list = new ArrayList<Type>(2); list.add(typeFactory.getNullType()); list.add(type); return union(list, getUnitForModule(moduleScope)); } private Type logModelResolutionError(Scope container, String message) { return logModelResolutionException((String)null, container, message); } private Type logModelResolutionException(ModelResolutionException x, Scope container, String message) { return logModelResolutionException(x.getMessage(), container, message); } private Type logModelResolutionException(final String exceptionMessage, Scope container, final String message) { final Module module = ModelUtil.getModuleContainer(container); return logModelResolutionException(exceptionMessage, module, message); } private Type logModelResolutionException(final String exceptionMessage, Module module, final String message) { UnknownType.ErrorReporter errorReporter; if(module != null && !module.isDefault()){ final StringBuilder sb = new StringBuilder(); sb.append("Error while loading the ").append(module.getNameAsString()).append("/").append(module.getVersion()); sb.append(" module:\n "); sb.append(message); if(exceptionMessage != null) sb.append(":\n ").append(exceptionMessage); errorReporter = makeModelErrorReporter(module, sb.toString()); }else if(exceptionMessage == null){ errorReporter = makeModelErrorReporter(message); }else{ errorReporter = makeModelErrorReporter(message+": "+exceptionMessage); } UnknownType ret = new UnknownType(typeFactory); ret.setErrorReporter(errorReporter); return ret.getType(); } /** * To be overridden by subclasses */ protected UnknownType.ErrorReporter makeModelErrorReporter(String message) { return new LogErrorRunnable(this, message); } /** * To be overridden by subclasses */ protected abstract UnknownType.ErrorReporter makeModelErrorReporter(Module module, String message); private static class LogErrorRunnable extends UnknownType.ErrorReporter { private AbstractModelLoader modelLoader; public LogErrorRunnable(AbstractModelLoader modelLoader, String message) { super(message); this.modelLoader = modelLoader; } @Override public void reportError() { modelLoader.logError(getMessage()); } } private void markTypeErased(TypedDeclaration decl, AnnotatedMirror typedMirror, TypeMirror type) { if (BooleanUtil.isTrue(getAnnotationBooleanValue(typedMirror, CEYLON_TYPE_INFO_ANNOTATION, "erased"))) { decl.setTypeErased(true); } else { decl.setTypeErased(sameType(type, OBJECT_TYPE)); } } private void markUntrustedType(TypedDeclaration decl, AnnotatedMirror typedMirror, TypeMirror type) { if (BooleanUtil.isTrue(getAnnotationBooleanValue(typedMirror, CEYLON_TYPE_INFO_ANNOTATION, "untrusted"))) { decl.setUntrustedType(true); } } private void markDeclaredVoid(Function decl, MethodMirror methodMirror) { if (methodMirror.isDeclaredVoid() || BooleanUtil.isTrue(getAnnotationBooleanValue(methodMirror, CEYLON_TYPE_INFO_ANNOTATION, "declaredVoid"))) { decl.setDeclaredVoid(true); } } /*private boolean hasTypeParameterWithConstraints(TypeMirror type) { switch(type.getKind()){ case BOOLEAN: case BYTE: case CHAR: case DOUBLE: case FLOAT: case INT: case LONG: case SHORT: case VOID: case WILDCARD: return false; case ARRAY: return hasTypeParameterWithConstraints(type.getComponentType()); case DECLARED: for(TypeMirror ta : type.getTypeArguments()){ if(hasTypeParameterWithConstraints(ta)) return true; } return false; case TYPEVAR: TypeParameterMirror typeParameter = type.getTypeParameter(); return typeParameter != null && hasNonErasedBounds(typeParameter); default: return false; } }*/ private void markUnboxed(TypedDeclaration decl, MethodMirror methodMirror, TypeMirror type) { boolean unboxed = false; if(type.isPrimitive() || type.getKind() == TypeKind.ARRAY || sameType(type, STRING_TYPE) || (methodMirror != null && methodMirror.isDeclaredVoid())) { unboxed = true; } decl.setUnboxed(unboxed); } @Override public void complete(LazyValue value) { synchronized(getLock()){ timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY); try{ MethodMirror meth = getGetterMethodMirror(value, value.classMirror, value.isToplevel()); if(meth == null || meth.getReturnType() == null){ value.setType(logModelResolutionError(value.getContainer(), "Error while resolving toplevel attribute "+value.getQualifiedNameString()+": getter method missing")); return; } value.setDeprecated(value.isDeprecated() | isDeprecated(meth)); value.setType(obtainType(meth.getReturnType(), meth, null, ModelUtil.getModuleContainer(value.getContainer()), VarianceLocation.INVARIANT, "toplevel attribute", value)); markVariable(value); setValueTransientLateFlags(value, meth, true); setAnnotations(value, meth, value.isNativeHeader()); markUnboxed(value, meth, meth.getReturnType()); markTypeErased(value, meth, meth.getReturnType()); TypeMirror setterClass = (TypeMirror) getAnnotationValue(value.classMirror, CEYLON_ATTRIBUTE_ANNOTATION, "setterClass"); // void.class is the default value, I guess it's a primitive? if(setterClass != null && !setterClass.isPrimitive()){ ClassMirror setterClassMirror = setterClass.getDeclaredClass(); value.setVariable(true); SetterWithLocalDeclarations setter = makeSetter(value, setterClassMirror); // adding local scopes should be done last, when we have the setter, because it may be needed by container chain addLocalDeclarations(value, value.classMirror, value.classMirror); addLocalDeclarations(setter, setterClassMirror, setterClassMirror); }else if(value.isToplevel() && value.isTransient() && value.isVariable()){ makeSetter(value, value.classMirror); // all local scopes for getter/setter are declared in the same class // adding local scopes should be done last, when we have the setter, because it may be needed by container chain addLocalDeclarations(value, value.classMirror, value.classMirror); }else{ // adding local scopes should be done last, when we have the setter, because it may be needed by container chain addLocalDeclarations(value, value.classMirror, value.classMirror); } }finally{ timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY); } } } private MethodMirror getGetterMethodMirror(Declaration value, ClassMirror classMirror, boolean toplevel) { MethodMirror meth = null; String getterName; if (toplevel) { // We do this to prevent calling complete() unnecessarily getterName = NamingBase.Unfix.get_.name(); } else { getterName = NamingBase.getGetterName(value); } for (MethodMirror m : classMirror.getDirectMethods()) { // Do not skip members marked with @Ignore, because the getter is supposed to be ignored if (m.getName().equals(getterName) && (!toplevel || m.isStatic()) && m.getParameters().size() == 0) { meth = m; break; } } return meth; } private void markVariable(LazyValue value) { String setterName = NamingBase.getSetterName(value); boolean toplevel = value.isToplevel(); for (MethodMirror m : value.classMirror.getDirectMethods()) { // Do not skip members marked with @Ignore, because the getter is supposed to be ignored if (m.getName().equals(setterName) && (!toplevel || m.isStatic()) && m.getParameters().size() == 1) { value.setVariable(true); } } } private SetterWithLocalDeclarations makeSetter(Value value, ClassMirror classMirror) { SetterWithLocalDeclarations setter = new SetterWithLocalDeclarations(classMirror); setter.setContainer(value.getContainer()); setter.setScope(value.getContainer()); setter.setType(value.getType()); setter.setName(value.getName()); Parameter p = new Parameter(); p.setHidden(true); Value v = new Value(); v.setType(value.getType()); v.setUnboxed(value.getUnboxed()); v.setInitializerParameter(p); v.setContainer(setter); p.setModel(v); v.setName(setter.getName()); p.setName(setter.getName()); p.setDeclaration(setter); setter.setParameter(p); value.setSetter(setter); setter.setGetter(value); return setter; } @Override public void complete(LazyFunction method) { synchronized(getLock()){ timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY); try{ MethodMirror meth = getFunctionMethodMirror(method); if(meth == null || meth.getReturnType() == null){ method.setType(logModelResolutionError(method.getContainer(), "Error while resolving toplevel method "+method.getQualifiedNameString()+": static method missing")); return; } // only check the static mod for toplevel classes if(!method.classMirror.isLocalClass() && !meth.isStatic()){ method.setType(logModelResolutionError(method.getContainer(), "Error while resolving toplevel method "+method.getQualifiedNameString()+": method is not static")); return; } method.setDeprecated(method.isDeprecated() | isDeprecated(meth)); // save the method name method.setRealMethodName(meth.getName()); // save the method method.setMethodMirror(meth); // type params first setTypeParameters(method, meth, true); method.setType(obtainType(meth.getReturnType(), meth, method, ModelUtil.getModuleContainer(method), VarianceLocation.COVARIANT, "toplevel method", method)); method.setDeclaredVoid(meth.isDeclaredVoid()); markDeclaredVoid(method, meth); markUnboxed(method, meth, meth.getReturnType()); markTypeErased(method, meth, meth.getReturnType()); markUntrustedType(method, meth, meth.getReturnType()); // now its parameters setParameters(method, method.classMirror, meth, true /* toplevel methods are always Ceylon */, method); method.setAnnotation(meth.getAnnotation(CEYLON_LANGUAGE_ANNOTATION_ANNOTATION) != null); setAnnotations(method, meth, method.isNativeHeader()); setAnnotationConstructor(method, meth); addLocalDeclarations(method, method.classMirror, method.classMirror); }finally{ timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY); } } } private MethodMirror getFunctionMethodMirror(LazyFunction method) { MethodMirror meth = null; String lookupName = method.getName(); for(MethodMirror m : method.classMirror.getDirectMethods()){ // We skip members marked with @Ignore if(m.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null) continue; if(NamingBase.stripLeadingDollar(m.getName()).equals(lookupName)){ meth = m; break; } } return meth; } // for subclasses protected abstract void setAnnotationConstructor(LazyFunction method, MethodMirror meth); public AnnotationProxyMethod makeInteropAnnotationConstructor(LazyInterface iface, AnnotationProxyClass klass, OutputElement oe, Package pkg){ String ctorName = oe == null ? NamingBase.getJavaBeanName(iface.getName()) : NamingBase.getDisambigAnnoCtorName(iface, oe); AnnotationProxyMethod ctor = new AnnotationProxyMethod(); ctor.setAnnotationTarget(oe); ctor.setProxyClass(klass); ctor.setContainer(pkg); ctor.setAnnotation(true); ctor.setName(ctorName); ctor.setShared(iface.isShared()); Annotation annotationAnnotation2 = new Annotation(); annotationAnnotation2.setName("annotation"); ctor.getAnnotations().add(annotationAnnotation2); ctor.setType(((TypeDeclaration)iface).getType()); ctor.setUnit(iface.getUnit()); ParameterList ctorpl = new ParameterList(); ctorpl.setPositionalParametersSupported(false); ctor.addParameterList(ctorpl); List<Parameter> ctorParams = new ArrayList<Parameter>(); for (Declaration member : iface.getMembers()) { boolean isValue = member.getName().equals("value"); if (member instanceof JavaMethod) { JavaMethod m = (JavaMethod)member; Parameter ctorParam = new Parameter(); ctorParams.add(ctorParam); Value value = new Value(); ctorParam.setModel(value); value.setInitializerParameter(ctorParam); ctorParam.setDeclaration(ctor); value.setContainer(klass); value.setScope(klass); ctorParam.setDefaulted(m.isDefaultedAnnotation()); value.setName(member.getName()); ctorParam.setName(member.getName()); value.setType(annotationParameterType(iface.getUnit(), m)); value.setUnboxed(true); value.setUnit(iface.getUnit()); if(isValue) ctorpl.getParameters().add(0, ctorParam); else ctorpl.getParameters().add(ctorParam); ctor.addMember(value); } } makeInteropAnnotationConstructorInvocation(ctor, klass, ctorParams); return ctor; } /** * For subclasses that provide compilation to Java annotations. */ protected abstract void makeInteropAnnotationConstructorInvocation(AnnotationProxyMethod ctor, AnnotationProxyClass klass, List<Parameter> ctorParams); /** * <pre> * annotation class Annotation$Proxy(...) satisfies Annotation { * // a `shared` class parameter for each method of Annotation * } * </pre> * @param iface The model of the annotation @interface * @return The annotation class for the given interface */ public AnnotationProxyClass makeInteropAnnotationClass( LazyInterface iface, Package pkg) { AnnotationProxyClass klass = new AnnotationProxyClass(iface); klass.setContainer(pkg); klass.setScope(pkg); klass.setName(iface.getName()+"$Proxy"); klass.setShared(iface.isShared()); klass.setAnnotation(true); Annotation annotationAnnotation = new Annotation(); annotationAnnotation.setName("annotation"); klass.getAnnotations().add(annotationAnnotation); klass.getSatisfiedTypes().add(iface.getType()); klass.setUnit(iface.getUnit()); ParameterList classpl = new ParameterList(); klass.addParameterList(classpl); klass.setScope(pkg); for (Declaration member : iface.getMembers()) { boolean isValue = member.getName().equals("value"); if (member instanceof JavaMethod) { JavaMethod m = (JavaMethod)member; Parameter klassParam = new Parameter(); Value value = new Value(); klassParam.setModel(value); value.setInitializerParameter(klassParam); klassParam.setDeclaration(klass); value.setContainer(klass); value.setScope(klass); value.setName(member.getName()); klassParam.setName(member.getName()); value.setType(annotationParameterType(iface.getUnit(), m)); value.setUnboxed(true); value.setUnit(iface.getUnit()); if(isValue) classpl.getParameters().add(0, klassParam); else classpl.getParameters().add(klassParam); klass.addMember(value); } } return klass; } private Type annotationParameterType(Unit unit, JavaMethod m) { Type type = m.getType(); if (JvmBackendUtil.isJavaArray(type.getDeclaration())) { String name = type.getDeclaration().getQualifiedNameString(); final Type elementType; String underlyingType = null; if(name.equals("java.lang::ObjectArray")){ Type eType = type.getTypeArgumentList().get(0); String elementTypeName = eType.getDeclaration().getQualifiedNameString(); if ("java.lang::String".equals(elementTypeName)) { elementType = unit.getStringType(); } else if ("java.lang::Class".equals(elementTypeName) || "java.lang.Class".equals(eType.getUnderlyingType())) { // Two cases because the types // Class[] and Class<?>[] are treated differently by // AbstractModelLoader.obtainType() // TODO Replace with metamodel ClassOrInterface type // once we have support for metamodel references elementType = unit.getAnythingType(); underlyingType = "java.lang.Class"; } else { elementType = eType; } // TODO Enum elements } else if(name.equals("java.lang::LongArray")) { elementType = unit.getIntegerType(); } else if (name.equals("java.lang::ByteArray")) { elementType = unit.getByteType(); } else if (name.equals("java.lang::ShortArray")) { elementType = unit.getIntegerType(); underlyingType = "short"; } else if (name.equals("java.lang::IntArray")){ elementType = unit.getIntegerType(); underlyingType = "int"; } else if(name.equals("java.lang::BooleanArray")){ elementType = unit.getBooleanType(); } else if(name.equals("java.lang::CharArray")){ elementType = unit.getCharacterType(); underlyingType = "char"; } else if(name.equals("java.lang::DoubleArray")) { elementType = unit.getFloatType(); } else if (name.equals("java.lang::FloatArray")){ elementType = unit.getFloatType(); underlyingType = "float"; } else { throw new RuntimeException(); } elementType.setUnderlyingType(underlyingType); Type iterableType = unit.getIterableType(elementType); return iterableType; } else if ("java.lang::Class".equals(type.getDeclaration().getQualifiedNameString())) { // TODO Replace with metamodel ClassOrInterface type // once we have support for metamodel references return unit.getAnythingType(); } else { return type; } } // // Satisfied Types private List<String> getSatisfiedTypesFromAnnotations(AnnotatedMirror symbol) { return getAnnotationArrayValue(symbol, CEYLON_SATISFIED_TYPES_ANNOTATION); } private void setSatisfiedTypes(ClassOrInterface klass, ClassMirror classMirror) { List<String> satisfiedTypes = getSatisfiedTypesFromAnnotations(classMirror); if(satisfiedTypes != null){ klass.getSatisfiedTypes().addAll(getTypesList(satisfiedTypes, klass, ModelUtil.getModuleContainer(klass), "satisfied types", klass.getQualifiedNameString())); }else{ if(classMirror.isAnnotationType()) // this only happens for Java annotations since Ceylon annotations are ignored // turn @Target into a subtype of ConstrainedAnnotation klass.getSatisfiedTypes().add(getJavaAnnotationExtendedType(klass, classMirror)); for(TypeMirror iface : classMirror.getInterfaces()){ // ignore generated interfaces if(sameType(iface, CEYLON_REIFIED_TYPE_TYPE) || sameType(iface, CEYLON_SERIALIZABLE_TYPE) || (classMirror.getAnnotation(CEYLON_CEYLON_ANNOTATION) != null && sameType(iface, JAVA_IO_SERIALIZABLE_TYPE_TYPE))) continue; try{ klass.getSatisfiedTypes().add(getNonPrimitiveType(ModelUtil.getModule(klass), iface, klass, VarianceLocation.INVARIANT)); }catch(ModelResolutionException x){ String classPackageName = unquotePackageName(classMirror.getPackage()); if(JDKUtils.isJDKAnyPackage(classPackageName)){ if(iface.getKind() == TypeKind.DECLARED){ // check if it's a JDK thing ClassMirror ifaceClass = iface.getDeclaredClass(); String ifacePackageName = unquotePackageName(ifaceClass.getPackage()); if(JDKUtils.isOracleJDKAnyPackage(ifacePackageName)){ // just log and ignore it logMissingOracleType(iface.getQualifiedName()); continue; } } } } } } } // // Case Types private List<String> getCaseTypesFromAnnotations(AnnotatedMirror symbol) { return getAnnotationArrayValue(symbol, CEYLON_CASE_TYPES_ANNOTATION); } private String getSelfTypeFromAnnotations(AnnotatedMirror symbol) { return getAnnotationStringValue(symbol, CEYLON_CASE_TYPES_ANNOTATION, "of"); } private void setCaseTypes(ClassOrInterface klass, ClassMirror classMirror) { if (classMirror.isEnum()) { ArrayList<Type> caseTypes = new ArrayList<Type>(); for (Declaration member : klass.getMembers()) { if (member instanceof FieldValue && ((FieldValue) member).isEnumValue()) { caseTypes.add(((FieldValue)member).getType()); } } klass.setCaseTypes(caseTypes); } else { String selfType = getSelfTypeFromAnnotations(classMirror); Module moduleScope = ModelUtil.getModuleContainer(klass); if(selfType != null && !selfType.isEmpty()){ Type type = decodeType(selfType, klass, moduleScope, "self type"); if(!type.isTypeParameter()){ logError("Invalid type signature for self type of "+klass.getQualifiedNameString()+": "+selfType+" is not a type parameter"); }else{ klass.setSelfType(type); List<Type> caseTypes = new LinkedList<Type>(); caseTypes.add(type); klass.setCaseTypes(caseTypes); } } else { List<String> caseTypes = getCaseTypesFromAnnotations(classMirror); if(caseTypes != null && !caseTypes.isEmpty()){ klass.setCaseTypes(getTypesList(caseTypes, klass, moduleScope, "case types", klass.getQualifiedNameString())); } } } } private List<Type> getTypesList(List<String> caseTypes, Scope scope, Module moduleScope, String targetType, String targetName) { List<Type> producedTypes = new LinkedList<Type>(); for(String type : caseTypes){ producedTypes.add(decodeType(type, scope, moduleScope, targetType)); } return producedTypes; } // // Type parameters loading @SuppressWarnings("unchecked") private List<AnnotationMirror> getTypeParametersFromAnnotations(AnnotatedMirror symbol) { return (List<AnnotationMirror>) getAnnotationValue(symbol, CEYLON_TYPE_PARAMETERS); } // from our annotation private void setTypeParametersFromAnnotations(Scope scope, List<TypeParameter> params, AnnotatedMirror mirror, List<AnnotationMirror> typeParameterAnnotations, List<TypeParameterMirror> typeParameterMirrors) { // We must first add every type param, before we resolve the bounds, which can // refer to type params. String selfTypeName = getSelfTypeFromAnnotations(mirror); int i=0; for(AnnotationMirror typeParamAnnotation : typeParameterAnnotations){ TypeParameter param = new TypeParameter(); param.setUnit(((Element)scope).getUnit()); param.setContainer(scope); param.setScope(scope); ModelUtil.setVisibleScope(param); param.setDeclaration((Declaration) scope); // let's not trigger the lazy-loading if we're completing a LazyClass/LazyInterface if(scope instanceof LazyContainer) ((LazyContainer)scope).addMember(param); else // must be a method scope.addMember(param); param.setName((String)typeParamAnnotation.getValue("value")); param.setExtendedType(typeFactory.getAnythingType()); if(i < typeParameterMirrors.size()){ TypeParameterMirror typeParameterMirror = typeParameterMirrors.get(i); param.setNonErasedBounds(hasNonErasedBounds(typeParameterMirror)); } String varianceName = (String) typeParamAnnotation.getValue("variance"); if(varianceName != null){ if(varianceName.equals("IN")){ param.setContravariant(true); }else if(varianceName.equals("OUT")) param.setCovariant(true); } // If this is a self type param then link it to its type's declaration if (param.getName().equals(selfTypeName)) { param.setSelfTypedDeclaration((TypeDeclaration)scope); } params.add(param); i++; } Module moduleScope = ModelUtil.getModuleContainer(scope); // Now all type params have been set, we can resolve the references parts Iterator<TypeParameter> paramsIterator = params.iterator(); for(AnnotationMirror typeParamAnnotation : typeParameterAnnotations){ TypeParameter param = paramsIterator.next(); @SuppressWarnings("unchecked") List<String> satisfiesAttribute = (List<String>)typeParamAnnotation.getValue("satisfies"); setListOfTypes(param.getSatisfiedTypes(), satisfiesAttribute, scope, moduleScope, "type parameter '"+param.getName()+"' satisfied types"); @SuppressWarnings("unchecked") List<String> caseTypesAttribute = (List<String>)typeParamAnnotation.getValue("caseTypes"); if(caseTypesAttribute != null && !caseTypesAttribute.isEmpty()) param.setCaseTypes(new LinkedList<Type>()); setListOfTypes(param.getCaseTypes(), caseTypesAttribute, scope, moduleScope, "type parameter '"+param.getName()+"' case types"); String defaultValueAttribute = (String)typeParamAnnotation.getValue("defaultValue"); if(defaultValueAttribute != null && !defaultValueAttribute.isEmpty()){ Type decodedType = decodeType(defaultValueAttribute, scope, moduleScope, "type parameter '"+param.getName()+"' defaultValue"); param.setDefaultTypeArgument(decodedType); param.setDefaulted(true); } } } private boolean hasNonErasedBounds(TypeParameterMirror typeParameterMirror) { List<TypeMirror> bounds = typeParameterMirror.getBounds(); // if we have at least one bound and not a single Object one return bounds.size() > 0 && (bounds.size() != 1 || !sameType(bounds.get(0), OBJECT_TYPE)); } private void setListOfTypes(List<Type> destinationTypeList, List<String> serialisedTypes, Scope scope, Module moduleScope, String targetType) { if(serialisedTypes != null){ for (String serialisedType : serialisedTypes) { Type decodedType = decodeType(serialisedType, scope, moduleScope, targetType); destinationTypeList.add(decodedType); } } } // from java type info private void setTypeParameters(Scope scope, List<TypeParameter> params, List<TypeParameterMirror> typeParameters, boolean isCeylon) { // We must first add every type param, before we resolve the bounds, which can // refer to type params. for(TypeParameterMirror typeParam : typeParameters){ TypeParameter param = new TypeParameter(); param.setUnit(((Element)scope).getUnit()); param.setContainer(scope); param.setScope(scope); ModelUtil.setVisibleScope(param); param.setDeclaration((Declaration) scope); // let's not trigger the lazy-loading if we're completing a LazyClass/LazyInterface if(scope instanceof LazyContainer) ((LazyContainer)scope).addMember(param); else // must be a method scope.addMember(param); param.setName(typeParam.getName()); param.setExtendedType(typeFactory.getAnythingType()); params.add(param); } boolean needsObjectBounds = !isCeylon && scope instanceof Function; // Now all type params have been set, we can resolve the references parts Iterator<TypeParameter> paramsIterator = params.iterator(); for(TypeParameterMirror typeParam : typeParameters){ TypeParameter param = paramsIterator.next(); List<TypeMirror> bounds = typeParam.getBounds(); for(TypeMirror bound : bounds){ Type boundType; // we turn java's default upper bound java.lang.Object into ceylon.language.Object if(sameType(bound, OBJECT_TYPE)){ // avoid adding java's default upper bound if it's just there with no meaning, // especially since we do not want it for types if(bounds.size() == 1) break; boundType = getNonPrimitiveType(getLanguageModule(), CEYLON_OBJECT_TYPE, scope, VarianceLocation.INVARIANT); }else boundType = getNonPrimitiveType(ModelUtil.getModuleContainer(scope), bound, scope, VarianceLocation.INVARIANT); param.getSatisfiedTypes().add(boundType); } if(needsObjectBounds && param.getSatisfiedTypes().isEmpty()){ Type boundType = getNonPrimitiveType(getLanguageModule(), CEYLON_OBJECT_TYPE, scope, VarianceLocation.INVARIANT); param.getSatisfiedTypes().add(boundType); } } } // method private void setTypeParameters(Function method, MethodMirror methodMirror, boolean isCeylon) { List<TypeParameter> params = new LinkedList<TypeParameter>(); method.setTypeParameters(params); List<AnnotationMirror> typeParameters = getTypeParametersFromAnnotations(methodMirror); if(typeParameters != null) { setTypeParametersFromAnnotations(method, params, methodMirror, typeParameters, methodMirror.getTypeParameters()); } else { setTypeParameters(method, params, methodMirror.getTypeParameters(), isCeylon); } } // class private void setTypeParameters(TypeDeclaration klass, ClassMirror classMirror, boolean isCeylon) { List<AnnotationMirror> typeParameters = getTypeParametersFromAnnotations(classMirror); List<TypeParameterMirror> mirrorTypeParameters = classMirror.getTypeParameters(); if(typeParameters != null) { if(typeParameters.isEmpty()) return; List<TypeParameter> params = new ArrayList<TypeParameter>(typeParameters.size()); klass.setTypeParameters(params); setTypeParametersFromAnnotations(klass, params, classMirror, typeParameters, mirrorTypeParameters); } else { if(mirrorTypeParameters.isEmpty()) return; List<TypeParameter> params = new ArrayList<TypeParameter>(mirrorTypeParameters.size()); klass.setTypeParameters(params); setTypeParameters(klass, params, mirrorTypeParameters, isCeylon); } } // // TypeParsing and ModelLoader private Type decodeType(String value, Scope scope, Module moduleScope, String targetType) { return decodeType(value, scope, moduleScope, targetType, null); } private Type decodeType(String value, Scope scope, Module moduleScope, String targetType, Declaration target) { try{ return typeParser.decodeType(value, scope, moduleScope, getUnitForModule(moduleScope)); }catch(TypeParserException x){ String text = formatTypeErrorMessage("Error while parsing type of", targetType, target, scope); return logModelResolutionException(x.getMessage(), scope, text); }catch(ModelResolutionException x){ String text = formatTypeErrorMessage("Error while resolving type of", targetType, target, scope); return logModelResolutionException(x, scope, text); } } private Unit getUnitForModule(Module module) { List<Package> packages = module.getPackages(); if(packages.isEmpty()){ System.err.println("No package for module "+module.getNameAsString()); return null; } Package pkg = packages.get(0); if(pkg instanceof LazyPackage == false){ System.err.println("No lazy package for module "+module.getNameAsString()); return null; } Unit unit = getCompiledUnit((LazyPackage) pkg, null); if(unit == null){ System.err.println("No unit for module "+module.getNameAsString()); return null; } return unit; } private String formatTypeErrorMessage(String prefix, String targetType, Declaration target, Scope scope) { String forTarget; if(target != null) forTarget = " for "+target.getQualifiedNameString(); else if(scope != null) forTarget = " for "+scope.getQualifiedNameString(); else forTarget = ""; return prefix+" "+targetType+forTarget; } /** Warning: only valid for toplevel types, not for type parameters */ private Type obtainType(TypeMirror type, AnnotatedMirror symbol, Scope scope, Module moduleScope, VarianceLocation variance, String targetType, Declaration target) { String typeName = getAnnotationStringValue(symbol, CEYLON_TYPE_INFO_ANNOTATION); if (typeName != null) { Type ret = decodeType(typeName, scope, moduleScope, targetType, target); // even decoded types need to fit with the reality of the underlying type ret.setUnderlyingType(getUnderlyingType(type, TypeLocation.TOPLEVEL)); return ret; } else { try{ return obtainType(moduleScope, type, scope, TypeLocation.TOPLEVEL, variance); }catch(ModelResolutionException x){ String text = formatTypeErrorMessage("Error while resolving type of", targetType, target, scope); return logModelResolutionException(x, scope, text); } } } private enum TypeLocation { TOPLEVEL, TYPE_PARAM; } private enum VarianceLocation { /** * Used in parameter */ CONTRAVARIANT, /** * Used in method return value */ COVARIANT, /** * For field */ INVARIANT; } private String getUnderlyingType(TypeMirror type, TypeLocation location){ // don't erase to c.l.String if in a type param location if ((sameType(type, STRING_TYPE) && location != TypeLocation.TYPE_PARAM) || sameType(type, PRIM_BYTE_TYPE) || sameType(type, PRIM_SHORT_TYPE) || sameType(type, PRIM_INT_TYPE) || sameType(type, PRIM_FLOAT_TYPE) || sameType(type, PRIM_CHAR_TYPE)) { return type.getQualifiedName(); } return null; } public Type obtainType(Module moduleScope, TypeMirror type, Scope scope, TypeLocation location, VarianceLocation variance) { TypeMirror originalType = type; // ERASURE type = applyTypeMapping(type, location); Type ret = getNonPrimitiveType(moduleScope, type, scope, variance); if (ret.getUnderlyingType() == null) { ret.setUnderlyingType(getUnderlyingType(originalType, location)); } return ret; } private TypeMirror applyTypeMapping(TypeMirror type, TypeLocation location) { // don't erase to c.l.String if in a type param location if (sameType(type, STRING_TYPE) && location != TypeLocation.TYPE_PARAM) { return CEYLON_STRING_TYPE; } else if (sameType(type, PRIM_BOOLEAN_TYPE)) { return CEYLON_BOOLEAN_TYPE; } else if (sameType(type, PRIM_BYTE_TYPE)) { return CEYLON_BYTE_TYPE; } else if (sameType(type, PRIM_SHORT_TYPE)) { return CEYLON_INTEGER_TYPE; } else if (sameType(type, PRIM_INT_TYPE)) { return CEYLON_INTEGER_TYPE; } else if (sameType(type, PRIM_LONG_TYPE)) { return CEYLON_INTEGER_TYPE; } else if (sameType(type, PRIM_FLOAT_TYPE)) { return CEYLON_FLOAT_TYPE; } else if (sameType(type, PRIM_DOUBLE_TYPE)) { return CEYLON_FLOAT_TYPE; } else if (sameType(type, PRIM_CHAR_TYPE)) { return CEYLON_CHARACTER_TYPE; } else if (sameType(type, OBJECT_TYPE)) { return CEYLON_OBJECT_TYPE; } else if (sameType(type, THROWABLE_TYPE)) { return CEYLON_THROWABLE_TYPE; } else if (sameType(type, EXCEPTION_TYPE)) { return CEYLON_EXCEPTION_TYPE; } else if (sameType(type, ANNOTATION_TYPE)) { // here we prefer Annotation over ConstrainedAnnotation but that's fine return CEYLON_ANNOTATION_TYPE; } else if (type.getKind() == TypeKind.ARRAY) { TypeMirror ct = type.getComponentType(); if (sameType(ct, PRIM_BOOLEAN_TYPE)) { return JAVA_BOOLEAN_ARRAY_TYPE; } else if (sameType(ct, PRIM_BYTE_TYPE)) { return JAVA_BYTE_ARRAY_TYPE; } else if (sameType(ct, PRIM_SHORT_TYPE)) { return JAVA_SHORT_ARRAY_TYPE; } else if (sameType(ct, PRIM_INT_TYPE)) { return JAVA_INT_ARRAY_TYPE; } else if (sameType(ct, PRIM_LONG_TYPE)) { return JAVA_LONG_ARRAY_TYPE; } else if (sameType(ct, PRIM_FLOAT_TYPE)) { return JAVA_FLOAT_ARRAY_TYPE; } else if (sameType(ct, PRIM_DOUBLE_TYPE)) { return JAVA_DOUBLE_ARRAY_TYPE; } else if (sameType(ct, PRIM_CHAR_TYPE)) { return JAVA_CHAR_ARRAY_TYPE; } else { // object array return new SimpleReflType(JAVA_LANG_OBJECT_ARRAY, SimpleReflType.Module.JDK, TypeKind.DECLARED, ct); } } return type; } private boolean sameType(TypeMirror t1, TypeMirror t2) { // make sure we deal with arrays which can't have a qualified name if(t1.getKind() == TypeKind.ARRAY){ if(t2.getKind() != TypeKind.ARRAY) return false; return sameType(t1.getComponentType(), t2.getComponentType()); } if(t2.getKind() == TypeKind.ARRAY) return false; // the rest should be OK return t1.getQualifiedName().equals(t2.getQualifiedName()); } @Override public Declaration getDeclaration(Module module, String typeName, DeclarationType declarationType) { return convertToDeclaration(module, typeName, declarationType); } private Type getNonPrimitiveType(Module moduleScope, TypeMirror type, Scope scope, VarianceLocation variance) { TypeDeclaration declaration = (TypeDeclaration) convertNonPrimitiveTypeToDeclaration(moduleScope, type, scope, DeclarationType.TYPE); if(declaration == null){ throw new ModelResolutionException("Failed to find declaration for "+type.getQualifiedName()); } return applyTypeArguments(moduleScope, declaration, type, scope, variance, TypeMappingMode.NORMAL, null); } private enum TypeMappingMode { NORMAL, GENERATOR } @SuppressWarnings("serial") private static class RecursiveTypeParameterBoundException extends RuntimeException {} private Type applyTypeArguments(Module moduleScope, TypeDeclaration declaration, TypeMirror type, Scope scope, VarianceLocation variance, TypeMappingMode mode, Set<TypeDeclaration> rawDeclarationsSeen) { List<TypeMirror> javacTypeArguments = type.getTypeArguments(); boolean hasTypeParameters = !declaration.getTypeParameters().isEmpty(); boolean hasTypeArguments = !javacTypeArguments.isEmpty(); boolean isRaw = !hasTypeArguments && hasTypeParameters; // if we have type arguments or type parameters (raw) if(hasTypeArguments || isRaw){ // if it's raw we will need the map anyways if(rawDeclarationsSeen == null) rawDeclarationsSeen = new HashSet<TypeDeclaration>(); // detect recursive bounds that we can't possibly satisfy, such as Foo<T extends Foo<T>> if(rawDeclarationsSeen != null && !rawDeclarationsSeen.add(declaration)) throw new RecursiveTypeParameterBoundException(); try{ List<Type> typeArguments = new ArrayList<Type>(javacTypeArguments.size()); List<TypeParameter> typeParameters = declaration.getTypeParameters(); List<TypeParameterMirror> typeParameterMirrors = null; // SimpleReflType for Object and friends don't have a type, but don't need one if(type.getDeclaredClass() != null) typeParameterMirrors = type.getDeclaredClass().getTypeParameters(); Map<TypeParameter,SiteVariance> siteVarianceMap = null; int len = hasTypeArguments ? javacTypeArguments.size() : typeParameters.size(); for(int i=0 ; i<len ; i++){ TypeParameter typeParameter = null; if(i < typeParameters.size()) typeParameter = typeParameters.get(i); Type producedTypeArgument = null; // do we have a type argument? TypeMirror typeArgument = null; SiteVariance siteVariance = null; if(hasTypeArguments){ typeArgument = javacTypeArguments.get(i); // if a single type argument is a wildcard and we are in a covariant location, we erase to Object if(typeArgument.getKind() == TypeKind.WILDCARD){ TypeMirror bound = typeArgument.getUpperBound(); if(bound != null){ siteVariance = SiteVariance.OUT; } else { bound = typeArgument.getLowerBound(); if(bound != null){ // it has a lower bound siteVariance = SiteVariance.IN; } } // use the bound in any case typeArgument = bound; } } // if we have no type argument, or if it's a wildcard with no bound, use the type parameter bounds if we can if(typeArgument == null && typeParameterMirrors != null && i < typeParameterMirrors.size()){ TypeParameterMirror typeParameterMirror = typeParameterMirrors.get(i); // FIXME: multiple bounds? if(typeParameterMirror.getBounds().size() == 1){ // make sure we don't go overboard if(rawDeclarationsSeen == null){ rawDeclarationsSeen = new HashSet<TypeDeclaration>(); // detect recursive bounds that we can't possibly satisfy, such as Foo<T extends Foo<T>> if(!rawDeclarationsSeen.add(declaration)) throw new RecursiveTypeParameterBoundException(); } TypeMirror bound = typeParameterMirror.getBounds().get(0); try{ producedTypeArgument = obtainTypeParameterBound(moduleScope, bound, declaration, rawDeclarationsSeen); siteVariance = SiteVariance.OUT; }catch(RecursiveTypeParameterBoundException x){ // damnit, go for Object later } } } // if we have no type argument, or it was a wildcard with no bounds and we could not use the type parameter bounds, // let's fall back to "out Object" if(typeArgument == null && producedTypeArgument == null){ producedTypeArgument = typeFactory.getObjectType(); siteVariance = SiteVariance.OUT; } // record use-site variance if required if(!JvmBackendUtil.isCeylon(declaration) && siteVariance != null){ // lazy alloc if(siteVarianceMap == null) siteVarianceMap = new HashMap<TypeParameter,SiteVariance>(); siteVarianceMap.put(typeParameter, siteVariance); } // in some cases we may already have a produced type argument we can use. if not let's fetch it if(producedTypeArgument == null){ if(mode == TypeMappingMode.NORMAL) producedTypeArgument = obtainType(moduleScope, typeArgument, scope, TypeLocation.TYPE_PARAM, variance); else producedTypeArgument = obtainTypeParameterBound(moduleScope, typeArgument, scope, rawDeclarationsSeen); } typeArguments.add(producedTypeArgument); } Type qualifyingType = null; if(type.getQualifyingType() != null){ qualifyingType = getNonPrimitiveType(moduleScope, type.getQualifyingType(), scope, variance); } Type ret = declaration.appliedType(qualifyingType, typeArguments); if(siteVarianceMap != null){ ret.setVarianceOverrides(siteVarianceMap); } ret.setUnderlyingType(type.getQualifiedName()); ret.setRaw(isRaw); return ret; }finally{ if(rawDeclarationsSeen != null) rawDeclarationsSeen.remove(declaration); } } // we have no type args, but perhaps we have a qualifying type which has some? if(type.getQualifyingType() != null){ // that one may have type arguments Type qualifyingType = getNonPrimitiveType(moduleScope, type.getQualifyingType(), scope, variance); Type ret = declaration.appliedType(qualifyingType, Collections.<Type>emptyList()); ret.setUnderlyingType(type.getQualifiedName()); ret.setRaw(isRaw); return ret; } // no type arg and no qualifying type return declaration.getType(); } private Type obtainTypeParameterBound(Module moduleScope, TypeMirror type, Scope scope, Set<TypeDeclaration> rawDeclarationsSeen) { // type variables are never mapped if(type.getKind() == TypeKind.TYPEVAR){ TypeParameterMirror typeParameter = type.getTypeParameter(); if(!typeParameter.getBounds().isEmpty()){ List<Type> bounds = new ArrayList<Type>(typeParameter.getBounds().size()); for(TypeMirror bound : typeParameter.getBounds()){ Type boundModel = obtainTypeParameterBound(moduleScope, bound, scope, rawDeclarationsSeen); bounds.add(boundModel); } return intersection(bounds, getUnitForModule(moduleScope)); }else // no bound is Object return typeFactory.getObjectType(); }else{ TypeMirror mappedType = applyTypeMapping(type, TypeLocation.TYPE_PARAM); TypeDeclaration declaration = (TypeDeclaration) convertNonPrimitiveTypeToDeclaration(moduleScope, mappedType, scope, DeclarationType.TYPE); if(declaration == null){ throw new RuntimeException("Failed to find declaration for "+type); } if(declaration instanceof UnknownType) return declaration.getType(); Type ret = applyTypeArguments(moduleScope, declaration, type, scope, VarianceLocation.CONTRAVARIANT, TypeMappingMode.GENERATOR, rawDeclarationsSeen); if (ret.getUnderlyingType() == null) { ret.setUnderlyingType(getUnderlyingType(type, TypeLocation.TYPE_PARAM)); } return ret; } } /*private Type getQualifyingType(TypeDeclaration declaration) { // As taken from Type.getType(): if (declaration.isMember()) { return((ClassOrInterface) declaration.getContainer()).getType(); } return null; }*/ @Override public Type getType(Module module, String pkgName, String name, Scope scope) { Declaration decl = getDeclaration(module, pkgName, name, scope); if(decl == null) return null; if(decl instanceof TypeDeclaration) return ((TypeDeclaration) decl).getType(); // it's a method or non-object value, but it's not a type return null; } @Override public Declaration getDeclaration(Module module, String pkgName, String name, Scope scope) { synchronized(getLock()){ if(scope != null){ TypeParameter typeParameter = lookupTypeParameter(scope, name); if(typeParameter != null) return typeParameter; } if(!isBootstrap || !name.startsWith(CEYLON_LANGUAGE)) { if(scope != null && pkgName != null){ Package containingPackage = ModelUtil.getPackageContainer(scope); Package pkg = containingPackage.getModule().getPackage(pkgName); String relativeName = null; String unquotedName = name.replace("$", ""); if(!pkgName.isEmpty()){ if(unquotedName.startsWith(pkgName+".")) relativeName = unquotedName.substring(pkgName.length()+1); // else we don't try it's not in this package }else relativeName = unquotedName; if(relativeName != null && pkg != null){ Declaration declaration = pkg.getDirectMember(relativeName, null, false); // if we get a value, we want its type if(JvmBackendUtil.isValue(declaration) && ((Value)declaration).getTypeDeclaration().getName().equals(relativeName)) declaration = ((Value)declaration).getTypeDeclaration(); if(declaration != null) return declaration; } } return convertToDeclaration(module, name, DeclarationType.TYPE); } return findLanguageModuleDeclarationForBootstrap(name); } } private Declaration findLanguageModuleDeclarationForBootstrap(String name) { // make sure we don't return anything for ceylon.language if(name.equals(CEYLON_LANGUAGE)) return null; // we're bootstrapping ceylon.language so we need to return the ProducedTypes straight from the model we're compiling Module languageModule = modules.getLanguageModule(); int lastDot = name.lastIndexOf("."); if(lastDot == -1) return null; String pkgName = name.substring(0, lastDot); String simpleName = name.substring(lastDot+1); // Nothing is a special case with no real decl if(name.equals("ceylon.language.Nothing")) return typeFactory.getNothingDeclaration(); // find the right package Package pkg = languageModule.getDirectPackage(pkgName); if(pkg != null){ Declaration member = pkg.getDirectMember(simpleName, null, false); // if we get a value, we want its type if(JvmBackendUtil.isValue(member) && ((Value)member).getTypeDeclaration().getName().equals(simpleName)){ member = ((Value)member).getTypeDeclaration(); } if(member != null) return member; } throw new ModelResolutionException("Failed to look up given type in language module while bootstrapping: "+name); } public ClassMirror[] getClassMirrorsToRemove(com.redhat.ceylon.model.typechecker.model.Declaration declaration) { if(declaration instanceof LazyClass){ return new ClassMirror[] { ((LazyClass) declaration).classMirror }; } if(declaration instanceof LazyInterface){ LazyInterface lazyInterface = (LazyInterface) declaration; if (lazyInterface.companionClass != null) { return new ClassMirror[] { lazyInterface.classMirror, lazyInterface.companionClass }; } else { return new ClassMirror[] { lazyInterface.classMirror }; } } if(declaration instanceof LazyFunction){ return new ClassMirror[] { ((LazyFunction) declaration).classMirror }; } if(declaration instanceof LazyValue){ return new ClassMirror[] { ((LazyValue) declaration).classMirror }; } if (declaration instanceof LazyClassAlias) { return new ClassMirror[] { ((LazyClassAlias) declaration).classMirror }; } if (declaration instanceof LazyInterfaceAlias) { return new ClassMirror[] { ((LazyInterfaceAlias) declaration).classMirror }; } if (declaration instanceof LazyTypeAlias) { return new ClassMirror[] { ((LazyTypeAlias) declaration).classMirror }; } return new ClassMirror[0]; } public void removeDeclarations(List<Declaration> declarations) { synchronized(getLock()){ Set<String> qualifiedNames = new HashSet<>(declarations.size() * 2); // keep in sync with getOrCreateDeclaration for (Declaration decl : declarations) { try { ClassMirror[] classMirrors = getClassMirrorsToRemove(decl); if (classMirrors == null || classMirrors.length == 0) { continue; } Map<String, Declaration> firstCache = null; Map<String, Declaration> secondCache = null; // String firstCacheName = null; // String secondCacheName = null; if(decl.isToplevel()){ if(JvmBackendUtil.isValue(decl)){ firstCache = valueDeclarationsByName; // firstCacheName = "value declarations cache"; TypeDeclaration typeDeclaration = ((Value)decl).getTypeDeclaration(); if (typeDeclaration != null) { if(typeDeclaration.isAnonymous()) { secondCache = typeDeclarationsByName; // secondCacheName = "type declarations cache"; } } else { // The value declaration has probably not been fully loaded yet. // => still try to clean the second cache also, just in case it is an anonymous object secondCache = typeDeclarationsByName; // secondCacheName = "type declarations cache"; } }else if(JvmBackendUtil.isMethod(decl)) { firstCache = valueDeclarationsByName; // firstCacheName = "value declarations cache"; } } if(decl instanceof ClassOrInterface){ firstCache = typeDeclarationsByName; // firstCacheName = "type declarations cache"; } Module module = ModelUtil.getModuleContainer(decl.getContainer()); // ignore declarations which we do not cache, like member method/attributes for (ClassMirror classMirror : classMirrors) { qualifiedNames.add(classMirror.getQualifiedName()); String key = classMirror.getCacheKey(module); // String notRemovedMessageFromFirstCache = "No non-null declaration removed from the " + firstCacheName + " for key :" + key; // String notRemovedMessageFromSecondCache = "No non-null declaration removed from the " + secondCacheName + " for key :" + key; if(firstCache != null) { if (firstCache.remove(key) == null) { // System.out.println(notRemovedMessageFromFirstCache); } if(secondCache != null) { if (secondCache.remove(key) == null) { // System.out.println(notRemovedMessageFromSecondCache); } } } } } catch(Exception e) { e.printStackTrace(); } } List<String> keysToRemove = new ArrayList<>(qualifiedNames.size()); for (Map.Entry<String, ClassMirror> entry : classMirrorCache.entrySet()) { ClassMirror mirror = entry.getValue(); if (mirror == null || qualifiedNames.contains(mirror.getQualifiedName())) { keysToRemove.add(entry.getKey()); } } for (String keyToRemove : keysToRemove) { classMirrorCache.remove(keyToRemove); } } } private static class Stats{ int loaded, total; } private int inspectForStats(Map<String,Declaration> cache, Map<Package, Stats> loadedByPackage){ int loaded = 0; for(Declaration decl : cache.values()){ if(decl instanceof LazyElement){ Package pkg = getPackage(decl); if(pkg == null){ logVerbose("[Model loader stats: declaration "+decl.getName()+" has no package. Skipping.]"); continue; } Stats stats = loadedByPackage.get(pkg); if(stats == null){ stats = new Stats(); loadedByPackage.put(pkg, stats); } stats.total++; if(((LazyElement)decl).isLoaded()){ loaded++; stats.loaded++; } } } return loaded; } public void printStats() { synchronized(getLock()){ Map<Package, Stats> loadedByPackage = new HashMap<Package, Stats>(); int loaded = inspectForStats(typeDeclarationsByName, loadedByPackage) + inspectForStats(valueDeclarationsByName, loadedByPackage); logVerbose("[Model loader: "+loaded+"(loaded)/"+(typeDeclarationsByName.size()+valueDeclarationsByName.size())+"(total) declarations]"); for(Entry<Package, Stats> packageEntry : loadedByPackage.entrySet()){ logVerbose("[ Package "+packageEntry.getKey().getNameAsString()+": " +packageEntry.getValue().loaded+"(loaded)/"+packageEntry.getValue().total+"(total) declarations]"); } } } private static Package getPackage(Object decl) { if(decl == null) return null; if(decl instanceof Package) return (Package) decl; return getPackage(((Declaration)decl).getContainer()); } protected void logMissingOracleType(String type) { logVerbose("Hopefully harmless completion failure in model loader: "+type +". This is most likely when the JDK depends on Oracle private classes that we can't find." +" As a result some model information will be incomplete."); } public void setupSourceFileObjects(List<?> treeHolders) { } public static boolean isJDKModule(String name) { return JDKUtils.isJDKModule(name) || JDKUtils.isOracleJDKModule(name); } @Override public Module getLoadedModule(String moduleName, String version) { return findModule(moduleName, version); } public Module getLanguageModule() { return modules.getLanguageModule(); } public Module findModule(String name, String version){ return moduleManager.findLoadedModule(name, version); } public Module getJDKBaseModule() { return findModule(JAVA_BASE_MODULE_NAME, JDKUtils.jdk.version); } public Module findModuleForFile(File file){ File path = file.getParentFile(); while (path != null) { String name = path.getPath().replaceAll("[\\\\/]", "."); // FIXME: this would load any version of this module Module m = getLoadedModule(name, null); if (m != null) { return m; } path = path.getParentFile(); } return modules.getDefaultModule(); } public abstract Module findModuleForClassMirror(ClassMirror classMirror); protected boolean isTypeHidden(Module module, String qualifiedName){ return module.getNameAsString().equals(JAVA_BASE_MODULE_NAME) && qualifiedName.equals("java.lang.Object"); } public Package findPackage(String quotedPkgName) { synchronized(getLock()){ String pkgName = quotedPkgName.replace("$", ""); // in theory we only have one package with the same name per module in javac for(Package pkg : packagesByName.values()){ if(pkg.getNameAsString().equals(pkgName)) return pkg; } return null; } } /** * See explanation in cacheModulelessPackages() below. This is called by LanguageCompiler during loadCompiledModules(). */ public LazyPackage findOrCreateModulelessPackage(String pkgName) { synchronized(getLock()){ LazyPackage pkg = modulelessPackages.get(pkgName); if(pkg != null) return pkg; pkg = new LazyPackage(this); // FIXME: some refactoring needed pkg.setName(pkgName == null ? Collections.<String>emptyList() : Arrays.asList(pkgName.split("\\."))); modulelessPackages.put(pkgName, pkg); return pkg; } } /** * Stef: this sucks balls, but the typechecker wants Packages created before we have any Module set up, including for parsing a module * file, and because the model loader looks up packages and caches them using their modules, we can't really have packages before we * have modules. Rather than rewrite the typechecker, we create moduleless packages during parsing, which means they are not cached with * their modules, and after the loadCompiledModules step above, we fix the package modules. Remains to be done is to move the packages * created from their cache to the right per-module cache. */ public void cacheModulelessPackages() { synchronized(getLock()){ for(LazyPackage pkg : modulelessPackages.values()){ String quotedPkgName = JVMModuleUtil.quoteJavaKeywords(pkg.getQualifiedNameString()); if (pkg.getModule() != null) { packagesByName.put(cacheKeyByModule(pkg.getModule(), quotedPkgName), pkg); } } modulelessPackages.clear(); } } /** * Stef: after a lot of attempting, I failed to make the CompilerModuleManager produce a LazyPackage when the ModuleManager.initCoreModules * is called for the default package. Because it is called by the PhasedUnits constructor, which is called by the ModelLoader constructor, * which means the model loader is not yet in the context, so the CompilerModuleManager can't obtain it to pass it to the LazyPackage * constructor. A rewrite of the logic of the typechecker scanning would fix this, but at this point it's just faster to let it create * the wrong default package and fix it before we start parsing anything. */ public void fixDefaultPackage() { synchronized(getLock()){ Module defaultModule = modules.getDefaultModule(); Package defaultPackage = defaultModule.getDirectPackage(""); if(defaultPackage instanceof LazyPackage == false){ LazyPackage newPkg = findOrCreateModulelessPackage(""); List<Package> defaultModulePackages = defaultModule.getPackages(); if(defaultModulePackages.size() != 1) throw new RuntimeException("Assertion failed: default module has more than the default package: "+defaultModulePackages.size()); defaultModulePackages.clear(); defaultModulePackages.add(newPkg); newPkg.setModule(defaultModule); defaultPackage.setModule(null); } } } public boolean isImported(Module moduleScope, Module importedModule) { if(ModelUtil.equalModules(moduleScope, importedModule)) return true; if(isImportedSpecialRules(moduleScope, importedModule)) return true; boolean isMaven = isAutoExportMavenDependencies() && isMavenModule(moduleScope); if(isMaven && isMavenModule(importedModule)) return true; Set<Module> visited = new HashSet<Module>(); visited.add(moduleScope); for(ModuleImport imp : moduleScope.getImports()){ if(ModelUtil.equalModules(imp.getModule(), importedModule)) return true; if((imp.isExport() || isMaven) && isImportedTransitively(imp.getModule(), importedModule, visited)) return true; } return false; } private boolean isMavenModule(Module moduleScope) { return moduleScope.isJava() && ModuleUtil.isMavenModule(moduleScope.getNameAsString()); } private boolean isImportedSpecialRules(Module moduleScope, Module importedModule) { String importedModuleName = importedModule.getNameAsString(); // every Java module imports the JDK // ceylon.language imports the JDK if((moduleScope.isJava() || ModelUtil.equalModules(moduleScope, getLanguageModule())) && (JDKUtils.isJDKModule(importedModuleName) || JDKUtils.isOracleJDKModule(importedModuleName))) return true; // everyone imports the language module if(ModelUtil.equalModules(importedModule, getLanguageModule())) return true; if(ModelUtil.equalModules(moduleScope, getLanguageModule())){ // this really sucks, I suppose we should set that up better somewhere else if((importedModuleName.equals("com.redhat.ceylon.compiler.java") || importedModuleName.equals("com.redhat.ceylon.typechecker") || importedModuleName.equals("com.redhat.ceylon.common") || importedModuleName.equals("com.redhat.ceylon.model") || importedModuleName.equals("com.redhat.ceylon.module-resolver")) && importedModule.getVersion().equals(Versions.CEYLON_VERSION_NUMBER)) return true; if(importedModuleName.equals("org.jboss.modules") && importedModule.getVersion().equals("1.3.3.Final")) return true; } return false; } private boolean isImportedTransitively(Module moduleScope, Module importedModule, Set<Module> visited) { if(!visited.add(moduleScope)) return false; boolean isMaven = isAutoExportMavenDependencies() && isMavenModule(moduleScope); for(ModuleImport imp : moduleScope.getImports()){ // only consider exported transitive deps if(!imp.isExport() && !isMaven) continue; if(ModelUtil.equalModules(imp.getModule(), importedModule)) return true; if(isImportedSpecialRules(imp.getModule(), importedModule)) return true; if(isImportedTransitively(imp.getModule(), importedModule, visited)) return true; } return false; } protected boolean isModuleOrPackageDescriptorName(String name) { return name.equals(NamingBase.MODULE_DESCRIPTOR_CLASS_NAME) || name.equals(NamingBase.PACKAGE_DESCRIPTOR_CLASS_NAME); } protected void loadJavaBaseArrays(){ convertToDeclaration(getJDKBaseModule(), JAVA_LANG_OBJECT_ARRAY, DeclarationType.TYPE); convertToDeclaration(getJDKBaseModule(), JAVA_LANG_BOOLEAN_ARRAY, DeclarationType.TYPE); convertToDeclaration(getJDKBaseModule(), JAVA_LANG_BYTE_ARRAY, DeclarationType.TYPE); convertToDeclaration(getJDKBaseModule(), JAVA_LANG_SHORT_ARRAY, DeclarationType.TYPE); convertToDeclaration(getJDKBaseModule(), JAVA_LANG_INT_ARRAY, DeclarationType.TYPE); convertToDeclaration(getJDKBaseModule(), JAVA_LANG_LONG_ARRAY, DeclarationType.TYPE); convertToDeclaration(getJDKBaseModule(), JAVA_LANG_FLOAT_ARRAY, DeclarationType.TYPE); convertToDeclaration(getJDKBaseModule(), JAVA_LANG_DOUBLE_ARRAY, DeclarationType.TYPE); convertToDeclaration(getJDKBaseModule(), JAVA_LANG_CHAR_ARRAY, DeclarationType.TYPE); } /** * To be overridden by subclasses, defaults to false. */ protected boolean isAutoExportMavenDependencies(){ return false; } /** * To be overridden by subclasses, defaults to false. */ protected boolean isFlatClasspath(){ return false; } private static void setDeclarationAliases(Declaration decl, AnnotatedMirror mirror){ AnnotationMirror annot = mirror.getAnnotation(AbstractModelLoader.CEYLON_LANGUAGE_ALIASES_ANNOTATION); if (annot != null) { @SuppressWarnings("unchecked") List<String> value = (List<String>) annot.getValue("aliases"); if(value != null && !value.isEmpty()) decl.setAliases(value); } } }
Deal with caching of inner classes in native headers and properly link up inner classes in a native container (ceylon/ceylon-compiler#2356)
src/com/redhat/ceylon/model/loader/AbstractModelLoader.java
Deal with caching of inner classes in native headers and properly link up inner classes in a native container (ceylon/ceylon-compiler#2356)
<ide><path>rc/com/redhat/ceylon/model/loader/AbstractModelLoader.java <ide> module = getJDKBaseModule(); <ide> } <ide> <del> Declaration decl = findCachedDeclaration(module, classMirror, declarationType); <add> Declaration decl = findCachedDeclaration(module, container, classMirror, declarationType); <ide> if (decl != null) { <ide> return decl; <ide> } <ide> LazyPackage pkg = findOrCreatePackage(module, pkgName); <ide> <ide> decl = createDeclaration(module, container, classMirror, declarationType, decls); <del> cacheDeclaration(module, classMirror, declarationType, decl, decls); <add> cacheDeclaration(module, container, classMirror, declarationType, decl, decls); <ide> <ide> // find/make its Unit <ide> Unit unit = getCompiledUnit(pkg, classMirror); <ide> } <ide> } <ide> <del> private Declaration findCachedDeclaration(Module module, ClassMirror classMirror, <del> DeclarationType declarationType) { <add> private Declaration findCachedDeclaration(Module module, Declaration container, <add> ClassMirror classMirror, DeclarationType declarationType) { <ide> ClassType type = getClassType(classMirror); <ide> String key = classMirror.getCacheKey(module); <add> boolean isNativeHeaderMember = container != null && container.isNativeHeader(); <add> if (isNativeHeaderMember) { <add> key = key + "$header"; <add> } <ide> // see if we already have it <ide> Map<String, Declaration> declarationCache = getCacheByType(type, declarationType); <ide> return declarationCache.get(key); <ide> } <ide> <del> private void cacheDeclaration(Module module, ClassMirror classMirror, <add> private void cacheDeclaration(Module module, Declaration container, ClassMirror classMirror, <ide> DeclarationType declarationType, Declaration decl, List<Declaration> decls) { <ide> ClassType type = getClassType(classMirror); <ide> String key = classMirror.getCacheKey(module); <add> boolean isNativeHeaderMember = container != null && container.isNativeHeader(); <add> if (isNativeHeaderMember) { <add> key = key + "$header"; <add> } <ide> if(type == ClassType.OBJECT){ <ide> typeDeclarationsByName.put(key, getByType(decls, Class.class)); <ide> valueDeclarationsByName.put(key, getByType(decls, Value.class)); <ide> } <ide> <ide> private void initNativeHeaderMember(Declaration hdr) { <del> Declaration impl = ModelUtil.getNativeDeclaration(hdr, Backend.Java); <add> Declaration impl = ModelUtil.getNativeDeclaration(hdr.getContainer(), hdr.getName(), Backends.JAVA); <ide> initNativeHeader(hdr, impl); <ide> } <ide>
Java
mit
514a1fdbe4a12012a2c7cab456d58dea0e57d853
0
5hirish/Android_repeating_alarms
package com.inifiniti.repeatalarm; import android.app.Activity; import android.app.AlarmManager; import android.app.AlertDialog; import android.app.PendingIntent; import android.app.TimePickerDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.TextView; import android.widget.TimePicker; import java.util.ArrayList; import java.util.Calendar; import java.util.Iterator; public class MainActivity extends Activity { TextView alarmtime,repeattype,result; Button set; int ahr,amin,size=0,aid=1; String repeat; ArrayList<Integer> weekdays; SQLiteDatabase db; SharedPreferences sp; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); alarmtime=(TextView)findViewById(R.id.timePicker); repeattype=(TextView)findViewById(R.id.repeat); result=(TextView)findViewById(R.id.textView); set=(Button)findViewById(R.id.button); weekdays=new ArrayList<Integer>(); /*String removealarm="DELETE FROM alarms WHERE RepeatType='No repeat'"; //Dont Use....!!! db.execSQL(removealarm);*/ String use=""; sp=getPreferences(MODE_PRIVATE); SharedPreferences.Editor editor=sp.edit(); use=sp.getString("Usage","No"); if(!use.equals("First")){ setParentAlarm(); editor.putString("Usage","First"); editor.commit(); } final ArrayAdapter weekdayadapter=ArrayAdapter.createFromResource(this, R.array.repeat, android.R.layout.select_dialog_item); final Calendar c= Calendar.getInstance(); alarmtime.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { TimePickerDialog timePickerDialog = new TimePickerDialog(MainActivity.this, new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(TimePicker timePicker, int shr, int smin) { ahr = shr; amin = smin; alarmtime.setText(ahr + ":" + amin); } }, c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE), false); timePickerDialog.show(); } }); final AlertDialog.Builder adb=new AlertDialog.Builder(MainActivity.this); adb.setTitle("Repeat On:"); adb.setAdapter(weekdayadapter, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int position) { repeat = weekdayadapter.getItem(position).toString(); repeattype.setText(repeat); if (repeat.equals("Selected week days")) { AlertDialog.Builder adbd = new AlertDialog.Builder(MainActivity.this); adbd.setTitle("Select Day:"); adbd.setMultiChoiceItems(R.array.weekdays, null, new DialogInterface.OnMultiChoiceClickListener() { @Override public void onClick(DialogInterface dialogInterface, int item, boolean ischecked) { if (ischecked) { weekdays.add(item); } else if (weekdays.contains(item)) { weekdays.remove(Integer.valueOf(item)); } } }); adbd.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { size = weekdays.size(); } }); adbd.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { repeat = "No repeat"; } }); AlertDialog wd = adbd.create(); wd.show(); } } }); repeattype.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { AlertDialog repertd = adb.create(); repertd.show(); } }); set.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { result.setText("Time:" + ahr + ":" + amin + " \nRepeat: " + repeat + " \nSize: " + size); setChildAlarms(ahr, amin, repeat, weekdays); } }); } private void setChildAlarms(int ahr, int amin, String repeat, ArrayList<Integer> weekdays) { db=getApplicationContext().openOrCreateDatabase("RepeatAlarm", Context.MODE_PRIVATE, null); Calendar cdate=Calendar.getInstance(); int d=cdate.get(Calendar.DATE); int m=cdate.get(Calendar.MONTH)+1; String date=d+"/"+m; Calendar cal=Calendar.getInstance(); cal.set(Calendar.HOUR_OF_DAY,ahr); cal.set(Calendar.MINUTE, amin); String time=ahr+":"+amin; String countalarm="SELECT MAX(Id) FROM alarms"; Cursor cur=db.rawQuery(countalarm, null); if(cur!=null){ if(cur.moveToFirst()){ aid = cur.getInt(0); } else{ aid=1; }cur.close(); }else {aid=1;} Intent intent=new Intent(getApplicationContext(),AlarmReciever.class); intent.putExtra("AId", aid); intent.putExtra("RepeatType",repeat); PendingIntent alarmintent=PendingIntent.getBroadcast(getApplicationContext(),aid,intent,PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager alarm=(AlarmManager)getApplicationContext().getSystemService(Context.ALARM_SERVICE); if(repeat.equals("Selected week days")){ Iterator it=weekdays.iterator(); int wid=0; if(aid!=0){ wid=aid*100;} else{ wid=9900; } if(!weekdays.isEmpty()){ repeat="Weekly"; //Are considered as repeating weekly only... while (it.hasNext()){ intent.putExtra("AId", wid); PendingIntent wpendingIntent = PendingIntent.getBroadcast(getApplicationContext(), wid, intent, PendingIntent.FLAG_UPDATE_CURRENT); int wd=Integer.parseInt(it.next().toString())+1; Calendar calw = Calendar.getInstance(); calw.set(Calendar.DAY_OF_WEEK, wd); calw.set(Calendar.HOUR_OF_DAY, ahr); calw.set(Calendar.MINUTE, amin); alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, calw.getTimeInMillis(), 0, wpendingIntent); Log.d("Child Alarm", "Child Alarm set at " + calw.getTime() + ", Id " + wid + ", Repeating " + repeat); String log="Child Alarm set at " + calw.getTime() + ", Id " + wid + ", Repeating " + repeat; String insertlog="INSERT INTO logs (Log) VALUES ('"+log+"')"; db.execSQL(insertlog); d=calw.get(Calendar.DATE); m=calw.get(Calendar.MONTH)+1; date=d+"/"+m; String insertalarm="INSERT INTO alarms ( AId, Time, Date, RepeatType) VALUES("+wid+",'"+time+"','"+date+"','"+repeat+"')"; db.execSQL(insertalarm); wid++; } } } else { alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP,cal.getTimeInMillis(),0,alarmintent); Log.d("Child Alarm", "Child Alarm set at " + cal.getTime() + ", Id " + aid+", Repeating "+repeat); String log="Child Alarm set at " + cal.getTime() + ", Id " + aid + ", Repeating " + repeat; String insertlog="INSERT INTO logs (Log) VALUES ('"+log+"')"; db.execSQL(insertlog); String insertalarm="INSERT INTO alarms ( AId, Time, Date, RepeatType) VALUES("+aid+",'"+time+"','"+date+"','"+repeat+"')"; db.execSQL(insertalarm); } } private void setParentAlarm() { db=getApplicationContext().openOrCreateDatabase("RepeatAlarm", Context.MODE_PRIVATE, null); int parentid=978912; Calendar cal=Calendar.getInstance(); cal.set(Calendar.HOUR_OF_DAY,0); cal.set(Calendar.MINUTE, 0); Intent parentintent=new Intent(getApplicationContext(),AlarmSetter.class); parentintent.putExtra("ParentId", parentid); PendingIntent parentpendingintent=PendingIntent.getBroadcast(getApplicationContext(),parentid,parentintent,0); AlarmManager parentalarm=(AlarmManager)getApplicationContext().getSystemService(Context.ALARM_SERVICE); parentalarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), AlarmManager.INTERVAL_DAY, parentpendingintent); Log.d("Parent Alarm", "Parent Alarm set at " + cal.getTime() + ", Id " + parentid); String log="Parent Alarm set at " + cal.getTime() + ", Id " + parentid; String insertlog="INSERT INTO logs (Log) VALUES ('"+log+"')"; db.execSQL(insertlog); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_log) { Intent in= new Intent(this,LogsActivity.class); startActivity(in); }else if(id == R.id.action_alarms){ Intent in= new Intent(this,AlarmsActivity.class); startActivity(in); }else if(id == R.id.action_test){ Intent in= new Intent(this,TestActivity.class); startActivity(in); } return super.onOptionsItemSelected(item); } }
app/src/main/java/com/inifiniti/repeatalarm/MainActivity.java
package com.inifiniti.repeatalarm; import android.app.Activity; import android.app.AlarmManager; import android.app.AlertDialog; import android.app.PendingIntent; import android.app.TimePickerDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.TextView; import android.widget.TimePicker; import java.util.ArrayList; import java.util.Calendar; import java.util.Iterator; public class MainActivity extends Activity { TextView alarmtime,repeattype,result; Button set; int ahr,amin,size=0,aid=1; String repeat; ArrayList<Integer> weekdays; SQLiteDatabase db; SharedPreferences sp; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); alarmtime=(TextView)findViewById(R.id.timePicker); repeattype=(TextView)findViewById(R.id.repeat); result=(TextView)findViewById(R.id.textView); set=(Button)findViewById(R.id.button); weekdays=new ArrayList<Integer>(); db=getApplicationContext().openOrCreateDatabase("RepeatAlarm", Context.MODE_PRIVATE, null); String createlogs="CREATE TABLE IF NOT EXISTS logs (Id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, Log VARCHAR NOT NULL)"; db.execSQL(createlogs); String createalarm="CREATE TABLE IF NOT EXISTS alarms ( Id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, AId INTEGER NOT NULL , Time VARCHAR NOT NULL, Date VARCHAR NOT NULL , RepeatType VARCHAR NOT NULL)"; db.execSQL(createalarm); /*String removealarm="DELETE FROM alarms WHERE RepeatType='No repeat'"; //Dont Use....!!! db.execSQL(removealarm);*/ String use=""; sp=getPreferences(MODE_PRIVATE); SharedPreferences.Editor editor=sp.edit(); use=sp.getString("Usage","No"); if(!use.equals("First")){ setParentAlarm(); editor.putString("Usage","First"); editor.commit(); } final ArrayAdapter weekdayadapter=ArrayAdapter.createFromResource(this, R.array.repeat, android.R.layout.select_dialog_item); final Calendar c= Calendar.getInstance(); alarmtime.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { TimePickerDialog timePickerDialog = new TimePickerDialog(MainActivity.this, new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(TimePicker timePicker, int shr, int smin) { ahr = shr; amin = smin; alarmtime.setText(ahr + ":" + amin); } }, c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE), false); timePickerDialog.show(); } }); final AlertDialog.Builder adb=new AlertDialog.Builder(MainActivity.this); adb.setTitle("Repeat On:"); adb.setAdapter(weekdayadapter, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int position) { repeat = weekdayadapter.getItem(position).toString(); repeattype.setText(repeat); if (repeat.equals("Selected week days")) { AlertDialog.Builder adbd = new AlertDialog.Builder(MainActivity.this); adbd.setTitle("Select Day:"); adbd.setMultiChoiceItems(R.array.weekdays, null, new DialogInterface.OnMultiChoiceClickListener() { @Override public void onClick(DialogInterface dialogInterface, int item, boolean ischecked) { if (ischecked) { weekdays.add(item); } else if (weekdays.contains(item)) { weekdays.remove(Integer.valueOf(item)); } } }); adbd.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { size = weekdays.size(); } }); adbd.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { repeat = "No repeat"; } }); AlertDialog wd = adbd.create(); wd.show(); } } }); repeattype.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { AlertDialog repertd = adb.create(); repertd.show(); } }); set.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { result.setText("Time:" + ahr + ":" + amin + " \nRepeat: " + repeat + " \nSize: " + size); setChildAlarms(ahr, amin, repeat, weekdays); } }); } private void setChildAlarms(int ahr, int amin, String repeat, ArrayList<Integer> weekdays) { db=getApplicationContext().openOrCreateDatabase("RepeatAlarm", Context.MODE_PRIVATE, null); Calendar cdate=Calendar.getInstance(); int d=cdate.get(Calendar.DATE); int m=cdate.get(Calendar.MONTH)+1; String date=d+"/"+m; Calendar cal=Calendar.getInstance(); cal.set(Calendar.HOUR_OF_DAY,ahr); cal.set(Calendar.MINUTE, amin); String time=ahr+":"+amin; String countalarm="SELECT MAX(Id) FROM alarms"; Cursor cur=db.rawQuery(countalarm, null); if(cur!=null){ if(cur.moveToFirst()){ aid = cur.getInt(0); } else{ aid=1; }cur.close(); }else {aid=1;} Intent intent=new Intent(getApplicationContext(),AlarmReciever.class); intent.putExtra("AId", aid); intent.putExtra("RepeatType",repeat); PendingIntent alarmintent=PendingIntent.getBroadcast(getApplicationContext(),aid,intent,PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager alarm=(AlarmManager)getApplicationContext().getSystemService(Context.ALARM_SERVICE); if(repeat.equals("Selected week days")){ Iterator it=weekdays.iterator(); int wid=0; if(aid!=0){ wid=aid*100;} else{ wid=9900; } if(!weekdays.isEmpty()){ repeat="Weekly"; //Are considered as repeating weekly only... while (it.hasNext()){ intent.putExtra("AId", wid); PendingIntent wpendingIntent = PendingIntent.getBroadcast(getApplicationContext(), wid, intent, PendingIntent.FLAG_UPDATE_CURRENT); int wd=Integer.parseInt(it.next().toString())+1; Calendar calw = Calendar.getInstance(); calw.set(Calendar.DAY_OF_WEEK, wd); calw.set(Calendar.HOUR_OF_DAY, ahr); calw.set(Calendar.MINUTE, amin); alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, calw.getTimeInMillis(), 0, wpendingIntent); Log.d("Child Alarm", "Child Alarm set at " + calw.getTime() + ", Id " + wid + ", Repeating " + repeat); String log="Child Alarm set at " + calw.getTime() + ", Id " + wid + ", Repeating " + repeat; String insertlog="INSERT INTO logs (Log) VALUES ('"+log+"')"; db.execSQL(insertlog); d=calw.get(Calendar.DATE); m=calw.get(Calendar.MONTH)+1; date=d+"/"+m; String insertalarm="INSERT INTO alarms ( AId, Time, Date, RepeatType) VALUES("+wid+",'"+time+"','"+date+"','"+repeat+"')"; db.execSQL(insertalarm); wid++; } } } else { alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP,cal.getTimeInMillis(),0,alarmintent); Log.d("Child Alarm", "Child Alarm set at " + cal.getTime() + ", Id " + aid+", Repeating "+repeat); String log="Child Alarm set at " + cal.getTime() + ", Id " + aid + ", Repeating " + repeat; String insertlog="INSERT INTO logs (Log) VALUES ('"+log+"')"; db.execSQL(insertlog); String insertalarm="INSERT INTO alarms ( AId, Time, Date, RepeatType) VALUES("+aid+",'"+time+"','"+date+"','"+repeat+"')"; db.execSQL(insertalarm); } } private void setParentAlarm() { db=getApplicationContext().openOrCreateDatabase("RepeatAlarm", Context.MODE_PRIVATE, null); int parentid=978912; Calendar cal=Calendar.getInstance(); cal.set(Calendar.HOUR_OF_DAY,0); cal.set(Calendar.MINUTE, 0); Intent parentintent=new Intent(getApplicationContext(),AlarmSetter.class); parentintent.putExtra("ParentId", parentid); PendingIntent parentpendingintent=PendingIntent.getBroadcast(getApplicationContext(),parentid,parentintent,0); AlarmManager parentalarm=(AlarmManager)getApplicationContext().getSystemService(Context.ALARM_SERVICE); parentalarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), AlarmManager.INTERVAL_DAY, parentpendingintent); Log.d("Parent Alarm", "Parent Alarm set at " + cal.getTime() + ", Id " + parentid); String log="Parent Alarm set at " + cal.getTime() + ", Id " + parentid; String insertlog="INSERT INTO logs (Log) VALUES ('"+log+"')"; db.execSQL(insertlog); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_log) { Intent in= new Intent(this,LogsActivity.class); startActivity(in); }else if(id == R.id.action_alarms){ Intent in= new Intent(this,AlarmsActivity.class); startActivity(in); }else if(id == R.id.action_test){ Intent in= new Intent(this,TestActivity.class); startActivity(in); } return super.onOptionsItemSelected(item); } }
Added SQLite Helper
app/src/main/java/com/inifiniti/repeatalarm/MainActivity.java
Added SQLite Helper
<ide><path>pp/src/main/java/com/inifiniti/repeatalarm/MainActivity.java <ide> result=(TextView)findViewById(R.id.textView); <ide> set=(Button)findViewById(R.id.button); <ide> weekdays=new ArrayList<Integer>(); <del> <del> db=getApplicationContext().openOrCreateDatabase("RepeatAlarm", Context.MODE_PRIVATE, null); <del> String createlogs="CREATE TABLE IF NOT EXISTS logs (Id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, Log VARCHAR NOT NULL)"; <del> db.execSQL(createlogs); <del> String createalarm="CREATE TABLE IF NOT EXISTS alarms ( Id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, AId INTEGER NOT NULL , Time VARCHAR NOT NULL, Date VARCHAR NOT NULL , RepeatType VARCHAR NOT NULL)"; <del> db.execSQL(createalarm); <ide> <ide> /*String removealarm="DELETE FROM alarms WHERE RepeatType='No repeat'"; //Dont Use....!!! <ide> db.execSQL(removealarm);*/
Java
mit
f79fa62ee2d504d44659a8a9b5215eb97af34393
0
InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service
package org.innovateuk.ifs.project.grantofferletter.viewmodel; import org.innovateuk.ifs.file.controller.viewmodel.FileDetailsViewModel; import org.innovateuk.ifs.project.grantofferletter.resource.GrantOfferLetterStateResource; import org.junit.Test; import static org.hamcrest.Matchers.is; import static org.innovateuk.ifs.project.grantofferletter.resource.GrantOfferLetterEvent.*; import static org.innovateuk.ifs.project.grantofferletter.resource.GrantOfferLetterState.*; import static org.innovateuk.ifs.project.grantofferletter.resource.GrantOfferLetterStateResource.stateInformationForNonPartnersView; import static org.innovateuk.ifs.project.grantofferletter.resource.GrantOfferLetterStateResource.stateInformationForPartnersView; import static org.junit.Assert.assertThat; public class GrantOfferLetterModelTest { public static final GrantOfferLetterStateResource stateForPmGeneratedOfferSentToProjectTeam = stateInformationForNonPartnersView(SENT, GOL_SENT); public static final GrantOfferLetterStateResource stateForPartnerGeneratedOfferSentToProjectTeam = stateInformationForPartnersView(SENT, GOL_SENT); public static final GrantOfferLetterStateResource stateForPmSignedGrantOfferSubmittedToInternalTeam = stateInformationForNonPartnersView(READY_TO_APPROVE, GOL_SIGNED); public static final GrantOfferLetterStateResource stateForPmSignedGrantOfferRejected = stateInformationForNonPartnersView(SENT, SIGNED_GOL_REJECTED); public static final GrantOfferLetterStateResource stateForPartnerSignedGrantOfferRejected = stateInformationForPartnersView(SENT, SIGNED_GOL_REJECTED); public static final GrantOfferLetterStateResource stateForPartnerSignedGrantOfferSubmittedToInternalTeam = stateInformationForPartnersView(READY_TO_APPROVE, GOL_SIGNED); public static final GrantOfferLetterStateResource stateForPmSignedGrantOfferApproved = stateInformationForNonPartnersView(APPROVED, SIGNED_GOL_APPROVED); public static final GrantOfferLetterStateResource stateForPmGeneratedGrantOfferNotYetSentToProjectTeam = stateInformationForNonPartnersView(PENDING, PROJECT_CREATED); @Test public void testShowSubmitButtonWhenSentSignedAndNotSubmittedAsProjectManager() { boolean leadPartner = true; boolean projectManager = true; boolean signedGrantOfferUploaded = true; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPmGeneratedOfferSentToProjectTeam); assertThat(model.isShowSubmitButton(), is(true)); } @Test public void testShowSubmitButtonNotShownWhenNotProjectManager() { boolean leadPartner = true; boolean projectManager = false; boolean signedGrantOfferUploaded = true; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPartnerGeneratedOfferSentToProjectTeam); assertThat(model.isShowSubmitButton(), is(false)); } @Test public void testShowSubmitButtonNotShownWhenSignedLetterNotYetUploaded() { boolean leadPartner = true; boolean projectManager = true; boolean signedGrantOfferUploaded = false; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPmGeneratedOfferSentToProjectTeam); assertThat(model.isShowSubmitButton(), is(false)); } @Test public void testShowSubmitButtonNotShownWhenSignedLetterAlreadySubmitted() { boolean leadPartner = true; boolean projectManager = true; boolean signedGrantOfferUploaded = true; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPmSignedGrantOfferSubmittedToInternalTeam); assertThat(model.isShowSubmitButton(), is(false)); } @Test public void testShowGrantOfferLetterRejectedMessageWhenProjectManagerAndGrantOfferIsRejected() { boolean leadPartner = true; boolean projectManager = true; boolean signedGrantOfferUploaded = true; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPmSignedGrantOfferRejected); assertThat(model.isShowGrantOfferLetterRejectedMessage(), is(true)); } @Test public void testShowGrantOfferLetterRejectedMessageNotShownWhenNotProjectManager() { boolean leadPartner = true; boolean projectManager = false; boolean signedGrantOfferUploaded = true; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPartnerSignedGrantOfferRejected); assertThat(model.isShowGrantOfferLetterRejectedMessage(), is(false)); } @Test public void testShowGrantOfferLetterRejectedMessageNotShownWhenGrantOfferLetterNotRejected() { boolean leadPartner = true; boolean projectManager = true; boolean signedGrantOfferUploaded = true; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPmSignedGrantOfferSubmittedToInternalTeam); assertThat(model.isShowGrantOfferLetterRejectedMessage(), is(false)); } @Test public void testAbleToRemoveSignedGrantOfferIfUploadedAndNotSubmittedAndLeadPartner() { boolean leadPartner = true; boolean projectManager = false; boolean signedGrantOfferUploaded = true; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPartnerGeneratedOfferSentToProjectTeam); assertThat(model.isAbleToRemoveSignedGrantOffer(), is(true)); } @Test public void testAbleToRemoveSignedGrantOfferNotAllowedIfNotLeadPartnerOrProjectManager() { boolean leadPartner = false; boolean projectManager = false; boolean signedGrantOfferUploaded = true; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPartnerGeneratedOfferSentToProjectTeam); assertThat(model.isAbleToRemoveSignedGrantOffer(), is(false)); } @Test public void testAbleToRemoveSignedGrantOfferNotAllowedIfNotUploaded() { boolean leadPartner = true; boolean projectManager = true; boolean signedGrantOfferUploaded = false; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPmGeneratedOfferSentToProjectTeam); assertThat(model.isAbleToRemoveSignedGrantOffer(), is(false)); } @Test public void testAbleToRemoveSignedGrantOfferNotAllowedIfSubmittedToInnovate() { boolean leadPartner = true; boolean projectManager = true; boolean signedGrantOfferUploaded = true; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPmSignedGrantOfferSubmittedToInternalTeam); assertThat(model.isAbleToRemoveSignedGrantOffer(), is(false)); } @Test public void testAbleToRemoveSignedGrantOfferIfRejectedAndProjectManager() { boolean leadPartner = true; boolean projectManager = true; boolean signedGrantOfferUploaded = true; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPmSignedGrantOfferRejected); assertThat(model.isAbleToRemoveSignedGrantOffer(), is(true)); } @Test public void testAbleToRemoveSignedGrantOfferNotAllowedIfRejectedButNotProjectManager() { boolean leadPartner = true; boolean projectManager = false; boolean signedGrantOfferUploaded = true; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPartnerSignedGrantOfferRejected); assertThat(model.isAbleToRemoveSignedGrantOffer(), is(false)); } @Test public void testAbleToRemoveSignedGrantOfferNotAllowedIfApproved() { boolean leadPartner = true; boolean projectManager = true; boolean signedGrantOfferUploaded = true; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPmSignedGrantOfferApproved); assertThat(model.isAbleToRemoveSignedGrantOffer(), is(false)); } @Test public void testShowGrantOfferLetterReceivedByInnovateMessageIfSubmittedToInnovate() { boolean leadPartner = false; boolean projectManager = false; boolean signedGrantOfferUploaded = true; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPartnerSignedGrantOfferSubmittedToInternalTeam); assertThat(model.isShowGrantOfferLetterReceivedByInnovateMessage(), is(true)); } @Test public void testShowGrantOfferLetterReceivedByInnovateMessageIfRejectedAndNotLeadPartnerOrProjectManager() { boolean leadPartner = false; boolean projectManager = false; boolean signedGrantOfferUploaded = true; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPartnerSignedGrantOfferRejected); assertThat(model.isShowGrantOfferLetterReceivedByInnovateMessage(), is(true)); } @Test public void testShowGrantOfferLetterReceivedByInnovateMessageShownIfRejectedAndLeadPartnerButNotProjectManager() { boolean leadPartner = true; boolean projectManager = false; boolean signedGrantOfferUploaded = true; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPartnerSignedGrantOfferRejected); assertThat(model.isShowGrantOfferLetterReceivedByInnovateMessage(), is(true)); } @Test public void testShowGrantOfferLetterReceivedByInnovateMessageNotAllowedIfRejectedAndProjectManager() { boolean leadPartner = true; boolean projectManager = true; boolean signedGrantOfferUploaded = true; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPmSignedGrantOfferRejected); assertThat(model.isShowGrantOfferLetterReceivedByInnovateMessage(), is(false)); } @Test public void testShowGrantOfferLetterReceivedByInnovateMessageNotAllowedIfApproved() { boolean leadPartner = true; boolean projectManager = true; boolean signedGrantOfferUploaded = true; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPmSignedGrantOfferApproved); assertThat(model.isShowGrantOfferLetterReceivedByInnovateMessage(), is(false)); } @Test public void testShowAwaitingSignatureFromLeadPartnerMessageIfGrantOfferLetterSentButNotYetSignedAndNotLeadPartner() { boolean leadPartner = false; boolean projectManager = false; boolean signedGrantOfferUploaded = false; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPartnerGeneratedOfferSentToProjectTeam); assertThat(model.isShowAwaitingSignatureFromLeadPartnerMessage(), is(true)); } @Test public void testShowAwaitingSignatureFromLeadPartnerMessageNotAllowedIfLeadPartner() { boolean leadPartner = true; boolean projectManager = false; boolean signedGrantOfferUploaded = false; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPartnerGeneratedOfferSentToProjectTeam); assertThat(model.isShowAwaitingSignatureFromLeadPartnerMessage(), is(false)); } @Test public void testShowAwaitingSignatureFromLeadPartnerMessageNotAllowedIfProjectManager() { boolean leadPartner = true; boolean projectManager = true; boolean signedGrantOfferUploaded = false; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPmGeneratedOfferSentToProjectTeam); assertThat(model.isShowAwaitingSignatureFromLeadPartnerMessage(), is(false)); } @Test public void testShowAwaitingSignatureFromLeadPartnerMessageNotAllowedIfGrantOfferNotYetSent() { boolean leadPartner = true; boolean projectManager = true; boolean signedGrantOfferUploaded = false; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPmGeneratedGrantOfferNotYetSentToProjectTeam); assertThat(model.isShowAwaitingSignatureFromLeadPartnerMessage(), is(false)); } @Test public void testShowAwaitingSignatureFromLeadPartnerMessageNotAllowedIfSigned() { boolean leadPartner = true; boolean projectManager = true; boolean signedGrantOfferUploaded = true; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPmSignedGrantOfferSubmittedToInternalTeam); assertThat(model.isShowAwaitingSignatureFromLeadPartnerMessage(), is(false)); } @Test public void testShowAwaitingSignatureFromLeadPartnerMessageNotAllowedIfGrantOfferLetterRejectedAndNotLeadPartner() { boolean leadPartner = false; boolean projectManager = false; boolean signedGrantOfferUploaded = false; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPartnerSignedGrantOfferRejected); assertThat(model.isShowAwaitingSignatureFromLeadPartnerMessage(), is(false)); } @Test public void testShowGrantOfferLetterApprovedByInnovateMessageIfApproved() { boolean leadPartner = true; boolean projectManager = true; boolean signedGrantOfferUploaded = true; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPmSignedGrantOfferApproved); assertThat(model.isShowGrantOfferLetterApprovedByInnovateMessage(), is(true)); } @Test public void testShowGrantOfferLetterApprovedByInnovateMessageNotAllowedIfNotApproved() { boolean leadPartner = true; boolean projectManager = true; boolean signedGrantOfferUploaded = true; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPmSignedGrantOfferSubmittedToInternalTeam); assertThat(model.isShowGrantOfferLetterApprovedByInnovateMessage(), is(false)); } @Test public void testShowDisabledSubmitButtonIfProjectManagerAndSignedGrantOfferLetterNotYetUploaded() { boolean leadPartner = true; boolean projectManager = true; boolean signedGrantOfferUploaded = false; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPmGeneratedOfferSentToProjectTeam); assertThat(model.isShowDisabledSubmitButton(), is(true)); } @Test public void testShowDisabledSubmitButtonNotAllowedIfLeadPartner() { boolean leadPartner = true; boolean projectManager = false; boolean signedGrantOfferUploaded = false; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPartnerGeneratedOfferSentToProjectTeam); assertThat(model.isShowDisabledSubmitButton(), is(false)); } @Test public void testShowDisabledSubmitButtonNotAllowedIfNonLeadPartner() { boolean leadPartner = false; boolean projectManager = false; boolean signedGrantOfferUploaded = false; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPartnerGeneratedOfferSentToProjectTeam); assertThat(model.isShowDisabledSubmitButton(), is(false)); } @Test public void testShowDisabledSubmitButtonNotAllowedIfSignedGrantOfferLetterUploaded() { boolean leadPartner = true; boolean projectManager = true; boolean signedGrantOfferUploaded = true; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPmGeneratedOfferSentToProjectTeam); assertThat(model.isShowDisabledSubmitButton(), is(false)); } @Test public void testShowDisabledSubmitButtonNotAllowedIfSignedGrantOfferLetterSubmitted() { boolean leadPartner = true; boolean projectManager = true; boolean signedGrantOfferUploaded = true; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPmSignedGrantOfferSubmittedToInternalTeam); assertThat(model.isShowDisabledSubmitButton(), is(false)); } private GrantOfferLetterModel createGrantOfferLetterModel( boolean leadPartner, boolean projectManager, boolean signedGrantOfferUploaded, GrantOfferLetterStateResource state) { FileDetailsViewModel grantOfferLetterFile = state.isGeneratedGrantOfferLetterAlreadySentToProjectTeam() ? new FileDetailsViewModel("grant-offer", 1000L) : null; FileDetailsViewModel additionalContractFile = state.isGeneratedGrantOfferLetterAlreadySentToProjectTeam() ? new FileDetailsViewModel("grant-offer", 1000L) : null; FileDetailsViewModel signedGrantOfferLetterFile = signedGrantOfferUploaded ? new FileDetailsViewModel("grant-offer", 1000L) : null; return new GrantOfferLetterModel("Grant offer letter", 123L, "Project name", leadPartner, grantOfferLetterFile, signedGrantOfferLetterFile, additionalContractFile, projectManager, state, false, false); } }
ifs-web-service/ifs-project-setup-service/src/test/java/org/innovateuk/ifs/project/grantofferletter/viewmodel/GrantOfferLetterModelTest.java
package org.innovateuk.ifs.project.grantofferletter.viewmodel; import org.innovateuk.ifs.file.controller.viewmodel.FileDetailsViewModel; import org.innovateuk.ifs.project.grantofferletter.resource.GrantOfferLetterStateResource; import org.junit.Test; import static org.hamcrest.Matchers.is; import static org.innovateuk.ifs.project.grantofferletter.resource.GrantOfferLetterEvent.*; import static org.innovateuk.ifs.project.grantofferletter.resource.GrantOfferLetterState.*; import static org.innovateuk.ifs.project.grantofferletter.resource.GrantOfferLetterStateResource.stateInformationForNonPartnersView; import static org.innovateuk.ifs.project.grantofferletter.resource.GrantOfferLetterStateResource.stateInformationForPartnersView; import static org.junit.Assert.assertThat; public class GrantOfferLetterModelTest { public static final GrantOfferLetterStateResource stateForPmGeneratedOfferSentToProjectTeam = stateInformationForNonPartnersView(SENT, GOL_SENT); public static final GrantOfferLetterStateResource stateForPartnerGeneratedOfferSentToProjectTeam = stateInformationForPartnersView(SENT, GOL_SENT); public static final GrantOfferLetterStateResource stateForPmSignedGrantOfferSubmittedToInternalTeam = stateInformationForNonPartnersView(READY_TO_APPROVE, GOL_SIGNED); public static final GrantOfferLetterStateResource stateForPmSignedGrantOfferRejected = stateInformationForNonPartnersView(SENT, SIGNED_GOL_REJECTED); public static final GrantOfferLetterStateResource stateForPartnerSignedGrantOfferRejected = stateInformationForPartnersView(SENT, SIGNED_GOL_REJECTED); public static final GrantOfferLetterStateResource stateForPartnerSignedGrantOfferSubmittedToInternalTeam = stateInformationForPartnersView(READY_TO_APPROVE, GOL_SIGNED); public static final GrantOfferLetterStateResource stateForPmSignedGrantOfferApproved = stateInformationForNonPartnersView(APPROVED, SIGNED_GOL_APPROVED); public static final GrantOfferLetterStateResource stateForPmGeneratedGrantOfferNotYetSentToProjectTeam = stateInformationForNonPartnersView(PENDING, PROJECT_CREATED); @Test public void testShowSubmitButtonWhenSentSignedAndNotSubmittedAsProjectManager() { boolean leadPartner = true; boolean projectManager = true; boolean signedGrantOfferUploaded = true; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPmGeneratedOfferSentToProjectTeam); assertThat(model.isShowSubmitButton(), is(true)); } @Test public void testShowSubmitButtonNotShownWhenNotProjectManager() { boolean leadPartner = true; boolean projectManager = false; boolean signedGrantOfferUploaded = true; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPartnerGeneratedOfferSentToProjectTeam); assertThat(model.isShowSubmitButton(), is(false)); } @Test public void testShowSubmitButtonNotShownWhenSignedLetterNotYetUploaded() { boolean leadPartner = true; boolean projectManager = true; boolean signedGrantOfferUploaded = false; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPmGeneratedOfferSentToProjectTeam); assertThat(model.isShowSubmitButton(), is(false)); } @Test public void testShowSubmitButtonNotShownWhenSignedLetterAlreadySubmitted() { boolean leadPartner = true; boolean projectManager = true; boolean signedGrantOfferUploaded = true; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPmSignedGrantOfferSubmittedToInternalTeam); assertThat(model.isShowSubmitButton(), is(false)); } @Test public void testShowGrantOfferLetterRejectedMessageWhenProjectManagerAndGrantOfferIsRejected() { boolean leadPartner = true; boolean projectManager = true; boolean signedGrantOfferUploaded = true; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPmSignedGrantOfferRejected); assertThat(model.isShowGrantOfferLetterRejectedMessage(), is(true)); } @Test public void testShowGrantOfferLetterRejectedMessageNotShownWhenNotProjectManager() { boolean leadPartner = true; boolean projectManager = false; boolean signedGrantOfferUploaded = true; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPartnerSignedGrantOfferRejected); assertThat(model.isShowGrantOfferLetterRejectedMessage(), is(false)); } @Test public void testShowGrantOfferLetterRejectedMessageNotShownWhenGrantOfferLetterNotRejected() { boolean leadPartner = true; boolean projectManager = true; boolean signedGrantOfferUploaded = true; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPmSignedGrantOfferSubmittedToInternalTeam); assertThat(model.isShowGrantOfferLetterRejectedMessage(), is(false)); } @Test public void testAbleToRemoveSignedGrantOfferIfUploadedAndNotSubmittedAndLeadPartner() { boolean leadPartner = true; boolean projectManager = false; boolean signedGrantOfferUploaded = true; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPartnerGeneratedOfferSentToProjectTeam); assertThat(model.isAbleToRemoveSignedGrantOffer(), is(true)); } @Test public void testAbleToRemoveSignedGrantOfferNotAllowedIfNotLeadPartnerOrProjectManager() { boolean leadPartner = false; boolean projectManager = false; boolean signedGrantOfferUploaded = true; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPartnerGeneratedOfferSentToProjectTeam); assertThat(model.isAbleToRemoveSignedGrantOffer(), is(false)); } @Test public void testAbleToRemoveSignedGrantOfferNotAllowedIfNotUploaded() { boolean leadPartner = true; boolean projectManager = true; boolean signedGrantOfferUploaded = false; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPmGeneratedOfferSentToProjectTeam); assertThat(model.isAbleToRemoveSignedGrantOffer(), is(false)); } @Test public void testAbleToRemoveSignedGrantOfferNotAllowedIfSubmittedToInnovate() { boolean leadPartner = true; boolean projectManager = true; boolean signedGrantOfferUploaded = true; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPmSignedGrantOfferSubmittedToInternalTeam); assertThat(model.isAbleToRemoveSignedGrantOffer(), is(false)); } @Test public void testAbleToRemoveSignedGrantOfferIfRejectedAndProjectManager() { boolean leadPartner = true; boolean projectManager = true; boolean signedGrantOfferUploaded = true; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPmSignedGrantOfferRejected); assertThat(model.isAbleToRemoveSignedGrantOffer(), is(true)); } @Test public void testAbleToRemoveSignedGrantOfferNotAllowedIfRejectedButNotProjectManager() { boolean leadPartner = true; boolean projectManager = false; boolean signedGrantOfferUploaded = true; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPartnerSignedGrantOfferRejected); assertThat(model.isAbleToRemoveSignedGrantOffer(), is(false)); } @Test public void testAbleToRemoveSignedGrantOfferNotAllowedIfApproved() { boolean leadPartner = true; boolean projectManager = true; boolean signedGrantOfferUploaded = true; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPmSignedGrantOfferApproved); assertThat(model.isAbleToRemoveSignedGrantOffer(), is(false)); } @Test public void testShowGrantOfferLetterReceivedByInnovateMessageIfSubmittedToInnovate() { boolean leadPartner = false; boolean projectManager = false; boolean signedGrantOfferUploaded = true; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPartnerSignedGrantOfferSubmittedToInternalTeam); assertThat(model.isShowGrantOfferLetterReceivedByInnovateMessage(), is(true)); } @Test public void testShowGrantOfferLetterReceivedByInnovateMessageIfRejectedAndNotLeadPartnerOrProjectManager() { boolean leadPartner = false; boolean projectManager = false; boolean signedGrantOfferUploaded = true; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPartnerSignedGrantOfferRejected); assertThat(model.isShowGrantOfferLetterReceivedByInnovateMessage(), is(true)); } @Test public void testShowGrantOfferLetterReceivedByInnovateMessageShownIfRejectedAndLeadPartnerButNotProjectManager() { boolean leadPartner = true; boolean projectManager = false; boolean signedGrantOfferUploaded = true; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPartnerSignedGrantOfferRejected); assertThat(model.isShowGrantOfferLetterReceivedByInnovateMessage(), is(true)); } @Test public void testShowGrantOfferLetterReceivedByInnovateMessageNotAllowedIfRejectedAndProjectManager() { boolean leadPartner = true; boolean projectManager = true; boolean signedGrantOfferUploaded = true; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPmSignedGrantOfferRejected); assertThat(model.isShowGrantOfferLetterReceivedByInnovateMessage(), is(false)); } @Test public void testShowGrantOfferLetterReceivedByInnovateMessageNotAllowedIfApproved() { boolean leadPartner = true; boolean projectManager = true; boolean signedGrantOfferUploaded = true; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPmSignedGrantOfferApproved); assertThat(model.isShowGrantOfferLetterReceivedByInnovateMessage(), is(false)); } @Test public void testShowAwaitingSignatureFromLeadPartnerMessageIfGrantOfferLetterSentButNotYetSignedAndNotLeadPartner() { boolean leadPartner = false; boolean projectManager = false; boolean signedGrantOfferUploaded = false; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPartnerGeneratedOfferSentToProjectTeam); assertThat(model.isShowAwaitingSignatureFromLeadPartnerMessage(), is(true)); } @Test public void testShowAwaitingSignatureFromLeadPartnerMessageNotAllowedIfLeadPartner() { boolean leadPartner = true; boolean projectManager = false; boolean signedGrantOfferUploaded = false; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPartnerGeneratedOfferSentToProjectTeam); assertThat(model.isShowAwaitingSignatureFromLeadPartnerMessage(), is(false)); } @Test public void testShowAwaitingSignatureFromLeadPartnerMessageNotAllowedIfProjectManager() { boolean leadPartner = true; boolean projectManager = true; boolean signedGrantOfferUploaded = false; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPmGeneratedOfferSentToProjectTeam); assertThat(model.isShowAwaitingSignatureFromLeadPartnerMessage(), is(false)); } @Test public void testShowAwaitingSignatureFromLeadPartnerMessageNotAllowedIfGrantOfferNotYetSent() { boolean leadPartner = true; boolean projectManager = true; boolean signedGrantOfferUploaded = false; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPmGeneratedGrantOfferNotYetSentToProjectTeam); assertThat(model.isShowAwaitingSignatureFromLeadPartnerMessage(), is(false)); } @Test public void testShowAwaitingSignatureFromLeadPartnerMessageNotAllowedIfSigned() { boolean leadPartner = true; boolean projectManager = true; boolean signedGrantOfferUploaded = true; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPmSignedGrantOfferSubmittedToInternalTeam); assertThat(model.isShowAwaitingSignatureFromLeadPartnerMessage(), is(false)); } @Test public void testShowAwaitingSignatureFromLeadPartnerMessageNotAllowedIfGrantOfferLetterRejectedAndNotLeadPartner() { boolean leadPartner = false; boolean projectManager = false; boolean signedGrantOfferUploaded = false; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPartnerSignedGrantOfferRejected); assertThat(model.isShowAwaitingSignatureFromLeadPartnerMessage(), is(false)); } @Test public void testShowGrantOfferLetterApprovedByInnovateMessageIfApproved() { boolean leadPartner = true; boolean projectManager = true; boolean signedGrantOfferUploaded = true; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPmSignedGrantOfferApproved); assertThat(model.isShowGrantOfferLetterApprovedByInnovateMessage(), is(true)); } @Test public void testShowGrantOfferLetterApprovedByInnovateMessageNotAllowedIfNotApproved() { boolean leadPartner = true; boolean projectManager = true; boolean signedGrantOfferUploaded = true; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPmSignedGrantOfferSubmittedToInternalTeam); assertThat(model.isShowGrantOfferLetterApprovedByInnovateMessage(), is(false)); } @Test public void testShowDisabledSubmitButtonIfProjectManagerAndSignedGrantOfferLetterNotYetUploaded() { boolean leadPartner = true; boolean projectManager = true; boolean signedGrantOfferUploaded = false; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPmGeneratedOfferSentToProjectTeam); assertThat(model.isShowDisabledSubmitButton(), is(true)); } @Test public void testShowDisabledSubmitButtonNotAllowedIfLeadPartner() { boolean leadPartner = true; boolean projectManager = false; boolean signedGrantOfferUploaded = false; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPartnerGeneratedOfferSentToProjectTeam); assertThat(model.isShowDisabledSubmitButton(), is(false)); } @Test public void testShowDisabledSubmitButtonNotAllowedIfNonLeadPartner() { boolean leadPartner = false; boolean projectManager = false; boolean signedGrantOfferUploaded = false; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPartnerGeneratedOfferSentToProjectTeam); assertThat(model.isShowDisabledSubmitButton(), is(false)); } @Test public void testShowDisabledSubmitButtonNotAllowedIfSignedGrantOfferLetterUploaded() { boolean leadPartner = true; boolean projectManager = true; boolean signedGrantOfferUploaded = true; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPmGeneratedOfferSentToProjectTeam); assertThat(model.isShowDisabledSubmitButton(), is(false)); } @Test public void testShowDisabledSubmitButtonNotAllowedIfSignedGrantOfferLetterSubmitted() { boolean leadPartner = true; boolean projectManager = true; boolean signedGrantOfferUploaded = true; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPmSignedGrantOfferSubmittedToInternalTeam); assertThat(model.isShowDisabledSubmitButton(), is(false)); } private GrantOfferLetterModel createGrantOfferLetterModel( boolean leadPartner, boolean projectManager, boolean signedGrantOfferUploaded, GrantOfferLetterStateResource state) { FileDetailsViewModel grantOfferLetterFile = state.isGeneratedGrantOfferLetterAlreadySentToProjectTeam() ? new FileDetailsViewModel("grant-offer", 1000L) : null; FileDetailsViewModel additionalContractFile = state.isGeneratedGrantOfferLetterAlreadySentToProjectTeam() ? new FileDetailsViewModel("grant-offer", 1000L) : null; FileDetailsViewModel signedGrantOfferLetterFile = signedGrantOfferUploaded ? new FileDetailsViewModel("grant-offer", 1000L) : null; return new GrantOfferLetterModel("Grant offer letter" 123L, "Project name", leadPartner, grantOfferLetterFile, signedGrantOfferLetterFile, additionalContractFile, projectManager, state, false); } }
IFS-8198 fixed.
ifs-web-service/ifs-project-setup-service/src/test/java/org/innovateuk/ifs/project/grantofferletter/viewmodel/GrantOfferLetterModelTest.java
IFS-8198 fixed.
<ide><path>fs-web-service/ifs-project-setup-service/src/test/java/org/innovateuk/ifs/project/grantofferletter/viewmodel/GrantOfferLetterModelTest.java <ide> new FileDetailsViewModel("grant-offer", 1000L) : <ide> null; <ide> <del> return new GrantOfferLetterModel("Grant offer letter" 123L, "Project name", leadPartner, <del> grantOfferLetterFile, signedGrantOfferLetterFile, additionalContractFile, projectManager, state, false); <add> return new GrantOfferLetterModel("Grant offer letter", 123L, "Project name", leadPartner, <add> grantOfferLetterFile, signedGrantOfferLetterFile, additionalContractFile, projectManager, state, false, false); <ide> } <ide> }
Java
mit
4f1d4dc102cf253fa1ce91cf49bb75f6119268bd
0
AmityHighCSDevTeam/TicTactical,AmityHighCSDevTeam/TicTactical,AmityHighCSDevTeam/TicTactical
package org.amityregion5.tictactical; import org.amityregion5.tictactical.ai.IAI; import org.amityregion5.tictactical.ai.MinimaxHeuristicAI; import com.badlogic.gdx.Game; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import org.amityregion5.tictactical.ai.MinimaxHeuristicAI; public class TicTactical extends Game{ // TODO is jus gam // TODO things n stuff //Grids arranged as follows: /* * 6 7 8 * 3 4 5 * 0 1 2 * */ OrthographicCamera cam; Texture X; Texture O; Texture grid; Texture movingDisplay; Texture winDisplay; Texture tieDisplay; Texture selectorR; Texture selectorB; Texture selectorG; SpriteBatch spritebatch; private IAI ai = new MinimaxHeuristicAI(5); private char[][] board = new char[9][9]; private char[] big_board = new char[10]; private boolean turn = false; // false is X, True is O private int next_move = 9; private char win = 0; private int players = 1; private String easter = "egg"; private boolean ai_team = true; // same as the other thing, just selecting ai's team(if applicable) @Override public void create () { cam = new OrthographicCamera(); X = new Texture(Gdx.files.internal("X.png")); O = new Texture(Gdx.files.internal("O.png")); selectorG = new Texture(Gdx.files.internal("selector.png")); selectorR = new Texture(Gdx.files.internal("redSelector.png")); selectorB = new Texture(Gdx.files.internal("bluSelector.png")); movingDisplay = new Texture(Gdx.files.internal("isMovingNow.png")); grid = new Texture(Gdx.files.internal("grid.png")); winDisplay = new Texture(Gdx.files.internal("hasWon.png")); tieDisplay = new Texture(Gdx.files.internal("GameTied.png")); easter.contains("secrets"); spritebatch = new SpriteBatch(); spritebatch.setBlendFunction(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA); big_board[9] = 1; } @Override public void render () { Gdx.gl.glClearColor(1, 1, 1, 1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); int grid_size = Math.min(Gdx.graphics.getHeight(), Gdx.graphics.getWidth() * 75 / 100); int miniboard_size = ((grid_size - 60) / 3) - 10; int slot_size = (miniboard_size / 3) - (miniboard_size / 9); int in_x = Gdx.input.getX() - 30; int in_y = Gdx.graphics.getHeight() - Gdx.input.getY() - 30; int miniboard = -1; int slot = -1; miniboard = ((((in_x + 4) / (miniboard_size + 10))) % 3) + 3 * ((in_y + 4) / (miniboard_size + 10)); slot = ((in_x - (miniboard % 3) * (miniboard_size + 10)) / ((miniboard_size + 10) / 3) % 3) + 3 * ((in_y - (miniboard / 3) * (miniboard_size + 10)) / ((miniboard_size + 10) / 3)); if(players == 0){ //you are on menu. So make a render_menu method and a menu_interaction method }else{ render_game(spritebatch, grid_size, miniboard_size, slot_size, miniboard, slot, in_x, in_y); if(players == 1){ if(turn == ai_team){ int[] lastMove = new int[2]; lastMove[1] = next_move; lastMove[0] = 5138008; // hold your screen upside down, and put some blocky font on that number. boolean[] availableBoards = ai.getAvailableBoards(board, big_board, lastMove); char temp; if(ai_team){ temp = 'o'; }else{ temp = 'x'; } int[] ai_moves = ai.chooseNextMove(board, big_board, availableBoards, temp); miniboard = ai_moves[0]; slot = ai_moves[1]; //sergey notice this and do the things } } if(slot > 8){ slot = 8; }else if(slot < 0){ slot = 0; } if(miniboard > 8){ miniboard = 8; }else if(miniboard < 0){ miniboard = 0; } if (Gdx.input.justTouched() && (players == 2 || (players == 1 && turn != ai_team))) { if(win == 0 && in_x <= grid_size - 60 && in_y <= grid_size - 60 && in_x >= 0 && in_y >= 0){ if(!(miniboard == -1 || slot == -1) && board[miniboard][slot] == 0 && (miniboard == next_move || big_board[next_move] != 0) && big_board[miniboard] == 0){ game_logic(miniboard, slot); } }else if(win != 0){ reset(); } }else if(players == 1 && turn == ai_team){ game_logic(miniboard, slot); } } } @Override public void dispose () { X.dispose(); O.dispose(); grid.dispose(); selectorG.dispose(); selectorR.dispose(); selectorB.dispose(); movingDisplay.dispose(); winDisplay.dispose(); tieDisplay.dispose(); spritebatch.dispose(); } @Override public void resize(int width, int height) { super.resize(width, height); cam.setToOrtho(false, width, height); cam.update(); } @Override public void resume() { // TODO Auto-generated method stub super.resume(); } @Override public void pause() { // TODO Auto-generated method stub super.pause(); } public char evaluate(char[] b, int s){ if(b[s] != ' '){ if(s == 0){ if((b[0] == b[1] && b[1] == b[2]) || (b[0] == b[3] && b[3] == b[6]) || (b[0] == b[4] && b[4] == b[8])){ return b[s]; } }else if(s == 1){ if((b[0] == b[1] && b[1] == b[2]) || (b[1] == b[4] && b[4] == b[7])){ return b[s]; } }else if(s == 2){ if((b[0] == b[1] && b[1] == b[2]) || (b[2] == b[5] && b[5] == b[8]) || (b[2] == b[4] && b[4] == b[6])){ return b[s]; } }else if(s == 3){ if((b[0] == b[3] && b[3] == b[6]) || (b[3] == b[4] && b[4] == b[5])){ return b[s]; } }else if(s == 4){ if((b[3] == b[4] && b[4] == b[5]) || (b[1] == b[4] && b[4] == b[7]) || (b[0] == b[4] && b[4] == b[8] || (b[2] == b[4] && b[4] == b[6]))){ return b[s]; } }else if(s == 5){ if((b[2] == b[5] && b[5] == b[8]) || (b[3] == b[4] && b[4] == b[5])){ return b[s]; } }else if(s == 6){ if((b[6] == b[7] && b[7] == b[8]) || (b[0] == b[3] && b[3] == b[6]) || (b[2] == b[4] && b[4] == b[6])){ return b[s]; } }else if(s == 7){ if((b[6] == b[7] && b[7] == b[8]) || (b[1] == b[4] && b[4] == b[7])){ return b[s]; } }else if(s == 8){ if((b[6] == b[7] && b[7] == b[8]) || (b[2] == b[5] && b[5] == b[8]) || (b[0] == b[4] && b[4] == b[8])){ return b[s]; } } } return 0; } public void reset(){ win = 0; next_move = 9; turn = false; board = new char[9][9]; big_board = new char[9]; players = 0; } public void game_logic(int miniboard, int slot){ if(turn){ board[miniboard][slot] = 'o'; }else{ board[miniboard][slot] = 'x'; } turn = !turn; char result = evaluate(board[miniboard], slot); if(result == 'x'){ big_board[miniboard] = 'X'; }else if(result == 'o'){ big_board[miniboard] = 'O'; }else{ int j = 0; for(int i = 0; i < 9; i ++){ if(board[miniboard][i] != 0){ j++; } } if(j == 9){ big_board[miniboard] = 3; } } char[] board0 = new char[9]; for(int i = 0; i < 9; i++){ board0[i] = big_board[i]; } char winner = evaluate(board0, miniboard); if(winner == 'X' || winner == 'O'){ win = winner; }else{ int tie_test = 0; for(int i = 0; i < 9; i++){ if(big_board[i] != 0){ tie_test += 9; }else{ for(int j = 0; j < 9; j ++){ if(board[i][j] != 0){ tie_test++; } } } } if(tie_test == 81){ win = 'T'; } } next_move = slot; } public void render_game (SpriteBatch spritebatch, int grid_size, int miniboard_size, int slot_size, int miniboard, int slot, int in_x, int in_y){ spritebatch.setProjectionMatrix(cam.combined); spritebatch.begin();{ spritebatch.draw(grid, 30, 30, grid_size - 60, grid_size - 60); for(int i = 1; i <= 3; i ++){ for(int j = 1; j <= 3; j ++){ spritebatch.draw(grid, 30 + (i * 2.5f) + ((grid_size - 60) * (i - 1)) / 3, 30 + (j * 2.5f) + ((grid_size - 60) * (j - 1)) / 3, miniboard_size, miniboard_size); if(((i - 1) + (j- 1) * 3 == next_move || big_board[next_move] != 0) && win == 0 && big_board[(i - 1) + (j - 1) * 3] == 0){ spritebatch.draw(selectorG, 30 + (i * 2.5f) + ((grid_size - 60) * (i - 1)) / 3, 30 + (j * 2.5f) + ((grid_size - 60) * (j - 1)) / 3, miniboard_size, miniboard_size); } } } //printing highlight for moused over tile if(in_x <= grid_size - 60 && in_y <= grid_size - 60 && in_x >= 0 && in_y >= 0){ if(turn){ spritebatch.draw(selectorB, 32.5f + ((miniboard % 3) * 2.5f) + ((slot % 3) * 2.5f) + ((grid_size - 60) * (miniboard % 3)) / 3 + ((miniboard_size * (slot % 3) / 3) + slot_size / 2) - (slot_size / 3), 32.5f + ((miniboard / 3) * 2.5f) + ((slot / 3) * 2.5f) + ((grid_size - 60) * (miniboard / 3)) / 3 + ((miniboard_size * (slot / 3) / 3) + slot_size / 2) - (slot_size / 3), slot_size, slot_size); }else{ spritebatch.draw(selectorR, 32.5f + ((miniboard % 3) * 2.5f) + ((slot % 3) * 2.5f) + ((grid_size - 60) * (miniboard % 3)) / 3 + ((miniboard_size * (slot % 3) / 3) + slot_size / 2) - (slot_size / 3), 32.5f + ((miniboard / 3) * 2.5f) + ((slot / 3) * 2.5f) + ((grid_size - 60) * (miniboard / 3)) / 3 + ((miniboard_size * (slot / 3) / 3) + slot_size / 2) - (slot_size / 3), slot_size, slot_size); } } //drawing x's and o's for(int i = 0; i < 9; i++){ for(int j = 0; j < 9; j ++){ if(board[i][j] == 'x'){ spritebatch.draw(X, 32.5f + ((i % 3) * 2.5f) + ((j % 3) * 2.5f) + ((grid_size - 60) * (i % 3)) / 3 + ((miniboard_size * (j % 3) / 3) + slot_size / 2) - (slot_size / 3), 32.5f + ((i / 3) * 2.5f) + ((j / 3) * 2.5f) + ((grid_size - 60) * (i / 3)) / 3 + ((miniboard_size * (j / 3) / 3) + slot_size / 2) - (slot_size / 3), slot_size, slot_size); }else if(board[i][j] == 'o'){ spritebatch.draw(O, 32.5f + ((i % 3) * 2.5f) + ((j % 3) * 2.5f) + ((grid_size - 60) * (i % 3)) / 3 + ((miniboard_size * (j % 3) / 3) + slot_size / 2) - (slot_size / 3), 32.5f + ((i / 3) * 2.5f) + ((j / 3) * 2.5f) + ((grid_size - 60) * (i / 3)) / 3 + ((miniboard_size * (j / 3) / 3) + slot_size / 2) - (slot_size / 3), slot_size, slot_size); } } if(big_board[i] == 'X'){ spritebatch.draw(X, 30 + (((i % 3) + 1) * 2.5f) + ((grid_size - 60) * (i % 3)) / 3, 30 + ((i / 3) * 2.5f) + ((grid_size - 60) * (i / 3)) / 3, miniboard_size, miniboard_size); }else if(big_board[i] == 'O'){ spritebatch.draw(O, 30 + (((i % 3) + 1) * 2.5f) + ((grid_size - 60) * (i % 3)) / 3, 30 + ((i / 3) * 2.5f) + ((grid_size - 60) * (i / 3)) / 3, miniboard_size, miniboard_size); } } //printing win statements if(win != 0){ if(win == 'X'){ spritebatch.draw(X, grid_size - 30 + slot_size, miniboard_size * 2 , miniboard_size, miniboard_size); spritebatch.draw(winDisplay, grid_size - 30 + slot_size * 1.25f, miniboard_size * 2 - slot_size * 1.25f, miniboard_size, miniboard_size); }else if(win == 'O'){ spritebatch.draw(O, grid_size - 30 + slot_size, miniboard_size * 2 , miniboard_size, miniboard_size); spritebatch.draw(winDisplay, grid_size - 30 + slot_size * 1.25f, miniboard_size * 2 - slot_size * 1.25f, miniboard_size, miniboard_size); }else{ spritebatch.draw(tieDisplay, grid_size - 30 + slot_size * 1.25f, miniboard_size * 2 - slot_size * 1.25f, miniboard_size * 1.5f, miniboard_size); } } //printing whose turn it b if(win == 0){ if(turn){ spritebatch.draw(O, grid_size - 30 + slot_size, miniboard_size * 2 , miniboard_size, miniboard_size); }else{ spritebatch.draw(X, grid_size - 30 + slot_size, miniboard_size * 2 , miniboard_size, miniboard_size); } spritebatch.draw(movingDisplay, grid_size - 30 + slot_size, miniboard_size * 2 - slot_size, miniboard_size, miniboard_size); } } spritebatch.end(); } }
core/src/org/amityregion5/tictactical/TicTactical.java
package org.amityregion5.tictactical; import org.amityregion5.tictactical.ai.IAI; import org.amityregion5.tictactical.ai.MinimaxHeuristicAI; import com.badlogic.gdx.Game; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.SpriteBatch; public class TicTactical extends Game{ // TODO is jus gam // TODO things n stuff //Grids arranged as follows: /* * 6 7 8 * 3 4 5 * 0 1 2 * */ OrthographicCamera cam; Texture X; Texture O; Texture grid; Texture movingDisplay; Texture winDisplay; Texture tieDisplay; Texture selectorR; Texture selectorB; Texture selectorG; SpriteBatch spritebatch; private IAI ai = new MinimaxHeuristicAI(5); private char[][] board = new char[9][9]; private char[] big_board = new char[9]; private boolean turn = false; // false is X, True is O private int next_move = -1; private char win = 0; private int players = 1; private String easter = "egg"; private boolean ai_team = true; // same as the other thing, just selecting ai's team(if applicable) @Override public void create () { cam = new OrthographicCamera(); X = new Texture(Gdx.files.internal("X.png")); O = new Texture(Gdx.files.internal("O.png")); selectorG = new Texture(Gdx.files.internal("selector.png")); selectorR = new Texture(Gdx.files.internal("redSelector.png")); selectorB = new Texture(Gdx.files.internal("bluSelector.png")); movingDisplay = new Texture(Gdx.files.internal("isMovingNow.png")); grid = new Texture(Gdx.files.internal("grid.png")); winDisplay = new Texture(Gdx.files.internal("hasWon.png")); tieDisplay = new Texture(Gdx.files.internal("GameTied.png")); easter.contains("secrets"); spritebatch = new SpriteBatch(); spritebatch.setBlendFunction(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA); /* for(int i = 0; i < 9; i ++){ for(int j = 0; j < 9; j ++){ board[i][j] = '1'; } } */ } @Override public void render () { Gdx.gl.glClearColor(1, 1, 1, 1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); int grid_size = Math.min(Gdx.graphics.getHeight(), Gdx.graphics.getWidth() * 75 / 100); int miniboard_size = ((grid_size - 60) / 3) - 10; int slot_size = (miniboard_size / 3) - (miniboard_size / 9); int in_x = Gdx.input.getX() - 30; int in_y = Gdx.graphics.getHeight() - Gdx.input.getY() - 30; int miniboard = -1; int slot = -1; if(players == 0){ //you are on menu. So make a render_menu method and a menu_interaction method }else{ render_game(spritebatch, grid_size, miniboard_size, slot_size, miniboard, slot, in_x, in_y); if(players == 1){ if(turn == ai_team){ boolean[] t = new boolean[9]; for(int i = 0; i < 9; i ++){ t[i] = false; } if(next_move == -1){ for(int i = 0; i < 9; i ++){ if(big_board[i] != 0){ t[i] = true; } } }else{ t[next_move] = true; } char temp; if(ai_team){ temp = 'o'; }else{ temp = 'x'; } int[] ai_moves = ai.chooseNextMove(board, big_board, t, temp); miniboard = ai_moves[0]; slot = ai_moves[1]; //sergey notice this and do the things }else{ miniboard = ((((in_x + 4) / (miniboard_size + 10))) % 3) + 3 * ((in_y + 4) / (miniboard_size + 10)); slot = ((in_x - (miniboard % 3) * (miniboard_size + 10)) / ((miniboard_size + 10) / 3) % 3) + 3 * ((in_y - (miniboard / 3) * (miniboard_size + 10)) / ((miniboard_size + 10) / 3)); } }else if(players == 2){ miniboard = ((((in_x + 4) / (miniboard_size + 10))) % 3) + 3 * ((in_y + 4) / (miniboard_size + 10)); slot = ((in_x - (miniboard % 3) * (miniboard_size + 10)) / ((miniboard_size + 10) / 3) % 3) + 3 * ((in_y - (miniboard / 3) * (miniboard_size + 10)) / ((miniboard_size + 10) / 3)); } if(slot > 8){ slot = 8; }else if(slot < 0){ slot = 0; } if(miniboard > 8){ miniboard = 8; }else if(miniboard < 0){ miniboard = 0; } if (Gdx.input.justTouched()) { if(win == 0 && in_x <= grid_size - 60 && in_y <= grid_size - 60 && in_x >= 0 && in_y >= 0){ if(!(miniboard == -1 || slot == -1) && board[miniboard][slot] == 0 && (miniboard == next_move || next_move == -1) && big_board[miniboard] == 0){ game_logic(miniboard, slot); } }else if(win != 0){ reset(); } } } } @Override public void dispose () { X.dispose(); O.dispose(); grid.dispose(); selectorG.dispose(); selectorR.dispose(); selectorB.dispose(); movingDisplay.dispose(); winDisplay.dispose(); tieDisplay.dispose(); spritebatch.dispose(); } @Override public void resize(int width, int height) { super.resize(width, height); cam.setToOrtho(false, width, height); cam.update(); } @Override public void resume() { // TODO Auto-generated method stub super.resume(); } @Override public void pause() { // TODO Auto-generated method stub super.pause(); } public char evaluate(char[] b, int s){ if(b[s] != ' '){ if(s == 0){ if((b[0] == b[1] && b[1] == b[2]) || (b[0] == b[3] && b[3] == b[6]) || (b[0] == b[4] && b[4] == b[8])){ return b[s]; } }else if(s == 1){ if((b[0] == b[1] && b[1] == b[2]) || (b[1] == b[4] && b[4] == b[7])){ return b[s]; } }else if(s == 2){ if((b[0] == b[1] && b[1] == b[2]) || (b[2] == b[5] && b[5] == b[8]) || (b[2] == b[4] && b[4] == b[6])){ return b[s]; } }else if(s == 3){ if((b[0] == b[3] && b[3] == b[6]) || (b[3] == b[4] && b[4] == b[5])){ return b[s]; } }else if(s == 4){ if((b[3] == b[4] && b[4] == b[5]) || (b[1] == b[4] && b[4] == b[7]) || (b[0] == b[4] && b[4] == b[8] || (b[2] == b[4] && b[4] == b[6]))){ return b[s]; } }else if(s == 5){ if((b[2] == b[5] && b[5] == b[8]) || (b[3] == b[4] && b[4] == b[5])){ return b[s]; } }else if(s == 6){ if((b[6] == b[7] && b[7] == b[8]) || (b[0] == b[3] && b[3] == b[6]) || (b[2] == b[4] && b[4] == b[6])){ return b[s]; } }else if(s == 7){ if((b[6] == b[7] && b[7] == b[8]) || (b[1] == b[4] && b[4] == b[7])){ return b[s]; } }else if(s == 8){ if((b[6] == b[7] && b[7] == b[8]) || (b[2] == b[5] && b[5] == b[8]) || (b[0] == b[4] && b[4] == b[8])){ return b[s]; } } } return 0; } public void reset(){ win = 0; next_move = -1; turn = false; board = new char[9][9]; big_board = new char[9]; players = 0; } public void game_logic(int miniboard, int slot){ if(turn){ board[miniboard][slot] = 'o'; }else{ board[miniboard][slot] = 'x'; } turn = !turn; char result = evaluate(board[miniboard], slot); if(result == 'x'){ big_board[miniboard] = 'X'; }else if(result == 'o'){ big_board[miniboard] = 'O'; }else{ int j = 0; for(int i = 0; i < 9; i ++){ if(board[miniboard][i] != 0){ j++; } } if(j == 9){ big_board[miniboard] = 3; } } char[] board0 = new char[9]; for(int i = 0; i < 9; i++){ board0[i] = big_board[i]; } char winner = evaluate(board0, miniboard); if(winner == 'X' || winner == 'O'){ win = winner; }else{ int tie_test = 0; for(int i = 0; i < 9; i++){ if(big_board[i] != 0){ tie_test += 9; }else{ for(int j = 0; j < 9; j ++){ if(board[i][j] != 0){ tie_test++; } } } } if(tie_test == 81){ win = 'T'; } } if(big_board[slot] == 0){ next_move = slot; }else{ next_move = -1; } } public void render_game (SpriteBatch spritebatch, int grid_size, int miniboard_size, int slot_size, int miniboard, int slot, int in_x, int in_y){ spritebatch.setProjectionMatrix(cam.combined); spritebatch.begin();{ spritebatch.draw(grid, 30, 30, grid_size - 60, grid_size - 60); for(int i = 1; i <= 3; i ++){ for(int j = 1; j <= 3; j ++){ spritebatch.draw(grid, 30 + (i * 2.5f) + ((grid_size - 60) * (i - 1)) / 3, 30 + (j * 2.5f) + ((grid_size - 60) * (j - 1)) / 3, miniboard_size, miniboard_size); if(((i - 1) + (j- 1) * 3 == next_move || next_move == -1) && win == 0 && big_board[(i - 1) + (j - 1) * 3] == 0){ spritebatch.draw(selectorG, 30 + (i * 2.5f) + ((grid_size - 60) * (i - 1)) / 3, 30 + (j * 2.5f) + ((grid_size - 60) * (j - 1)) / 3, miniboard_size, miniboard_size); } } } //printing highlight for moused over tile if(in_x <= grid_size - 60 && in_y <= grid_size - 60 && in_x >= 0 && in_y >= 0){ if(turn){ spritebatch.draw(selectorB, 32.5f + ((miniboard % 3) * 2.5f) + ((slot % 3) * 2.5f) + ((grid_size - 60) * (miniboard % 3)) / 3 + ((miniboard_size * (slot % 3) / 3) + slot_size / 2) - (slot_size / 3), 32.5f + ((miniboard / 3) * 2.5f) + ((slot / 3) * 2.5f) + ((grid_size - 60) * (miniboard / 3)) / 3 + ((miniboard_size * (slot / 3) / 3) + slot_size / 2) - (slot_size / 3), slot_size, slot_size); }else{ spritebatch.draw(selectorR, 32.5f + ((miniboard % 3) * 2.5f) + ((slot % 3) * 2.5f) + ((grid_size - 60) * (miniboard % 3)) / 3 + ((miniboard_size * (slot % 3) / 3) + slot_size / 2) - (slot_size / 3), 32.5f + ((miniboard / 3) * 2.5f) + ((slot / 3) * 2.5f) + ((grid_size - 60) * (miniboard / 3)) / 3 + ((miniboard_size * (slot / 3) / 3) + slot_size / 2) - (slot_size / 3), slot_size, slot_size); } } //drawing x's and o's for(int i = 0; i < 9; i++){ for(int j = 0; j < 9; j ++){ if(board[i][j] == 'x'){ spritebatch.draw(X, 32.5f + ((i % 3) * 2.5f) + ((j % 3) * 2.5f) + ((grid_size - 60) * (i % 3)) / 3 + ((miniboard_size * (j % 3) / 3) + slot_size / 2) - (slot_size / 3), 32.5f + ((i / 3) * 2.5f) + ((j / 3) * 2.5f) + ((grid_size - 60) * (i / 3)) / 3 + ((miniboard_size * (j / 3) / 3) + slot_size / 2) - (slot_size / 3), slot_size, slot_size); }else if(board[i][j] == 'o'){ spritebatch.draw(O, 32.5f + ((i % 3) * 2.5f) + ((j % 3) * 2.5f) + ((grid_size - 60) * (i % 3)) / 3 + ((miniboard_size * (j % 3) / 3) + slot_size / 2) - (slot_size / 3), 32.5f + ((i / 3) * 2.5f) + ((j / 3) * 2.5f) + ((grid_size - 60) * (i / 3)) / 3 + ((miniboard_size * (j / 3) / 3) + slot_size / 2) - (slot_size / 3), slot_size, slot_size); } } if(big_board[i] == 'X'){ spritebatch.draw(X, 30 + (((i % 3) + 1) * 2.5f) + ((grid_size - 60) * (i % 3)) / 3, 30 + ((i / 3) * 2.5f) + ((grid_size - 60) * (i / 3)) / 3, miniboard_size, miniboard_size); }else if(big_board[i] == 'O'){ spritebatch.draw(O, 30 + (((i % 3) + 1) * 2.5f) + ((grid_size - 60) * (i % 3)) / 3, 30 + ((i / 3) * 2.5f) + ((grid_size - 60) * (i / 3)) / 3, miniboard_size, miniboard_size); } } //printing win statements if(win != 0){ if(win == 'X'){ spritebatch.draw(X, grid_size - 30 + slot_size, miniboard_size * 2 , miniboard_size, miniboard_size); spritebatch.draw(winDisplay, grid_size - 30 + slot_size * 1.25f, miniboard_size * 2 - slot_size * 1.25f, miniboard_size, miniboard_size); }else if(win == 'O'){ spritebatch.draw(O, grid_size - 30 + slot_size, miniboard_size * 2 , miniboard_size, miniboard_size); spritebatch.draw(winDisplay, grid_size - 30 + slot_size * 1.25f, miniboard_size * 2 - slot_size * 1.25f, miniboard_size, miniboard_size); }else{ spritebatch.draw(tieDisplay, grid_size - 30 + slot_size * 1.25f, miniboard_size * 2 - slot_size * 1.25f, miniboard_size * 1.5f, miniboard_size); } } //printing whose turn it b if(win == 0){ if(turn){ spritebatch.draw(O, grid_size - 30 + slot_size, miniboard_size * 2 , miniboard_size, miniboard_size); }else{ spritebatch.draw(X, grid_size - 30 + slot_size, miniboard_size * 2 , miniboard_size, miniboard_size); } spritebatch.draw(movingDisplay, grid_size - 30 + slot_size, miniboard_size * 2 - slot_size, miniboard_size, miniboard_size); } } spritebatch.end(); } }
Made the ai work and all that stuff.
core/src/org/amityregion5/tictactical/TicTactical.java
Made the ai work and all that stuff.
<ide><path>ore/src/org/amityregion5/tictactical/TicTactical.java <ide> import com.badlogic.gdx.graphics.OrthographicCamera; <ide> import com.badlogic.gdx.graphics.Texture; <ide> import com.badlogic.gdx.graphics.g2d.SpriteBatch; <add>import org.amityregion5.tictactical.ai.MinimaxHeuristicAI; <ide> <ide> public class TicTactical extends Game{ <ide> // TODO is jus gam <ide> <ide> private IAI ai = new MinimaxHeuristicAI(5); <ide> private char[][] board = new char[9][9]; <del> private char[] big_board = new char[9]; <add> private char[] big_board = new char[10]; <ide> private boolean turn = false; // false is X, True is O <del> private int next_move = -1; <add> private int next_move = 9; <ide> private char win = 0; <ide> private int players = 1; <ide> private String easter = "egg"; <ide> <ide> spritebatch = new SpriteBatch(); <ide> spritebatch.setBlendFunction(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA); <del> /* <del> for(int i = 0; i < 9; i ++){ <del> for(int j = 0; j < 9; j ++){ <del> board[i][j] = '1'; <del> } <del> } <del> */ <add> <add> big_board[9] = 1; <ide> } <ide> <ide> @Override <ide> int in_x = Gdx.input.getX() - 30; <ide> int in_y = Gdx.graphics.getHeight() - Gdx.input.getY() - 30; <ide> int miniboard = -1; <del> int slot = -1; <add> int slot = -1; <add> miniboard = ((((in_x + 4) / (miniboard_size + 10))) % 3) + 3 * ((in_y + 4) / (miniboard_size + 10)); <add> slot = ((in_x - (miniboard % 3) * (miniboard_size + 10)) / ((miniboard_size + 10) / 3) % 3) + 3 * ((in_y - (miniboard / 3) * (miniboard_size + 10)) / ((miniboard_size + 10) / 3)); <add> <ide> if(players == 0){ <ide> //you are on menu. So make a render_menu method and a menu_interaction method <ide> }else{ <ide> render_game(spritebatch, grid_size, miniboard_size, slot_size, miniboard, slot, in_x, in_y); <ide> if(players == 1){ <ide> if(turn == ai_team){ <del> boolean[] t = new boolean[9]; <del> for(int i = 0; i < 9; i ++){ <del> t[i] = false; <del> } <del> if(next_move == -1){ <del> for(int i = 0; i < 9; i ++){ <del> if(big_board[i] != 0){ <del> t[i] = true; <del> } <del> } <del> }else{ <del> t[next_move] = true; <del> } <add> int[] lastMove = new int[2]; <add> lastMove[1] = next_move; <add> lastMove[0] = 5138008; // hold your screen upside down, and put some blocky font on that number. <add> boolean[] availableBoards = ai.getAvailableBoards(board, big_board, lastMove); <ide> char temp; <ide> <ide> if(ai_team){ <ide> temp = 'x'; <ide> } <ide> <del> int[] ai_moves = ai.chooseNextMove(board, big_board, t, temp); <add> int[] ai_moves = ai.chooseNextMove(board, big_board, availableBoards, temp); <ide> miniboard = ai_moves[0]; <ide> slot = ai_moves[1]; <ide> <ide> //sergey notice this and do the things <del> }else{ <del> miniboard = ((((in_x + 4) / (miniboard_size + 10))) % 3) + 3 * ((in_y + 4) / (miniboard_size + 10)); <del> slot = ((in_x - (miniboard % 3) * (miniboard_size + 10)) / ((miniboard_size + 10) / 3) % 3) + 3 * ((in_y - (miniboard / 3) * (miniboard_size + 10)) / ((miniboard_size + 10) / 3)); <del> } <del> <del> }else if(players == 2){ <del> miniboard = ((((in_x + 4) / (miniboard_size + 10))) % 3) + 3 * ((in_y + 4) / (miniboard_size + 10)); <del> slot = ((in_x - (miniboard % 3) * (miniboard_size + 10)) / ((miniboard_size + 10) / 3) % 3) + 3 * ((in_y - (miniboard / 3) * (miniboard_size + 10)) / ((miniboard_size + 10) / 3)); <add> } <add> <ide> } <ide> if(slot > 8){ <ide> slot = 8; <ide> miniboard = 0; <ide> } <ide> <del> if (Gdx.input.justTouched()) { <add> <add> if (Gdx.input.justTouched() && (players == 2 || (players == 1 && turn != ai_team))) { <ide> if(win == 0 && in_x <= grid_size - 60 && in_y <= grid_size - 60 && in_x >= 0 && in_y >= 0){ <ide> <del> if(!(miniboard == -1 || slot == -1) && board[miniboard][slot] == 0 && (miniboard == next_move || next_move == -1) && big_board[miniboard] == 0){ <add> if(!(miniboard == -1 || slot == -1) && board[miniboard][slot] == 0 && (miniboard == next_move || big_board[next_move] != 0) && big_board[miniboard] == 0){ <ide> game_logic(miniboard, slot); <ide> } <ide> <ide> }else if(win != 0){ <ide> reset(); <ide> } <add> }else if(players == 1 && turn == ai_team){ <add> game_logic(miniboard, slot); <ide> } <ide> <ide> } <ide> <ide> public void reset(){ <ide> win = 0; <del> next_move = -1; <add> next_move = 9; <ide> turn = false; <ide> board = new char[9][9]; <ide> big_board = new char[9]; <ide> win = 'T'; <ide> } <ide> } <del> if(big_board[slot] == 0){ <del> next_move = slot; <del> }else{ <del> next_move = -1; <del> } <add> next_move = slot; <ide> } <ide> <ide> public void render_game (SpriteBatch spritebatch, int grid_size, int miniboard_size, int slot_size, int miniboard, int slot, int in_x, int in_y){ <ide> for(int i = 1; i <= 3; i ++){ <ide> for(int j = 1; j <= 3; j ++){ <ide> spritebatch.draw(grid, 30 + (i * 2.5f) + ((grid_size - 60) * (i - 1)) / 3, 30 + (j * 2.5f) + ((grid_size - 60) * (j - 1)) / 3, miniboard_size, miniboard_size); <del> if(((i - 1) + (j- 1) * 3 == next_move || next_move == -1) && win == 0 && big_board[(i - 1) + (j - 1) * 3] == 0){ <add> if(((i - 1) + (j- 1) * 3 == next_move || big_board[next_move] != 0) && win == 0 && big_board[(i - 1) + (j - 1) * 3] == 0){ <ide> spritebatch.draw(selectorG, 30 + (i * 2.5f) + ((grid_size - 60) * (i - 1)) / 3, 30 + (j * 2.5f) + ((grid_size - 60) * (j - 1)) / 3, miniboard_size, miniboard_size); <ide> } <ide> }
JavaScript
bsd-2-clause
bab44d97f9ce6cd2b98b194e291685e7483f370a
0
Billmate/prestashop,Billmate/prestashop
/** * Created by Boxedsolutions on 2017-03-20. */ window.method = null; window.address_selected = null; window.latestScroll = null; window.previousSelectedMethod = null; var BillmateIframe = new function(){ var self = this; var childWindow = null; this.updatePsCheckout = function(){ // When address in checkout updates; var data = {}; data['action'] = 'updateCheckout'; data['ajax'] = 1; jQuery.ajax({ url : billmate_checkout_url, data: data, type: 'POST', success: function(response){ var result = JSON.parse(response); if (result.success) { if(result.hasOwnProperty("update_checkout") && result.update_checkout === true) self.updateCheckout(); }else { location.reload(); } } }); } this.updateAddress = function (data) { // When address in checkout updates; data['action'] = 'setAddress'; data['ajax'] = 1; jQuery.ajax({ url : billmate_checkout_url, data: data, type: 'POST', success: function(response){ var result = JSON.parse(response); if(result.success) { jQuery('#shippingdiv').html(result.carrier_block); } window.address_selected = true; } }); }; this.updateShippingMethod = function(method){ jQuery.ajax({ url: UPDATE_SHIPPING_METHOD_URL, data: {'shipping_method': method}, type: 'POST', success: function (response) { var result = JSON.parse(response); if (result.success) { if(result.hasOwnProperty("update_checkout") && result.update_checkout === true) self.updateCheckout(); if(data.method == 8 || data.method == 16) self.updateCheckout(); window.method = data.method; } } }); } this.updatePaymentMethod = function(data){ if(window.method != data.method) { data['action'] = 'setPaymentMethod'; data['ajax'] = 1; jQuery.ajax({ url: billmate_checkout_url, data: data, type: 'POST', success: function (response) { var result = JSON.parse(response); if (result.success) { if(result.hasOwnProperty("update_checkout") && result.update_checkout === true) self.updateCheckout(); if(data.method == 8 || data.method == 16) self.updateCheckout(); window.method = data.method; } } }); } }; this.updateShippingMethod = function(){ } this.createOrder = function(data){ // Create Order data['action'] = 'validateOrder'; data['ajax'] = 1; jQuery.ajax({ url : billmate_checkout_url, data: data, type: 'POST', success: function(response){ var result = JSON.parse(response); if(result.success){ location.href=result.redirect; } } }); }; this.initListeners = function () { jQuery(document).ready(function(){ console.log('initEventListeners'); window.addEventListener("message",self.handleEvent); }); } this.handleEvent = function(event){ console.log(event); if(event.origin == "https://checkout.billmate.se") { try { var json = JSON.parse(event.data); } catch (e) { return; } self.childWindow = json.source; console.log(json); switch (json.event) { case 'address_selected': self.updateAddress(json.data); self.updatePaymentMethod(json.data); if(window.method == null || window.method == json.data.method) { jQuery('#checkoutdiv').removeClass('loading'); } break; case 'payment_method_selected': if (window.address_selected !== null) { self.updatePaymentMethod(json.data); if(window.method == json.data.method) { jQuery('#checkoutdiv').removeClass('loading'); } } break; case 'checkout_success': self.createOrder(json.data); break; case 'content_height': $('checkout').height = json.data; break; case 'content_scroll_position': console.log('Scroll position'+json.data); window.latestScroll = jQuery(document).find( "#checkout" ).offset().top + json.data; jQuery('html, body').animate({scrollTop: jQuery(document).find( "#checkout" ).offset().top + json.data}, 400); break; case 'checkout_loaded': jQuery('#checkoutdiv').removeClass('loading'); break; default: console.log(event); console.log('not implemented') break; } } }; this.updateCheckout = function(){ console.log('update_checkout'); var win = document.getElementById('checkout').contentWindow; win.postMessage(JSON.stringify({event: 'update_checkout'}),'*') } }; window.b_iframe = BillmateIframe; window.b_iframe.initListeners(); window.tmpshippingvalue = $('#total_shipping').html(); var BillmateCart = new function () { this.updateProduct = function(type,id,qty){ var self = this; var val = $('input[name=quantity_'+id+']').val(); console.log(val); console.log(qty); var newQty = val; var action = ''; if(type == 'sub') { if (typeof(qty) === 'undefined' || !qty) { qty = 1; newQty = val - 1; action = '&op=down'; } else if (qty < 0) qty = -qty; } else { if (typeof(qty) === 'undefined' || !qty) { qty = 1; } } console.log(qty); console.log(newQty); var customizationId = 0; var productId = 0; var productAttributeId = 0; var id_address_delivery = 0; var ids = 0; ids = id.split('_'); productId = parseInt(ids[0]); if (typeof(ids[1]) !== 'undefined') productAttributeId = parseInt(ids[1]); if (typeof(ids[2]) !== 'undefined') customizationId = parseInt(ids[2]); if (typeof(ids[3]) !== 'undefined') id_address_delivery = parseInt(ids[3]); if (newQty > 0 || $('#product_'+id+'_gift').length) { $.ajax({ type: 'GET', url: baseUri, async: true, cache: false, dataType: 'json', data: 'controller=cart' +'&ajax=true' +'&add' +'&getproductprice' +'&summary' +'&id_product='+productId +'&ipa='+productAttributeId +'&id_address_delivery='+id_address_delivery +action + ((customizationId !== 0) ? '&id_customization='+customizationId : '') +'&qty='+qty +'&token='+static_token +'&allow_refresh=1', success: function(jsonData) { if (jsonData.hasError) { var errors = ''; for(var error in jsonData.errors) if(error !== 'indexOf') errors += jsonData.errors[error] + "\n"; alert(errors); $('input[name=quantity_'+ id +']').val($('input[name=quantity_'+ id +'_hidden]').val()); } else { if (jsonData.refresh) location.reload(); self.updateCart(jsonData.summary); self.updateHookShoppingCart(jsonData.HOOK_SHOPPING_CART); self.updateHookShoppingCartExtra(jsonData.HOOK_SHOPPING_CART_EXTRA); if (newQty === 0) $('#product_'+id).hide(); if (typeof(getCarrierListAndUpdate) !== 'undefined') getCarrierListAndUpdate(); } }, error: function(XMLHttpRequest, textStatus, errorThrown) { if (textStatus !== 'abort') alert("TECHNICAL ERROR: unable to save update quantity \n\nDetails:\nError thrown: " + XMLHttpRequest + "\n" + 'Text status: ' + textStatus); } }); } else { self.deleteProductFromSummary(id); } }; this.deleteProductFromSummary = function(id){ var self = this; var customizationId = 0; var productId = 0; var productAttributeId = 0; var id_address_delivery = 0; var ids = id.split('_'); productId = parseInt(ids[0]); if (typeof(ids[1]) !== 'undefined') productAttributeId = parseInt(ids[1]); if (typeof(ids[2]) !== 'undefined') customizationId = parseInt(ids[2]); if (typeof(ids[3]) !== 'undefined') id_address_delivery = parseInt(ids[3]); $.ajax({ type: 'GET', url: baseUri, async: true, cache: false, dataType: 'json', data: 'controller=cart' +'&ajax=true&delete&summary' +'&id_product='+productId +'&ipa='+productAttributeId +'&id_address_delivery='+id_address_delivery+ ( (customizationId !== 0) ? '&id_customization='+customizationId : '') +'&token=' + static_token +'&allow_refresh=1', success: function(jsonData) { if (jsonData.hasError) { var errors = ''; for(var error in jsonData.errors) //IE6 bug fix if (error !== 'indexOf') errors += jsonData.errors[error] + "\n"; } else { if (jsonData.refresh) location.reload(); if (parseInt(jsonData.summary.products.length) === 0) { if (typeof(orderProcess) === 'undefined' || orderProcess !== 'order-opc') document.location.href = document.location.href; // redirection else { $('#center_column').children().each(function() { if ($(this).attr('id') !== 'emptyCartWarning' && $(this).attr('class') !== 'breadcrumb' && $(this).attr('id') !== 'cart_title') { $(this).fadeOut('slow', function () { $(this).remove(); }); } }); $('#summary_products_label').remove(); $('#emptyCartWarning').fadeIn('slow'); } } else { $('#product_'+ id).fadeOut('slow', function() { $(this).remove(); if (!customizationId) self.refreshOddRow(); }); var exist = false; $.each(jsonData.summary.products,function(i,value){ if(value.id_product === productId && value.id_product_attribute === productAttributeId && value.id_address.delivery == id_address_delivery) exist = true; }) // if all customization removed => delete product line if (!exist && customizationId) { $('#product_' + productId + '_' + productAttributeId + '_0_' + id_address_delivery).fadeOut('slow', function() { $(this).remove(); self.refreshOddRow(); }); } } self.updateCart(jsonData.summary); //updateCustomizedDatas(jsonData.customizedDatas); self.updateHookShoppingCart(jsonData.HOOK_SHOPPING_CART); self.updateHookShoppingCartExtra(jsonData.HOOK_SHOPPING_CART_EXTRA); if (typeof(getCarrierListAndUpdate) !== 'undefined') getCarrierListAndUpdate(); } }, error: function(XMLHttpRequest, textStatus, errorThrown) { if (textStatus !== 'abort') alert("TECHNICAL ERROR: unable to save update quantity \n\nDetails:\nError thrown: " + XMLHttpRequest + "\n" + 'Text status: ' + textStatus); } }); }; this.updateCart = function(json) { var i; var nbrProducts = 0; if (typeof json === 'undefined') return; $('.cart_quantity_input').val(0); product_list = {}; for (i=0;i<json.products.length;i++) product_list[json.products[i].id_product+'_'+json.products[i].id_product_attribute+'_'+json.products[i].id_address_delivery] = json.products[i]; if (!$('.multishipping-cart:visible').length) { for (i=0;i<json.gift_products.length;i++) { if (typeof(product_list[json.gift_products[i].id_product+'_'+json.gift_products[i].id_product_attribute+'_'+json.gift_products[i].id_address_delivery]) !== 'undefined') product_list[json.gift_products[i].id_product+'_'+json.gift_products[i].id_product_attribute+'_'+json.gift_products[i].id_address_delivery].quantity -= json.gift_products[i].cart_quantity; } } else { for (i=0;i<json.gift_products.length;i++) { if (typeof(product_list[json.gift_products[i].id_product+'_'+json.gift_products[i].id_product_attribute+'_'+json.gift_products[i].id_address_delivery]) === 'undefined') product_list[json.gift_products[i].id_product+'_'+json.gift_products[i].id_product_attribute+'_'+json.gift_products[i].id_address_delivery] = json.gift_products[i]; } } for (i in product_list) { // if reduction, we need to show it in the cart by showing the initial price above the current one var reduction = product_list[i].reduction_applies; var reduction_type = product_list[i].reduction_type; var reduction_symbol = ''; var initial_price_text = ''; var initial_price = ''; if (typeof(product_list[i].price_without_quantity_discount) !== 'undefined') initial_price = formatCurrency(product_list[i].price_without_quantity_discount, currencyFormat, currencySign, currencyBlank); var current_price = ''; var product_total = ''; var product_customization_total = ''; if (priceDisplayMethod !== 0) { current_price = formatCurrency(product_list[i].price, currencyFormat, currencySign, currencyBlank); product_total = product_list[i].total; product_customization_total = product_list[i].total_customization; } else { current_price = formatCurrency(product_list[i].price_wt, currencyFormat, currencySign, currencyBlank); product_total = product_list[i].total_wt; product_customization_total = product_list[i].total_customization_wt; } var current_price_class ='price'; var price_reduction = ''; if (reduction && typeof(initial_price) !== 'undefined') { if (reduction_type == 'amount') price_reduction = product_list[i].reduction_formatted; else { var display_price = 0; if (priceDisplayMethod !== 0) display_price = product_list[i].price; else display_price = product_list[i].price_wt; price_reduction = ps_round((product_list[i].price_without_quantity_discount - display_price)/product_list[i].price_without_quantity_discount * -100); reduction_symbol = '%'; } if (initial_price !== '' && product_list[i].price_without_quantity_discount > product_list[i].price) { initial_price_text = '<li class="price-percent-reduction small">&nbsp;'+price_reduction+reduction_symbol+'&nbsp;</li><li class="old-price">' + initial_price + '</li>'; current_price_class += ' special-price'; } } var key_for_blockcart = product_list[i].id_product + '_' + product_list[i].id_product_attribute + '_' + product_list[i].id_address_delivery; var key_for_blockcart_nocustom = product_list[i].id_product + '_' + product_list[i].id_product_attribute + '_' + ((product_list[i].id_customization && product_list[i].quantity_without_customization != product_list[i].quantity)? 'nocustom' : '0') + '_' + product_list[i].id_address_delivery; $('#product_price_' + key_for_blockcart).html('<li class="' + current_price_class + '">' + current_price + '</li>' + initial_price_text); if (typeof(product_list[i].customizationQuantityTotal) !== 'undefined' && product_list[i].customizationQuantityTotal > 0) $('#total_product_price_' + key_for_blockcart).html(formatCurrency(product_customization_total, currencyFormat, currencySign, currencyBlank)); else $('#total_product_price_' + key_for_blockcart).html(formatCurrency(product_total, currencyFormat, currencySign, currencyBlank)); if (product_list[i].quantity_without_customization != product_list[i].quantity) $('#total_product_price_' + key_for_blockcart_nocustom).html(formatCurrency(product_total, currencyFormat, currencySign, currencyBlank)); $('input[name=quantity_' + key_for_blockcart_nocustom + ']').val(product_list[i].id_customization? product_list[i].quantity_without_customization : product_list[i].cart_quantity); $('input[name=quantity_' + key_for_blockcart_nocustom + '_hidden]').val(product_list[i].id_customization? product_list[i].quantity_without_customization : product_list[i].cart_quantity); if (typeof(product_list[i].customizationQuantityTotal) !== 'undefined' && product_list[i].customizationQuantityTotal > 0) $('#cart_quantity_custom_' + key_for_blockcart).html(product_list[i].customizationQuantityTotal); nbrProducts += parseInt(product_list[i].quantity); } // Update discounts if (json.discounts.length === 0) { $('.cart_discount').each(function(){$(this).remove();}); $('.cart_total_voucher').remove(); } else { if ($('.cart_discount').length === 0) location.reload(); if (priceDisplayMethod !== 0) $('#total_discount').html(formatCurrency(json.total_discounts_tax_exc, currencyFormat, currencySign, currencyBlank)); else $('#total_discount').html(formatCurrency(json.total_discounts, currencyFormat, currencySign, currencyBlank)); $('.cart_discount').each(function(){ var idElmt = $(this).attr('id').replace('cart_discount_',''); var toDelete = true; for (i=0;i<json.discounts.length;i++) { if (json.discounts[i].id_discount === idElmt) { if (json.discounts[i].value_real !== '!') { if (priceDisplayMethod !== 0) $('#cart_discount_' + idElmt + ' td.cart_discount_price span.price-discount').html(formatCurrency(json.discounts[i].value_tax_exc * -1, currencyFormat, currencySign, currencyBlank)); else $('#cart_discount_' + idElmt + ' td.cart_discount_price span.price-discount').html(formatCurrency(json.discounts[i].value_real * -1, currencyFormat, currencySign, currencyBlank)); } toDelete = false; } } if (toDelete) $('#cart_discount_' + idElmt + ', #cart_total_voucher').fadeTo('fast', 0, function(){ $(this).remove(); }); }); } // Block cart if (priceDisplayMethod !== 0) { $('#cart_block_shipping_cost').html(formatCurrency(json.total_shipping_tax_exc, currencyFormat, currencySign, currencyBlank)); $('#cart_block_wrapping_cost').html(formatCurrency(json.total_wrapping_tax_exc, currencyFormat, currencySign, currencyBlank)); $('#cart_block_total').html(formatCurrency(json.total_price_without_tax, currencyFormat, currencySign, currencyBlank)); } else { $('#cart_block_shipping_cost').html(formatCurrency(json.total_shipping, currencyFormat, currencySign, currencyBlank)); $('#cart_block_wrapping_cost').html(formatCurrency(json.total_wrapping, currencyFormat, currencySign, currencyBlank)); $('#cart_block_total').html(formatCurrency(json.total_price, currencyFormat, currencySign, currencyBlank)); } $('#cart_block_tax_cost').html(formatCurrency(json.total_tax, currencyFormat, currencySign, currencyBlank)); $('.ajax_cart_quantity').html(nbrProducts); // Cart summary $('#summary_products_quantity').html(nbrProducts+' '+(nbrProducts > 1 ? txtProducts : txtProduct)); if (priceDisplayMethod !== 0) { $('#total_product').html(formatCurrency(json.total_products, currencyFormat, currencySign, currencyBlank)); } else { $('#total_product').html(formatCurrency(json.total_products_wt, currencyFormat, currencySign, currencyBlank)); } $('#total_price').html(formatCurrency(json.total_price, currencyFormat, currencySign, currencyBlank)); $('#total_price_without_tax').html(formatCurrency(json.total_price_without_tax, currencyFormat, currencySign, currencyBlank)); $('#total_tax').html(formatCurrency(json.total_tax, currencyFormat, currencySign, currencyBlank)); if (json.total_shipping > 0) { if (priceDisplayMethod !== 0) { $('#total_shipping').html(formatCurrency(json.total_shipping_tax_exc, currencyFormat, currencySign, currencyBlank)); } else { $('#total_shipping').html(formatCurrency(json.total_shipping, currencyFormat, currencySign, currencyBlank)); } } else { $('#total_shipping').html(freeShippingTranslation); } if($('#total_shipping').html() != window.tmpshippingvalue) { //force page reload location.href = billmate_checkout_url; } else { window.tmpshippingvalue = $('#total_shipping').html(); } if (json.total_wrapping > 0) { $('#total_wrapping').html(formatCurrency(json.total_wrapping, currencyFormat, currencySign, currencyBlank)); $('#total_wrapping').parent().show(); } else { $('#total_wrapping').html(formatCurrency(json.total_wrapping, currencyFormat, currencySign, currencyBlank)); $('#total_wrapping').parent().hide(); } if (window.ajaxCart !== undefined) ajaxCart.refresh(); window.b_iframe.updatePsCheckout(); }; this.refreshOddRow = function() { var odd_class = 'odd'; var even_class = 'even'; $.each($('.cart_item'), function(i, it) { if (i === 0) { if ($(this).hasClass('even')) { odd_class = 'even'; even_class = 'odd'; } $(this).addClass('first_item'); } if(i % 2) $(this).removeClass(odd_class).addClass(even_class); else $(this).removeClass(even_class).addClass(odd_class); }); $('.cart_item:last-child, .customization:last-child').addClass('last_item'); } this.updateHookShoppingCart = function(html) { $('#HOOK_SHOPPING_CART').html(html); }; this.updateHookShoppingCartExtra = function(html) { $('#HOOK_SHOPPING_CART_EXTRA').html(html); } }; window.b_cart = BillmateCart; jQuery(document).ready(function(){ jQuery(document).ajaxStart(function(){ jQuery('#checkoutdiv').addClass('loading'); jQuery("#checkoutdiv.loading .billmateoverlay").height(jQuery("#checkoutdiv").height()); }) jQuery(document).ajaxComplete(function(){ jQuery('#checkoutdiv').removeClass('loading'); }) $("#button_order_cart").attr("href", billmate_checkout_url); $("#layer_cart .layer_cart_cart a.button-medium").attr("href", billmate_checkout_url); $("#order p.cart_navigation a.standard-checkout").attr("href", billmate_checkout_url); $('.cart-summary .checkout .btn').attr("href", billmate_checkout_url); $('.cart-content-btn .btn').attr("href", billmate_checkout_url); if( $("#billmate_summary a.cart_quantity_delete").length) { $("#billmate_summary a.cart_quantity_delete").unbind('click').live('click', function () { window.b_cart.deleteProductFromSummary($(this).attr('id')); return false; }); } if($("#billmate_summary a.cart_quantity_up").length) { $("#billmate_summary a.cart_quantity_up").unbind('click').live('click', function () { window.b_cart.updateProduct('add', $(this).attr('id').replace('cart_quantity_up_', '')); return false; }); } if($("#billmate_summary a.cart_quantity_down").length) { $("#billmate_summary a.cart_quantity_down").unbind('click').live('click', function () { window.b_cart.updateProduct('sub', $(this).attr('id').replace('cart_quantity_down_', '')); return false; }); } if(window.location.href == billmate_checkout_url) { $('body').attr('id', 'order'); } $('body').on('click','.delivery-option input[type="radio"]',function(e){ e.preventDefault(); var selectedMethod = e.target.value; if(selectedMethod != window.previousSelectedMethod){ window.previousSelectedMethod = selectedMethod; var url = billmate_checkout_url var delivery_option = $('.delivery-option input[type="radio"]:checked').val(); var name = $('.delivery-option input[type="radio"]:checked').attr('name'); var address_id = $('.delivery_option_radio:checked').data('id_address'); var values = {}; values[name] = delivery_option; values['action'] = 'setShipping'; values['ajax'] = 1 jQuery.ajax({ url: url, data: values, success: function(response){ var result = JSON.parse(response); console.log(result); if(result.hasOwnProperty("update_checkout") && result.update_checkout === true){ window.b_iframe.updateCheckout(); } } }) } }) $('body').on('click','.delivery_option_radio',function(e){ e.preventDefault(); var selectedMethod = e.target.value; if(selectedMethod != window.previousSelectedMethod){ window.previousSelectedMethod = selectedMethod; var url = billmate_checkout_url var delivery_option = $('.delivery_option_radio:checked').val(); var address_id = $('.delivery_option_radio:checked').data('id_address'); var values = {}; values['delivery_option['+address_id+']'] = delivery_option; values['action'] = 'setShipping'; values['ajax'] = 1 jQuery.ajax({ url: url, data: values, success: function(response){ var result = JSON.parse(response); console.log(result); if(result.hasOwnProperty("update_checkout") && result.update_checkout === true){ window.b_iframe.updateCheckout(); } } }) } }) }); function deleteProductFromSummary(id){ console.log('product removed'); window.b_iframe.updatePsCheckout(); }
billmatecheckout/views/js/checkout.js
/** * Created by Boxedsolutions on 2017-03-20. */ window.method = null; window.address_selected = null; window.latestScroll = null; window.previousSelectedMethod = null; var BillmateIframe = new function(){ var self = this; var childWindow = null; this.updatePsCheckout = function(){ // When address in checkout updates; var data = {}; data['action'] = 'updateCheckout'; data['ajax'] = 1; jQuery.ajax({ url : billmate_checkout_url, data: data, type: 'POST', success: function(response){ var result = JSON.parse(response); if (result.success) { if(result.hasOwnProperty("update_checkout") && result.update_checkout === true) self.updateCheckout(); }else { location.reload(); } } }); } this.updateAddress = function (data) { // When address in checkout updates; data['action'] = 'setAddress'; data['ajax'] = 1; jQuery.ajax({ url : billmate_checkout_url, data: data, type: 'POST', success: function(response){ var result = JSON.parse(response); if(result.success) { jQuery('#shippingdiv').html(result.carrier_block); } window.address_selected = true; } }); }; this.updateShippingMethod = function(method){ jQuery.ajax({ url: UPDATE_SHIPPING_METHOD_URL, data: {'shipping_method': method}, type: 'POST', success: function (response) { var result = JSON.parse(response); if (result.success) { if(result.hasOwnProperty("update_checkout") && result.update_checkout === true) self.updateCheckout(); if(data.method == 8 || data.method == 16) self.updateCheckout(); window.method = data.method; } } }); } this.updatePaymentMethod = function(data){ if(window.method != data.method) { data['action'] = 'setPaymentMethod'; data['ajax'] = 1; jQuery.ajax({ url: billmate_checkout_url, data: data, type: 'POST', success: function (response) { var result = JSON.parse(response); if (result.success) { if(result.hasOwnProperty("update_checkout") && result.update_checkout === true) self.updateCheckout(); if(data.method == 8 || data.method == 16) self.updateCheckout(); window.method = data.method; } } }); } }; this.updateShippingMethod = function(){ } this.createOrder = function(data){ // Create Order data['action'] = 'validateOrder'; data['ajax'] = 1; jQuery.ajax({ url : billmate_checkout_url, data: data, type: 'POST', success: function(response){ var result = JSON.parse(response); if(result.success){ location.href=result.redirect; } } }); }; this.initListeners = function () { jQuery(document).ready(function(){ console.log('initEventListeners'); window.addEventListener("message",self.handleEvent); }); } this.handleEvent = function(event){ console.log(event); if(event.origin == "https://checkout.billmate.se") { try { var json = JSON.parse(event.data); } catch (e) { return; } self.childWindow = json.source; console.log(json); switch (json.event) { case 'address_selected': self.updateAddress(json.data); self.updatePaymentMethod(json.data); if(window.method == null || window.method == json.data.method) { jQuery('#checkoutdiv').removeClass('loading'); } break; case 'payment_method_selected': if (window.address_selected !== null) { self.updatePaymentMethod(json.data); if(window.method == json.data.method) { jQuery('#checkoutdiv').removeClass('loading'); } } break; case 'checkout_success': self.createOrder(json.data); break; case 'content_height': $('checkout').height = json.data; break; case 'content_scroll_position': console.log('Scroll position'+json.data); window.latestScroll = jQuery(document).find( "#checkout" ).offset().top + json.data; jQuery('html, body').animate({scrollTop: jQuery(document).find( "#checkout" ).offset().top + json.data}, 400); break; case 'checkout_loaded': jQuery('#checkoutdiv').removeClass('loading'); break; default: console.log(event); console.log('not implemented') break; } } }; this.updateCheckout = function(){ console.log('update_checkout'); var win = document.getElementById('checkout').contentWindow; win.postMessage(JSON.stringify({event: 'update_checkout'}),'*') } }; window.b_iframe = BillmateIframe; window.b_iframe.initListeners(); window.tmpshippingvalue = $('#total_shipping').html(); var BillmateCart = new function () { this.updateProduct = function(type,id,qty){ var self = this; var val = $('input[name=quantity_'+id+']').val(); console.log(val); console.log(qty); var newQty = val; var action = ''; if(type == 'sub') { if (typeof(qty) === 'undefined' || !qty) { qty = 1; newQty = val - 1; action = '&op=down'; } else if (qty < 0) qty = -qty; } else { if (typeof(qty) === 'undefined' || !qty) { qty = 1; } } console.log(qty); console.log(newQty); var customizationId = 0; var productId = 0; var productAttributeId = 0; var id_address_delivery = 0; var ids = 0; ids = id.split('_'); productId = parseInt(ids[0]); if (typeof(ids[1]) !== 'undefined') productAttributeId = parseInt(ids[1]); if (typeof(ids[2]) !== 'undefined') customizationId = parseInt(ids[2]); if (typeof(ids[3]) !== 'undefined') id_address_delivery = parseInt(ids[3]); if (newQty > 0 || $('#product_'+id+'_gift').length) { $.ajax({ type: 'GET', url: baseUri, async: true, cache: false, dataType: 'json', data: 'controller=cart' +'&ajax=true' +'&add' +'&getproductprice' +'&summary' +'&id_product='+productId +'&ipa='+productAttributeId +'&id_address_delivery='+id_address_delivery +action + ((customizationId !== 0) ? '&id_customization='+customizationId : '') +'&qty='+qty +'&token='+static_token +'&allow_refresh=1', success: function(jsonData) { if (jsonData.hasError) { var errors = ''; for(var error in jsonData.errors) if(error !== 'indexOf') errors += jsonData.errors[error] + "\n"; alert(errors); $('input[name=quantity_'+ id +']').val($('input[name=quantity_'+ id +'_hidden]').val()); } else { if (jsonData.refresh) location.reload(); self.updateCart(jsonData.summary); self.updateHookShoppingCart(jsonData.HOOK_SHOPPING_CART); self.updateHookShoppingCartExtra(jsonData.HOOK_SHOPPING_CART_EXTRA); if (newQty === 0) $('#product_'+id).hide(); if (typeof(getCarrierListAndUpdate) !== 'undefined') getCarrierListAndUpdate(); } }, error: function(XMLHttpRequest, textStatus, errorThrown) { if (textStatus !== 'abort') alert("TECHNICAL ERROR: unable to save update quantity \n\nDetails:\nError thrown: " + XMLHttpRequest + "\n" + 'Text status: ' + textStatus); } }); } else { self.deleteProductFromSummary(id); } }; this.deleteProductFromSummary = function(id){ var self = this; var customizationId = 0; var productId = 0; var productAttributeId = 0; var id_address_delivery = 0; var ids = id.split('_'); productId = parseInt(ids[0]); if (typeof(ids[1]) !== 'undefined') productAttributeId = parseInt(ids[1]); if (typeof(ids[2]) !== 'undefined') customizationId = parseInt(ids[2]); if (typeof(ids[3]) !== 'undefined') id_address_delivery = parseInt(ids[3]); $.ajax({ type: 'GET', url: baseUri, async: true, cache: false, dataType: 'json', data: 'controller=cart' +'&ajax=true&delete&summary' +'&id_product='+productId +'&ipa='+productAttributeId +'&id_address_delivery='+id_address_delivery+ ( (customizationId !== 0) ? '&id_customization='+customizationId : '') +'&token=' + static_token +'&allow_refresh=1', success: function(jsonData) { if (jsonData.hasError) { var errors = ''; for(var error in jsonData.errors) //IE6 bug fix if (error !== 'indexOf') errors += jsonData.errors[error] + "\n"; } else { if (jsonData.refresh) location.reload(); if (parseInt(jsonData.summary.products.length) === 0) { if (typeof(orderProcess) === 'undefined' || orderProcess !== 'order-opc') document.location.href = document.location.href; // redirection else { $('#center_column').children().each(function() { if ($(this).attr('id') !== 'emptyCartWarning' && $(this).attr('class') !== 'breadcrumb' && $(this).attr('id') !== 'cart_title') { $(this).fadeOut('slow', function () { $(this).remove(); }); } }); $('#summary_products_label').remove(); $('#emptyCartWarning').fadeIn('slow'); } } else { $('#product_'+ id).fadeOut('slow', function() { $(this).remove(); if (!customizationId) self.refreshOddRow(); }); var exist = false; $.each(jsonData.summary.products,function(i,value){ if(value.id_product === productId && value.id_product_attribute === productAttributeId && value.id_address.delivery == id_address_delivery) exist = true; }) // if all customization removed => delete product line if (!exist && customizationId) { $('#product_' + productId + '_' + productAttributeId + '_0_' + id_address_delivery).fadeOut('slow', function() { $(this).remove(); self.refreshOddRow(); }); } } self.updateCart(jsonData.summary); //updateCustomizedDatas(jsonData.customizedDatas); self.updateHookShoppingCart(jsonData.HOOK_SHOPPING_CART); self.updateHookShoppingCartExtra(jsonData.HOOK_SHOPPING_CART_EXTRA); if (typeof(getCarrierListAndUpdate) !== 'undefined') getCarrierListAndUpdate(); } }, error: function(XMLHttpRequest, textStatus, errorThrown) { if (textStatus !== 'abort') alert("TECHNICAL ERROR: unable to save update quantity \n\nDetails:\nError thrown: " + XMLHttpRequest + "\n" + 'Text status: ' + textStatus); } }); }; this.updateCart = function(json) { var i; var nbrProducts = 0; if (typeof json === 'undefined') return; $('.cart_quantity_input').val(0); product_list = {}; for (i=0;i<json.products.length;i++) product_list[json.products[i].id_product+'_'+json.products[i].id_product_attribute+'_'+json.products[i].id_address_delivery] = json.products[i]; if (!$('.multishipping-cart:visible').length) { for (i=0;i<json.gift_products.length;i++) { if (typeof(product_list[json.gift_products[i].id_product+'_'+json.gift_products[i].id_product_attribute+'_'+json.gift_products[i].id_address_delivery]) !== 'undefined') product_list[json.gift_products[i].id_product+'_'+json.gift_products[i].id_product_attribute+'_'+json.gift_products[i].id_address_delivery].quantity -= json.gift_products[i].cart_quantity; } } else { for (i=0;i<json.gift_products.length;i++) { if (typeof(product_list[json.gift_products[i].id_product+'_'+json.gift_products[i].id_product_attribute+'_'+json.gift_products[i].id_address_delivery]) === 'undefined') product_list[json.gift_products[i].id_product+'_'+json.gift_products[i].id_product_attribute+'_'+json.gift_products[i].id_address_delivery] = json.gift_products[i]; } } for (i in product_list) { // if reduction, we need to show it in the cart by showing the initial price above the current one var reduction = product_list[i].reduction_applies; var reduction_type = product_list[i].reduction_type; var reduction_symbol = ''; var initial_price_text = ''; var initial_price = ''; if (typeof(product_list[i].price_without_quantity_discount) !== 'undefined') initial_price = formatCurrency(product_list[i].price_without_quantity_discount, currencyFormat, currencySign, currencyBlank); var current_price = ''; var product_total = ''; var product_customization_total = ''; if (priceDisplayMethod !== 0) { current_price = formatCurrency(product_list[i].price, currencyFormat, currencySign, currencyBlank); product_total = product_list[i].total; product_customization_total = product_list[i].total_customization; } else { current_price = formatCurrency(product_list[i].price_wt, currencyFormat, currencySign, currencyBlank); product_total = product_list[i].total_wt; product_customization_total = product_list[i].total_customization_wt; } var current_price_class ='price'; var price_reduction = ''; if (reduction && typeof(initial_price) !== 'undefined') { if (reduction_type == 'amount') price_reduction = product_list[i].reduction_formatted; else { var display_price = 0; if (priceDisplayMethod !== 0) display_price = product_list[i].price; else display_price = product_list[i].price_wt; price_reduction = ps_round((product_list[i].price_without_quantity_discount - display_price)/product_list[i].price_without_quantity_discount * -100); reduction_symbol = '%'; } if (initial_price !== '' && product_list[i].price_without_quantity_discount > product_list[i].price) { initial_price_text = '<li class="price-percent-reduction small">&nbsp;'+price_reduction+reduction_symbol+'&nbsp;</li><li class="old-price">' + initial_price + '</li>'; current_price_class += ' special-price'; } } var key_for_blockcart = product_list[i].id_product + '_' + product_list[i].id_product_attribute + '_' + product_list[i].id_address_delivery; var key_for_blockcart_nocustom = product_list[i].id_product + '_' + product_list[i].id_product_attribute + '_' + ((product_list[i].id_customization && product_list[i].quantity_without_customization != product_list[i].quantity)? 'nocustom' : '0') + '_' + product_list[i].id_address_delivery; $('#product_price_' + key_for_blockcart).html('<li class="' + current_price_class + '">' + current_price + '</li>' + initial_price_text); if (typeof(product_list[i].customizationQuantityTotal) !== 'undefined' && product_list[i].customizationQuantityTotal > 0) $('#total_product_price_' + key_for_blockcart).html(formatCurrency(product_customization_total, currencyFormat, currencySign, currencyBlank)); else $('#total_product_price_' + key_for_blockcart).html(formatCurrency(product_total, currencyFormat, currencySign, currencyBlank)); if (product_list[i].quantity_without_customization != product_list[i].quantity) $('#total_product_price_' + key_for_blockcart_nocustom).html(formatCurrency(product_total, currencyFormat, currencySign, currencyBlank)); $('input[name=quantity_' + key_for_blockcart_nocustom + ']').val(product_list[i].id_customization? product_list[i].quantity_without_customization : product_list[i].cart_quantity); $('input[name=quantity_' + key_for_blockcart_nocustom + '_hidden]').val(product_list[i].id_customization? product_list[i].quantity_without_customization : product_list[i].cart_quantity); if (typeof(product_list[i].customizationQuantityTotal) !== 'undefined' && product_list[i].customizationQuantityTotal > 0) $('#cart_quantity_custom_' + key_for_blockcart).html(product_list[i].customizationQuantityTotal); nbrProducts += parseInt(product_list[i].quantity); } // Update discounts if (json.discounts.length === 0) { $('.cart_discount').each(function(){$(this).remove();}); $('.cart_total_voucher').remove(); } else { if ($('.cart_discount').length === 0) location.reload(); if (priceDisplayMethod !== 0) $('#total_discount').html(formatCurrency(json.total_discounts_tax_exc, currencyFormat, currencySign, currencyBlank)); else $('#total_discount').html(formatCurrency(json.total_discounts, currencyFormat, currencySign, currencyBlank)); $('.cart_discount').each(function(){ var idElmt = $(this).attr('id').replace('cart_discount_',''); var toDelete = true; for (i=0;i<json.discounts.length;i++) { if (json.discounts[i].id_discount === idElmt) { if (json.discounts[i].value_real !== '!') { if (priceDisplayMethod !== 0) $('#cart_discount_' + idElmt + ' td.cart_discount_price span.price-discount').html(formatCurrency(json.discounts[i].value_tax_exc * -1, currencyFormat, currencySign, currencyBlank)); else $('#cart_discount_' + idElmt + ' td.cart_discount_price span.price-discount').html(formatCurrency(json.discounts[i].value_real * -1, currencyFormat, currencySign, currencyBlank)); } toDelete = false; } } if (toDelete) $('#cart_discount_' + idElmt + ', #cart_total_voucher').fadeTo('fast', 0, function(){ $(this).remove(); }); }); } // Block cart if (priceDisplayMethod !== 0) { $('#cart_block_shipping_cost').html(formatCurrency(json.total_shipping_tax_exc, currencyFormat, currencySign, currencyBlank)); $('#cart_block_wrapping_cost').html(formatCurrency(json.total_wrapping_tax_exc, currencyFormat, currencySign, currencyBlank)); $('#cart_block_total').html(formatCurrency(json.total_price_without_tax, currencyFormat, currencySign, currencyBlank)); } else { $('#cart_block_shipping_cost').html(formatCurrency(json.total_shipping, currencyFormat, currencySign, currencyBlank)); $('#cart_block_wrapping_cost').html(formatCurrency(json.total_wrapping, currencyFormat, currencySign, currencyBlank)); $('#cart_block_total').html(formatCurrency(json.total_price, currencyFormat, currencySign, currencyBlank)); } $('#cart_block_tax_cost').html(formatCurrency(json.total_tax, currencyFormat, currencySign, currencyBlank)); $('.ajax_cart_quantity').html(nbrProducts); // Cart summary $('#summary_products_quantity').html(nbrProducts+' '+(nbrProducts > 1 ? txtProducts : txtProduct)); if (priceDisplayMethod !== 0) { $('#total_product').html(formatCurrency(json.total_products, currencyFormat, currencySign, currencyBlank)); } else { $('#total_product').html(formatCurrency(json.total_products_wt, currencyFormat, currencySign, currencyBlank)); } $('#total_price').html(formatCurrency(json.total_price, currencyFormat, currencySign, currencyBlank)); $('#total_price_without_tax').html(formatCurrency(json.total_price_without_tax, currencyFormat, currencySign, currencyBlank)); $('#total_tax').html(formatCurrency(json.total_tax, currencyFormat, currencySign, currencyBlank)); if (json.total_shipping > 0) { if (priceDisplayMethod !== 0) { $('#total_shipping').html(formatCurrency(json.total_shipping_tax_exc, currencyFormat, currencySign, currencyBlank)); } else { $('#total_shipping').html(formatCurrency(json.total_shipping, currencyFormat, currencySign, currencyBlank)); } } else { $('#total_shipping').html(freeShippingTranslation); } if($('#total_shipping').html() != window.tmpshippingvalue) { //force page reload location.href = billmate_checkout_url; } else { window.tmpshippingvalue = $('#total_shipping').html(); } if (json.total_wrapping > 0) { $('#total_wrapping').html(formatCurrency(json.total_wrapping, currencyFormat, currencySign, currencyBlank)); $('#total_wrapping').parent().show(); } else { $('#total_wrapping').html(formatCurrency(json.total_wrapping, currencyFormat, currencySign, currencyBlank)); $('#total_wrapping').parent().hide(); } if (window.ajaxCart !== undefined) ajaxCart.refresh(); window.b_iframe.updatePsCheckout(); }; this.refreshOddRow = function() { var odd_class = 'odd'; var even_class = 'even'; $.each($('.cart_item'), function(i, it) { if (i === 0) { if ($(this).hasClass('even')) { odd_class = 'even'; even_class = 'odd'; } $(this).addClass('first_item'); } if(i % 2) $(this).removeClass(odd_class).addClass(even_class); else $(this).removeClass(even_class).addClass(odd_class); }); $('.cart_item:last-child, .customization:last-child').addClass('last_item'); } this.updateHookShoppingCart = function(html) { $('#HOOK_SHOPPING_CART').html(html); }; this.updateHookShoppingCartExtra = function(html) { $('#HOOK_SHOPPING_CART_EXTRA').html(html); } }; window.b_cart = BillmateCart; jQuery(document).ready(function(){ jQuery(document).ajaxStart(function(){ jQuery('#checkoutdiv').addClass('loading'); jQuery("#checkoutdiv.loading .billmateoverlay").height(jQuery("#checkoutdiv").height()); }) jQuery(document).ajaxComplete(function(){ jQuery('#checkoutdiv').removeClass('loading'); }) $("#button_order_cart").attr("href", billmate_checkout_url); $("#layer_cart .layer_cart_cart a.button-medium").attr("href", billmate_checkout_url); $("#order p.cart_navigation a.standard-checkout").attr("href", billmate_checkout_url); $('.cart-summary .checkout .btn').attr("href", billmate_checkout_url); $('.cart-content-btn .btn').attr("href", billmate_checkout_url); $("#billmate_summary a.cart_quantity_delete").unbind('click').live('click', function(){ window.b_cart.deleteProductFromSummary($(this).attr('id')); return false; }); $("#billmate_summary a.cart_quantity_up").unbind('click').live('click', function(){ window.b_cart.updateProduct('add',$(this).attr('id').replace('cart_quantity_up_', '')); return false; }); $("#billmate_summary a.cart_quantity_down").unbind('click').live('click', function(){ window.b_cart.updateProduct('sub',$(this).attr('id').replace('cart_quantity_down_', '')); return false; }); if(window.location.href == billmate_checkout_url) { $('body').attr('id', 'order'); } $('body').on('click','.delivery-option input[type="radio"]',function(e){ e.preventDefault(); var selectedMethod = e.target.value; if(selectedMethod != window.previousSelectedMethod){ window.previousSelectedMethod = selectedMethod; var url = billmate_checkout_url var delivery_option = $('.delivery-option input[type="radio"]').val(); var address_id = $('.delivery_option_radio:checked').data('id_address'); var values = {}; values['delivery_option['+address_id+']'] = delivery_option; values['action'] = 'setShipping'; values['ajax'] = 1 jQuery.ajax({ url: url, data: values, success: function(response){ var result = JSON.parse(response); console.log(result); if(result.hasOwnProperty("update_checkout") && result.update_checkout === true){ window.b_iframe.updateCheckout(); } } }) } }) $('body').on('click','.delivery_option_radio',function(e){ e.preventDefault(); var selectedMethod = e.target.value; if(selectedMethod != window.previousSelectedMethod){ window.previousSelectedMethod = selectedMethod; var url = billmate_checkout_url var delivery_option = $('.delivery_option_radio:checked').val(); var address_id = $('.delivery_option_radio:checked').data('id_address'); var values = {}; values['delivery_option['+address_id+']'] = delivery_option; values['action'] = 'setShipping'; values['ajax'] = 1 jQuery.ajax({ url: url, data: values, success: function(response){ var result = JSON.parse(response); console.log(result); if(result.hasOwnProperty("update_checkout") && result.update_checkout === true){ window.b_iframe.updateCheckout(); } } }) } }) }); function deleteProductFromSummary(id){ console.log('product removed'); window.b_iframe.updatePsCheckout(); }
jQuery fixes to check if element exists.
billmatecheckout/views/js/checkout.js
jQuery fixes to check if element exists.
<ide><path>illmatecheckout/views/js/checkout.js <ide> <ide> $('.cart-summary .checkout .btn').attr("href", billmate_checkout_url); <ide> $('.cart-content-btn .btn').attr("href", billmate_checkout_url); <del> <del> $("#billmate_summary a.cart_quantity_delete").unbind('click').live('click', function(){ window.b_cart.deleteProductFromSummary($(this).attr('id')); return false; }); <del> $("#billmate_summary a.cart_quantity_up").unbind('click').live('click', function(){ window.b_cart.updateProduct('add',$(this).attr('id').replace('cart_quantity_up_', '')); return false; }); <del> $("#billmate_summary a.cart_quantity_down").unbind('click').live('click', function(){ window.b_cart.updateProduct('sub',$(this).attr('id').replace('cart_quantity_down_', '')); return false; }); <del> <add> if( $("#billmate_summary a.cart_quantity_delete").length) { <add> $("#billmate_summary a.cart_quantity_delete").unbind('click').live('click', function () { <add> window.b_cart.deleteProductFromSummary($(this).attr('id')); <add> return false; <add> }); <add> } <add> if($("#billmate_summary a.cart_quantity_up").length) { <add> $("#billmate_summary a.cart_quantity_up").unbind('click').live('click', function () { <add> window.b_cart.updateProduct('add', $(this).attr('id').replace('cart_quantity_up_', '')); <add> return false; <add> }); <add> } <add> if($("#billmate_summary a.cart_quantity_down").length) { <add> $("#billmate_summary a.cart_quantity_down").unbind('click').live('click', function () { <add> window.b_cart.updateProduct('sub', $(this).attr('id').replace('cart_quantity_down_', '')); <add> return false; <add> }); <add> } <ide> if(window.location.href == billmate_checkout_url) { <ide> $('body').attr('id', 'order'); <ide> } <ide> if(selectedMethod != window.previousSelectedMethod){ <ide> window.previousSelectedMethod = selectedMethod; <ide> var url = billmate_checkout_url <del> var delivery_option = $('.delivery-option input[type="radio"]').val(); <add> var delivery_option = $('.delivery-option input[type="radio"]:checked').val(); <add> var name = $('.delivery-option input[type="radio"]:checked').attr('name'); <ide> var address_id = $('.delivery_option_radio:checked').data('id_address'); <ide> var values = {}; <del> values['delivery_option['+address_id+']'] = delivery_option; <add> values[name] = delivery_option; <ide> values['action'] = 'setShipping'; <ide> values['ajax'] = 1 <ide> jQuery.ajax({
Java
apache-2.0
d04cd80bc8f6fbcbd3399223e2d0d846e6e0dabb
0
OpenHFT/Chronicle-Bytes
/* * Copyright 2014 Higher Frequency Trading http://www.higherfrequencytrading.com * * 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 net.openhft.chronicle.bytes; import net.openhft.chronicle.core.Maths; public interface WriteAccess<T> extends AccessCommon<T> { default void writeByte(T handle, long offset, int i) { writeByte(handle, offset, Maths.toInt8(i)); } default void writeUnsignedByte(T handle, long offset, int i) { writeByte(handle, offset, (byte) Maths.toUInt8(i)); } default void writeBoolean(T handle, long offset, boolean flag) { writeByte(handle, offset, flag ? 'Y' : 0); } default void writeUnsignedShort(T handle, long offset, int i) { writeShort(handle, offset, (short) Maths.toUInt16(i)); } default void writeChar(T handle, long offset, char c) { writeShort(handle, offset, (short) c); } default void writeUnsignedInt(T handle, long offset, long i) { writeInt(handle, offset, (int) Maths.toUInt32(i)); } void writeByte(T handle, long offset, byte i8); void writeShort(T handle, long offset, short i); void writeInt(T handle, long offset, int i); /** * Default implementation: throws {@code UnsupportedOperationException}. */ default void writeOrderedInt(T handle, long offset, int i) { throw new UnsupportedOperationException(); } void writeLong(T handle, long offset, long i); /** * Default implementation: throws {@code UnsupportedOperationException}. */ default void writeOrderedLong(T handle, long offset, long i) { throw new UnsupportedOperationException(); } void writeFloat(T handle, long offset, float d); void writeDouble(T handle, long offset, double d); default <S> void writeFrom( T handle, long offset, ReadAccess<S> sourceAccess, S source, long sourceOffset, long len) { long i = 0; while (len - i >= 8L) { writeLong(handle, offset + i, sourceAccess.readLong(source, sourceOffset + i)); i += 8L; } if (len - i >= 4L) { writeInt(handle, offset + i, sourceAccess.readInt(source, sourceOffset + i)); i += 4L; } if (len - i >= 2L) { writeShort(handle, offset + i, sourceAccess.readShort(source, sourceOffset + i)); i += 2L; } if (i < len) writeByte(handle, offset + i, sourceAccess.readByte(source, sourceOffset + i)); } default void writeBytes(T handle, long offset, long len, byte b) { char c; int i; long l; switch (b) { case 0: c = 0; i = 0; l = 0; break; case -1: c = Character.MAX_VALUE; i = -1; l = -1; break; default: int ub = b & 0xFF; int ic = ub | (ub << 8); c = (char) ic; i = ic | (ic << 16); long ui = i & 0xFFFFFFFFL; l = ui | (ui << 32); } long index = 0; while (len - index >= 8L) { writeLong(handle, offset + index, l); index += 8L; } if (len - index >= 4L) { writeInt(handle, offset + index, i); index += 4L; } if (len - index >= 2L) { writeChar(handle, offset + index, c); index += 2L; } if (index < len) writeByte(handle, offset + index, b); } }
src/main/java/net/openhft/chronicle/bytes/WriteAccess.java
/* * Copyright 2014 Higher Frequency Trading http://www.higherfrequencytrading.com * * 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 net.openhft.chronicle.bytes; import net.openhft.chronicle.core.Maths; public interface WriteAccess<T> extends AccessCommon<T> { default void writeByte(T handle, long offset, int i) { writeByte(handle, offset, Maths.toInt8(i)); } default void writeUnsignedByte(T handle, long offset, int i) { writeByte(handle, offset, (byte) Maths.toUInt8(i)); } default void writeBoolean(T handle, long offset, boolean flag) { writeByte(handle, offset, flag ? 'Y' : 0); } default void writeUnsignedShort(T handle, long offset, int i) { writeShort(handle, offset, (short) Maths.toUInt16(i)); } default void writeChar(T handle, long offset, char c) { writeShort(handle, offset, (short) c); } default void writeUnsignedInt(T handle, long offset, long i) { writeInt(handle, offset, (int) Maths.toUInt32(i)); } void writeByte(T handle, long offset, byte i8); void writeShort(T handle, long offset, short i); void writeInt(T handle, long offset, int i); /** * Default implementation: throws {@code UnsupportedOperationException}. */ default void writeOrderedInt(T handle, long offset, int i) { throw new UnsupportedOperationException(); } void writeLong(T handle, long offset, long i); /** * Default implementation: throws {@code UnsupportedOperationException}. */ default void writeOrderedLong(T handle, long offset, long i) { throw new UnsupportedOperationException(); } void writeFloat(T handle, long offset, float d); void writeDouble(T handle, long offset, double d); default <S> void writeFrom( T handle, long offset, ReadAccess<S> sourceAccess, S source, long sourceOffset, long len) { long i = 0; while (len - i >= 8L) { writeLong(handle, offset + i, sourceAccess.readLong(source, sourceOffset + i)); i += 8L; } if (len - i >= 4L) { writeInt(handle, offset + i, sourceAccess.readInt(source, sourceOffset + i)); i += 4L; } if (len - i >= 2L) { writeShort(handle, offset + i, sourceAccess.readShort(source, sourceOffset + i)); i += 2L; } if (i < len) writeByte(handle, offset + i, sourceAccess.readByte(source, sourceOffset + i)); } default void writeBytes(T handle, long offset, long len, byte b) { int ic; char c; int i; long l; switch (b) { case 0: c = 0; i = 0; l = 0; break; case -1: c = Character.MAX_VALUE; i = -1; l = -1; break; default: ic = b | ((b & 0xFF) << 8); c = (char) ic; i = ic | (ic << 16); l = i | ((i & 0xFFFFFFFFL) << 32); } long index = 0; while (len - index >= 8L) { writeLong(handle, offset + index, l); index += 8L; } if (len - index >= 4L) { writeInt(handle, offset + index, i); index += 4L; } if (len - index >= 2L) { writeChar(handle, offset + index, c); index += 2L; } if (index < len) writeByte(handle, offset + index, b); } }
Fixed bug in WriteAccess.writeBytes()
src/main/java/net/openhft/chronicle/bytes/WriteAccess.java
Fixed bug in WriteAccess.writeBytes()
<ide><path>rc/main/java/net/openhft/chronicle/bytes/WriteAccess.java <ide> } <ide> <ide> default void writeBytes(T handle, long offset, long len, byte b) { <del> int ic; <ide> char c; <ide> int i; <ide> long l; <ide> l = -1; <ide> break; <ide> default: <del> ic = b | ((b & 0xFF) << 8); <add> int ub = b & 0xFF; <add> int ic = ub | (ub << 8); <ide> c = (char) ic; <ide> i = ic | (ic << 16); <del> l = i | ((i & 0xFFFFFFFFL) << 32); <add> long ui = i & 0xFFFFFFFFL; <add> l = ui | (ui << 32); <ide> } <ide> long index = 0; <ide> while (len - index >= 8L) {
Java
apache-2.0
af88dd7104df38bab4d4d985c90f09c5c9e38f68
0
jagguli/intellij-community,nicolargo/intellij-community,diorcety/intellij-community,caot/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,kool79/intellij-community,vladmm/intellij-community,tmpgit/intellij-community,supersven/intellij-community,fengbaicanhe/intellij-community,muntasirsyed/intellij-community,gnuhub/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,vladmm/intellij-community,robovm/robovm-studio,supersven/intellij-community,amith01994/intellij-community,asedunov/intellij-community,fitermay/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,consulo/consulo,asedunov/intellij-community,slisson/intellij-community,ibinti/intellij-community,xfournet/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,kool79/intellij-community,blademainer/intellij-community,blademainer/intellij-community,salguarnieri/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,Lekanich/intellij-community,MichaelNedzelsky/intellij-community,nicolargo/intellij-community,vladmm/intellij-community,fnouama/intellij-community,MichaelNedzelsky/intellij-community,vladmm/intellij-community,kool79/intellij-community,samthor/intellij-community,signed/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,supersven/intellij-community,fengbaicanhe/intellij-community,slisson/intellij-community,hurricup/intellij-community,adedayo/intellij-community,blademainer/intellij-community,semonte/intellij-community,supersven/intellij-community,Distrotech/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,ftomassetti/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,MER-GROUP/intellij-community,Lekanich/intellij-community,akosyakov/intellij-community,holmes/intellij-community,fengbaicanhe/intellij-community,kdwink/intellij-community,TangHao1987/intellij-community,dslomov/intellij-community,pwoodworth/intellij-community,akosyakov/intellij-community,robovm/robovm-studio,fitermay/intellij-community,akosyakov/intellij-community,holmes/intellij-community,fitermay/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,vladmm/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,caot/intellij-community,fitermay/intellij-community,diorcety/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,semonte/intellij-community,fitermay/intellij-community,supersven/intellij-community,apixandru/intellij-community,izonder/intellij-community,nicolargo/intellij-community,orekyuu/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,dslomov/intellij-community,dslomov/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,kool79/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,clumsy/intellij-community,caot/intellij-community,ernestp/consulo,allotria/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,izonder/intellij-community,orekyuu/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,Distrotech/intellij-community,supersven/intellij-community,clumsy/intellij-community,apixandru/intellij-community,SerCeMan/intellij-community,wreckJ/intellij-community,joewalnes/idea-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,robovm/robovm-studio,fnouama/intellij-community,xfournet/intellij-community,alphafoobar/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,izonder/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,orekyuu/intellij-community,petteyg/intellij-community,tmpgit/intellij-community,pwoodworth/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,FHannes/intellij-community,Distrotech/intellij-community,retomerz/intellij-community,joewalnes/idea-community,samthor/intellij-community,retomerz/intellij-community,xfournet/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,ol-loginov/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,samthor/intellij-community,xfournet/intellij-community,retomerz/intellij-community,alphafoobar/intellij-community,samthor/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,Lekanich/intellij-community,semonte/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,slisson/intellij-community,da1z/intellij-community,signed/intellij-community,da1z/intellij-community,samthor/intellij-community,ol-loginov/intellij-community,semonte/intellij-community,ivan-fedorov/intellij-community,Distrotech/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,asedunov/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,diorcety/intellij-community,holmes/intellij-community,ryano144/intellij-community,FHannes/intellij-community,semonte/intellij-community,kdwink/intellij-community,fengbaicanhe/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,SerCeMan/intellij-community,da1z/intellij-community,fitermay/intellij-community,amith01994/intellij-community,robovm/robovm-studio,ivan-fedorov/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,clumsy/intellij-community,ol-loginov/intellij-community,ahb0327/intellij-community,signed/intellij-community,da1z/intellij-community,blademainer/intellij-community,da1z/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,joewalnes/idea-community,youdonghai/intellij-community,joewalnes/idea-community,jexp/idea2,samthor/intellij-community,adedayo/intellij-community,idea4bsd/idea4bsd,kdwink/intellij-community,ibinti/intellij-community,supersven/intellij-community,tmpgit/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,vladmm/intellij-community,da1z/intellij-community,gnuhub/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,clumsy/intellij-community,TangHao1987/intellij-community,da1z/intellij-community,ibinti/intellij-community,gnuhub/intellij-community,ryano144/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,SerCeMan/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,SerCeMan/intellij-community,caot/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,Distrotech/intellij-community,gnuhub/intellij-community,Distrotech/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,jexp/idea2,michaelgallacher/intellij-community,petteyg/intellij-community,caot/intellij-community,orekyuu/intellij-community,samthor/intellij-community,fnouama/intellij-community,vladmm/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,robovm/robovm-studio,signed/intellij-community,dslomov/intellij-community,fnouama/intellij-community,Distrotech/intellij-community,petteyg/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,izonder/intellij-community,supersven/intellij-community,kdwink/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,joewalnes/idea-community,diorcety/intellij-community,youdonghai/intellij-community,diorcety/intellij-community,Lekanich/intellij-community,hurricup/intellij-community,kool79/intellij-community,ahb0327/intellij-community,ftomassetti/intellij-community,gnuhub/intellij-community,fengbaicanhe/intellij-community,nicolargo/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,MER-GROUP/intellij-community,ThiagoGarciaAlves/intellij-community,ryano144/intellij-community,consulo/consulo,ahb0327/intellij-community,petteyg/intellij-community,ol-loginov/intellij-community,semonte/intellij-community,ryano144/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,fitermay/intellij-community,xfournet/intellij-community,fengbaicanhe/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,tmpgit/intellij-community,samthor/intellij-community,supersven/intellij-community,ivan-fedorov/intellij-community,TangHao1987/intellij-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,caot/intellij-community,tmpgit/intellij-community,pwoodworth/intellij-community,youdonghai/intellij-community,Lekanich/intellij-community,semonte/intellij-community,Distrotech/intellij-community,slisson/intellij-community,izonder/intellij-community,michaelgallacher/intellij-community,nicolargo/intellij-community,muntasirsyed/intellij-community,dslomov/intellij-community,dslomov/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,Distrotech/intellij-community,nicolargo/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,akosyakov/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,consulo/consulo,suncycheng/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,orekyuu/intellij-community,tmpgit/intellij-community,blademainer/intellij-community,amith01994/intellij-community,tmpgit/intellij-community,kool79/intellij-community,petteyg/intellij-community,akosyakov/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,vladmm/intellij-community,amith01994/intellij-community,adedayo/intellij-community,ernestp/consulo,fnouama/intellij-community,joewalnes/idea-community,TangHao1987/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,kool79/intellij-community,kdwink/intellij-community,izonder/intellij-community,suncycheng/intellij-community,ernestp/consulo,FHannes/intellij-community,allotria/intellij-community,vladmm/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,akosyakov/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,ivan-fedorov/intellij-community,ol-loginov/intellij-community,apixandru/intellij-community,apixandru/intellij-community,allotria/intellij-community,apixandru/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,hurricup/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,asedunov/intellij-community,ftomassetti/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,Distrotech/intellij-community,izonder/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,clumsy/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community,ryano144/intellij-community,signed/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,retomerz/intellij-community,caot/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,robovm/robovm-studio,samthor/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,signed/intellij-community,muntasirsyed/intellij-community,ahb0327/intellij-community,MER-GROUP/intellij-community,alphafoobar/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,fnouama/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,holmes/intellij-community,kdwink/intellij-community,alphafoobar/intellij-community,jagguli/intellij-community,izonder/intellij-community,amith01994/intellij-community,jexp/idea2,muntasirsyed/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,MichaelNedzelsky/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,kool79/intellij-community,hurricup/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,pwoodworth/intellij-community,semonte/intellij-community,samthor/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,slisson/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,akosyakov/intellij-community,jexp/idea2,fengbaicanhe/intellij-community,akosyakov/intellij-community,MichaelNedzelsky/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,hurricup/intellij-community,akosyakov/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,MichaelNedzelsky/intellij-community,kdwink/intellij-community,hurricup/intellij-community,allotria/intellij-community,jagguli/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,izonder/intellij-community,jagguli/intellij-community,supersven/intellij-community,MichaelNedzelsky/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,wreckJ/intellij-community,SerCeMan/intellij-community,jagguli/intellij-community,TangHao1987/intellij-community,ol-loginov/intellij-community,holmes/intellij-community,diorcety/intellij-community,Lekanich/intellij-community,ibinti/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,joewalnes/idea-community,petteyg/intellij-community,signed/intellij-community,youdonghai/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community,amith01994/intellij-community,apixandru/intellij-community,diorcety/intellij-community,pwoodworth/intellij-community,clumsy/intellij-community,adedayo/intellij-community,joewalnes/idea-community,michaelgallacher/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,fengbaicanhe/intellij-community,ahb0327/intellij-community,ivan-fedorov/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,ftomassetti/intellij-community,Lekanich/intellij-community,retomerz/intellij-community,clumsy/intellij-community,ftomassetti/intellij-community,ivan-fedorov/intellij-community,kool79/intellij-community,ryano144/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,adedayo/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,signed/intellij-community,kool79/intellij-community,ahb0327/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,supersven/intellij-community,diorcety/intellij-community,MER-GROUP/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,adedayo/intellij-community,fengbaicanhe/intellij-community,retomerz/intellij-community,hurricup/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,petteyg/intellij-community,ftomassetti/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,ibinti/intellij-community,blademainer/intellij-community,gnuhub/intellij-community,orekyuu/intellij-community,semonte/intellij-community,adedayo/intellij-community,idea4bsd/idea4bsd,gnuhub/intellij-community,holmes/intellij-community,orekyuu/intellij-community,caot/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,wreckJ/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,dslomov/intellij-community,consulo/consulo,xfournet/intellij-community,MichaelNedzelsky/intellij-community,idea4bsd/idea4bsd,Distrotech/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,ernestp/consulo,slisson/intellij-community,clumsy/intellij-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,retomerz/intellij-community,izonder/intellij-community,FHannes/intellij-community,SerCeMan/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,fnouama/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,hurricup/intellij-community,alphafoobar/intellij-community,TangHao1987/intellij-community,salguarnieri/intellij-community,adedayo/intellij-community,da1z/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,caot/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,adedayo/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,ernestp/consulo,jagguli/intellij-community,asedunov/intellij-community,petteyg/intellij-community,kdwink/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,diorcety/intellij-community,ibinti/intellij-community,caot/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,ibinti/intellij-community,robovm/robovm-studio,petteyg/intellij-community,jexp/idea2,fnouama/intellij-community,ol-loginov/intellij-community,gnuhub/intellij-community,caot/intellij-community,izonder/intellij-community,ryano144/intellij-community,ahb0327/intellij-community,ryano144/intellij-community,holmes/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,amith01994/intellij-community,retomerz/intellij-community,SerCeMan/intellij-community,Lekanich/intellij-community,asedunov/intellij-community,consulo/consulo,MER-GROUP/intellij-community,signed/intellij-community,petteyg/intellij-community,blademainer/intellij-community,diorcety/intellij-community,holmes/intellij-community,ryano144/intellij-community,MichaelNedzelsky/intellij-community,ryano144/intellij-community,wreckJ/intellij-community,holmes/intellij-community,jagguli/intellij-community,signed/intellij-community,holmes/intellij-community,vladmm/intellij-community,FHannes/intellij-community,holmes/intellij-community,amith01994/intellij-community,alphafoobar/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,fnouama/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,vvv1559/intellij-community,kool79/intellij-community,diorcety/intellij-community,dslomov/intellij-community,apixandru/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,akosyakov/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,robovm/robovm-studio,amith01994/intellij-community,SerCeMan/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,jagguli/intellij-community,gnuhub/intellij-community,jexp/idea2,youdonghai/intellij-community,jexp/idea2,FHannes/intellij-community,salguarnieri/intellij-community,ThiagoGarciaAlves/intellij-community,TangHao1987/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,ryano144/intellij-community,joewalnes/idea-community,dslomov/intellij-community,dslomov/intellij-community,ol-loginov/intellij-community,consulo/consulo,izonder/intellij-community,adedayo/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,fnouama/intellij-community,caot/intellij-community,ftomassetti/intellij-community,dslomov/intellij-community,ivan-fedorov/intellij-community,MichaelNedzelsky/intellij-community,alphafoobar/intellij-community,allotria/intellij-community,tmpgit/intellij-community,wreckJ/intellij-community,akosyakov/intellij-community,amith01994/intellij-community,Lekanich/intellij-community,adedayo/intellij-community,SerCeMan/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,petteyg/intellij-community,tmpgit/intellij-community,lucafavatella/intellij-community,ol-loginov/intellij-community,lucafavatella/intellij-community,nicolargo/intellij-community,ahb0327/intellij-community,holmes/intellij-community,signed/intellij-community,blademainer/intellij-community,slisson/intellij-community,kdwink/intellij-community,ernestp/consulo,alphafoobar/intellij-community,kdwink/intellij-community,allotria/intellij-community,clumsy/intellij-community,fitermay/intellij-community,ftomassetti/intellij-community,jexp/idea2,hurricup/intellij-community,fengbaicanhe/intellij-community,ol-loginov/intellij-community,apixandru/intellij-community,xfournet/intellij-community
/* * Copyright 2000-2007 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.util.containers; import gnu.trove.THashMap; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.NonNls; import java.util.*; import java.util.HashSet; /** * @author peter */ public abstract class FactoryMap<K,V> { static final Object NULL = new Object() { @NonNls public String toString() { return "NULL"; } }; protected final Map<K,V> myMap = createMap(); protected Map<K, V> createMap() { return new THashMap<K, V>(); } @Nullable protected abstract V create(K key); @Nullable public V get(K key) { V value = myMap.get(getKey(key)); if (value == null) { value = create(key); myMap.put(getKey(key), value == null ? (V)NULL : value); } return value == NULL ? null : value; } private static <K> K getKey(final K key) { return key == null ? (K)NULL : key; } public final boolean containsKey(K key) { return myMap.containsKey(getKey(key)); } public void put(K key, V value) { myMap.put(getKey(key), value == null ? (V)NULL : value); } public void removeEntry(K key) { myMap.remove(key); } public Set<K> keySet() { final Set<K> ts = myMap.keySet(); if (ts.contains(NULL)) { final HashSet<K> hashSet = new HashSet<K>(ts); hashSet.remove(NULL); hashSet.add(null); return hashSet; } return ts; } public Collection<V> notNullValues() { final Collection<V> values = myMap.values(); for (Iterator<V> iterator = values.iterator(); iterator.hasNext();) { if (iterator.next() == NULL) { iterator.remove(); } } return values; } public void clear() { myMap.clear(); } }
util/src/com/intellij/util/containers/FactoryMap.java
/* * Copyright 2000-2007 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.util.containers; import gnu.trove.THashMap; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.NonNls; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * @author peter */ public abstract class FactoryMap<K,V> { static final Object NULL = new Object() { @NonNls public String toString() { return "NULL"; } }; protected final Map<K,V> myMap = createMap(); protected Map<K, V> createMap() { return new THashMap<K, V>(); } @Nullable protected abstract V create(K key); @Nullable public V get(K key) { V value = myMap.get(getKey(key)); if (value == null) { value = create(key); myMap.put(getKey(key), value == null ? (V)NULL : value); } return value == NULL ? null : value; } private static <K> K getKey(final K key) { return key == null ? (K)NULL : key; } public final boolean containsKey(K key) { return myMap.containsKey(getKey(key)); } public void put(K key, V value) { myMap.put(getKey(key), value == null ? (V)NULL : value); } public void removeEntry(K key) { myMap.remove(key); } public Set<K> keySet() { final Set<K> ts = myMap.keySet(); if (ts.contains(NULL)) { final HashSet<K> hashSet = new HashSet<K>(ts); hashSet.remove(NULL); hashSet.add(null); return hashSet; } return ts; } public void clear() { myMap.clear(); } }
one more getter
util/src/com/intellij/util/containers/FactoryMap.java
one more getter
<ide><path>til/src/com/intellij/util/containers/FactoryMap.java <ide> import org.jetbrains.annotations.Nullable; <ide> import org.jetbrains.annotations.NonNls; <ide> <add>import java.util.*; <ide> import java.util.HashSet; <del>import java.util.Map; <del>import java.util.Set; <ide> <ide> /** <ide> * @author peter <ide> return ts; <ide> } <ide> <add> public Collection<V> notNullValues() { <add> final Collection<V> values = myMap.values(); <add> for (Iterator<V> iterator = values.iterator(); iterator.hasNext();) { <add> if (iterator.next() == NULL) { <add> iterator.remove(); <add> } <add> } <add> return values; <add> } <add> <ide> public void clear() { <ide> myMap.clear(); <ide> }
JavaScript
mit
48b35b4af9b38658fa72c5f3c7426308d2d1845d
0
NMandapaty/Rocket.Chat,JamesHGreen/Rocket_API,LearnersGuild/echo-chat,pitamar/Rocket.Chat,wtsarchive/Rocket.Chat,LearnersGuild/echo-chat,LearnersGuild/Rocket.Chat,inoio/Rocket.Chat,k0nsl/Rocket.Chat,nishimaki10/Rocket.Chat,trt15-ssci-organization/Rocket.Chat,LearnersGuild/Rocket.Chat,wicked539/Rocket.Chat,ahmadassaf/Rocket.Chat,pkgodara/Rocket.Chat,mrsimpson/Rocket.Chat,igorstajic/Rocket.Chat,ziedmahdi/Rocket.Chat,4thParty/Rocket.Chat,abduljanjua/TheHub,k0nsl/Rocket.Chat,snaiperskaya96/Rocket.Chat,Achaikos/Rocket.Chat,nishimaki10/Rocket.Chat,pitamar/Rocket.Chat,pkgodara/Rocket.Chat,AlecTroemel/Rocket.Chat,wtsarchive/Rocket.Chat,inoxth/Rocket.Chat,galrotem1993/Rocket.Chat,wtsarchive/Rocket.Chat,danielbressan/Rocket.Chat,Gyubin/Rocket.Chat,mwharrison/Rocket.Chat,mwharrison/Rocket.Chat,mccambridge/Rocket.Chat,mrsimpson/Rocket.Chat,galrotem1993/Rocket.Chat,igorstajic/Rocket.Chat,mrinaldhar/Rocket.Chat,Kiran-Rao/Rocket.Chat,AlecTroemel/Rocket.Chat,pachox/Rocket.Chat,trt15-ssci-organization/Rocket.Chat,AimenJoe/Rocket.Chat,danielbressan/Rocket.Chat,ahmadassaf/Rocket.Chat,VoiSmart/Rocket.Chat,Gudii/Rocket.Chat,pkgodara/Rocket.Chat,alexbrazier/Rocket.Chat,fatihwk/Rocket.Chat,ziedmahdi/Rocket.Chat,cnash/Rocket.Chat,ggazzo/Rocket.Chat,Gyubin/Rocket.Chat,timkinnane/Rocket.Chat,alexbrazier/Rocket.Chat,pachox/Rocket.Chat,pkgodara/Rocket.Chat,LearnersGuild/Rocket.Chat,Achaikos/Rocket.Chat,igorstajic/Rocket.Chat,marzieh312/Rocket.Chat,AlecTroemel/Rocket.Chat,ggazzo/Rocket.Chat,yuyixg/Rocket.Chat,abduljanjua/TheHub,inoxth/Rocket.Chat,fatihwk/Rocket.Chat,tntobias/Rocket.Chat,LearnersGuild/Rocket.Chat,mrsimpson/Rocket.Chat,OtkurBiz/Rocket.Chat,JamesHGreen/Rocket_API,Gudii/Rocket.Chat,igorstajic/Rocket.Chat,matthewshirley/Rocket.Chat,AimenJoe/Rocket.Chat,nishimaki10/Rocket.Chat,ahmadassaf/Rocket.Chat,karlprieb/Rocket.Chat,Kiran-Rao/Rocket.Chat,Gudii/Rocket.Chat,timkinnane/Rocket.Chat,abduljanjua/TheHub,snaiperskaya96/Rocket.Chat,ealbers/Rocket.Chat,inoxth/Rocket.Chat,intelradoux/Rocket.Chat,pitamar/Rocket.Chat,mccambridge/Rocket.Chat,NMandapaty/Rocket.Chat,k0nsl/Rocket.Chat,cnash/Rocket.Chat,pachox/Rocket.Chat,mrinaldhar/Rocket.Chat,mccambridge/Rocket.Chat,NMandapaty/Rocket.Chat,BorntraegerMarc/Rocket.Chat,marzieh312/Rocket.Chat,ggazzo/Rocket.Chat,Achaikos/Rocket.Chat,subesokun/Rocket.Chat,4thParty/Rocket.Chat,LearnersGuild/echo-chat,jbsavoy18/rocketchat-1,AlecTroemel/Rocket.Chat,AimenJoe/Rocket.Chat,JamesHGreen/Rocket.Chat,NMandapaty/Rocket.Chat,BorntraegerMarc/Rocket.Chat,yuyixg/Rocket.Chat,tntobias/Rocket.Chat,xasx/Rocket.Chat,mrsimpson/Rocket.Chat,cnash/Rocket.Chat,jbsavoy18/rocketchat-1,Sing-Li/Rocket.Chat,VoiSmart/Rocket.Chat,OtkurBiz/Rocket.Chat,xasx/Rocket.Chat,mccambridge/Rocket.Chat,Sing-Li/Rocket.Chat,fatihwk/Rocket.Chat,ealbers/Rocket.Chat,Movile/Rocket.Chat,abduljanjua/TheHub,wicked539/Rocket.Chat,alexbrazier/Rocket.Chat,trt15-ssci-organization/Rocket.Chat,inoio/Rocket.Chat,karlprieb/Rocket.Chat,marzieh312/Rocket.Chat,OtkurBiz/Rocket.Chat,flaviogrossi/Rocket.Chat,yuyixg/Rocket.Chat,jbsavoy18/rocketchat-1,matthewshirley/Rocket.Chat,subesokun/Rocket.Chat,LearnersGuild/echo-chat,BorntraegerMarc/Rocket.Chat,subesokun/Rocket.Chat,BorntraegerMarc/Rocket.Chat,tntobias/Rocket.Chat,4thParty/Rocket.Chat,intelradoux/Rocket.Chat,intelradoux/Rocket.Chat,tntobias/Rocket.Chat,wtsarchive/Rocket.Chat,JamesHGreen/Rocket.Chat,Movile/Rocket.Chat,matthewshirley/Rocket.Chat,marzieh312/Rocket.Chat,ziedmahdi/Rocket.Chat,Movile/Rocket.Chat,inoio/Rocket.Chat,Achaikos/Rocket.Chat,Gyubin/Rocket.Chat,JamesHGreen/Rocket_API,OtkurBiz/Rocket.Chat,timkinnane/Rocket.Chat,Sing-Li/Rocket.Chat,cnash/Rocket.Chat,pachox/Rocket.Chat,yuyixg/Rocket.Chat,ealbers/Rocket.Chat,galrotem1993/Rocket.Chat,pitamar/Rocket.Chat,flaviogrossi/Rocket.Chat,subesokun/Rocket.Chat,mrinaldhar/Rocket.Chat,JamesHGreen/Rocket.Chat,karlprieb/Rocket.Chat,flaviogrossi/Rocket.Chat,trt15-ssci-organization/Rocket.Chat,galrotem1993/Rocket.Chat,k0nsl/Rocket.Chat,danielbressan/Rocket.Chat,Gudii/Rocket.Chat,xasx/Rocket.Chat,jbsavoy18/rocketchat-1,Kiran-Rao/Rocket.Chat,inoxth/Rocket.Chat,ziedmahdi/Rocket.Chat,ggazzo/Rocket.Chat,Gyubin/Rocket.Chat,danielbressan/Rocket.Chat,JamesHGreen/Rocket_API,Kiran-Rao/Rocket.Chat,flaviogrossi/Rocket.Chat,matthewshirley/Rocket.Chat,snaiperskaya96/Rocket.Chat,wicked539/Rocket.Chat,nishimaki10/Rocket.Chat,timkinnane/Rocket.Chat,snaiperskaya96/Rocket.Chat,JamesHGreen/Rocket.Chat,4thParty/Rocket.Chat,mwharrison/Rocket.Chat,karlprieb/Rocket.Chat,intelradoux/Rocket.Chat,fatihwk/Rocket.Chat,xasx/Rocket.Chat,Movile/Rocket.Chat,wicked539/Rocket.Chat,ahmadassaf/Rocket.Chat,mwharrison/Rocket.Chat,ealbers/Rocket.Chat,VoiSmart/Rocket.Chat,AimenJoe/Rocket.Chat,mrinaldhar/Rocket.Chat,Sing-Li/Rocket.Chat,alexbrazier/Rocket.Chat
var ManagerUsers; Meteor.startup(function() { ManagerUsers = new Mongo.Collection('managerUsers'); }); Template.livechatUsers.helpers({ managers() { return ManagerUsers.find({}, { sort: { name: 1 } }); }, agents() { return AgentUsers.find({}, { sort: { name: 1 } }); }, emailAddress() { if (this.emails && this.emails.length > 0) { return this.emails[0].address; } }, agentAutocompleteSettings() { return { limit: 10, // inputDelay: 300 rules: [{ // @TODO maybe change this 'collection' and/or template collection: 'UserAndRoom', subscription: 'userAutocomplete', field: 'username', template: Template.userSearch, noMatchTemplate: Template.userSearchEmpty, matchAll: true, filter: { exceptions: _.map(AgentUsers.find({}, { fields: { username: 1 } }).fetch(), user => { return user.username; }) }, selector(match) { return { term: match }; }, sort: 'username' }] }; }, managerAutocompleteSettings() { return { limit: 10, // inputDelay: 300 rules: [{ // @TODO maybe change this 'collection' and/or template collection: 'UserAndRoom', subscription: 'userAutocomplete', field: 'username', template: Template.userSearch, noMatchTemplate: Template.userSearchEmpty, matchAll: true, filter: { exceptions: _.map(ManagerUsers.find({}, { fields: { username: 1 } }).fetch(), user => { return user.username; }) }, selector(match) { return { term: match }; }, sort: 'username' }] }; } }); Template.livechatUsers.events({ 'click .remove-manager'(e/*, instance*/) { e.preventDefault(); swal({ title: t('Are_you_sure'), type: 'warning', showCancelButton: true, confirmButtonColor: '#DD6B55', confirmButtonText: t('Yes'), cancelButtonText: t('Cancel'), closeOnConfirm: false, html: false }, () => { Meteor.call('livechat:removeManager', this.username, function(error/*, result*/) { if (error) { return handleError(error); } swal({ title: t('Removed'), text: t('Manager_removed'), type: 'success', timer: 1000, showConfirmButton: false }); }); }); }, 'click .remove-agent'(e/*, instance*/) { e.preventDefault(); swal({ title: t('Are_you_sure'), type: 'warning', showCancelButton: true, confirmButtonColor: '#DD6B55', confirmButtonText: t('Yes'), cancelButtonText: t('Cancel'), closeOnConfirm: false, html: false }, () => { Meteor.call('livechat:removeAgent', this.username, function(error/*, result*/) { if (error) { return handleError(error); } swal({ title: t('Removed'), text: t('Agent_removed'), type: 'success', timer: 1000, showConfirmButton: false }); }); }); }, 'submit #form-manager'(e/*, instance*/) { e.preventDefault(); if (e.currentTarget.elements.username.value.trim() === '') { return toastr.error(t('Please_fill_a_username')); } var oldBtnValue = e.currentTarget.elements.add.value; e.currentTarget.elements.add.value = t('Saving'); Meteor.call('livechat:addManager', e.currentTarget.elements.username.value, function(error/*, result*/) { e.currentTarget.elements.add.value = oldBtnValue; if (error) { return handleError(error); } toastr.success(t('Manager_added')); e.currentTarget.reset(); }); }, 'submit #form-agent'(e/*, instance*/) { e.preventDefault(); if (e.currentTarget.elements.username.value.trim() === '') { return toastr.error(t('Please_fill_a_username')); } var oldBtnValue = e.currentTarget.elements.add.value; e.currentTarget.elements.add.value = t('Saving'); Meteor.call('livechat:addAgent', e.currentTarget.elements.username.value, function(error/*, result*/) { e.currentTarget.elements.add.value = oldBtnValue; if (error) { return handleError(error); } toastr.success(t('Agent_added')); e.currentTarget.reset(); }); } }); Template.livechatUsers.onCreated(function() { this.subscribe('livechat:agents'); this.subscribe('livechat:managers'); });
packages/rocketchat-livechat/client/views/app/livechatUsers.js
var ManagerUsers; Meteor.startup(function() { ManagerUsers = new Mongo.Collection('managerUsers'); }); Template.livechatUsers.helpers({ managers() { return ManagerUsers.find({}, { sort: { name: 1 } }); }, agents() { return AgentUsers.find({}, { sort: { name: 1 } }); }, emailAddress() { if (this.emails && this.emails.length > 0) { return this.emails[0].address; } }, agentAutocompleteSettings() { return { limit: 10, // inputDelay: 300 rules: [{ // @TODO maybe change this 'collection' and/or template collection: 'UserAndRoom', subscription: 'userAutocomplete', field: 'username', template: Template.userSearch, noMatchTemplate: Template.userSearchEmpty, matchAll: true, filter: { exceptions: _.map(AgentUsers.find({}, { fields: { username: 1 } }).fetch(), user => { return user.username; }) }, selector(match) { return { username: match }; }, sort: 'username' }] }; }, managerAutocompleteSettings() { return { limit: 10, // inputDelay: 300 rules: [{ // @TODO maybe change this 'collection' and/or template collection: 'UserAndRoom', subscription: 'userAutocomplete', field: 'username', template: Template.userSearch, noMatchTemplate: Template.userSearchEmpty, matchAll: true, filter: { exceptions: _.map(ManagerUsers.find({}, { fields: { username: 1 } }).fetch(), user => { return user.username; }) }, selector(match) { return { username: match }; }, sort: 'username' }] }; } }); Template.livechatUsers.events({ 'click .remove-manager'(e/*, instance*/) { e.preventDefault(); swal({ title: t('Are_you_sure'), type: 'warning', showCancelButton: true, confirmButtonColor: '#DD6B55', confirmButtonText: t('Yes'), cancelButtonText: t('Cancel'), closeOnConfirm: false, html: false }, () => { Meteor.call('livechat:removeManager', this.username, function(error/*, result*/) { if (error) { return handleError(error); } swal({ title: t('Removed'), text: t('Manager_removed'), type: 'success', timer: 1000, showConfirmButton: false }); }); }); }, 'click .remove-agent'(e/*, instance*/) { e.preventDefault(); swal({ title: t('Are_you_sure'), type: 'warning', showCancelButton: true, confirmButtonColor: '#DD6B55', confirmButtonText: t('Yes'), cancelButtonText: t('Cancel'), closeOnConfirm: false, html: false }, () => { Meteor.call('livechat:removeAgent', this.username, function(error/*, result*/) { if (error) { return handleError(error); } swal({ title: t('Removed'), text: t('Agent_removed'), type: 'success', timer: 1000, showConfirmButton: false }); }); }); }, 'submit #form-manager'(e/*, instance*/) { e.preventDefault(); if (e.currentTarget.elements.username.value.trim() === '') { return toastr.error(t('Please_fill_a_username')); } var oldBtnValue = e.currentTarget.elements.add.value; e.currentTarget.elements.add.value = t('Saving'); Meteor.call('livechat:addManager', e.currentTarget.elements.username.value, function(error/*, result*/) { e.currentTarget.elements.add.value = oldBtnValue; if (error) { return handleError(error); } toastr.success(t('Manager_added')); e.currentTarget.reset(); }); }, 'submit #form-agent'(e/*, instance*/) { e.preventDefault(); if (e.currentTarget.elements.username.value.trim() === '') { return toastr.error(t('Please_fill_a_username')); } var oldBtnValue = e.currentTarget.elements.add.value; e.currentTarget.elements.add.value = t('Saving'); Meteor.call('livechat:addAgent', e.currentTarget.elements.username.value, function(error/*, result*/) { e.currentTarget.elements.add.value = oldBtnValue; if (error) { return handleError(error); } toastr.success(t('Agent_added')); e.currentTarget.reset(); }); } }); Template.livechatUsers.onCreated(function() { this.subscribe('livechat:agents'); this.subscribe('livechat:managers'); });
Fix user search on livechat user management page
packages/rocketchat-livechat/client/views/app/livechatUsers.js
Fix user search on livechat user management page
<ide><path>ackages/rocketchat-livechat/client/views/app/livechatUsers.js <ide> exceptions: _.map(AgentUsers.find({}, { fields: { username: 1 } }).fetch(), user => { return user.username; }) <ide> }, <ide> selector(match) { <del> return { username: match }; <add> return { term: match }; <ide> }, <ide> sort: 'username' <ide> }] <ide> exceptions: _.map(ManagerUsers.find({}, { fields: { username: 1 } }).fetch(), user => { return user.username; }) <ide> }, <ide> selector(match) { <del> return { username: match }; <add> return { term: match }; <ide> }, <ide> sort: 'username' <ide> }]
Java
apache-2.0
829bf4b1b1cbcd29d483e173dc057448e51ead88
0
ol-loginov/intellij-community,blademainer/intellij-community,robovm/robovm-studio,mglukhikh/intellij-community,izonder/intellij-community,fitermay/intellij-community,allotria/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,gnuhub/intellij-community,clumsy/intellij-community,ivan-fedorov/intellij-community,orekyuu/intellij-community,retomerz/intellij-community,asedunov/intellij-community,ftomassetti/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,jexp/idea2,FHannes/intellij-community,kool79/intellij-community,akosyakov/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,retomerz/intellij-community,muntasirsyed/intellij-community,wreckJ/intellij-community,nicolargo/intellij-community,ahb0327/intellij-community,vvv1559/intellij-community,petteyg/intellij-community,apixandru/intellij-community,fitermay/intellij-community,alphafoobar/intellij-community,muntasirsyed/intellij-community,TangHao1987/intellij-community,TangHao1987/intellij-community,diorcety/intellij-community,Lekanich/intellij-community,adedayo/intellij-community,Lekanich/intellij-community,semonte/intellij-community,caot/intellij-community,amith01994/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,jexp/idea2,ahb0327/intellij-community,samthor/intellij-community,semonte/intellij-community,joewalnes/idea-community,orekyuu/intellij-community,amith01994/intellij-community,vladmm/intellij-community,allotria/intellij-community,pwoodworth/intellij-community,consulo/consulo,fengbaicanhe/intellij-community,fnouama/intellij-community,ol-loginov/intellij-community,wreckJ/intellij-community,retomerz/intellij-community,MER-GROUP/intellij-community,robovm/robovm-studio,blademainer/intellij-community,allotria/intellij-community,apixandru/intellij-community,gnuhub/intellij-community,adedayo/intellij-community,vladmm/intellij-community,retomerz/intellij-community,blademainer/intellij-community,SerCeMan/intellij-community,supersven/intellij-community,vvv1559/intellij-community,ernestp/consulo,clumsy/intellij-community,izonder/intellij-community,dslomov/intellij-community,amith01994/intellij-community,ibinti/intellij-community,xfournet/intellij-community,consulo/consulo,joewalnes/idea-community,SerCeMan/intellij-community,FHannes/intellij-community,da1z/intellij-community,diorcety/intellij-community,MichaelNedzelsky/intellij-community,kool79/intellij-community,nicolargo/intellij-community,tmpgit/intellij-community,consulo/consulo,ol-loginov/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,ftomassetti/intellij-community,ol-loginov/intellij-community,fitermay/intellij-community,wreckJ/intellij-community,asedunov/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,diorcety/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,SerCeMan/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,pwoodworth/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,holmes/intellij-community,signed/intellij-community,caot/intellij-community,samthor/intellij-community,akosyakov/intellij-community,robovm/robovm-studio,ThiagoGarciaAlves/intellij-community,gnuhub/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,gnuhub/intellij-community,tmpgit/intellij-community,retomerz/intellij-community,Lekanich/intellij-community,pwoodworth/intellij-community,holmes/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,apixandru/intellij-community,SerCeMan/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,caot/intellij-community,ryano144/intellij-community,fitermay/intellij-community,amith01994/intellij-community,semonte/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,supersven/intellij-community,TangHao1987/intellij-community,ibinti/intellij-community,clumsy/intellij-community,dslomov/intellij-community,diorcety/intellij-community,jagguli/intellij-community,salguarnieri/intellij-community,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,petteyg/intellij-community,idea4bsd/idea4bsd,TangHao1987/intellij-community,adedayo/intellij-community,FHannes/intellij-community,samthor/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,da1z/intellij-community,kdwink/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,alphafoobar/intellij-community,izonder/intellij-community,apixandru/intellij-community,fnouama/intellij-community,ivan-fedorov/intellij-community,izonder/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,SerCeMan/intellij-community,adedayo/intellij-community,jagguli/intellij-community,joewalnes/idea-community,ibinti/intellij-community,signed/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,clumsy/intellij-community,fnouama/intellij-community,slisson/intellij-community,akosyakov/intellij-community,diorcety/intellij-community,ol-loginov/intellij-community,TangHao1987/intellij-community,da1z/intellij-community,kdwink/intellij-community,apixandru/intellij-community,SerCeMan/intellij-community,suncycheng/intellij-community,izonder/intellij-community,ThiagoGarciaAlves/intellij-community,izonder/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,akosyakov/intellij-community,da1z/intellij-community,supersven/intellij-community,asedunov/intellij-community,ftomassetti/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,kdwink/intellij-community,xfournet/intellij-community,ahb0327/intellij-community,signed/intellij-community,dslomov/intellij-community,petteyg/intellij-community,apixandru/intellij-community,holmes/intellij-community,suncycheng/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,slisson/intellij-community,suncycheng/intellij-community,ftomassetti/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,ThiagoGarciaAlves/intellij-community,petteyg/intellij-community,hurricup/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,jagguli/intellij-community,clumsy/intellij-community,kool79/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,robovm/robovm-studio,semonte/intellij-community,SerCeMan/intellij-community,nicolargo/intellij-community,tmpgit/intellij-community,blademainer/intellij-community,FHannes/intellij-community,blademainer/intellij-community,blademainer/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,ryano144/intellij-community,retomerz/intellij-community,tmpgit/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,signed/intellij-community,wreckJ/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,alphafoobar/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,MichaelNedzelsky/intellij-community,robovm/robovm-studio,gnuhub/intellij-community,Distrotech/intellij-community,clumsy/intellij-community,MER-GROUP/intellij-community,robovm/robovm-studio,signed/intellij-community,orekyuu/intellij-community,SerCeMan/intellij-community,jagguli/intellij-community,ol-loginov/intellij-community,MichaelNedzelsky/intellij-community,jagguli/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,alphafoobar/intellij-community,fnouama/intellij-community,lucafavatella/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,petteyg/intellij-community,kool79/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,suncycheng/intellij-community,allotria/intellij-community,wreckJ/intellij-community,asedunov/intellij-community,tmpgit/intellij-community,xfournet/intellij-community,jagguli/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,signed/intellij-community,kdwink/intellij-community,akosyakov/intellij-community,Distrotech/intellij-community,blademainer/intellij-community,dslomov/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,da1z/intellij-community,kool79/intellij-community,supersven/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,joewalnes/idea-community,semonte/intellij-community,orekyuu/intellij-community,xfournet/intellij-community,asedunov/intellij-community,dslomov/intellij-community,fengbaicanhe/intellij-community,apixandru/intellij-community,Distrotech/intellij-community,clumsy/intellij-community,jexp/idea2,petteyg/intellij-community,supersven/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,suncycheng/intellij-community,robovm/robovm-studio,michaelgallacher/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,orekyuu/intellij-community,da1z/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,MER-GROUP/intellij-community,orekyuu/intellij-community,FHannes/intellij-community,adedayo/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,fnouama/intellij-community,signed/intellij-community,FHannes/intellij-community,ftomassetti/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,caot/intellij-community,fnouama/intellij-community,caot/intellij-community,Lekanich/intellij-community,robovm/robovm-studio,caot/intellij-community,fitermay/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,jagguli/intellij-community,holmes/intellij-community,robovm/robovm-studio,ryano144/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,supersven/intellij-community,asedunov/intellij-community,holmes/intellij-community,asedunov/intellij-community,retomerz/intellij-community,blademainer/intellij-community,fitermay/intellij-community,joewalnes/idea-community,fnouama/intellij-community,allotria/intellij-community,ernestp/consulo,diorcety/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,samthor/intellij-community,TangHao1987/intellij-community,supersven/intellij-community,slisson/intellij-community,nicolargo/intellij-community,joewalnes/idea-community,xfournet/intellij-community,salguarnieri/intellij-community,nicolargo/intellij-community,caot/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,pwoodworth/intellij-community,hurricup/intellij-community,semonte/intellij-community,kdwink/intellij-community,ivan-fedorov/intellij-community,MER-GROUP/intellij-community,caot/intellij-community,ahb0327/intellij-community,diorcety/intellij-community,michaelgallacher/intellij-community,muntasirsyed/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,pwoodworth/intellij-community,dslomov/intellij-community,alphafoobar/intellij-community,Lekanich/intellij-community,Lekanich/intellij-community,gnuhub/intellij-community,holmes/intellij-community,ahb0327/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,lucafavatella/intellij-community,Distrotech/intellij-community,youdonghai/intellij-community,supersven/intellij-community,amith01994/intellij-community,adedayo/intellij-community,idea4bsd/idea4bsd,ivan-fedorov/intellij-community,amith01994/intellij-community,vladmm/intellij-community,holmes/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,kool79/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,ftomassetti/intellij-community,clumsy/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,ahb0327/intellij-community,vladmm/intellij-community,jagguli/intellij-community,kool79/intellij-community,blademainer/intellij-community,ryano144/intellij-community,slisson/intellij-community,petteyg/intellij-community,kdwink/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,signed/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,ernestp/consulo,ryano144/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,ryano144/intellij-community,fitermay/intellij-community,retomerz/intellij-community,fengbaicanhe/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,amith01994/intellij-community,tmpgit/intellij-community,TangHao1987/intellij-community,akosyakov/intellij-community,clumsy/intellij-community,kool79/intellij-community,orekyuu/intellij-community,jagguli/intellij-community,pwoodworth/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community,ibinti/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,signed/intellij-community,blademainer/intellij-community,allotria/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,kool79/intellij-community,ftomassetti/intellij-community,clumsy/intellij-community,apixandru/intellij-community,samthor/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,nicolargo/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,mglukhikh/intellij-community,jexp/idea2,ivan-fedorov/intellij-community,clumsy/intellij-community,slisson/intellij-community,hurricup/intellij-community,FHannes/intellij-community,dslomov/intellij-community,petteyg/intellij-community,ivan-fedorov/intellij-community,caot/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,nicolargo/intellij-community,ibinti/intellij-community,ahb0327/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,diorcety/intellij-community,pwoodworth/intellij-community,ftomassetti/intellij-community,izonder/intellij-community,retomerz/intellij-community,fnouama/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,slisson/intellij-community,petteyg/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,kool79/intellij-community,hurricup/intellij-community,caot/intellij-community,blademainer/intellij-community,youdonghai/intellij-community,akosyakov/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,muntasirsyed/intellij-community,alphafoobar/intellij-community,joewalnes/idea-community,wreckJ/intellij-community,lucafavatella/intellij-community,tmpgit/intellij-community,ernestp/consulo,samthor/intellij-community,consulo/consulo,adedayo/intellij-community,michaelgallacher/intellij-community,izonder/intellij-community,gnuhub/intellij-community,Lekanich/intellij-community,tmpgit/intellij-community,pwoodworth/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,adedayo/intellij-community,fengbaicanhe/intellij-community,salguarnieri/intellij-community,jexp/idea2,diorcety/intellij-community,Distrotech/intellij-community,wreckJ/intellij-community,joewalnes/idea-community,apixandru/intellij-community,apixandru/intellij-community,xfournet/intellij-community,izonder/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,Distrotech/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,petteyg/intellij-community,SerCeMan/intellij-community,suncycheng/intellij-community,tmpgit/intellij-community,orekyuu/intellij-community,Distrotech/intellij-community,supersven/intellij-community,slisson/intellij-community,semonte/intellij-community,alphafoobar/intellij-community,ahb0327/intellij-community,petteyg/intellij-community,ryano144/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,slisson/intellij-community,Lekanich/intellij-community,orekyuu/intellij-community,jexp/idea2,ibinti/intellij-community,hurricup/intellij-community,hurricup/intellij-community,dslomov/intellij-community,xfournet/intellij-community,FHannes/intellij-community,ftomassetti/intellij-community,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,wreckJ/intellij-community,ahb0327/intellij-community,fengbaicanhe/intellij-community,robovm/robovm-studio,hurricup/intellij-community,pwoodworth/intellij-community,amith01994/intellij-community,ol-loginov/intellij-community,semonte/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,vladmm/intellij-community,ernestp/consulo,vladmm/intellij-community,MichaelNedzelsky/intellij-community,nicolargo/intellij-community,MichaelNedzelsky/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,Lekanich/intellij-community,Distrotech/intellij-community,holmes/intellij-community,allotria/intellij-community,consulo/consulo,kool79/intellij-community,retomerz/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,ernestp/consulo,SerCeMan/intellij-community,TangHao1987/intellij-community,holmes/intellij-community,Distrotech/intellij-community,dslomov/intellij-community,ivan-fedorov/intellij-community,vladmm/intellij-community,samthor/intellij-community,MichaelNedzelsky/intellij-community,tmpgit/intellij-community,dslomov/intellij-community,ol-loginov/intellij-community,amith01994/intellij-community,ryano144/intellij-community,nicolargo/intellij-community,gnuhub/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,semonte/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,fengbaicanhe/intellij-community,nicolargo/intellij-community,idea4bsd/idea4bsd,nicolargo/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,slisson/intellij-community,vladmm/intellij-community,akosyakov/intellij-community,caot/intellij-community,slisson/intellij-community,diorcety/intellij-community,fengbaicanhe/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,ol-loginov/intellij-community,alphafoobar/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,holmes/intellij-community,da1z/intellij-community,kdwink/intellij-community,kool79/intellij-community,asedunov/intellij-community,fengbaicanhe/intellij-community,vladmm/intellij-community,jexp/idea2,fengbaicanhe/intellij-community,alphafoobar/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,ryano144/intellij-community,apixandru/intellij-community,samthor/intellij-community,fnouama/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,jexp/idea2,SerCeMan/intellij-community,diorcety/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,joewalnes/idea-community,akosyakov/intellij-community,vladmm/intellij-community,ivan-fedorov/intellij-community,slisson/intellij-community,allotria/intellij-community,Distrotech/intellij-community,alphafoobar/intellij-community,allotria/intellij-community,da1z/intellij-community,supersven/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,amith01994/intellij-community,vladmm/intellij-community,hurricup/intellij-community,da1z/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,signed/intellij-community,fitermay/intellij-community,kdwink/intellij-community,robovm/robovm-studio,ibinti/intellij-community,samthor/intellij-community,semonte/intellij-community,caot/intellij-community,robovm/robovm-studio,allotria/intellij-community,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,consulo/consulo,da1z/intellij-community,jagguli/intellij-community,holmes/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,holmes/intellij-community,vvv1559/intellij-community
package com.intellij.codeInsight.completion; import com.intellij.codeInsight.lookup.Lookup; import com.intellij.codeInsight.lookup.LookupItem; import com.intellij.codeInsight.template.Expression; import com.intellij.codeInsight.template.Template; import com.intellij.codeInsight.template.TemplateManager; import com.intellij.codeInsight.template.impl.MacroCallNode; import com.intellij.codeInsight.template.macro.MacroFactory; import com.intellij.codeInsight.TailType; import com.intellij.openapi.editor.CaretModel; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.ScrollType; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.StdFileTypes; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiElement; import com.intellij.psi.filters.*; import com.intellij.psi.filters.getters.XmlAttributeValueGetter; import com.intellij.psi.filters.getters.AllWordsGetter; import com.intellij.psi.filters.position.LeftNeighbour; import com.intellij.psi.filters.position.TokenTypeFilter; import com.intellij.psi.html.HtmlTag; import com.intellij.psi.search.PsiElementProcessor; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.xml.*; import com.intellij.util.text.CharArrayUtil; import com.intellij.xml.XmlAttributeDescriptor; import com.intellij.xml.XmlElementDescriptor; import com.intellij.xml.impl.schema.ComplexTypeDescriptor; import com.intellij.xml.impl.schema.TypeDescriptor; import com.intellij.xml.impl.schema.XmlElementDescriptorImpl; import com.intellij.xml.util.HtmlUtil; import com.intellij.xml.util.XmlUtil; import java.util.ArrayList; import java.util.HashSet; import java.util.List; /** * Created by IntelliJ IDEA. * User: ik * Date: 05.06.2003 * Time: 18:55:15 * To change this template use Options | File Templates. */ public class XmlCompletionData extends CompletionData { public XmlCompletionData(){ declareFinalScope(XmlTag.class); declareFinalScope(XmlAttribute.class); declareFinalScope(XmlAttributeValue.class); { final CompletionVariant variant = new CompletionVariant(createTagCompletionFilter()); variant.includeScopeClass(XmlTag.class); variant.addCompletionFilterOnElement(TrueFilter.INSTANCE); variant.setInsertHandler(new XmlTagInsertHandler()); registerVariant(variant); } { final CompletionVariant variant = new CompletionVariant(createAttributeCompletion()); variant.includeScopeClass(XmlAttribute.class); variant.addCompletionFilterOnElement(TrueFilter.INSTANCE); variant.setInsertHandler(new XmlAttributeInsertHandler()); registerVariant(variant); } { final CompletionVariant variant = new CompletionVariant(createAttributeValueCompletionFilter()); variant.includeScopeClass(XmlAttributeValue.class); variant.addCompletion(new XmlAttributeValueGetter()); variant.addCompletionFilter(TrueFilter.INSTANCE, TailType.NONE); variant.setInsertHandler(new XmlAttributeValueInsertHandler()); registerVariant(variant); } { final CompletionVariant variant = new CompletionVariant(new TokenTypeFilter(XmlTokenType.XML_DATA_CHARACTERS)); variant.includeScopeClass(XmlToken.class, true); variant.addCompletion(new SimpleTagContentEnumerationValuesGetter(),TailType.NONE); registerVariant(variant); } { final CompletionVariant variant = new CompletionVariant( new AndFilter( new LeftNeighbour(new TextFilter("&")), new OrFilter( new TokenTypeFilter(XmlTokenType.XML_DATA_CHARACTERS), new TokenTypeFilter(XmlTokenType.XML_ATTRIBUTE_VALUE_TOKEN) ) ) ); variant.includeScopeClass(XmlToken.class, true); variant.addCompletion(new EntityRefGetter()); variant.setInsertHandler(new EntityRefInsertHandler()); registerVariant(variant); } } protected ElementFilter createAttributeCompletion() { return TrueFilter.INSTANCE; } protected ElementFilter createAttributeValueCompletionFilter() { return TrueFilter.INSTANCE; } protected ElementFilter createTagCompletionFilter() { return TrueFilter.INSTANCE; } private static class XmlAttributeValueInsertHandler extends DefaultInsertHandler{ public void handleInsert(CompletionContext context, int startOffset, LookupData data, LookupItem item, boolean signatureSelected, char completionChar) { super.handleInsert(context, startOffset, data, item, signatureSelected, completionChar); final PsiElement current = context.file.findElementAt(context.startOffset); final String text = current.getText(); final CaretModel caretModel = context.editor.getCaretModel(); int localOffset = caretModel.getOffset() - current.getTextRange().getStartOffset() - 1; startOffset = localOffset; while(localOffset > 0){ final char cur = text.charAt(localOffset--); if(cur == '}') break; if(cur == '{'){ if(localOffset >= 0 && text.charAt(localOffset) == '$'){ if (startOffset >= text.length() - 1 || text.charAt(startOffset + 1) != '}') { context.editor.getDocument().insertString(caretModel.getOffset(), "}"); } caretModel.moveToOffset(caretModel.getOffset() + 1); } break; } } } } private static class XmlAttributeInsertHandler extends BasicInsertHandler { public XmlAttributeInsertHandler() { } public void handleInsert( CompletionContext context, int startOffset, LookupData data, LookupItem item, boolean signatureSelected, char completionChar) { super.handleInsert(context, startOffset, data, item, signatureSelected, completionChar); final Editor editor = context.editor; final Document document = editor.getDocument(); final int caretOffset = editor.getCaretModel().getOffset(); if (PsiDocumentManager.getInstance(editor.getProject()).getPsiFile(document).getFileType() == StdFileTypes.HTML && HtmlUtil.isSingleHtmlAttribute((String)item.getObject()) ) { return; } final CharSequence chars = document.getCharsSequence(); if (!CharArrayUtil.regionMatches(chars, caretOffset, "=\"") && !CharArrayUtil.regionMatches(chars, caretOffset, "='")) { if("/> \n\t\r".indexOf(document.getCharsSequence().charAt(caretOffset)) < 0) document.insertString(caretOffset, "=\"\" "); else document.insertString(caretOffset, "=\"\""); } editor.getCaretModel().moveToOffset(caretOffset + 2); editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); editor.getSelectionModel().removeSelection(); } } private static class XmlTagInsertHandler extends BasicInsertHandler { public XmlTagInsertHandler() {} public void handleInsert( CompletionContext context, int startOffset, LookupData data, LookupItem item, boolean signatureSelected, char completionChar) { super.handleInsert(context, startOffset, data, item, signatureSelected, completionChar); Project project = context.project; Editor editor = context.editor; // Need to insert " " to prevent creating tags like <tagThis is my text editor.getDocument().insertString(editor.getCaretModel().getOffset(), " "); PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument()); PsiElement current = context.file.findElementAt(context.startOffset); editor.getDocument().deleteString(editor.getCaretModel().getOffset(), editor.getCaretModel().getOffset() + 1); final XmlTag tag = PsiTreeUtil.getContextOfType(current, XmlTag.class, true); if (tag == null) return; final XmlElementDescriptor descriptor = tag.getDescriptor(); if (XmlUtil.getTokenOfType(tag, XmlTokenType.XML_TAG_END) == null && XmlUtil.getTokenOfType(tag, XmlTokenType.XML_EMPTY_ELEMENT_END) == null) { Template t = TemplateManager.getInstance(project).getActiveTemplate(editor); if (t == null && descriptor != null) { insertIncompleteTag(completionChar, editor, project, descriptor, tag); } } else if (completionChar == Lookup.REPLACE_SELECT_CHAR) { PsiDocumentManager.getInstance(project).commitAllDocuments(); int caretOffset = editor.getCaretModel().getOffset(); PsiElement otherTag = PsiTreeUtil.getParentOfType(context.file.findElementAt(caretOffset), getTagClass()); PsiElement endTagStart = getEndTagStart(otherTag); if (endTagStart != null) { PsiElement sibling = endTagStart.getNextSibling(); if (isTagNameToken(sibling)) { int sOffset = sibling.getTextRange().getStartOffset(); int eOffset = sibling.getTextRange().getEndOffset(); editor.getDocument().deleteString(sOffset, eOffset); editor.getDocument().insertString(sOffset, getTagText(otherTag)); } } editor.getCaretModel().moveToOffset(caretOffset + 1); editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); editor.getSelectionModel().removeSelection(); } current = context.file.findElementAt(context.startOffset); if(current != null && current.getPrevSibling() instanceof XmlToken){ if(!isClosed(current) && ((XmlToken)current.getPrevSibling()).getTokenType() == XmlTokenType.XML_END_TAG_START){ editor.getDocument().insertString(current.getTextRange().getEndOffset(), ">"); editor.getCaretModel().moveToOffset(editor.getCaretModel().getOffset() + 1); } } } private boolean isClosed(PsiElement current) { PsiElement e = current; while (e != null) { if (e instanceof XmlToken) { XmlToken token = (XmlToken)e; if (token.getTokenType() == XmlTokenType.XML_TAG_END) return true; if (token.getTokenType() == XmlTokenType.XML_EMPTY_ELEMENT_END) return true; } e = e.getNextSibling(); } return false; } private void insertIncompleteTag(char completionChar, Editor editor, Project project, XmlElementDescriptor descriptor, XmlTag tag) { TemplateManager templateManager = TemplateManager.getInstance(project); Template template = templateManager.createTemplate("", ""); template.setToReformat(true); template.setToIndent(true); // temp code FileType fileType = tag.getContainingFile().getFileType(); boolean htmlCode = fileType==StdFileTypes.HTML || fileType==StdFileTypes.XHTML; XmlAttributeDescriptor[] attributes = descriptor.getAttributesDescriptors(); for (XmlAttributeDescriptor attributeDecl : attributes) { String attributeName = attributeDecl.getName(tag); if (attributeDecl.isRequired()) { template.addTextSegment(" " + attributeName + "=\""); Expression expression = new MacroCallNode(MacroFactory.createMacro("complete")); template.addVariable(attributeName, expression, expression, true); template.addTextSegment("\""); } else if (attributeDecl.isFixed() && attributeDecl.getDefaultValue() != null && !htmlCode) { template.addTextSegment(" " + attributeName + "=\"" + attributeDecl.getDefaultValue() + "\""); } } if (completionChar == '>') { template.addTextSegment(">"); template.addEndVariable(); if ( !(tag instanceof HtmlTag) || !HtmlUtil.isSingleHtmlTag(tag.getName()) ) { template.addTextSegment("</"); template.addTextSegment(descriptor.getName(tag)); template.addTextSegment(">"); } } else if (completionChar == '/') { template.addTextSegment("/>"); } templateManager.startTemplate(editor, template); } private Class getTagClass() { return XmlTag.class; } private PsiElement getEndTagStart(PsiElement tag) { return XmlUtil.getTokenOfType(tag, XmlTokenType.XML_END_TAG_START); } private String getTagText(PsiElement tag) { return ((XmlTag)tag).getName(); } private boolean isTagNameToken(PsiElement token) { return ((XmlToken)token).getTokenType() == XmlTokenType.XML_NAME; } } private static class SimpleTagContentEnumerationValuesGetter implements ContextGetter { public Object[] get(final PsiElement context, CompletionContext completionContext) { XmlTag tag = PsiTreeUtil.getParentOfType(context, XmlTag.class, false); XmlElementDescriptor descriptor = tag != null ? tag.getDescriptor() : null; if (descriptor instanceof XmlElementDescriptorImpl) { final TypeDescriptor type = ((XmlElementDescriptorImpl)descriptor).getType(); if (type instanceof ComplexTypeDescriptor) { final XmlTag[] simpleContent = new XmlTag[1]; XmlUtil.processXmlElements(((ComplexTypeDescriptor)type).getDeclaration(),new PsiElementProcessor() { public boolean execute(final PsiElement element) { if (element instanceof XmlTag && ((XmlTag)element).getLocalName().equals("simpleContent") && ((XmlTag)element).getNamespace().equals(XmlUtil.XML_SCHEMA_URI) ) { simpleContent[0] = (XmlTag)element; return false; } return true; } }, true); if (simpleContent[0]!=null) { final HashSet<String> variants = new HashSet<String>(); XmlUtil.collectEnumerationValues(simpleContent[0],variants); if (variants.size() > 0) return variants.toArray(new Object[variants.size()]); } } } return new AllWordsGetter().get(context, completionContext); } } private static class EntityRefGetter implements ContextGetter { public Object[] get(final PsiElement context, CompletionContext completionContext) { final XmlTag parentOfType = PsiTreeUtil.getParentOfType(context, XmlTag.class); if (parentOfType != null) { final XmlElementDescriptor descriptor = parentOfType.getDescriptor(); final List<String> results = new ArrayList<String>(); if (descriptor != null) { final XmlFile descriptorFile = descriptor.getNSDescriptor().getDescriptorFile(); // skip content of embedded dtd, its content will be inserted by word completion if (descriptorFile != null && !descriptorFile.equals(parentOfType.getContainingFile())) { final PsiElementProcessor processor = new PsiElementProcessor() { public boolean execute(final PsiElement element) { if (element instanceof XmlEntityDecl) { final XmlEntityDecl xmlEntityDecl = (XmlEntityDecl)element; if (xmlEntityDecl.isInternalReference()) results.add(xmlEntityDecl.getName()); } return true; } }; XmlUtil.processXmlElements( descriptorFile, processor, true ); return results.toArray(new Object[results.size()]); } } } return new Object[0]; } } private static class EntityRefInsertHandler extends BasicInsertHandler { public void handleInsert(CompletionContext context, int startOffset, LookupData data, LookupItem item, boolean signatureSelected, char completionChar) { super.handleInsert(context, startOffset, data, item, signatureSelected, completionChar); final CaretModel caretModel = context.editor.getCaretModel(); context.editor.getDocument().insertString(caretModel.getOffset(), ";"); caretModel.moveToOffset(caretModel.getOffset() + 1); } } }
source/com/intellij/codeInsight/completion/XmlCompletionData.java
package com.intellij.codeInsight.completion; import com.intellij.codeInsight.lookup.Lookup; import com.intellij.codeInsight.lookup.LookupItem; import com.intellij.codeInsight.template.Expression; import com.intellij.codeInsight.template.Template; import com.intellij.codeInsight.template.TemplateManager; import com.intellij.codeInsight.template.impl.MacroCallNode; import com.intellij.codeInsight.template.macro.MacroFactory; import com.intellij.codeInsight.TailType; import com.intellij.openapi.editor.CaretModel; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.ScrollType; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.StdFileTypes; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiElement; import com.intellij.psi.filters.*; import com.intellij.psi.filters.getters.XmlAttributeValueGetter; import com.intellij.psi.filters.getters.AllWordsGetter; import com.intellij.psi.filters.position.LeftNeighbour; import com.intellij.psi.filters.position.TokenTypeFilter; import com.intellij.psi.html.HtmlTag; import com.intellij.psi.search.PsiElementProcessor; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.xml.*; import com.intellij.util.text.CharArrayUtil; import com.intellij.xml.XmlAttributeDescriptor; import com.intellij.xml.XmlElementDescriptor; import com.intellij.xml.impl.schema.ComplexTypeDescriptor; import com.intellij.xml.impl.schema.TypeDescriptor; import com.intellij.xml.impl.schema.XmlElementDescriptorImpl; import com.intellij.xml.util.HtmlUtil; import com.intellij.xml.util.XmlUtil; import java.util.ArrayList; import java.util.HashSet; import java.util.List; /** * Created by IntelliJ IDEA. * User: ik * Date: 05.06.2003 * Time: 18:55:15 * To change this template use Options | File Templates. */ public class XmlCompletionData extends CompletionData { public XmlCompletionData(){ declareFinalScope(XmlTag.class); declareFinalScope(XmlAttribute.class); declareFinalScope(XmlAttributeValue.class); { final CompletionVariant variant = new CompletionVariant(createTagCompletionFilter()); variant.includeScopeClass(XmlTag.class); variant.addCompletionFilterOnElement(TrueFilter.INSTANCE); variant.setInsertHandler(new XmlTagInsertHandler()); registerVariant(variant); } { final CompletionVariant variant = new CompletionVariant(createAttributeCompletion()); variant.includeScopeClass(XmlAttribute.class); variant.addCompletionFilterOnElement(TrueFilter.INSTANCE); variant.setInsertHandler(new XmlAttributeInsertHandler()); registerVariant(variant); } { final CompletionVariant variant = new CompletionVariant(createAttributeValueCompletionFilter()); variant.includeScopeClass(XmlAttributeValue.class); variant.addCompletion(new XmlAttributeValueGetter()); variant.addCompletionFilter(TrueFilter.INSTANCE, TailType.NONE); variant.setInsertHandler(new XmlAttributeValueInsertHandler()); registerVariant(variant); } { final CompletionVariant variant = new CompletionVariant(new TokenTypeFilter(XmlTokenType.XML_DATA_CHARACTERS)); variant.includeScopeClass(XmlToken.class, true); variant.addCompletion(new SimpleTagContentEnumerationValuesGetter(),TailType.NONE); registerVariant(variant); } { final CompletionVariant variant = new CompletionVariant( new AndFilter( new LeftNeighbour(new TextFilter("&")), new OrFilter( new TokenTypeFilter(XmlTokenType.XML_DATA_CHARACTERS), new TokenTypeFilter(XmlTokenType.XML_ATTRIBUTE_VALUE_TOKEN) ) ) ); variant.includeScopeClass(XmlToken.class, true); variant.addCompletion(new EntityRefGetter()); variant.setInsertHandler(new EntityRefInsertHandler()); registerVariant(variant); } } protected ElementFilter createAttributeCompletion() { return TrueFilter.INSTANCE; } protected ElementFilter createAttributeValueCompletionFilter() { return TrueFilter.INSTANCE; } protected ElementFilter createTagCompletionFilter() { return TrueFilter.INSTANCE; } private static class XmlAttributeValueInsertHandler extends DefaultInsertHandler{ public void handleInsert(CompletionContext context, int startOffset, LookupData data, LookupItem item, boolean signatureSelected, char completionChar) { super.handleInsert(context, startOffset, data, item, signatureSelected, completionChar); final PsiElement current = context.file.findElementAt(context.startOffset); final String text = current.getText(); final CaretModel caretModel = context.editor.getCaretModel(); int localOffset = caretModel.getOffset() - current.getTextRange().getStartOffset() - 1; startOffset = localOffset; while(localOffset > 0){ final char cur = text.charAt(localOffset--); if(cur == '}') break; if(cur == '{'){ if(localOffset >= 0 && text.charAt(localOffset) == '$'){ if (startOffset >= text.length() - 1 || text.charAt(startOffset + 1) != '}') { context.editor.getDocument().insertString(caretModel.getOffset(), "}"); } caretModel.moveToOffset(caretModel.getOffset() + 1); } break; } } } } private static class XmlAttributeInsertHandler extends BasicInsertHandler { public XmlAttributeInsertHandler() { } public void handleInsert( CompletionContext context, int startOffset, LookupData data, LookupItem item, boolean signatureSelected, char completionChar) { super.handleInsert(context, startOffset, data, item, signatureSelected, completionChar); final Editor editor = context.editor; final Document document = editor.getDocument(); final int caretOffset = editor.getCaretModel().getOffset(); if (PsiDocumentManager.getInstance(editor.getProject()).getPsiFile(document).getFileType() == StdFileTypes.HTML && HtmlUtil.isSingleHtmlAttribute((String)item.getObject()) ) { return; } final CharSequence chars = document.getCharsSequence(); if (!CharArrayUtil.regionMatches(chars, caretOffset, "=\"") && !CharArrayUtil.regionMatches(chars, caretOffset, "='")) { if("/> \n\t\r".indexOf(document.getCharsSequence().charAt(caretOffset)) < 0) document.insertString(caretOffset, "=\"\" "); else document.insertString(caretOffset, "=\"\""); } editor.getCaretModel().moveToOffset(caretOffset + 2); editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); editor.getSelectionModel().removeSelection(); } } private static class XmlTagInsertHandler extends BasicInsertHandler { public XmlTagInsertHandler() {} public void handleInsert( CompletionContext context, int startOffset, LookupData data, LookupItem item, boolean signatureSelected, char completionChar) { super.handleInsert(context, startOffset, data, item, signatureSelected, completionChar); Project project = context.project; Editor editor = context.editor; // Need to insert " " to prevent creating tags like <tagThis is my text editor.getDocument().insertString(editor.getCaretModel().getOffset(), " "); PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument()); PsiElement current = context.file.findElementAt(context.startOffset); editor.getDocument().deleteString(editor.getCaretModel().getOffset(), editor.getCaretModel().getOffset() + 1); final XmlTag tag = PsiTreeUtil.getContextOfType(current, XmlTag.class, true); if (tag == null) return; final XmlElementDescriptor descriptor = tag.getDescriptor(); if (XmlUtil.getTokenOfType(tag, XmlTokenType.XML_TAG_END) == null && XmlUtil.getTokenOfType(tag, XmlTokenType.XML_EMPTY_ELEMENT_END) == null) { Template t = TemplateManager.getInstance(project).getActiveTemplate(editor); if (t == null && descriptor != null) { insertIncompleteTag(completionChar, editor, project, descriptor, tag); } } else if (completionChar == Lookup.REPLACE_SELECT_CHAR) { PsiDocumentManager.getInstance(project).commitAllDocuments(); int caretOffset = editor.getCaretModel().getOffset(); PsiElement otherTag = PsiTreeUtil.getParentOfType(context.file.findElementAt(caretOffset), getTagClass()); PsiElement endTagStart = getEndTagStart(otherTag); if (endTagStart != null) { PsiElement sibling = endTagStart.getNextSibling(); if (isTagNameToken(sibling)) { int sOffset = sibling.getTextRange().getStartOffset(); int eOffset = sibling.getTextRange().getEndOffset(); editor.getDocument().deleteString(sOffset, eOffset); editor.getDocument().insertString(sOffset, getTagText(otherTag)); } } editor.getCaretModel().moveToOffset(caretOffset + 1); editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); editor.getSelectionModel().removeSelection(); } current = context.file.findElementAt(context.startOffset); if(current.getPrevSibling() instanceof XmlToken){ if(!isClosed(current) && ((XmlToken)current.getPrevSibling()).getTokenType() == XmlTokenType.XML_END_TAG_START){ editor.getDocument().insertString(current.getTextRange().getEndOffset(), ">"); editor.getCaretModel().moveToOffset(editor.getCaretModel().getOffset() + 1); } } } private boolean isClosed(PsiElement current) { PsiElement e = current; while (e != null) { if (e instanceof XmlToken) { XmlToken token = (XmlToken)e; if (token.getTokenType() == XmlTokenType.XML_TAG_END) return true; if (token.getTokenType() == XmlTokenType.XML_EMPTY_ELEMENT_END) return true; } e = e.getNextSibling(); } return false; } private void insertIncompleteTag(char completionChar, Editor editor, Project project, XmlElementDescriptor descriptor, XmlTag tag) { TemplateManager templateManager = TemplateManager.getInstance(project); Template template = templateManager.createTemplate("", ""); template.setToReformat(true); template.setToIndent(true); // temp code FileType fileType = tag.getContainingFile().getFileType(); boolean htmlCode = fileType==StdFileTypes.HTML || fileType==StdFileTypes.XHTML; XmlAttributeDescriptor[] attributes = descriptor.getAttributesDescriptors(); for (XmlAttributeDescriptor attributeDecl : attributes) { String attributeName = attributeDecl.getName(tag); if (attributeDecl.isRequired()) { template.addTextSegment(" " + attributeName + "=\""); Expression expression = new MacroCallNode(MacroFactory.createMacro("complete")); template.addVariable(attributeName, expression, expression, true); template.addTextSegment("\""); } else if (attributeDecl.isFixed() && attributeDecl.getDefaultValue() != null && !htmlCode) { template.addTextSegment(" " + attributeName + "=\"" + attributeDecl.getDefaultValue() + "\""); } } if (completionChar == '>') { template.addTextSegment(">"); template.addEndVariable(); if ( !(tag instanceof HtmlTag) || !HtmlUtil.isSingleHtmlTag(tag.getName()) ) { template.addTextSegment("</"); template.addTextSegment(descriptor.getName(tag)); template.addTextSegment(">"); } } else if (completionChar == '/') { template.addTextSegment("/>"); } templateManager.startTemplate(editor, template); } private Class getTagClass() { return XmlTag.class; } private PsiElement getEndTagStart(PsiElement tag) { return XmlUtil.getTokenOfType(tag, XmlTokenType.XML_END_TAG_START); } private String getTagText(PsiElement tag) { return ((XmlTag)tag).getName(); } private boolean isTagNameToken(PsiElement token) { return ((XmlToken)token).getTokenType() == XmlTokenType.XML_NAME; } } private static class SimpleTagContentEnumerationValuesGetter implements ContextGetter { public Object[] get(final PsiElement context, CompletionContext completionContext) { XmlTag tag = PsiTreeUtil.getParentOfType(context, XmlTag.class, false); XmlElementDescriptor descriptor = tag != null ? tag.getDescriptor() : null; if (descriptor instanceof XmlElementDescriptorImpl) { final TypeDescriptor type = ((XmlElementDescriptorImpl)descriptor).getType(); if (type instanceof ComplexTypeDescriptor) { final XmlTag[] simpleContent = new XmlTag[1]; XmlUtil.processXmlElements(((ComplexTypeDescriptor)type).getDeclaration(),new PsiElementProcessor() { public boolean execute(final PsiElement element) { if (element instanceof XmlTag && ((XmlTag)element).getLocalName().equals("simpleContent") && ((XmlTag)element).getNamespace().equals(XmlUtil.XML_SCHEMA_URI) ) { simpleContent[0] = (XmlTag)element; return false; } return true; } }, true); if (simpleContent[0]!=null) { final HashSet<String> variants = new HashSet<String>(); XmlUtil.collectEnumerationValues(simpleContent[0],variants); if (variants.size() > 0) return variants.toArray(new Object[variants.size()]); } } } return new AllWordsGetter().get(context, completionContext); } } private static class EntityRefGetter implements ContextGetter { public Object[] get(final PsiElement context, CompletionContext completionContext) { final XmlTag parentOfType = PsiTreeUtil.getParentOfType(context, XmlTag.class); if (parentOfType != null) { final XmlElementDescriptor descriptor = parentOfType.getDescriptor(); final List<String> results = new ArrayList<String>(); if (descriptor != null) { final XmlFile descriptorFile = descriptor.getNSDescriptor().getDescriptorFile(); // skip content of embedded dtd, its content will be inserted by word completion if (descriptorFile != null && !descriptorFile.equals(parentOfType.getContainingFile())) { final PsiElementProcessor processor = new PsiElementProcessor() { public boolean execute(final PsiElement element) { if (element instanceof XmlEntityDecl) { final XmlEntityDecl xmlEntityDecl = (XmlEntityDecl)element; if (xmlEntityDecl.isInternalReference()) results.add(xmlEntityDecl.getName()); } return true; } }; XmlUtil.processXmlElements( descriptorFile, processor, true ); return results.toArray(new Object[results.size()]); } } } return new Object[0]; } } private static class EntityRefInsertHandler extends BasicInsertHandler { public void handleInsert(CompletionContext context, int startOffset, LookupData data, LookupItem item, boolean signatureSelected, char completionChar) { super.handleInsert(context, startOffset, data, item, signatureSelected, completionChar); final CaretModel caretModel = context.editor.getCaretModel(); context.editor.getDocument().insertString(caretModel.getOffset(), ";"); caretModel.moveToOffset(caretModel.getOffset() + 1); } } }
NPE fix
source/com/intellij/codeInsight/completion/XmlCompletionData.java
NPE fix
<ide><path>ource/com/intellij/codeInsight/completion/XmlCompletionData.java <ide> editor.getSelectionModel().removeSelection(); <ide> } <ide> current = context.file.findElementAt(context.startOffset); <del> if(current.getPrevSibling() instanceof XmlToken){ <add> if(current != null && current.getPrevSibling() instanceof XmlToken){ <ide> if(!isClosed(current) && ((XmlToken)current.getPrevSibling()).getTokenType() == XmlTokenType.XML_END_TAG_START){ <ide> editor.getDocument().insertString(current.getTextRange().getEndOffset(), ">"); <ide> editor.getCaretModel().moveToOffset(editor.getCaretModel().getOffset() + 1);
Java
mit
3c371050f4f8828a2934d838b727f05bd8ed4ce5
0
LivePersonInc/ephemerals
package com.liveperson.ephemerals.deploy.wait; import com.liveperson.ephemerals.deploy.Deployment; import com.liveperson.ephemerals.deploy.DeploymentStatus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Created by waseemh on 9/16/16. */ public abstract class DeploymentStatusWaiter extends Waiter { protected Deployment deployment; protected DeploymentStatus desiredStatus; private final static Logger logger = LoggerFactory.getLogger(DeploymentStatusWaiter.class); public DeploymentStatusWaiter(Deployment deployment, DeploymentStatus desiredStatus) { this.deployment = deployment; this.desiredStatus = desiredStatus; } public abstract DeploymentStatus getDeploymentStatus(); @Override protected boolean isConditionMet() { try { DeploymentStatus deploymentStatus = getDeploymentStatus(); logger.info("Deployment {} status: {} - desired status: {}",deployment.getId(),deploymentStatus,desiredStatus); return deploymentStatus.equals(desiredStatus); } catch(Exception e) { logger.warn("Unable to fetch deployment status"); return false; } } }
core/src/main/java/com/liveperson/ephemerals/deploy/wait/DeploymentStatusWaiter.java
package com.liveperson.ephemerals.deploy.wait; import com.liveperson.ephemerals.deploy.Deployment; import com.liveperson.ephemerals.deploy.DeploymentStatus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Created by waseemh on 9/16/16. */ public abstract class DeploymentStatusWaiter extends Waiter { protected Deployment deployment; protected DeploymentStatus desiredStatus; private final static Logger logger = LoggerFactory.getLogger(DeploymentStatusWaiter.class); public DeploymentStatusWaiter(Deployment deployment, DeploymentStatus desiredStatus) { this.deployment = deployment; this.desiredStatus = desiredStatus; } public abstract DeploymentStatus getDeploymentStatus(); @Override protected boolean isConditionMet() { DeploymentStatus deploymentStatus = getDeploymentStatus(); logger.info("Deployment {} status: {} - desired status: {}",deployment.getId(),deploymentStatus,desiredStatus); return deploymentStatus.equals(desiredStatus); } }
catch exception when fetching deployment status
core/src/main/java/com/liveperson/ephemerals/deploy/wait/DeploymentStatusWaiter.java
catch exception when fetching deployment status
<ide><path>ore/src/main/java/com/liveperson/ephemerals/deploy/wait/DeploymentStatusWaiter.java <ide> <ide> @Override <ide> protected boolean isConditionMet() { <del> DeploymentStatus deploymentStatus = getDeploymentStatus(); <del> logger.info("Deployment {} status: {} - desired status: {}",deployment.getId(),deploymentStatus,desiredStatus); <del> return deploymentStatus.equals(desiredStatus); <add> try { <add> DeploymentStatus deploymentStatus = getDeploymentStatus(); <add> logger.info("Deployment {} status: {} - desired status: {}",deployment.getId(),deploymentStatus,desiredStatus); <add> return deploymentStatus.equals(desiredStatus); <add> } catch(Exception e) { <add> logger.warn("Unable to fetch deployment status"); <add> return false; <add> } <ide> } <ide> <ide> }
Java
apache-2.0
error: pathspec 'Euler18/Euler18.java' did not match any file(s) known to git
f3d17b4a2242771e540547c6c248632f56dabe66
1
skiller185/Euler
// Anthony Carpenetti // When executed, Euler18 finds the mini-max of the binary tree displayed at https://projecteuler.net/problem=18 import java.util.Arrays; public class Euler18 { public static void main(String[] args) { int[][] data = {{75},{95,64},{17,47,82},{18,35,87,10},{20,4,82,47,65},{19,1,23,75,3,34},{88,2,77,73,7,63,67},{99,65,4,28,6,16,70,92},{41,41,26,56,83,40,80,70,33},{41,48,72,33,47,32,37,16,94,29},{53,71,44,65,25,43,91,52,97,51,14},{70,11,33,28,77,73,17,78,39,68,17,57},{91,71,52,38,17,14,91,43,58,50,27,29,48},{63,66,4,68,89,53,67,30,73,16,69,87,40,31},{4,62,98,27,23,9,70,98,73,93,38,53,60,4,23}}; int[][] workingSet = new int[15][0]; for(int i = 0;i < data.length;i++) { // System.out.print(Arrays.toString(data[i]) + " = "); workingSet[i] = Arrays.copyOf(data[i], data[i].length); // System.out.println(Arrays.toString(workingSet[i])); } for(int i = workingSet.length - 2;i > -1;i--) { for(int j = 0;j < workingSet[i].length;j++) { if(workingSet[i + 1][j] < workingSet[i + 1][j + 1]) { System.out.println(workingSet[i + 1][j] + " < " + workingSet[i + 1][j + 1]); workingSet[i][j] += workingSet[i + 1][j + 1]; } else { System.out.println(workingSet[i + 1][j + 1] + " < " + workingSet[i + 1][j]); workingSet[i][j] += workingSet[i + 1][j]; } } } System.out.println(workingSet[0][0]); } }
Euler18/Euler18.java
upload-euler18
Euler18/Euler18.java
upload-euler18
<ide><path>uler18/Euler18.java <add>// Anthony Carpenetti <add>// When executed, Euler18 finds the mini-max of the binary tree displayed at https://projecteuler.net/problem=18 <add> <add>import java.util.Arrays; <add> <add>public class Euler18 <add>{ <add> public static void main(String[] args) <add> { <add> int[][] data = {{75},{95,64},{17,47,82},{18,35,87,10},{20,4,82,47,65},{19,1,23,75,3,34},{88,2,77,73,7,63,67},{99,65,4,28,6,16,70,92},{41,41,26,56,83,40,80,70,33},{41,48,72,33,47,32,37,16,94,29},{53,71,44,65,25,43,91,52,97,51,14},{70,11,33,28,77,73,17,78,39,68,17,57},{91,71,52,38,17,14,91,43,58,50,27,29,48},{63,66,4,68,89,53,67,30,73,16,69,87,40,31},{4,62,98,27,23,9,70,98,73,93,38,53,60,4,23}}; <add> int[][] workingSet = new int[15][0]; <add> for(int i = 0;i < data.length;i++) <add> { <add> // System.out.print(Arrays.toString(data[i]) + " = "); <add> workingSet[i] = Arrays.copyOf(data[i], data[i].length); <add> // System.out.println(Arrays.toString(workingSet[i])); <add> } <add> for(int i = workingSet.length - 2;i > -1;i--) <add> { <add> for(int j = 0;j < workingSet[i].length;j++) <add> { <add> if(workingSet[i + 1][j] < workingSet[i + 1][j + 1]) <add> { <add> System.out.println(workingSet[i + 1][j] + " < " + workingSet[i + 1][j + 1]); <add> workingSet[i][j] += workingSet[i + 1][j + 1]; <add> } <add> else <add> { <add> System.out.println(workingSet[i + 1][j + 1] + " < " + workingSet[i + 1][j]); <add> workingSet[i][j] += workingSet[i + 1][j]; <add> } <add> } <add> } <add> System.out.println(workingSet[0][0]); <add> } <add>}
JavaScript
mit
4b3def117e5c33d44bdb6d57cb0a7f08121974ae
0
jjohnson338/GrillKeeper
var math = require('mathjs'); var adcinterface = require('./adcinterface'); var temperatureControlerObject = function() { var targetTemperature = 225; var actualTempurature = 0; var GetTargetTemperature = function(){ return targetTemperature; } var SetTargetTemperature = function(newTargetTemp){ targetTemperature = newTargetTemp; } var IncrementTargetTemperature = function() { SetTargetTemperature(++targetTemperature); } var DecrementTargetTemperature = function() { SetTargetTemperature(--targetTemperature); } var GetActualTemperature = function(){ //Run code to determine actual temperature adcinterface.readChannel(0, function(thermValue){ adcinterface.readChannel(1, function(controlValue){ console.log('ThermValue =' + thermValue); console.log('ControlValue =' + controlValue); var controlVoltage = (controlValue * 5.0)/1023; var thermVoltage = (thermValue * 5.0)/1023; var voltageDiff = controlVoltage - thermVoltage; console.log("DiffVoltage =" + voltageDiff); actualTempurature = DiffVoltageToTemp(voltageDiff); console.log("Actual Temperature =" + actualTempurature); }); }); return actualTempurature; } var DiffVoltageToTemp = function(DiffVoltage){ //Constants var ExcitationVoltage = 5.0; var R = 47000; //Resistance of Known Resistors //Stienhart-Hart Coefficients var A = 0.000515942869144762; var B = 0.000172084582161862; var C = 2.38992092042526e-7; //Calculate Resistance of Thermistor var ThermistorResistance = (-2*R)*(((DiffVoltage/ExcitationVoltage)+0.5)/((2*(DiffVoltage/ExcitationVoltage))-1)); //Calculate Temp in Kelvin var TempKelvin = 1/(A+(B*(math.log(ThermistorResistance)))+(C*math.pow(math.log(ThermistorResistance), 3))); console.log('Temp K =' + TempKelvin); //Convert Kelvin to Fahrenheit and return it return ((TempKelvin - 273.15)*1.8)+32; }; return { //Pubic functions GetTargetTemperature: GetTargetTemperature, SetTargetTemperature: SetTargetTemperature, IncrementTargetTemperature: IncrementTargetTemperature, DecrementTargetTemperature: DecrementTargetTemperature, GetActualTemperature: GetActualTemperature } }(); module.exports = temperatureControlerObject;
src/temperatureController.js
var math = require('mathjs'); var adcinterface = require('./adcinterface'); var temperatureControlerObject = function() { var targetTemperature = 225; var actualTempurature = 0; var GetTargetTemperature = function(){ return targetTemperature; } var SetTargetTemperature = function(newTargetTemp){ targetTemperature = newTargetTemp; } var IncrementTargetTemperature = function() { SetTargetTemperature(++targetTemperature); } var DecrementTargetTemperature = function() { SetTargetTemperature(--targetTemperature); } var GetActualTemperature = function(){ //Run code to determine actual temperature adcinterface.readChannel(0, function(thermValue){ adcinterface.readChannel(1, function(controlValue){ console.log('ThermValue =' + thermValue); console.log('ControlValue =' + controlValue); var controlVoltage = (controlValue * 5.0)/1023; var thermVoltage = (thermValue * 5.0)/1023; var voltageDiff = controlVoltage - thermVoltage; console.log("DiffVoltage =" + voltageDiff); actualTempurature = DiffVoltageToTemp(voltageDiff); console.log("Actual Temperature =" + actualTempurature); }); }); return actualTempurature; } var DiffVoltageToTemp = function(DiffVoltage){ //Constants var ExcitationVoltage = 5.0; var R = 47000; //Resistance of Known Resistors //Stienhart-Hart Coefficients var A = 0.000515942869144762; var B = 0.000172084582161862; var C = 2.38992092042526e-7; //Calculate Resistance of Thermistor var ThermistorResistance = (-2*R)*(((DiffVoltage/ExcitationVoltage)+0.5)/((2*(DiffVoltage/ExcitationVoltage))-1)); //Calculate Temp in Kelvin var TempKelvin = 1/(A+(B*(math.log(ThermistorResistance)))+(C*math.pow(math.log(ThermistorResistance), 3))); //Convert Kelvin to Fahrenheit and return it return ((TempKelvin - 273.15)*1.8)+32; }; return { //Pubic functions GetTargetTemperature: GetTargetTemperature, SetTargetTemperature: SetTargetTemperature, IncrementTargetTemperature: IncrementTargetTemperature, DecrementTargetTemperature: DecrementTargetTemperature, GetActualTemperature: GetActualTemperature } }(); module.exports = temperatureControlerObject;
More Debugging info
src/temperatureController.js
More Debugging info
<ide><path>rc/temperatureController.js <ide> <ide> //Calculate Temp in Kelvin <ide> var TempKelvin = 1/(A+(B*(math.log(ThermistorResistance)))+(C*math.pow(math.log(ThermistorResistance), 3))); <del> <add> console.log('Temp K =' + TempKelvin); <ide> //Convert Kelvin to Fahrenheit and return it <ide> return ((TempKelvin - 273.15)*1.8)+32; <ide> };
Java
apache-2.0
cd125ded3b6d10cdd2ab6bbd0135fc3e4e578ece
0
kuujo/onos,kuujo/onos,opennetworkinglab/onos,oplinkoms/onos,oplinkoms/onos,gkatsikas/onos,opennetworkinglab/onos,kuujo/onos,kuujo/onos,gkatsikas/onos,oplinkoms/onos,gkatsikas/onos,kuujo/onos,opennetworkinglab/onos,opennetworkinglab/onos,oplinkoms/onos,opennetworkinglab/onos,kuujo/onos,gkatsikas/onos,gkatsikas/onos,oplinkoms/onos,opennetworkinglab/onos,oplinkoms/onos,oplinkoms/onos,kuujo/onos,gkatsikas/onos
/* * Copyright 2015-present Open Networking Foundation * * 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. * * Originally created by Pengfei Lu, Network and Cloud Computing Laboratory, Dalian University of Technology, China * Advisers: Keqiu Li, Heng Qi and Haisheng Yu * This work is supported by the State Key Program of National Natural Science of China(Grant No. 61432002) * and Prospective Research Project on Future Networks in Jiangsu Future Networks Innovation Institute. */ package org.onosproject.acl; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import org.onlab.packet.IPv4; import org.onlab.packet.Ip4Prefix; import org.onlab.packet.MacAddress; import org.onosproject.rest.AbstractWebResource; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.util.List; import static org.onlab.util.Tools.readTreeFromStream; /** * Manage ACL rules. */ @Path("rules") public class AclWebResource extends AbstractWebResource { /** * Get all ACL rules. * Returns array of all ACL rules. * * @return 200 OK */ @GET public Response queryAclRule() { List<AclRule> rules = get(AclService.class).getAclRules(); ObjectMapper mapper = new ObjectMapper(); ObjectNode root = mapper.createObjectNode(); ArrayNode arrayNode = mapper.createArrayNode(); for (AclRule rule : rules) { ObjectNode node = mapper.createObjectNode(); node.put("id", rule.id().toString()); if (rule.srcMac() != null) { node.put("srcMac", rule.srcMac().toString()); } if (rule.dstMac() != null) { node.put("dstMac", rule.dstMac().toString()); } if (rule.srcIp() != null) { node.put("srcIp", rule.srcIp().toString()); } if (rule.dstIp() != null) { node.put("dstIp", rule.dstIp().toString()); } if (rule.dscp() != 0) { node.put("dscp", rule.dscp()); } if (rule.ipProto() != 0) { switch (rule.ipProto()) { case IPv4.PROTOCOL_ICMP: node.put("ipProto", "ICMP"); break; case IPv4.PROTOCOL_TCP: node.put("ipProto", "TCP"); break; case IPv4.PROTOCOL_UDP: node.put("ipProto", "UDP"); break; default: break; } } if (rule.dstTpPort() != 0) { node.put("dstTpPort", rule.dstTpPort()); } if (rule.srcTpPort() != 0) { node.put("srcTpPort", rule.srcTpPort()); } node.put("action", rule.action().toString()); arrayNode.add(node); } root.set("aclRules", arrayNode); return Response.ok(root.toString(), MediaType.APPLICATION_JSON_TYPE).build(); } /** * Add a new ACL rule. * * @param stream JSON data describing the rule * @return 200 OK * @throws URISyntaxException uri syntax exception */ @POST @Consumes(MediaType.APPLICATION_JSON) public Response addAclRule(InputStream stream) throws URISyntaxException { AclRule newRule = jsonToRule(stream); return get(AclService.class).addAclRule(newRule) ? Response.created(new URI(newRule.id().toString())).build() : Response.serverError().build(); } /** * Remove ACL rule. * * @param id ACL rule id (in hex string format) * @return 204 NO CONTENT */ @DELETE @Path("{id}") public Response removeAclRule(@PathParam("id") String id) { RuleId ruleId = new RuleId(Long.parseLong(id.substring(2), 16)); get(AclService.class).removeAclRule(ruleId); return Response.noContent().build(); } /** * Remove all ACL rules. * * @return 204 NO CONTENT */ @DELETE public Response clearAcl() { get(AclService.class).clearAcl(); return Response.noContent().build(); } /** * Turns a JSON string into an ACL rule instance. */ private AclRule jsonToRule(InputStream stream) { JsonNode node; try { node = readTreeFromStream(mapper(), stream); } catch (IOException e) { throw new IllegalArgumentException("Unable to parse ACL request", e); } AclRule.Builder rule = AclRule.builder(); String s = node.path("srcIp").asText(null); if (s != null) { rule.srcIp(Ip4Prefix.valueOf(s)); } s = node.path("dstIp").asText(null); if (s != null) { rule.dstIp(Ip4Prefix.valueOf(s)); } s = node.path("srcMac").asText(null); if (s != null) { rule.srcMac(MacAddress.valueOf(s)); } s = node.path("dstMac").asText(null); if (s != null) { rule.dstMac(MacAddress.valueOf(s)); } s = node.path("dscp").asText(null); if (s != null) { rule.dscp(Byte.valueOf(s)); } s = node.path("ipProto").asText(null); if (s != null) { if ("TCP".equalsIgnoreCase(s)) { rule.ipProto(IPv4.PROTOCOL_TCP); } else if ("UDP".equalsIgnoreCase(s)) { rule.ipProto(IPv4.PROTOCOL_UDP); } else if ("ICMP".equalsIgnoreCase(s)) { rule.ipProto(IPv4.PROTOCOL_ICMP); } else { throw new IllegalArgumentException("ipProto must be assigned to TCP, UDP, or ICMP"); } } int port = node.path("dstTpPort").asInt(0); if (port > 0) { if ("TCP".equalsIgnoreCase(s) || "UDP".equalsIgnoreCase(s)) { rule.dstTpPort((short) port); } else { throw new IllegalArgumentException("dstTpPort can be set only when ipProto is TCP or UDP"); } } port = node.path("srcTpPort").asInt(0); if (port > 0) { if ("TCP".equalsIgnoreCase(s) || "UDP".equalsIgnoreCase(s)) { rule.srcTpPort((short) port); } else { throw new IllegalArgumentException("srcTpPort can be set only when ipProto is TCP or UDP"); } } s = node.path("action").asText(null); if (s != null) { if ("allow".equalsIgnoreCase(s)) { rule.action(AclRule.Action.ALLOW); } else if ("deny".equalsIgnoreCase(s)) { rule.action(AclRule.Action.DENY); } else { throw new IllegalArgumentException("action must be ALLOW or DENY"); } } return rule.build(); } }
apps/acl/src/main/java/org/onosproject/acl/AclWebResource.java
/* * Copyright 2015-present Open Networking Foundation * * 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. * * Originally created by Pengfei Lu, Network and Cloud Computing Laboratory, Dalian University of Technology, China * Advisers: Keqiu Li, Heng Qi and Haisheng Yu * This work is supported by the State Key Program of National Natural Science of China(Grant No. 61432002) * and Prospective Research Project on Future Networks in Jiangsu Future Networks Innovation Institute. */ package org.onosproject.acl; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import org.onlab.packet.IPv4; import org.onlab.packet.Ip4Prefix; import org.onlab.packet.MacAddress; import org.onosproject.rest.AbstractWebResource; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.util.List; import static org.onlab.util.Tools.readTreeFromStream; /** * Manage ACL rules. */ @Path("rules") public class AclWebResource extends AbstractWebResource { /** * Get all ACL rules. * Returns array of all ACL rules. * * @return 200 OK */ @GET public Response queryAclRule() { List<AclRule> rules = get(AclService.class).getAclRules(); ObjectMapper mapper = new ObjectMapper(); ObjectNode root = mapper.createObjectNode(); ArrayNode arrayNode = mapper.createArrayNode(); for (AclRule rule : rules) { ObjectNode node = mapper.createObjectNode(); node.put("id", rule.id().toString()); if (rule.srcMac() != null) { node.put("srcMac", rule.srcMac().toString()); } if (rule.dstMac() != null) { node.put("dstMac", rule.dstMac().toString()); } if (rule.srcIp() != null) { node.put("srcIp", rule.srcIp().toString()); } if (rule.dstIp() != null) { node.put("dstIp", rule.dstIp().toString()); } if (rule.dscp() != 0) { node.put("dscp", rule.dscp()); } if (rule.ipProto() != 0) { switch (rule.ipProto()) { case IPv4.PROTOCOL_ICMP: node.put("ipProto", "ICMP"); break; case IPv4.PROTOCOL_TCP: node.put("ipProto", "TCP"); break; case IPv4.PROTOCOL_UDP: node.put("ipProto", "UDP"); break; default: break; } } if (rule.dstTpPort() != 0) { node.put("dstTpPort", rule.dstTpPort()); } if (rule.srcTpPort() != 0) { node.put("srcTpPort", rule.srcTpPort()); } node.put("action", rule.action().toString()); arrayNode.add(node); } root.set("aclRules", arrayNode); return Response.ok(root.toString(), MediaType.APPLICATION_JSON_TYPE).build(); } /** * Add a new ACL rule. * * @param stream JSON data describing the rule * @return 200 OK * @throws URISyntaxException uri syntax exception */ @POST @Consumes(MediaType.APPLICATION_JSON) public Response addAclRule(InputStream stream) throws URISyntaxException { AclRule newRule = jsonToRule(stream); return get(AclService.class).addAclRule(newRule) ? Response.created(new URI(newRule.id().toString())).build() : Response.serverError().build(); } /** * Remove ACL rule. * * @param id ACL rule id (in hex string format) * @return 204 NO CONTENT */ @DELETE @Path("{id}") public Response removeAclRule(@PathParam("id") String id) { RuleId ruleId = new RuleId(Long.parseLong(id.substring(2), 16)); get(AclService.class).removeAclRule(ruleId); return Response.noContent().build(); } /** * Remove all ACL rules. * * @return 204 NO CONTENT */ @DELETE public Response clearAcl() { get(AclService.class).clearAcl(); return Response.noContent().build(); } /** * Turns a JSON string into an ACL rule instance. */ private AclRule jsonToRule(InputStream stream) { JsonNode node; try { node = readTreeFromStream(mapper(), stream); } catch (IOException e) { throw new IllegalArgumentException("Unable to parse ACL request", e); } AclRule.Builder rule = AclRule.builder(); String s = node.path("srcIp").asText(null); if (s != null) { rule.srcIp(Ip4Prefix.valueOf(s)); } s = node.path("dstIp").asText(null); if (s != null) { rule.dstIp(Ip4Prefix.valueOf(s)); } s = node.path("srcMac").asText(null); if (s != null) { rule.srcMac(MacAddress.valueOf(s)); } s = node.path("dstMac").asText(null); if (s != null) { rule.dstMac(MacAddress.valueOf(s)); } s = node.path("dscp").asText(null); if (s != null) { rule.dscp(Byte.valueOf(s)); } s = node.path("ipProto").asText(null); if (s != null) { if ("TCP".equalsIgnoreCase(s)) { rule.ipProto(IPv4.PROTOCOL_TCP); } else if ("UDP".equalsIgnoreCase(s)) { rule.ipProto(IPv4.PROTOCOL_UDP); } else if ("ICMP".equalsIgnoreCase(s)) { rule.ipProto(IPv4.PROTOCOL_ICMP); } else { throw new IllegalArgumentException("ipProto must be assigned to TCP, UDP, or ICMP"); } } int port = node.path("dstTpPort").asInt(0); if (port > 0) { rule.dstTpPort((short) port); } port = node.path("srcTpPort").asInt(0); if (port > 0) { rule.srcTpPort((short) port); } s = node.path("action").asText(null); if (s != null) { if ("allow".equalsIgnoreCase(s)) { rule.action(AclRule.Action.ALLOW); } else if ("deny".equalsIgnoreCase(s)) { rule.action(AclRule.Action.DENY); } else { throw new IllegalArgumentException("action must be ALLOW or DENY"); } } return rule.build(); } }
ACL Input param validation for L4 port Change-Id: I5862aab56404afaf4d36e982a0259a498fdab216
apps/acl/src/main/java/org/onosproject/acl/AclWebResource.java
ACL Input param validation for L4 port
<ide><path>pps/acl/src/main/java/org/onosproject/acl/AclWebResource.java <ide> <ide> int port = node.path("dstTpPort").asInt(0); <ide> if (port > 0) { <del> rule.dstTpPort((short) port); <add> if ("TCP".equalsIgnoreCase(s) || "UDP".equalsIgnoreCase(s)) { <add> rule.dstTpPort((short) port); <add> } else { <add> throw new IllegalArgumentException("dstTpPort can be set only when ipProto is TCP or UDP"); <add> } <ide> } <ide> <ide> port = node.path("srcTpPort").asInt(0); <ide> if (port > 0) { <del> rule.srcTpPort((short) port); <add> if ("TCP".equalsIgnoreCase(s) || "UDP".equalsIgnoreCase(s)) { <add> rule.srcTpPort((short) port); <add> } else { <add> throw new IllegalArgumentException("srcTpPort can be set only when ipProto is TCP or UDP"); <add> } <ide> } <ide> <ide> s = node.path("action").asText(null);
JavaScript
mit
2e9abde9112807237223bb25a08bdbec6b05093e
0
Hivebeat/LoginSignup,Hivebeat/LoginSignup
module.exports = require('./src/scripts/components/LoginSignup.react');
index.js
module.exports = require('./src/scripts/components/LoginSignup');
move ref
index.js
move ref
<ide><path>ndex.js <del>module.exports = require('./src/scripts/components/LoginSignup'); <add>module.exports = require('./src/scripts/components/LoginSignup.react');
Java
bsd-2-clause
a7eed0552d5ec894b3244e14d42a887d56a87260
0
develoken/p4-plugin,Palmr/p4-plugin,rpocase/p4-plugin,Palmr/p4-plugin,develoken/p4-plugin,rpocase/p4-plugin,jenkinsci/p4-plugin,jenkinsci/p4-plugin,tanium/p4-plugin,tanium/p4-plugin,Palmr/p4-plugin,jenkinsci/p4-plugin,tanium/p4-plugin,rpocase/p4-plugin,develoken/p4-plugin
package org.jenkinsci.plugins.p4.asset; import hudson.EnvVars; import hudson.Extension; import hudson.Launcher; import hudson.model.BuildListener; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.security.ACL; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.BuildStepMonitor; import hudson.tasks.Notifier; import hudson.tasks.Publisher; import hudson.util.ListBoxModel; import java.io.IOException; import java.util.List; import java.util.logging.Logger; import jenkins.model.Jenkins; import org.acegisecurity.Authentication; import org.jenkinsci.plugins.p4.client.ClientHelper; import org.jenkinsci.plugins.p4.client.ConnectionHelper; import org.jenkinsci.plugins.p4.credentials.P4StandardCredentials; import org.jenkinsci.plugins.p4.publish.Publish; import org.jenkinsci.plugins.p4.workspace.Workspace; import org.kohsuke.stapler.DataBoundConstructor; import com.cloudbees.plugins.credentials.CredentialsProvider; import com.cloudbees.plugins.credentials.domains.DomainRequirement; public class AssetNotifier extends Notifier { private static Logger logger = Logger.getLogger(AssetNotifier.class .getName()); private final String credential; private final Workspace workspace; private final Publish publish; public String getCredential() { return credential; } public Workspace getWorkspace() { return workspace; } public Publish getPublish() { return publish; } @DataBoundConstructor public AssetNotifier(String credential, Workspace workspace, Publish publish) { this.credential = credential; this.workspace = workspace; this.publish = publish; } public BuildStepMonitor getRequiredMonitorService() { return BuildStepMonitor.NONE; } @Override public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException { // open connection to Perforce P4StandardCredentials cdt; cdt = ConnectionHelper.findCredential(credential); Workspace ws = (Workspace) workspace.clone(); try { EnvVars envVars = build.getEnvironment(listener); ws.clear(); ws.load(envVars); String desc = publish.getDescription(); desc = ws.expand(desc, false); publish.setExpandedDesc(desc); } catch (IOException e) { e.printStackTrace(); } String client = ws.getFullName(); ClientHelper p4 = new ClientHelper(cdt, listener, client); // test server connection try { if (!p4.isConnected()) { p4.log("P4: Server connection error:" + cdt.getP4port()); return false; } p4.log("Connected to server: " + cdt.getP4port()); // test client connection if (p4.getClient() == null) { p4.log("P4: Client unknown: " + client); return false; } p4.log("Connected to client: " + client); boolean open = p4.buildChange(); if (open) { p4.publishChange(publish); } } catch (Exception e) { String msg = "Unable to update workspace: " + e; logger.warning(msg); throw new InterruptedException(msg); } finally { p4.disconnect(); } return true; } public static DescriptorImpl descriptor() { return Jenkins.getInstance().getDescriptorByType( AssetNotifier.DescriptorImpl.class); } @Extension public static final class DescriptorImpl extends BuildStepDescriptor<Publisher> { @Override public boolean isApplicable(Class<? extends AbstractProject> jobType) { return true; } @Override public String getDisplayName() { return "Perforce: Publish assets"; } /** * Credentials list, a Jelly config method for a build job. * * @return A list of Perforce credential items to populate the jelly * Select list. */ public ListBoxModel doFillCredentialItems() { ListBoxModel list = new ListBoxModel(); Class<P4StandardCredentials> type = P4StandardCredentials.class; Jenkins scope = Jenkins.getInstance(); Authentication acl = ACL.SYSTEM; DomainRequirement domain = new DomainRequirement(); List<P4StandardCredentials> credentials; credentials = CredentialsProvider.lookupCredentials(type, scope, acl, domain); if (credentials.isEmpty()) { list.add("Select credential...", null); } for (P4StandardCredentials c : credentials) { StringBuffer sb = new StringBuffer(); sb.append(c.getDescription()); sb.append(" ("); sb.append(c.getUsername()); sb.append(":"); sb.append(c.getP4port()); sb.append(")"); list.add(sb.toString(), c.getId()); } return list; } } }
src/main/java/org/jenkinsci/plugins/p4/asset/AssetNotifier.java
package org.jenkinsci.plugins.p4.asset; import hudson.EnvVars; import hudson.Extension; import hudson.Launcher; import hudson.model.BuildListener; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.security.ACL; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.BuildStepMonitor; import hudson.tasks.Notifier; import hudson.tasks.Publisher; import hudson.util.ListBoxModel; import java.io.IOException; import java.util.List; import java.util.logging.Logger; import jenkins.model.Jenkins; import org.acegisecurity.Authentication; import org.jenkinsci.plugins.p4.client.ClientHelper; import org.jenkinsci.plugins.p4.client.ConnectionHelper; import org.jenkinsci.plugins.p4.credentials.P4StandardCredentials; import org.jenkinsci.plugins.p4.publish.Publish; import org.jenkinsci.plugins.p4.workspace.Workspace; import org.kohsuke.stapler.DataBoundConstructor; import com.cloudbees.plugins.credentials.CredentialsProvider; import com.cloudbees.plugins.credentials.domains.DomainRequirement; public class AssetNotifier extends Notifier { private static Logger logger = Logger.getLogger(AssetNotifier.class .getName()); private final String credential; private final Workspace workspace; private final Publish publish; public String getCredential() { return credential; } public Workspace getWorkspace() { return workspace; } public Publish getPublish() { return publish; } @DataBoundConstructor public AssetNotifier(String credential, Workspace workspace, Publish publish) { this.credential = credential; this.workspace = workspace; this.publish = publish; } public BuildStepMonitor getRequiredMonitorService() { return BuildStepMonitor.NONE; } @Override public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException { // open connection to Perforce P4StandardCredentials cdt; cdt = ConnectionHelper.findCredential(credential); Workspace ws = (Workspace) workspace.clone(); try { EnvVars envVars = build.getEnvironment(listener); ws.clear(); ws.load(envVars); String desc = publish.getDescription(); desc = ws.expand(desc, false); publish.setExpandedDesc(desc); } catch (IOException e) { e.printStackTrace(); } String client = ws.getFullName(); ClientHelper p4 = new ClientHelper(cdt, listener, client); // test server connection try { if (!p4.isConnected()) { p4.log("P4: Server connection error:" + cdt.getP4port()); return false; } p4.log("Connected to server: " + cdt.getP4port()); // test client connection if (p4.getClient() == null) { p4.log("P4: Client unknown: " + client); return false; } p4.log("Connected to client: " + client); boolean open = p4.buildChange(); if (open) { p4.publishChange(publish); } } catch (Exception e) { String msg = "Unable to update workspace: " + e; logger.warning(msg); throw new InterruptedException(msg); } finally { p4.disconnect(); } return true; } public static DescriptorImpl descriptor() { return Jenkins.getInstance().getDescriptorByType( AssetNotifier.DescriptorImpl.class); } @Extension public static final class DescriptorImpl extends BuildStepDescriptor<Publisher> { @Override public boolean isApplicable(Class<? extends AbstractProject> jobType) { return true; } @Override public String getDisplayName() { return "Perforce: publish assets"; } /** * Credentials list, a Jelly config method for a build job. * * @return A list of Perforce credential items to populate the jelly * Select list. */ public ListBoxModel doFillCredentialItems() { ListBoxModel list = new ListBoxModel(); Class<P4StandardCredentials> type = P4StandardCredentials.class; Jenkins scope = Jenkins.getInstance(); Authentication acl = ACL.SYSTEM; DomainRequirement domain = new DomainRequirement(); List<P4StandardCredentials> credentials; credentials = CredentialsProvider.lookupCredentials(type, scope, acl, domain); if (credentials.isEmpty()) { list.add("Select credential...", null); } for (P4StandardCredentials c : credentials) { StringBuffer sb = new StringBuffer(); sb.append(c.getDescription()); sb.append(" ("); sb.append(c.getUsername()); sb.append(":"); sb.append(c.getP4port()); sb.append(")"); list.add(sb.toString(), c.getId()); } return list; } } }
Update AssetNotifier.java
src/main/java/org/jenkinsci/plugins/p4/asset/AssetNotifier.java
Update AssetNotifier.java
<ide><path>rc/main/java/org/jenkinsci/plugins/p4/asset/AssetNotifier.java <ide> <ide> @Override <ide> public String getDisplayName() { <del> return "Perforce: publish assets"; <add> return "Perforce: Publish assets"; <ide> } <ide> <ide> /**
Java
mit
356b956cf7e050184df9058e9d7f1bd62ab38280
0
infsci2560sp16/full-stack-web-project-mansouralsaleh,infsci2560sp16/full-stack-web-project-mansouralsaleh,infsci2560sp16/full-stack-web-project-mansouralsaleh,infsci2560sp16/full-stack-web-project-mansouralsaleh
package Services; import java.util.*; public class BooksService { private static HashMap<String, String[]> books = new HashMap<>(); private String[] BooksIDs = {"00001", "00002"}; private String[] BooksNames = {"Engineering Psychology and Human Performance", "Some Book"}; private String[] BooksAuthors = {"Christopher D. Wickens , Justin G. Hollands, Simon Banbury, Raja Parasuraman", "Many Authors"}; private String[] BooksCondition = {"New", "Used - Very Good"}; private String[] BooksUniversity = {"University of Pittsburgh", "CMU"}; private String[] BooksSchool = {"School of Information Science", "CS"}; private String[] BooksDescription = {"Forming connections between human performance and design Engineering Psychology and Human" + " Performance, 4e examines human-machine interaction. The book is organized directly from the psychological " + "perspective of human information processing. The chapters generally correspond to the flow of information as it is " + "processed by a human being--from the senses, through the brain, to action--rather than from the perspective of " + "system components or engineering design concepts. This book is ideal for a psychology student, engineering student, " + "or actual practitioner in engineering psychology, human performance, and human factors Learning Goals Upon " + "completing this book, readers should be able to: * Identify how human ability contributes to the design of " + "technology. * Understand the connections within human information processing and human performance. * Challenge the" + " way they think about technology's influence on human performance. * show how theoretical advances have been, or " + "might be, applied to improving human-machine interaction", "Test Description"}; private String[] BooksISBN13 = {"978-0205021987", "111-2233445566"}; private String[] BooksISBN10 = {"0205021980", "1122334455"}; private String[] BooksImages = {"book1.jpg", "Book.JPG"}; public HashMap<String, String[]> getAllBooks(){ int length = BooksIDs.length; length = length+5; for (int i = 0; i < length; i++) { if(i<2){ books.put(BooksIDs[0],new String[] {BooksNames[0], BooksAuthors[0], BooksCondition[0], BooksUniversity[0], BooksSchool[0], BooksDescription[0], BooksISBN13[0], BooksISBN10[0], BooksImages[0]}); }else{ books.put(BooksIDs[1],new String[] {BooksNames[1], BooksAuthors[1], BooksCondition[1], BooksUniversity[1], BooksSchool[1], BooksDescription[1], BooksISBN13[1], BooksISBN10[1], BooksImages[1]}); } i++; } return books; } }
src/main/java/Services/BooksService.java
package Services; import java.util.*; public class BooksService { private static HashMap<String, String[]> books = new HashMap<>(); private String[] BooksIDs = {"00001", "00002"}; private String[] BooksNames = {"Engineering Psychology and Human Performance", "Some Book"}; private String[] BooksAuthors = {"Christopher D. Wickens , Justin G. Hollands, Simon Banbury, Raja Parasuraman", "Many Authors"}; private String[] BooksCondition = {"New", "Used - Very Good"}; private String[] BooksUniversity = {"University of Pittsburgh", "CMU"}; private String[] BooksSchool = {"School of Information Science", "CS"}; private String[] BooksDescription = {"Forming connections between human performance and design Engineering Psychology and Human" + " Performance, 4e examines human-machine interaction. The book is organized directly from the psychological " + "perspective of human information processing. The chapters generally correspond to the flow of information as it is " + "processed by a human being--from the senses, through the brain, to action--rather than from the perspective of " + "system components or engineering design concepts. This book is ideal for a psychology student, engineering student, " + "or actual practitioner in engineering psychology, human performance, and human factors Learning Goals Upon " + "completing this book, readers should be able to: * Identify how human ability contributes to the design of " + "technology. * Understand the connections within human information processing and human performance. * Challenge the" + " way they think about technology's influence on human performance. * show how theoretical advances have been, or " + "might be, applied to improving human-machine interaction", "Test Description"}; private String[] BooksISBN13 = {"978-0205021987", "111-2233445566"}; private String[] BooksISBN10 = {"0205021980", "1122334455"}; private String[] BooksImages = {"book1.jpg", "Book.JPG"}; public HashMap<String, String[]> getAllBooks(){ int length = BooksIDs.length(); length = length+5; for (int i = 0; i < length; i++) { if(i<2){ books.put(BooksIDs[0],new String[] {BooksNames[0], BooksAuthors[0], BooksCondition[0], BooksUniversity[0], BooksSchool[0], BooksDescription[0], BooksISBN13[0], BooksISBN10[0], BooksImages[0]}); }else{ books.put(BooksIDs[1],new String[] {BooksNames[1], BooksAuthors[1], BooksCondition[1], BooksUniversity[1], BooksSchool[1], BooksDescription[1], BooksISBN13[1], BooksISBN10[1], BooksImages[1]}); } i++; } return books; } }
Added service
src/main/java/Services/BooksService.java
Added service
<ide><path>rc/main/java/Services/BooksService.java <ide> private String[] BooksImages = {"book1.jpg", "Book.JPG"}; <ide> <ide> public HashMap<String, String[]> getAllBooks(){ <del> int length = BooksIDs.length(); <add> int length = BooksIDs.length; <ide> length = length+5; <ide> for (int i = 0; i < length; i++) { <ide> if(i<2){
Java
apache-2.0
20793849d3f11ba8787d8f8da3f383e61a9682d7
0
researchstudio-sat/webofneeds,researchstudio-sat/webofneeds,researchstudio-sat/webofneeds,researchstudio-sat/webofneeds,researchstudio-sat/webofneeds,researchstudio-sat/webofneeds,researchstudio-sat/webofneeds
/* * Copyright 2012 Research Studios Austria Forschungsges.m.b.H. * * 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 won.protocol.vocabulary; import org.apache.jena.rdf.model.Model; import org.apache.jena.rdf.model.ModelFactory; import org.apache.jena.rdf.model.Property; import org.apache.jena.rdf.model.Resource; import won.protocol.model.ConnectionState; import won.protocol.model.NeedState; /** * WoN Vocabulary */ public class WON { public static final String BASE_URI = "http://purl.org/webofneeds/model#"; private static Model m = ModelFactory.createDefaultModel(); public static final Resource NEED = m.createResource(BASE_URI + "Need"); public static final Property HAS_WON_NODE = m.createProperty(BASE_URI, "hasWonNode"); public static final Property HAS_DEFAULT_GRAPH_SIGNING_METHOD = m.createProperty(BASE_URI, "hasDefaultGraphSigningMethod"); public static final Property HAS_NEED_PROTOCOL_ENDPOINT = m.createProperty(BASE_URI, "hasNeedProtocolEndpoint"); public static final Property HAS_MATCHER_PROTOCOL_ENDPOINT = m.createProperty(BASE_URI, "hasMatcherProtocolEndpoint"); public static final Property HAS_OWNER_PROTOCOL_ENDPOINT = m.createProperty(BASE_URI, "hasOwnerProtocolEndpoint"); public static final Property HAS_ACTIVEMQ_NEED_PROTOCOL_QUEUE_NAME = m.createProperty(BASE_URI, "hasActiveMQNeedProtocolQueueName"); public static final Property HAS_ACTIVEMQ_OWNER_PROTOCOL_QUEUE_NAME = m.createProperty(BASE_URI, "hasActiveMQOwnerProtocolQueueName"); public static final Property HAS_ACTIVEMQ_MATCHER_PROTOCOL_QUEUE_NAME = m.createProperty(BASE_URI, "hasActiveMQMatcherProtocolQueueName"); public static final Property HAS_ACTIVEMQ_MATCHER_PROTOCOL_OUT_NEED_CREATED_TOPIC_NAME = m.createProperty(BASE_URI, "hasActiveMQMatcherProtocolOutNeedCreatedTopicName"); public static final Property HAS_ACTIVEMQ_MATCHER_PROTOCOL_OUT_NEED_ACTIVATED_TOPIC_NAME = m.createProperty(BASE_URI, "hasActiveMQMatcherProtocolOutNeedActivatedTopicName"); public static final Property HAS_ACTIVEMQ_MATCHER_PROTOCOL_OUT_NEED_DEACTIVATED_TOPIC_NAME = m.createProperty(BASE_URI, "hasActiveMQMatcherProtocolOutNeedDeactivatedTopicName"); public static final Property HAS_ACTIVEMQ_MATCHER_PROTOCOL_OUT_MATCHER_REGISTERED_TOPIC_NAME = m.createProperty (BASE_URI, "hasActiveMQMatcherProtocolOutMatcherRegisteredTopicName"); public static final Property HAS_URI_PATTERN_SPECIFICATION = m.createProperty(BASE_URI, "hasUriPrefixSpecification"); public static final Property HAS_NEED_URI_PREFIX = m.createProperty(BASE_URI, "hasNeedUriPrefix"); public static final Property HAS_CONNECTION_URI_PREFIX = m.createProperty(BASE_URI, "hasConnectionUriPrefix"); public static final Property HAS_EVENT_URI_PREFIX = m.createProperty(BASE_URI, "hasEventUriPrefix"); public static final Property HAS_NEED_LIST = m.createProperty(BASE_URI, "hasNeedList"); public static final Property EMBED_SPIN_ASK = m.createProperty(BASE_URI, "embedSpinAsk"); public static final Property SUPPORTS_WON_PROTOCOL_IMPL = m.createProperty(BASE_URI + "supportsWonProtocolImpl"); public static final Resource WON_OVER_ACTIVE_MQ = m.createResource(BASE_URI + "WonOverActiveMq"); public static final Property HAS_BROKER_URI = m.createProperty(BASE_URI, "hasBrokerUri"); public static final Resource WON_OVER_SOAP_WS = m.createResource(BASE_URI + "WonOverSoapWs"); public static final Property IS_IN_STATE = m.createProperty(BASE_URI, "isInState"); public static final Property HAS_CONTENT_GRAPH = m.createProperty(BASE_URI, "hasContentGraph"); public static final Property HAS_DERIVED_GRAPH = m.createProperty(BASE_URI, "hasDerivedGraph"); public static final Property HAS_TEXT_MESSAGE = m.createProperty(BASE_URI + "hasTextMessage"); public static final Property IS_PROCESSING = m.createProperty(BASE_URI + "isProcessing"); public static final Resource MESSAGE = m.createResource(BASE_URI + "Message"); public static final Property HAS_FEEDBACK = m.createProperty(BASE_URI, "hasFeedback"); public static final Property HAS_FEEDBACK_EVENT = m.createProperty(BASE_URI, "hasFeedbackEvent"); //used to express which URI the feedback relates to public static final Property FOR_RESOURCE = m.createProperty(BASE_URI, "forResource"); public static final Property HAS_BINARY_RATING = m.createProperty(BASE_URI, "hasBinaryRating"); public static final Resource GOOD = m.createResource(BASE_URI + "Good"); public static final Resource BAD = m.createResource(BASE_URI + "Bad"); public static final Property HAS_TAG = m.createProperty(BASE_URI, "hasTag"); public static final Property HAS_ATTACHED_MEDIA = m.createProperty(BASE_URI, "hasAttachedMedia"); public static final Property HAS_HEIGHT = m.createProperty(BASE_URI, "hasHeight"); public static final Property HAS_DEPTH = m.createProperty(BASE_URI, "hasDepth"); public static final Property HAS_WIDTH = m.createProperty(BASE_URI, "hasWidth"); public static final Property HAS_WEIGHT = m.createProperty(BASE_URI, "hasWeight"); public static final Property HAS_QUANTITATIVE_PROPERTY = m.createProperty(BASE_URI, "hasQuantitativeProperty"); public static final Property HAS_FACET = m.createProperty(BASE_URI, "hasFacet"); public static final Property HAS_DEFAULT_FACET = m.createProperty(BASE_URI, "hasDefaultFacet"); public static final Resource FACET = m.createResource(BASE_URI + "Facet"); //This property is used in the rdf-model part of connect (from owner) and hint //to specify a facet to which a connection is created public static final Property HAS_REMOTE_FACET = m.createProperty(BASE_URI + "hasRemoteFacet"); public static final Property HAS_CONNECTIONS = m.createProperty(BASE_URI, "hasConnections"); public static final Resource CONNECTION_CONTAINER = m.createResource(BASE_URI + "ConnectionContainer"); public static final Resource CONNECTION = m.createResource(BASE_URI + "Connection"); public static final Property HAS_CONNECTION_STATE = m.createProperty(BASE_URI, "hasConnectionState"); public static final Property HAS_REMOTE_CONNECTION = m.createProperty(BASE_URI, "hasRemoteConnection"); public static final Property HAS_REMOTE_NEED = m.createProperty(BASE_URI, "hasRemoteNeed"); public static final Property BELONGS_TO_NEED = m.createProperty(BASE_URI, "belongsToNeed"); public static final Property HAS_EVENT_CONTAINER = m.createProperty(BASE_URI, "hasEventContainer"); public static final Resource EVENT_CONTAINER = m.createResource(BASE_URI + "EventContainer"); public static final Property HAS_TIME_STAMP = m.createProperty(BASE_URI, "hasTimeStamp"); public static final Property HAS_ORIGINATOR = m.createProperty(BASE_URI, "hasOriginator"); public static final Property HAS_ADDITIONAL_DATA = m.createProperty(BASE_URI, "hasAdditionalData"); public static final Resource ADDITIONAL_DATA_CONTAINER = m.createResource(BASE_URI + "AdditionalDataContainer"); public static final Property HAS_MATCH_SCORE = m.createProperty(BASE_URI, "hasMatchScore"); public static final Property HAS_MATCH_COUNTERPART = m.createProperty(BASE_URI, "hasMatchCounterpart"); public static final Property SEEKS = m.createProperty(BASE_URI, "seeks"); public static final Property GOAL = m.createProperty(BASE_URI, "goal"); public static final Property HAS_SHAPES_GRAPH = m.createProperty(BASE_URI, "hasShapesGraph"); public static final Property HAS_DATA_GRAPH = m.createProperty(BASE_URI, "hasDataGraph"); public static final Property HAS_NEED_MODALITY = m.createProperty(BASE_URI, "hasNeedModality"); public static final Resource NEED_MODALITY = m.createResource(BASE_URI + "NeedModality"); public static final Property HAS_PRICE_SPECIFICATION = m.createProperty(BASE_URI, "hasPriceSpecification"); public static final Resource PRICE_SPECIFICATION = m.createResource(BASE_URI + "PriceSpecification"); public static final Property HAS_LOWER_PRICE_LIMIT = m.createProperty(BASE_URI, "hasLowerPriceLimit"); public static final Property HAS_UPPER_PRICE_LIMIT = m.createProperty(BASE_URI, "hasUpperPriceLimit"); public static final Property HAS_CURRENCY = m.createProperty(BASE_URI, "hasCurrency"); public static final Property HAS_LOCATION = m.createProperty(BASE_URI, "hasLocation"); public static final Property HAS_BOUNDING_BOX = m.createProperty(BASE_URI, "hasBoundingBox"); public static final Property HAS_NORTH_WEST_CORNER = m.createProperty(BASE_URI, "hasNorthWestCorner"); public static final Property HAS_SOUTH_EAST_CORNER = m.createProperty(BASE_URI, "hasSouthEastCorner"); public static final Property HAS_BOUNDS_NORTH_WEST = m.createProperty(BASE_URI, "hasBoundsNorthWest"); public static final Property HAS_BOUNDS_SOUTH_EAST = m.createProperty(BASE_URI, "hasBoundsSouthEast"); public static final Resource LOCATION_SPECIFICATION = m.createResource(BASE_URI + "Location"); public static final Property GEO_SPATIAL = m.createProperty(BASE_URI + "geoSpatial"); public static final Property IS_CONCEALED = m.createProperty(BASE_URI, "isConcealed"); public static final Resource REGION = m.createResource(BASE_URI + "Region"); public static final Property HAS_ISO_CODE = m.createProperty(BASE_URI, "hasISOCode"); public static final Property HAS_TIME_SPECIFICATION = m.createProperty(BASE_URI, "hasTimeSpecification"); public static final Resource TIME_SPECIFICATION = m.createResource(BASE_URI + "TimeSpecification"); public static final Property HAS_START_TIME = m.createProperty(BASE_URI, "hasStartTime"); public static final Property HAS_END_TIME = m.createProperty(BASE_URI, "hasEndTime"); public static final Property HAS_RECURS_IN = m.createProperty(BASE_URI, "hasRecursIn"); public static final Property HAS_RECURS_TIMES = m.createProperty(BASE_URI, "hasRecursTimes"); public static final Property HAS_RECUR_INFINITE_TIMES = m.createProperty(BASE_URI, "hasRecurInfiniteTimes"); // Resource individuals public static final Resource NEED_STATE_ACTIVE = m.createResource(NeedState.ACTIVE.getURI().toString()); public static final Resource NEED_STATE_INACTIVE = m.createResource(NeedState.INACTIVE.getURI().toString()); public static final Resource CONNECTION_STATE_SUGGESTED = m.createResource(ConnectionState.SUGGESTED.getURI().toString()); public static final Resource CONNECTION_STATE_REQUEST_SENT = m.createResource(ConnectionState.REQUEST_SENT.getURI().toString()); public static final Resource CONNECTION_STATE_REQUEST_RECEIVED = m.createResource(ConnectionState.REQUEST_RECEIVED.getURI().toString()); public static final Resource CONNECTION_STATE_CONNECTED = m.createResource(ConnectionState.CONNECTED.getURI().toString()); public static final Resource CONNECTION_STATE_CLOSED = m.createResource(ConnectionState.CLOSED.getURI().toString()); public static final Property HAS_SUGGESTED_COUNT = m.createProperty(BASE_URI, "hasSuggestedCount"); public static final Property HAS_REQUEST_RECEIVED_COUNT = m.createProperty(BASE_URI, "hasRequestReceivedCount"); public static final Property HAS_REQUEST_SENT_COUNT = m.createProperty(BASE_URI, "hasRequestSentCount"); public static final Property HAS_CONNECTED_COUNT = m.createProperty(BASE_URI, "hasConnectedCount"); public static final Property HAS_CLOSED_COUNT = m.createProperty(BASE_URI, "hasClosedCount"); //adds a flag to a need public static final Property HAS_FLAG = m.createProperty(BASE_URI + "hasFlag"); public static final Property DO_NOT_MATCH_BEFORE = m.createProperty(BASE_URI + "doNotMatchBefore"); public static final Property DO_NOT_MATCH_AFTER = m.createProperty(BASE_URI + "doNotMatchAfter"); //the usedForTesting flag: need is not a real need, only match with other needs flagged with usedForTesting public static final Resource USED_FOR_TESTING = m.createResource(BASE_URI + "UsedForTesting"); public static final Resource WHATS_AROUND = m.createResource(BASE_URI + "WhatsAround"); public static final Resource WHATS_NEW = m.createResource(BASE_URI + "WhatsNew"); // hint behaviour public static final Resource NO_HINT_FOR_COUNTERPART = m.createResource(BASE_URI + "NoHintForCounterpart"); public static final Resource NO_HINT_FOR_ME = m.createResource(BASE_URI + "NoHintForMe"); public static final Property HAS_MATCHING_CONTEXT = m.createProperty(BASE_URI + "hasMatchingContext"); public static final Property HAS_QUERY = m.createProperty(BASE_URI + "hasQuery"); public static final Property HAS_GRAPH = m.createProperty(BASE_URI, "hasGraph"); //search result model public static final Resource Match = m.createResource(BASE_URI + "Match"); public static final Property SEARCH_RESULT_URI = m.createProperty(BASE_URI, "uri"); public static final Property SEARCH_RESULT_PREVIEW = m.createProperty(BASE_URI, "preview"); public static final String PRIVATE_DATA_GRAPH_URI = BASE_URI + "privateDataGraph"; public static final String GROUP_FACET_STRING = BASE_URI + "GroupFacet"; public static final String HAS_GROUP_MEMBER_String = BASE_URI + "hasGroupMember"; public static final Property HAS_GROUP_MEMBER = m.createProperty(BASE_URI, "hasGroupMember"); public static final String OWNED_BY_STRING = BASE_URI + "ownedBy"; public static final Property OWNED_BY = m.createProperty(BASE_URI + "ownedBy"); public static final String HELD_BY_STRING = BASE_URI + "heldBy"; public static final Property HELD_BY = m.createProperty(BASE_URI + "heldBy"); public static final String HOLDS_STRING = BASE_URI + "holds"; public static final Property HOLDS = m.createProperty(BASE_URI + "holds"); public static final String OWNS_STRING = BASE_URI + "owns"; public static final Property OWNS = m.createProperty(BASE_URI + "owns"); public static final String CONNECTED_WITH_STRING = BASE_URI + "connectedWith"; public static final Property CONNECTED_WITH = m.createProperty(BASE_URI + "connectedWith"); public static final Property REVIEWS = m.createProperty(BASE_URI + "reviews"); public static final String REVIEWS_STRING = BASE_URI + "reviews"; public static final String CHAT_FACET_STRING = BASE_URI + "ChatFacet"; //unread information public static final Property HAS_UNREAD_SUGGESTED = m.createProperty(BASE_URI + "hasUnreadSuggested"); public static final Property HAS_UNREAD_REQUEST_SENT = m.createProperty(BASE_URI + "hasUnreadRequestSent"); public static final Property HAS_UNREAD_REQUEST_RECEIVED = m.createProperty(BASE_URI + "hasUnreadRequestReceived"); public static final Property HAS_UNREAD_CONNECTED = m.createProperty(BASE_URI + "hasUnreadConnected"); public static final Property HAS_UNREAD_CLOSED = m.createProperty(BASE_URI + "hasUnreadClosed"); public static final Property HAS_UNREAD_OLDEST_TIMESTAMP = m.createProperty(BASE_URI + "hasUnreadOldestTimestamp"); public static final Property HAS_UNREAD_NEWEST_TIMESTAMP = m.createProperty(BASE_URI + "hasUnreadNewestTimestamp"); public static final Property HAS_UNREAD_COUNT = m.createProperty(BASE_URI + "hasUnreadCount"); /** * Returns the base URI for this schema. * * @return the URI for this schema */ public static String getURI() { return BASE_URI; } /** * Converts the NeedState Enum to a Resource. * * @param state * @return */ public static Resource toResource(NeedState state) { switch (state) { case ACTIVE: return NEED_STATE_ACTIVE; case INACTIVE: return NEED_STATE_INACTIVE; default: throw new IllegalArgumentException("No case specified for " + state.name()); } } /** * Converts the ConnectionState Enum to a Resource. * * @param type * @return */ public static Resource toResource(ConnectionState type) { switch (type) { case SUGGESTED: return CONNECTION_STATE_SUGGESTED; case REQUEST_SENT: return CONNECTION_STATE_REQUEST_SENT; case REQUEST_RECEIVED: return CONNECTION_STATE_REQUEST_RECEIVED; case CONNECTED: return CONNECTION_STATE_CONNECTED; case CLOSED: return CONNECTION_STATE_CLOSED; default: throw new IllegalArgumentException("No such case specified for " + type.name()); } } }
webofneeds/won-core/src/main/java/won/protocol/vocabulary/WON.java
/* * Copyright 2012 Research Studios Austria Forschungsges.m.b.H. * * 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 won.protocol.vocabulary; import org.apache.jena.rdf.model.Model; import org.apache.jena.rdf.model.ModelFactory; import org.apache.jena.rdf.model.Property; import org.apache.jena.rdf.model.Resource; import won.protocol.model.ConnectionState; import won.protocol.model.NeedState; /** * WoN Vocabulary */ public class WON { public static final String BASE_URI = "http://purl.org/webofneeds/model#"; private static Model m = ModelFactory.createDefaultModel(); public static final Resource NEED = m.createResource(BASE_URI + "Need"); public static final Property HAS_WON_NODE = m.createProperty(BASE_URI, "hasWonNode"); public static final Property HAS_DEFAULT_GRAPH_SIGNING_METHOD = m.createProperty(BASE_URI, "hasDefaultGraphSigningMethod"); public static final Property HAS_NEED_PROTOCOL_ENDPOINT = m.createProperty(BASE_URI, "hasNeedProtocolEndpoint"); public static final Property HAS_MATCHER_PROTOCOL_ENDPOINT = m.createProperty(BASE_URI, "hasMatcherProtocolEndpoint"); public static final Property HAS_OWNER_PROTOCOL_ENDPOINT = m.createProperty(BASE_URI, "hasOwnerProtocolEndpoint"); public static final Property HAS_ACTIVEMQ_NEED_PROTOCOL_QUEUE_NAME = m.createProperty(BASE_URI, "hasActiveMQNeedProtocolQueueName"); public static final Property HAS_ACTIVEMQ_OWNER_PROTOCOL_QUEUE_NAME = m.createProperty(BASE_URI, "hasActiveMQOwnerProtocolQueueName"); public static final Property HAS_ACTIVEMQ_MATCHER_PROTOCOL_QUEUE_NAME = m.createProperty(BASE_URI, "hasActiveMQMatcherProtocolQueueName"); public static final Property HAS_ACTIVEMQ_MATCHER_PROTOCOL_OUT_NEED_CREATED_TOPIC_NAME = m.createProperty(BASE_URI, "hasActiveMQMatcherProtocolOutNeedCreatedTopicName"); public static final Property HAS_ACTIVEMQ_MATCHER_PROTOCOL_OUT_NEED_ACTIVATED_TOPIC_NAME = m.createProperty(BASE_URI, "hasActiveMQMatcherProtocolOutNeedActivatedTopicName"); public static final Property HAS_ACTIVEMQ_MATCHER_PROTOCOL_OUT_NEED_DEACTIVATED_TOPIC_NAME = m.createProperty(BASE_URI, "hasActiveMQMatcherProtocolOutNeedDeactivatedTopicName"); public static final Property HAS_ACTIVEMQ_MATCHER_PROTOCOL_OUT_MATCHER_REGISTERED_TOPIC_NAME = m.createProperty (BASE_URI, "hasActiveMQMatcherProtocolOutMatcherRegisteredTopicName"); public static final Property HAS_URI_PATTERN_SPECIFICATION = m.createProperty(BASE_URI, "hasUriPrefixSpecification"); public static final Property HAS_NEED_URI_PREFIX = m.createProperty(BASE_URI, "hasNeedUriPrefix"); public static final Property HAS_CONNECTION_URI_PREFIX = m.createProperty(BASE_URI, "hasConnectionUriPrefix"); public static final Property HAS_EVENT_URI_PREFIX = m.createProperty(BASE_URI, "hasEventUriPrefix"); public static final Property HAS_NEED_LIST = m.createProperty(BASE_URI, "hasNeedList"); public static final Property EMBED_SPIN_ASK = m.createProperty(BASE_URI, "embedSpinAsk"); public static final Property SUPPORTS_WON_PROTOCOL_IMPL = m.createProperty(BASE_URI + "supportsWonProtocolImpl"); public static final Resource WON_OVER_ACTIVE_MQ = m.createResource(BASE_URI + "WonOverActiveMq"); public static final Property HAS_BROKER_URI = m.createProperty(BASE_URI, "hasBrokerUri"); public static final Resource WON_OVER_SOAP_WS = m.createResource(BASE_URI + "WonOverSoapWs"); public static final Property IS_IN_STATE = m.createProperty(BASE_URI, "isInState"); public static final Property HAS_CONTENT_GRAPH = m.createProperty(BASE_URI, "hasContentGraph"); public static final Property HAS_DERIVED_GRAPH = m.createProperty(BASE_URI, "hasDerivedGraph"); public static final Property HAS_TEXT_MESSAGE = m.createProperty(BASE_URI + "hasTextMessage"); public static final Property IS_PROCESSING = m.createProperty(BASE_URI + "isProcessing"); public static final Resource MESSAGE = m.createResource(BASE_URI + "Message"); public static final Property HAS_FEEDBACK = m.createProperty(BASE_URI, "hasFeedback"); public static final Property HAS_FEEDBACK_EVENT = m.createProperty(BASE_URI, "hasFeedbackEvent"); //used to express which URI the feedback relates to public static final Property FOR_RESOURCE = m.createProperty(BASE_URI, "forResource"); public static final Property HAS_BINARY_RATING = m.createProperty(BASE_URI, "hasBinaryRating"); public static final Resource GOOD = m.createResource(BASE_URI + "Good"); public static final Resource BAD = m.createResource(BASE_URI + "Bad"); public static final Property HAS_TAG = m.createProperty(BASE_URI, "hasTag"); public static final Property HAS_ATTACHED_MEDIA = m.createProperty(BASE_URI, "hasAttachedMedia"); public static final Property HAS_HEIGHT = m.createProperty(BASE_URI, "hasHeight"); public static final Property HAS_DEPTH = m.createProperty(BASE_URI, "hasDepth"); public static final Property HAS_WIDTH = m.createProperty(BASE_URI, "hasWidth"); public static final Property HAS_WEIGHT = m.createProperty(BASE_URI, "hasWeight"); public static final Property HAS_QUANTITATIVE_PROPERTY = m.createProperty(BASE_URI, "hasQuantitativeProperty"); public static final Property HAS_FACET = m.createProperty(BASE_URI, "hasFacet"); public static final Property HAS_DEFAULT_FACET = m.createProperty(BASE_URI, "hasDefaultFacet"); public static final Resource FACET = m.createResource(BASE_URI + "Facet"); //This property is used in the rdf-model part of connect (from owner) and hint //to specify a facet to which a connection is created public static final Property HAS_REMOTE_FACET = m.createProperty(BASE_URI + "hasRemoteFacet"); public static final Property HAS_CONNECTIONS = m.createProperty(BASE_URI, "hasConnections"); public static final Resource CONNECTION_CONTAINER = m.createResource(BASE_URI + "ConnectionContainer"); public static final Resource CONNECTION = m.createResource(BASE_URI + "Connection"); public static final Property HAS_CONNECTION_STATE = m.createProperty(BASE_URI, "hasConnectionState"); public static final Property HAS_REMOTE_CONNECTION = m.createProperty(BASE_URI, "hasRemoteConnection"); public static final Property HAS_REMOTE_NEED = m.createProperty(BASE_URI, "hasRemoteNeed"); public static final Property BELONGS_TO_NEED = m.createProperty(BASE_URI, "belongsToNeed"); public static final Property HAS_EVENT_CONTAINER = m.createProperty(BASE_URI, "hasEventContainer"); public static final Resource EVENT_CONTAINER = m.createResource(BASE_URI + "EventContainer"); public static final Property HAS_TIME_STAMP = m.createProperty(BASE_URI, "hasTimeStamp"); public static final Property HAS_ORIGINATOR = m.createProperty(BASE_URI, "hasOriginator"); public static final Property HAS_ADDITIONAL_DATA = m.createProperty(BASE_URI, "hasAdditionalData"); public static final Resource ADDITIONAL_DATA_CONTAINER = m.createResource(BASE_URI + "AdditionalDataContainer"); public static final Property HAS_MATCH_SCORE = m.createProperty(BASE_URI, "hasMatchScore"); public static final Property HAS_MATCH_COUNTERPART = m.createProperty(BASE_URI, "hasMatchCounterpart"); public static final Property IS = m.createProperty(BASE_URI, "is"); public static final Property SEEKS = m.createProperty(BASE_URI, "seeks"); public static final Property GOAL = m.createProperty(BASE_URI, "goal"); public static final Property HAS_SHAPES_GRAPH = m.createProperty(BASE_URI, "hasShapesGraph"); public static final Property HAS_DATA_GRAPH = m.createProperty(BASE_URI, "hasDataGraph"); public static final Property HAS_NEED_MODALITY = m.createProperty(BASE_URI, "hasNeedModality"); public static final Resource NEED_MODALITY = m.createResource(BASE_URI + "NeedModality"); public static final Property HAS_PRICE_SPECIFICATION = m.createProperty(BASE_URI, "hasPriceSpecification"); public static final Resource PRICE_SPECIFICATION = m.createResource(BASE_URI + "PriceSpecification"); public static final Property HAS_LOWER_PRICE_LIMIT = m.createProperty(BASE_URI, "hasLowerPriceLimit"); public static final Property HAS_UPPER_PRICE_LIMIT = m.createProperty(BASE_URI, "hasUpperPriceLimit"); public static final Property HAS_CURRENCY = m.createProperty(BASE_URI, "hasCurrency"); public static final Property HAS_LOCATION = m.createProperty(BASE_URI, "hasLocation"); public static final Property HAS_BOUNDING_BOX = m.createProperty(BASE_URI, "hasBoundingBox"); public static final Property HAS_NORTH_WEST_CORNER = m.createProperty(BASE_URI, "hasNorthWestCorner"); public static final Property HAS_SOUTH_EAST_CORNER = m.createProperty(BASE_URI, "hasSouthEastCorner"); public static final Property HAS_BOUNDS_NORTH_WEST = m.createProperty(BASE_URI, "hasBoundsNorthWest"); public static final Property HAS_BOUNDS_SOUTH_EAST = m.createProperty(BASE_URI, "hasBoundsSouthEast"); public static final Resource LOCATION_SPECIFICATION = m.createResource(BASE_URI + "Location"); public static final Property GEO_SPATIAL = m.createProperty(BASE_URI + "geoSpatial"); public static final Property IS_CONCEALED = m.createProperty(BASE_URI, "isConcealed"); public static final Resource REGION = m.createResource(BASE_URI + "Region"); public static final Property HAS_ISO_CODE = m.createProperty(BASE_URI, "hasISOCode"); public static final Property HAS_TIME_SPECIFICATION = m.createProperty(BASE_URI, "hasTimeSpecification"); public static final Resource TIME_SPECIFICATION = m.createResource(BASE_URI + "TimeSpecification"); public static final Property HAS_START_TIME = m.createProperty(BASE_URI, "hasStartTime"); public static final Property HAS_END_TIME = m.createProperty(BASE_URI, "hasEndTime"); public static final Property HAS_RECURS_IN = m.createProperty(BASE_URI, "hasRecursIn"); public static final Property HAS_RECURS_TIMES = m.createProperty(BASE_URI, "hasRecursTimes"); public static final Property HAS_RECUR_INFINITE_TIMES = m.createProperty(BASE_URI, "hasRecurInfiniteTimes"); // Resource individuals public static final Resource NEED_STATE_ACTIVE = m.createResource(NeedState.ACTIVE.getURI().toString()); public static final Resource NEED_STATE_INACTIVE = m.createResource(NeedState.INACTIVE.getURI().toString()); public static final Resource CONNECTION_STATE_SUGGESTED = m.createResource(ConnectionState.SUGGESTED.getURI().toString()); public static final Resource CONNECTION_STATE_REQUEST_SENT = m.createResource(ConnectionState.REQUEST_SENT.getURI().toString()); public static final Resource CONNECTION_STATE_REQUEST_RECEIVED = m.createResource(ConnectionState.REQUEST_RECEIVED.getURI().toString()); public static final Resource CONNECTION_STATE_CONNECTED = m.createResource(ConnectionState.CONNECTED.getURI().toString()); public static final Resource CONNECTION_STATE_CLOSED = m.createResource(ConnectionState.CLOSED.getURI().toString()); public static final Property HAS_SUGGESTED_COUNT = m.createProperty(BASE_URI, "hasSuggestedCount"); public static final Property HAS_REQUEST_RECEIVED_COUNT = m.createProperty(BASE_URI, "hasRequestReceivedCount"); public static final Property HAS_REQUEST_SENT_COUNT = m.createProperty(BASE_URI, "hasRequestSentCount"); public static final Property HAS_CONNECTED_COUNT = m.createProperty(BASE_URI, "hasConnectedCount"); public static final Property HAS_CLOSED_COUNT = m.createProperty(BASE_URI, "hasClosedCount"); //adds a flag to a need public static final Property HAS_FLAG = m.createProperty(BASE_URI + "hasFlag"); public static final Property DO_NOT_MATCH_BEFORE = m.createProperty(BASE_URI + "doNotMatchBefore"); public static final Property DO_NOT_MATCH_AFTER = m.createProperty(BASE_URI + "doNotMatchAfter"); //the usedForTesting flag: need is not a real need, only match with other needs flagged with usedForTesting public static final Resource USED_FOR_TESTING = m.createResource(BASE_URI + "UsedForTesting"); public static final Resource WHATS_AROUND = m.createResource(BASE_URI + "WhatsAround"); public static final Resource WHATS_NEW = m.createResource(BASE_URI + "WhatsNew"); // hint behaviour public static final Resource NO_HINT_FOR_COUNTERPART = m.createResource(BASE_URI + "NoHintForCounterpart"); public static final Resource NO_HINT_FOR_ME = m.createResource(BASE_URI + "NoHintForMe"); public static final Property HAS_MATCHING_CONTEXT = m.createProperty(BASE_URI + "hasMatchingContext"); public static final Property HAS_QUERY = m.createProperty(BASE_URI + "hasQuery"); public static final Property HAS_GRAPH = m.createProperty(BASE_URI, "hasGraph"); //search result model public static final Resource Match = m.createResource(BASE_URI + "Match"); public static final Property SEARCH_RESULT_URI = m.createProperty(BASE_URI, "uri"); public static final Property SEARCH_RESULT_PREVIEW = m.createProperty(BASE_URI, "preview"); public static final String PRIVATE_DATA_GRAPH_URI = BASE_URI + "privateDataGraph"; public static final String GROUP_FACET_STRING = BASE_URI + "GroupFacet"; public static final String HAS_GROUP_MEMBER_String = BASE_URI + "hasGroupMember"; public static final Property HAS_GROUP_MEMBER = m.createProperty(BASE_URI, "hasGroupMember"); public static final String OWNED_BY_STRING = BASE_URI + "ownedBy"; public static final Property OWNED_BY = m.createProperty(BASE_URI + "ownedBy"); public static final String HELD_BY_STRING = BASE_URI + "heldBy"; public static final Property HELD_BY = m.createProperty(BASE_URI + "heldBy"); public static final String HOLDS_STRING = BASE_URI + "holds"; public static final Property HOLDS = m.createProperty(BASE_URI + "holds"); public static final String OWNS_STRING = BASE_URI + "owns"; public static final Property OWNS = m.createProperty(BASE_URI + "owns"); public static final String CONNECTED_WITH_STRING = BASE_URI + "connectedWith"; public static final Property CONNECTED_WITH = m.createProperty(BASE_URI + "connectedWith"); public static final Property REVIEWS = m.createProperty(BASE_URI + "reviews"); public static final String REVIEWS_STRING = BASE_URI + "reviews"; public static final String CHAT_FACET_STRING = BASE_URI + "ChatFacet"; //unread information public static final Property HAS_UNREAD_SUGGESTED = m.createProperty(BASE_URI + "hasUnreadSuggested"); public static final Property HAS_UNREAD_REQUEST_SENT = m.createProperty(BASE_URI + "hasUnreadRequestSent"); public static final Property HAS_UNREAD_REQUEST_RECEIVED = m.createProperty(BASE_URI + "hasUnreadRequestReceived"); public static final Property HAS_UNREAD_CONNECTED = m.createProperty(BASE_URI + "hasUnreadConnected"); public static final Property HAS_UNREAD_CLOSED = m.createProperty(BASE_URI + "hasUnreadClosed"); public static final Property HAS_UNREAD_OLDEST_TIMESTAMP = m.createProperty(BASE_URI + "hasUnreadOldestTimestamp"); public static final Property HAS_UNREAD_NEWEST_TIMESTAMP = m.createProperty(BASE_URI + "hasUnreadNewestTimestamp"); public static final Property HAS_UNREAD_COUNT = m.createProperty(BASE_URI + "hasUnreadCount"); /** * Returns the base URI for this schema. * * @return the URI for this schema */ public static String getURI() { return BASE_URI; } /** * Converts the NeedState Enum to a Resource. * * @param state * @return */ public static Resource toResource(NeedState state) { switch (state) { case ACTIVE: return NEED_STATE_ACTIVE; case INACTIVE: return NEED_STATE_INACTIVE; default: throw new IllegalArgumentException("No case specified for " + state.name()); } } /** * Converts the ConnectionState Enum to a Resource. * * @param type * @return */ public static Resource toResource(ConnectionState type) { switch (type) { case SUGGESTED: return CONNECTION_STATE_SUGGESTED; case REQUEST_SENT: return CONNECTION_STATE_REQUEST_SENT; case REQUEST_RECEIVED: return CONNECTION_STATE_REQUEST_RECEIVED; case CONNECTED: return CONNECTION_STATE_CONNECTED; case CLOSED: return CONNECTION_STATE_CLOSED; default: throw new IllegalArgumentException("No such case specified for " + type.name()); } } }
removes won:is from properties
webofneeds/won-core/src/main/java/won/protocol/vocabulary/WON.java
removes won:is from properties
<ide><path>ebofneeds/won-core/src/main/java/won/protocol/vocabulary/WON.java <ide> public static final Property HAS_MATCH_SCORE = m.createProperty(BASE_URI, "hasMatchScore"); <ide> public static final Property HAS_MATCH_COUNTERPART = m.createProperty(BASE_URI, "hasMatchCounterpart"); <ide> <del> public static final Property IS = m.createProperty(BASE_URI, "is"); <ide> public static final Property SEEKS = m.createProperty(BASE_URI, "seeks"); <ide> <ide> public static final Property GOAL = m.createProperty(BASE_URI, "goal");
Java
apache-2.0
966e0bb20922d1e886b82df74047cc9ed802cefa
0
Netflix/genie,tgianos/genie,ajoymajumdar/genie,irontable/genie,irontable/genie,tgianos/genie,ajoymajumdar/genie,ajoymajumdar/genie,irontable/genie,Netflix/genie,ajoymajumdar/genie,Netflix/genie,tgianos/genie,irontable/genie,ajoymajumdar/genie,tgianos/genie,Netflix/genie,Netflix/genie,tgianos/genie,irontable/genie
/* * * Copyright 2015 Netflix, 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.netflix.genie.core.jobs; import com.netflix.genie.common.dto.Application; import com.netflix.genie.common.dto.Cluster; import com.netflix.genie.common.dto.Command; import com.netflix.genie.common.dto.JobRequest; import com.netflix.genie.common.exceptions.GenieException; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.hibernate.validator.constraints.NotBlank; import javax.validation.constraints.NotNull; import java.io.File; import java.util.ArrayList; import java.util.List; /** * Encapsulates the details of the job, cluster , command and applications needed to run a job. * * @author amsharma * @since 3.0.0 */ @Getter @Slf4j public class JobExecutionEnvironment { private JobRequest jobRequest; private Cluster cluster; private Command command; private List<Application> applications = new ArrayList<>(); private File jobWorkingDir; /** * Constructor used by the builder build() method. * * @param builder The builder to use */ public JobExecutionEnvironment(final Builder builder) { this.jobRequest = builder.jobRequest; this.cluster = builder.cluster; this.command = builder.command; this.applications.addAll(builder.applications); this.jobWorkingDir = builder.jobWorkingDir; } /** * A builder to create Job Execution Environment objects. * * @author tgianos * @since 3.0.0 */ public static class Builder { private JobRequest jobRequest; private Cluster cluster; private Command command; private List<Application> applications = new ArrayList<>(); private File jobWorkingDir; /** * Constructor. * * @param request The job request object. * @param clusterObj The cluster object. * @param commandObj The command object. * @param dir The directory location for the jobs * @throws GenieException If there is an error */ public Builder( @NotNull(message = "Job Request cannot be null") final JobRequest request, @NotNull(message = "Cluster cannot be null") final Cluster clusterObj, @NotNull(message = "Command cannot be null") final Command commandObj, @NotBlank(message = "Job working directory cannot be empty") final File dir ) throws GenieException { this.jobRequest = request; this.cluster = clusterObj; this.command = commandObj; this.jobWorkingDir = dir; } /** * Set the applications needed for the jobs' execution. * * @param applications The list of application objects. * @return The builder */ public Builder withApplications(final List<Application> applications) { if (applications != null) { this.applications.addAll(applications); } return this; } /** * Build the job execution environment object. * * @return Create the final read-only JobRequest instance * @throws GenieException If there is any problem. */ public JobExecutionEnvironment build() throws GenieException { return new JobExecutionEnvironment(this); } } }
genie-core/src/main/java/com/netflix/genie/core/jobs/JobExecutionEnvironment.java
/* * * Copyright 2015 Netflix, 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.netflix.genie.core.jobs; import com.netflix.genie.common.dto.Application; import com.netflix.genie.common.dto.Cluster; import com.netflix.genie.common.dto.Command; import com.netflix.genie.common.dto.JobRequest; import com.netflix.genie.common.exceptions.GenieException; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.hibernate.validator.constraints.NotBlank; import javax.validation.constraints.NotNull; import java.io.File; import java.util.ArrayList; import java.util.List; /** * Encapsulates the details of the job, cluster , command and applications needed to run a job. * * @author amsharma * @since 3.0.0 */ @Getter @Slf4j public class JobExecutionEnvironment { private JobRequest jobRequest; private Cluster cluster; private Command command; private List<Application> applications = new ArrayList<>(); private File jobWorkingDir; /** * Constructor used by the builder build() method. * * @param builder The builder to use */ public JobExecutionEnvironment(final Builder builder) { this.jobRequest = builder.jobRequest; this.cluster = builder.cluster; this.command = builder.command; this.applications.addAll(builder.applications); this.jobWorkingDir = builder.jobWorkingDir; } /** * A builder to create Job Execution Environment objects. * * @author tgianos * @since 3.0.0 */ public static class Builder { private JobRequest jobRequest; private Cluster cluster; private Command command; private List<Application> applications = new ArrayList<>(); private File jobWorkingDir; /** * Constructor. * * @param request The job request object. * @param clusterObj The cluster object. * @param commandObj The command object. * @param dir The directory location for the jobs * @throws GenieException If there is an error */ public Builder( @NotNull(message = "Job Request cannot be null") final JobRequest request, @NotNull(message = "Cluster cannot be null") final Cluster clusterObj, @NotNull(message = "Command cannot be null") final Command commandObj, @NotBlank(message = "Job working directory cannot be empty") final File dir ) throws GenieException { this.jobRequest = request; this.cluster = clusterObj; this.command = commandObj; this.jobWorkingDir = dir; } /** * Set the applications needed for the jobs' execution. * * @param applicationSet The set of application objects. * @return The builder */ public Builder withApplications(final List<Application> applicationSet) { if (applicationSet != null) { this.applications.addAll(applicationSet); } return this; } /** * Build the job execution environment object. * * @return Create the final read-only JobRequest instance * @throws GenieException If there is any problem. */ public JobExecutionEnvironment build() throws GenieException { return new JobExecutionEnvironment(this); } } }
Fixing a comment and variable naming to be consistent
genie-core/src/main/java/com/netflix/genie/core/jobs/JobExecutionEnvironment.java
Fixing a comment and variable naming to be consistent
<ide><path>enie-core/src/main/java/com/netflix/genie/core/jobs/JobExecutionEnvironment.java <ide> /** <ide> * Set the applications needed for the jobs' execution. <ide> * <del> * @param applicationSet The set of application objects. <add> * @param applications The list of application objects. <ide> * @return The builder <ide> */ <del> public Builder withApplications(final List<Application> applicationSet) { <del> if (applicationSet != null) { <del> this.applications.addAll(applicationSet); <add> public Builder withApplications(final List<Application> applications) { <add> if (applications != null) { <add> this.applications.addAll(applications); <ide> } <ide> return this; <ide> }
Java
apache-2.0
e63e2e9c4cbb6ebb6d9a966a525841d4ec76c1ce
0
Catpaw42/Area51_E2014,Catpaw42/Area51_E2014,Catpaw42/Area51_E2014
package servlets; import helperClasses.Const; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.Timestamp; import java.util.Date; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.spoledge.audao.db.dao.DaoException; import database.DataSourceConnector; import database.dao.BrugerDao; import database.dao.CtKontrastKontrolskemaDao; import database.dao.MRKontrolskemaDao; import database.dao.ModalitetDao; import database.dao.PETCTKontrolskemaDao; import database.dao.PatientDao; import database.dao.RekvisitionDao; import database.dao.UndersoegelsesTypeDao; import database.dao.mysql.BrugerDaoImpl; import database.dao.mysql.CtKontrastKontrolskemaDaoImpl; import database.dao.mysql.MRKontrolskemaDaoImpl; import database.dao.mysql.ModalitetDaoImpl; import database.dao.mysql.PETCTKontrolskemaDaoImpl; import database.dao.mysql.PatientDaoImpl; import database.dao.mysql.RekvisitionDaoImplExt; import database.dao.mysql.UndersoegelsesTypeDaoImpl; import database.dto.Bruger; import database.dto.CtKontrastKontrolskema; import database.dto.MRKontrolskema; import database.dto.Modalitet; import database.dto.PETCTKontrolskema; import database.dto.Patient; import database.dto.RekvisitionExtended; import database.dto.MRKontrolskema.MRBoern; import database.dto.MRKontrolskema.MRVoksen; import database.dto.PETCTKontrolskema.Formaal; import database.dto.PETCTKontrolskema.KemoOgStraale; import database.dto.RekvisitionExtended.AmbulantKoersel; import database.dto.RekvisitionExtended.HenvistTil; import database.dto.RekvisitionExtended.HospitalOenske; import database.dto.RekvisitionExtended.IndlaeggelseTransport; import database.dto.RekvisitionExtended.Prioritering; import database.dto.RekvisitionExtended.Samtykke; import database.dto.UndersoegelsesType; import database.interfaces.IDataSourceConnector.ConnectionException; /** * Servlet implementation class NyRekvisitionServlet */ @SuppressWarnings("serial") @WebServlet("/NyRekvisitionServlet") public class NyRekvisitionServlet extends HttpServlet { private static final String HENV_AFD = "henv_afd"; private static final String PATIENT_TLF = "patient_tlf"; private static final String PATIENT_NAVN = "patient_navn"; private static final String PATIENT_ADRESSE = "patient_adresse"; private static final String PATIENT_CPR = "patient_cpr"; private static final boolean DEBUG = false; /** * @see HttpServlet#HttpServlet() */ public NyRekvisitionServlet() { super(); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Getting List of modalities - first create connection Connection conn = null; try { conn = DataSourceConnector.getConnection(); } catch (ConnectionException e) { //Connection Fails TODO message to user e.printStackTrace(); } //And DAO ModalitetDao modDao = new ModalitetDaoImpl(conn); //Getting Modalities Modalitet[] modList = modDao.findDynamic(null, 0, -1, null); request.setAttribute(Const.MODALITY_LIST, modList); if (Const.DEBUG) System.out.println(modList); request.getRequestDispatcher(Const.NEW_REKVISITION_PAGE).forward(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Getting active user Bruger activeBruger = (Bruger) request.getSession().getAttribute(Const.ACTIVE_USER); //Checking if activeUser if (activeBruger == null) response.sendRedirect(Const.MAIN_SERVLET); request.setCharacterEncoding("UTF-8"); //Getting a database connection.... Connection conn = null; try { conn = DataSourceConnector.getConnection(); } catch (ConnectionException e1) { e1.printStackTrace(); } //Getting active user //Storing patient data. Integer ptId = storePatient(request, conn, activeBruger); //Making Rekvisition DTO RekvisitionExtended rek = new RekvisitionExtended(); rek.setPaaroerende(request.getParameter("paaroerende")); rek.setSamtykke(convertSamtykke(request)); //TODO validate samtykke. rek.setTriage(request.getParameter("triage")); rek.setCave(request.getParameter("cave"));//TODO validate try { rek.setRekvirentId(Integer.valueOf(request.getParameter("rekvirent_id"))); } catch (NumberFormatException e){ //Should never happen TODO - Now handles by setting rekvirent to null - should give backend exception rek.setRekvirentId(null); e.printStackTrace(); } rek.setRekvirentId(activeBruger.getBrugerId()); rek.setHenvAfd(request.getParameter(HENV_AFD)); rek.setHenvLaege(request.getParameter("henv_laege")); rek.setKontaktTlf(request.getParameter("kontakt_tlf")); rek.setUdfIndlagt(Boolean.valueOf(request.getParameter("udf_indlagt"))); rek.setAmbulant(!rek.getUdfIndlagt()); rek.setHenvistTil(convertHenvistTil(request)); rek.setHospitalOenske(convertHospitalOenske(request)); rek.setPrioritering(convertPrioritering(request)); //Get undersøgelsesType data og gem en ny. Integer USTypeID = -1; UndersoegelsesType USType = new UndersoegelsesType(); USType.setModalitetId(Integer.valueOf(request.getParameter("modalitet_navn"))); USType.setUndersoegelsesNavn(request.getParameter("undersoegelses_type")); UndersoegelsesTypeDao usTypeDao = new UndersoegelsesTypeDaoImpl(conn) ; try { USTypeID = usTypeDao.insert(USType); } catch (DaoException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } rek.setUndersoegelsesTypeId(USTypeID); //TODO FIXXX!!! rek.setKliniskProblemstilling(request.getParameter("klinisk_problemstilling")); rek.setAmbulantKoersel(convertAmbulantKoersel(request)); rek.setIndlaeggelseTransport(convertIndlaeggelseTransport(request)); rek.setDatoForslag(request.getParameter("dato_forslag")); rek.setGraviditet(Boolean.valueOf(request.getParameter("graviditet"))); rek.setHoerehaemmet(getBoolFromCheckbox(request,"hoerehaemmet")); rek.setSynshaemmet(getBoolFromCheckbox(request, "synshaemmet")); rek.setAmputeret(getBoolFromCheckbox(request, "amputeret")); rek.setKanIkkeStaa(getBoolFromCheckbox(request, "kan_ikke_staa")); rek.setDement(getBoolFromCheckbox(request, "dement")); rek.setAfasi(getBoolFromCheckbox(request, "afasi")); try { rek.setIltLiterPrmin(Integer.valueOf(request.getParameter("ilt"))); } catch (NumberFormatException e){ rek.setIltLiterPrmin(null); } rek.setTolkSprog(request.getParameter("tolk")); rek.setIsolation(request.getParameter("isolation")); try { rek.setCytostatikaDato(java.sql.Date.valueOf(request.getParameter("cytostatika"))); System.out.println(rek.getCytostatikaDato()); } catch (IllegalArgumentException e) { rek.setCytostatikaDato(null); } rek.setTidlBilledDiagnostik(request.getParameter("tidl_billed_diagnostik")); rek.setPatientId(ptId); rek.setStatus(RekvisitionExtended.Status.PENDING); rek.setAfsendtDato(new Date()); System.out.println(rek); //Check Modalitet String modalitet = request.getParameter("modalitet_navn"); // can not switch on null - makes empty string instead should not happen modalitet = modalitet == null ? "" : modalitet; switch (modalitet) { case "invasiv_UL": Integer ULSkemaID = storeULInvKontrolSkema(request,response); rek.setInvasivULKontrolskemaId(ULSkemaID); break; case "MR": Integer MRSkemaID = null; try { MRSkemaID = storeMRSkema(request, response); } catch (DaoException e1) { // TODO Error page??? e1.printStackTrace(); } rek.setMRKontrolskemaId(MRSkemaID); break; case "CT_kontrast": Integer CTKSkemaID = null; try { CTKSkemaID = storeCTKSkema(request, response); } catch (DaoException e1) { // TODO Error page??? e1.printStackTrace(); } rek.setCTKontrastKontrolskemaId(CTKSkemaID); break; case "PETCT": Integer PETCTSkemaID = null; try { PETCTSkemaID = storePETCTSkema(request,response); } catch (DaoException e1) { // TODO Error page??? e1.printStackTrace(); } rek.setPETCTKontrolskemaId(PETCTSkemaID); break; default: //Now store the requisition RekvisitionDao rekDao = new RekvisitionDaoImplExt(conn); try { rekDao.insert(rek); } catch (DaoException e) { // TODO Auto-generated catch block e.printStackTrace(); } //HopeFully it went well ;) //TODO - real page PrintWriter out = response.getWriter(); out.println("<HTML><BODY>Tak for din henvendelse - du kan følge med i status for din rekvisition i oversigten <BR>"); out.println("<A HREF='RekvisitionServlet'>Tilbage til rekvisitioner</A></BODY><HTML>"); break; } } private Integer storePatient(HttpServletRequest request, Connection conn, Bruger activeBruger) { Patient pt = new Patient(); // pt.setFoedselsdag(Timestamp.valueOf(parseCPRBirthday(request.getParameter(PATIENT_CPR)))); pt.setFoedselsdag(java.sql.Date.valueOf(parseCPRBirthday(request.getParameter(PATIENT_CPR)))); pt.setPatientCpr(request.getParameter(PATIENT_CPR)); pt.setPatientAdresse(request.getParameter(PATIENT_ADRESSE)); pt.setPatientNavn(request.getParameter(PATIENT_NAVN)); pt.setPatientTlf(request.getParameter(PATIENT_TLF)); pt.setStamafdeling(activeBruger.getBrugerNavn()); if (Const.DEBUG)System.out.println(pt); //Time to store patient Integer ptId = null; PatientDao ptDao = new PatientDaoImpl(conn); try { ptId = ptDao.insert(pt); } catch (DaoException e1) { e1.printStackTrace(); } return ptId; } private Integer storePETCTSkema(HttpServletRequest request, HttpServletResponse response) throws DaoException { Connection conn = null; try { conn = DataSourceConnector.getConnection(); } catch (ConnectionException e1) { e1.printStackTrace(); } PETCTKontrolskema pck = new PETCTKontrolskema(); pck.setFormaal(convertFormaalMetode(request)); pck.setFormaalTekst(request.getParameter("formaal_text")); pck.setKanPtLiggeStille30(Boolean.valueOf(request.getParameter("kanPtLiggeStille30"))); pck.setPtTaalerFaste(Boolean.valueOf(request.getParameter("ptTaalerFaste"))); pck.setDiabetes(Boolean.valueOf(request.getParameter("diabetes"))); pck.setDMBeh(request.getParameter("DM_Beh")); pck.setSmerter(Boolean.valueOf(request.getParameter("smerter"))); pck.setRespInsuff(Boolean.valueOf(request.getParameter("respInsuff"))); pck.setKlaustrofobi(Boolean.valueOf(request.getParameter("klaustrofobi"))); pck.setAllergi(Boolean.valueOf(request.getParameter("allergi"))); pck.setAllergiTekst(request.getParameter("allergi_tekst")); pck.setFedme(Boolean.valueOf(request.getParameter("fedme"))); pck.setVaegt(Integer.valueOf(request.getParameter("vaegt"))); pck.setBiopsi(Boolean.valueOf(request.getParameter("biopsi"))); pck.setBiopsiTekst(request.getParameter("biopsi_tekst")); pck.setOperation(Boolean.valueOf(request.getParameter("operation"))); pck.setOperationTekst(request.getParameter("operation_tekst")); pck.setKemoOgStraale(convertKemostraale(request)); pck.setSidstePKreatTimestamp(Timestamp.valueOf(request.getParameter("straaleDato"))); pck.setNedsatNyreFkt(Boolean.valueOf(request.getParameter("nedsatNyreFkt"))); pck.setSidstePKreatinin(Integer.valueOf(request.getParameter("sidstePKreatinin"))); pck.setSidstePKreatTimestamp(Timestamp.valueOf(request.getParameter("sidstePKreatTimestamp"))); PETCTKontrolskemaDao petctkDao = new PETCTKontrolskemaDaoImpl(conn); return petctkDao.insert(pck); } private Integer storeCTKSkema(HttpServletRequest request, HttpServletResponse response) throws DaoException { Connection conn = null; try { conn = DataSourceConnector.getConnection(); } catch (ConnectionException e1) { e1.printStackTrace(); } // Making CTTKontrolskema dto CtKontrastKontrolskema ctk = new CtKontrastKontrolskema(); ctk.setDiabetes(Boolean.valueOf(request.getParameter("diabetes"))); ctk.setNyrefunktion(Boolean.valueOf(request.getParameter("nyrefunktion"))); ctk.setNyreopereret(Boolean.valueOf(request.getParameter("nyreopereret"))); ctk.setHjertesygdom(Boolean.valueOf(request.getParameter("hjertesygdom"))); ctk.setMyokardieinfarkt(Boolean.valueOf(request.getParameter("myokardieinfarkt"))); ctk.setProteinuri(Boolean.valueOf(request.getParameter("proteinuri"))); ctk.setUrinsyregigt(Boolean.valueOf(request.getParameter("urinsyregigt"))); ctk.setOver70(Boolean.valueOf(request.getParameter("over70"))); ctk.setHypertension(Boolean.valueOf(request.getParameter("hypertension"))); ctk.setNsaidPraeparat(Boolean.valueOf(request.getParameter("NSAIDpræparat"))); ctk.setAllergi(Boolean.valueOf(request.getParameter("alergi"))); ctk.setKontraststofreaktion(Boolean.valueOf(request.getParameter("konstrastofreaktion"))); ctk.setAstma(Boolean.valueOf(request.getParameter("astma"))); ctk.setHyperthyreoidisme(Boolean.valueOf(request.getParameter("hyperthyreoidisme"))); ctk.setMetformin(Boolean.valueOf(request.getParameter("metformin"))); ctk.setInterleukin2(Boolean.valueOf(request.getParameter("interleukin"))); ctk.setBetaBlokkere(Boolean.valueOf(request.getParameter("betaBlokkere"))); ctk.setPKreatininVaerdi(request.getParameter("Værdi")); // setPKreatininTimestamp??? ctk.setPtHoejde(Integer.valueOf(request.getParameter("Højde"))); ctk.setPtVaegt(Integer.valueOf(request.getParameter("Vægt"))); CtKontrastKontrolskemaDao ctkDao = new CtKontrastKontrolskemaDaoImpl(conn); return ctkDao.insert(ctk); } private Integer storeMRSkema(HttpServletRequest request, HttpServletResponse response) throws DaoException { Connection conn = null; try { conn = DataSourceConnector.getConnection(); } catch (ConnectionException e1) { e1.printStackTrace(); } MRKontrolskema mrk = new MRKontrolskema(); mrk.setPacemaker(Boolean.valueOf(request.getParameter("pacemaker"))); mrk.setMetalImplantater(Boolean.valueOf(request.getParameter("metal_implantater"))); mrk.setMetalImplantaterBeskrivelse(request.getParameter("metal_implantater_beskrivelse")); mrk.setAndetMetalisk(Boolean.valueOf(request.getParameter("andet_metalisk"))); mrk.setAndetMetaliskBeskrivelse(request.getParameter("andet_metalisk_beskrivelse")); mrk.setNyresygdom(Boolean.valueOf(request.getParameter("nyresygdom"))); mrk.setNyresygdomKreatinin(Integer.valueOf(request.getParameter("nyresygdom_kreatinin"))); mrk.setGraviditet(Boolean.valueOf(request.getParameter("graviditet"))); mrk.setGraviditetUge(Integer.valueOf(request.getParameter("graviditet_uge"))); mrk.setKlaustrofobi(Boolean.valueOf(request.getParameter("klaustrofobi"))); mrk.setHoejde(Integer.valueOf(request.getParameter("hoejde"))); mrk.setVaegt(Integer.valueOf(request.getParameter("vaegt"))); mrk.setMRBoern(convertSederingBoern(request)); mrk.setMRVoksen(convertSederingVoksen(request)); mrk.setPraepForsyn(request.getParameter("praep_forsyn")); MRKontrolskemaDao mrkDao = new MRKontrolskemaDaoImpl(conn); return mrkDao.insert(mrk); } private Integer storeULInvKontrolSkema(HttpServletRequest request, HttpServletResponse response) { // TODO Auto-generated method stub return -1; } private String parseCPRBirthday(String foedselsdagString) { // String = request.getParameter(PATIENT_CPR); Integer foedeaar = Integer.valueOf(foedselsdagString.substring(4, 6)); String digit7String = foedselsdagString.substring(6,7); if (digit7String.equalsIgnoreCase("-") ) digit7String = foedselsdagString.substring(7, 8); Integer digit7 = Integer.valueOf(digit7String); if (digit7 <= 3 ){ foedeaar = 1900 + foedeaar; } else { if ((digit7 == 4 || digit7 == 9) && foedeaar >=37){ foedeaar = 1900 + foedeaar; } else { if (foedeaar >=58 && (digit7 !=4||digit7!=9)){ foedeaar = 1800 + foedeaar; } else { foedeaar = 2000 + foedeaar; } } } foedselsdagString = String.valueOf(foedeaar) + "-" + foedselsdagString.substring(2,4)+"-"+foedselsdagString.substring(0, 2); System.out.println("birthday from cpr: " + foedselsdagString); // Date d = new Date(); // System.out.println("Date format: " + d.toString()); // Timestamp t = Timestamp.valueOf(foedselsdagString); // new Date(foedselsdagString); // new Date(123); // System.out.println("come on: " + Date.parse(foedselsdagString)); // System.out.println("new format: " + java.sql.Date.valueOf(d.toString())); // System.out.println("second fomrat: " + Date.parse(d.toString())); // foedselsdagString = foedselsdagString + " 00:00:00.000000000"; return foedselsdagString; } private Boolean getBoolFromCheckbox(HttpServletRequest request, String boxname) { if("on".equals(request.getParameter(boxname))){ // check box is selected return true; } else{ // check box is not selected return false; } } private IndlaeggelseTransport convertIndlaeggelseTransport( HttpServletRequest request) { IndlaeggelseTransport indlTrans; String transString = request.getParameter("indlagt_transport"); if (transString==null) return null; switch (transString) { case "selv": indlTrans = RekvisitionExtended.IndlaeggelseTransport.GAA_UDEN_PORTOER; break; case "portoer": indlTrans = RekvisitionExtended.IndlaeggelseTransport.GAA_MED_PORTOER; break; case "koerestol": indlTrans = RekvisitionExtended.IndlaeggelseTransport.KOERESTOL; break; case "seng": indlTrans = RekvisitionExtended.IndlaeggelseTransport.SENG; break; default: indlTrans=null; break; } return indlTrans; } private AmbulantKoersel convertAmbulantKoersel(HttpServletRequest request) { AmbulantKoersel ambuTrans; String transString = request.getParameter("ambulant_transport"); if (transString==null) return null; switch (transString) { case "ingen": ambuTrans = RekvisitionExtended.AmbulantKoersel.INGEN; break; case "siddende": ambuTrans = RekvisitionExtended.AmbulantKoersel.SIDDENDE; break; case "liggende": ambuTrans = RekvisitionExtended.AmbulantKoersel.LIGGENDE; break; default: ambuTrans = null; break; } return ambuTrans; } private Prioritering convertPrioritering(HttpServletRequest request) { Prioritering prio; String prioString = request.getParameter("prioriterings_oenske"); if (prioString==null)return null; switch (prioString) { case "haste": prio = RekvisitionExtended.Prioritering.HASTE; break; case "fremskyndet": prio = RekvisitionExtended.Prioritering.FREMSKYNDET; break; case "rutine": prio = RekvisitionExtended.Prioritering.RUTINE; break; case "pakke": prio = RekvisitionExtended.Prioritering.PAKKEFORLOEB; break; default: prio = null; break; } return prio; } private HospitalOenske convertHospitalOenske(HttpServletRequest request) { HospitalOenske hospOensk; String hospOenskString = request.getParameter("hospitals_oenske"); if (hospOenskString==null) return null; switch (hospOenskString) { case "hilleroed": hospOensk = RekvisitionExtended.HospitalOenske.HILLEROED; break; case "frederikssund": hospOensk = RekvisitionExtended.HospitalOenske.FREDERIKSSUND; break; case "helsingoer": hospOensk = RekvisitionExtended.HospitalOenske.HELSINGOER; break; default: hospOensk=null; break; } return hospOensk; } private HenvistTil convertHenvistTil(HttpServletRequest request) { HenvistTil henv; String henvString = request.getParameter("henvist_til"); if (henvString==null) return null; switch (henvString) { case "radiologisk": henv = RekvisitionExtended.HenvistTil.RADIOLOGISK; break; case "klinfys": henv = RekvisitionExtended.HenvistTil.KLINISK; break; default: henv = null; break; } return henv; } private Samtykke convertSamtykke(HttpServletRequest request) { Samtykke samtykke; String samtykkeString = request.getParameter("samtykke"); if (samtykkeString == null) return null; switch (samtykkeString) { case "ja": samtykke = RekvisitionExtended.Samtykke.JA; break; case "nej": samtykke = RekvisitionExtended.Samtykke.NEJ; break; default: samtykke = RekvisitionExtended.Samtykke.UDEN_SAMTYKKE; break; } return samtykke; } private MRBoern convertSederingBoern(HttpServletRequest request){ MRBoern mrboern; String mrboernString = request.getParameter("sederingBoern"); if (mrboernString == null) return null; switch (mrboernString) { case "uden_sedering": mrboern = MRKontrolskema.MRBoern.UDEN_SEDERING; break; case "i_generel_anaestesi": mrboern = MRKontrolskema.MRBoern.I_GENEREL_ANAESTESI; break; default: mrboern = MRKontrolskema.MRBoern.UDEN_SEDERING; break; } return mrboern; } private MRVoksen convertSederingVoksen(HttpServletRequest request){ MRVoksen mrvoksen; String mrvoksenString = request.getParameter("sederingVoksne"); if (mrvoksenString == null) return null; switch (mrvoksenString) { case "uden_sedering": mrvoksen = MRKontrolskema.MRVoksen.UDEN_SEDERING; break; case "i_generel_anaestesi": mrvoksen = MRKontrolskema.MRVoksen.I_GENEREL_ANAESTESI; break; default: mrvoksen = MRKontrolskema.MRVoksen.UDEN_SEDERING; break; } return mrvoksen; } private KemoOgStraale convertKemostraale(HttpServletRequest request){ KemoOgStraale kemoOgStraale; String kemiOgStraaleString = request.getParameter("aldrigGivetKemo"); if (kemiOgStraaleString == null) return null; switch (kemiOgStraaleString) { case "aldrigGivetKemoJa": kemoOgStraale = PETCTKontrolskema.KemoOgStraale.ALDRIGGIVET; break; case "kemoterapiJa": case "stråleterapiNej": kemoOgStraale = PETCTKontrolskema.KemoOgStraale.KEMOTERAPI; break; case "kemoterapiNej": case "stråleterapiJa": kemoOgStraale = PETCTKontrolskema.KemoOgStraale.STRAALETERAPI; break; default: kemoOgStraale = PETCTKontrolskema.KemoOgStraale.KEMO_OG_STRAALE; break; } return kemoOgStraale; } private Formaal convertFormaalMetode(HttpServletRequest request){ Formaal formaal = null; String formaalString = request.getParameter("formaal"); if (formaalString == null) return null; switch (formaalString) { case "primardiag": formaal = PETCTKontrolskema.Formaal.PRIMAERDIAG; break; case "kontrolbeh": formaal = PETCTKontrolskema.Formaal.KONTROLBEH; break; case "kontrolremission": formaal = PETCTKontrolskema.Formaal.KONTROLREMISSION; break; case "kontrolrecidiv": formaal = PETCTKontrolskema.Formaal.KONTROLRECIDIV; break; } return formaal; } }
Xray/src/servlets/NyRekvisitionServlet.java
package servlets; import helperClasses.Const; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.Timestamp; import java.util.Date; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.spoledge.audao.db.dao.DaoException; import database.DataSourceConnector; import database.dao.BrugerDao; import database.dao.CtKontrastKontrolskemaDao; import database.dao.MRKontrolskemaDao; import database.dao.ModalitetDao; import database.dao.PETCTKontrolskemaDao; import database.dao.PatientDao; import database.dao.RekvisitionDao; import database.dao.UndersoegelsesTypeDao; import database.dao.mysql.BrugerDaoImpl; import database.dao.mysql.CtKontrastKontrolskemaDaoImpl; import database.dao.mysql.MRKontrolskemaDaoImpl; import database.dao.mysql.ModalitetDaoImpl; import database.dao.mysql.PETCTKontrolskemaDaoImpl; import database.dao.mysql.PatientDaoImpl; import database.dao.mysql.RekvisitionDaoImplExt; import database.dao.mysql.UndersoegelsesTypeDaoImpl; import database.dto.Bruger; import database.dto.CtKontrastKontrolskema; import database.dto.MRKontrolskema; import database.dto.Modalitet; import database.dto.PETCTKontrolskema; import database.dto.Patient; import database.dto.RekvisitionExtended; import database.dto.MRKontrolskema.MRBoern; import database.dto.MRKontrolskema.MRVoksen; import database.dto.PETCTKontrolskema.Formaal; import database.dto.PETCTKontrolskema.KemoOgStraale; import database.dto.RekvisitionExtended.AmbulantKoersel; import database.dto.RekvisitionExtended.HenvistTil; import database.dto.RekvisitionExtended.HospitalOenske; import database.dto.RekvisitionExtended.IndlaeggelseTransport; import database.dto.RekvisitionExtended.Prioritering; import database.dto.RekvisitionExtended.Samtykke; import database.dto.UndersoegelsesType; import database.interfaces.IDataSourceConnector.ConnectionException; /** * Servlet implementation class NyRekvisitionServlet */ @SuppressWarnings("serial") @WebServlet("/NyRekvisitionServlet") public class NyRekvisitionServlet extends HttpServlet { private static final String HENV_AFD = "henv_afd"; private static final String PATIENT_TLF = "patient_tlf"; private static final String PATIENT_NAVN = "patient_navn"; private static final String PATIENT_ADRESSE = "patient_adresse"; private static final String PATIENT_CPR = "patient_cpr"; private static final boolean DEBUG = false; /** * @see HttpServlet#HttpServlet() */ public NyRekvisitionServlet() { super(); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Getting List of modalities - first create connection Connection conn = null; try { conn = DataSourceConnector.getConnection(); } catch (ConnectionException e) { //Connection Fails TODO message to user e.printStackTrace(); } //And DAO ModalitetDao modDao = new ModalitetDaoImpl(conn); //Getting Modalities Modalitet[] modList = modDao.findDynamic(null, 0, -1, null); request.setAttribute(Const.MODALITY_LIST, modList); if (Const.DEBUG) System.out.println(modList); request.getRequestDispatcher(Const.NEW_REKVISITION_PAGE).forward(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Getting active user Bruger activeBruger = (Bruger) request.getSession().getAttribute(Const.ACTIVE_USER); //Checking if activeUser if (activeBruger == null) response.sendRedirect(Const.MAIN_SERVLET); request.setCharacterEncoding("UTF-8"); //Getting a database connection.... Connection conn = null; try { conn = DataSourceConnector.getConnection(); } catch (ConnectionException e1) { e1.printStackTrace(); } //Getting active user //Storing patient data. Integer ptId = storePatient(request, conn, activeBruger); //Making Rekvisition DTO RekvisitionExtended rek = new RekvisitionExtended(); rek.setPaaroerende(request.getParameter("paaroerende")); rek.setSamtykke(convertSamtykke(request)); //TODO validate samtykke. rek.setTriage(request.getParameter("triage")); rek.setCave(request.getParameter("cave"));//TODO validate try { rek.setRekvirentId(Integer.valueOf(request.getParameter("rekvirent_id"))); } catch (NumberFormatException e){ //Should never happen TODO - rek.setRekvirentId(null); e.printStackTrace(); } rek.setRekvirentId(activeBruger.getBrugerId()); rek.setHenvAfd(request.getParameter(HENV_AFD)); rek.setHenvLaege(request.getParameter("henv_laege")); rek.setKontaktTlf(request.getParameter("kontakt_tlf")); rek.setUdfIndlagt(Boolean.valueOf(request.getParameter("udf_indlagt"))); rek.setAmbulant(!rek.getUdfIndlagt()); rek.setHenvistTil(convertHenvistTil(request)); rek.setHospitalOenske(convertHospitalOenske(request)); rek.setPrioritering(convertPrioritering(request)); //Get undersøgelsesType data og gem en ny. Integer USTypeID = -1; UndersoegelsesType USType = new UndersoegelsesType(); USType.setModalitetId(Integer.valueOf(request.getParameter("modalitet_navn"))); USType.setUndersoegelsesNavn(request.getParameter("undersoegelses_type")); UndersoegelsesTypeDao usTypeDao = new UndersoegelsesTypeDaoImpl(conn) ; try { USTypeID = usTypeDao.insert(USType); } catch (DaoException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } rek.setUndersoegelsesTypeId(USTypeID); //TODO FIXXX!!! rek.setKliniskProblemstilling(request.getParameter("klinisk_problemstilling")); rek.setAmbulantKoersel(convertAmbulantKoersel(request)); rek.setIndlaeggelseTransport(convertIndlaeggelseTransport(request)); rek.setDatoForslag(request.getParameter("dato_forslag")); rek.setGraviditet(Boolean.valueOf(request.getParameter("graviditet"))); rek.setHoerehaemmet(getBoolFromCheckbox(request,"hoerehaemmet")); rek.setSynshaemmet(getBoolFromCheckbox(request, "synshaemmet")); rek.setAmputeret(getBoolFromCheckbox(request, "amputeret")); rek.setKanIkkeStaa(getBoolFromCheckbox(request, "kan_ikke_staa")); rek.setDement(getBoolFromCheckbox(request, "dement")); rek.setAfasi(getBoolFromCheckbox(request, "afasi")); try { rek.setIltLiterPrmin(Integer.valueOf(request.getParameter("ilt"))); } catch (NumberFormatException e){ rek.setIltLiterPrmin(null); } rek.setTolkSprog(request.getParameter("tolk")); rek.setIsolation(request.getParameter("isolation")); try { rek.setCytostatikaDato(java.sql.Date.valueOf(request.getParameter("cytostatika"))); System.out.println(rek.getCytostatikaDato()); } catch (IllegalArgumentException e) { rek.setCytostatikaDato(null); } rek.setTidlBilledDiagnostik(request.getParameter("tidl_billed_diagnostik")); rek.setPatientId(ptId); rek.setStatus(RekvisitionExtended.Status.PENDING); rek.setAfsendtDato(new Date()); System.out.println(rek); //Check Modalitet String modalitet = request.getParameter("modalitet_navn"); // can not switch on null - makes empty string instead should not happen modalitet = modalitet == null ? "" : modalitet; switch (modalitet) { case "invasiv_UL": Integer ULSkemaID = storeULInvKontrolSkema(request,response); rek.setInvasivULKontrolskemaId(ULSkemaID); break; case "MR": Integer MRSkemaID = null; try { MRSkemaID = storeMRSkema(request, response); } catch (DaoException e1) { // TODO Error page??? e1.printStackTrace(); } rek.setMRKontrolskemaId(MRSkemaID); break; case "CT_kontrast": Integer CTKSkemaID = null; try { CTKSkemaID = storeCTKSkema(request, response); } catch (DaoException e1) { // TODO Error page??? e1.printStackTrace(); } rek.setCTKontrastKontrolskemaId(CTKSkemaID); break; case "PETCT": Integer PETCTSkemaID = null; try { PETCTSkemaID = storePETCTSkema(request,response); } catch (DaoException e1) { // TODO Error page??? e1.printStackTrace(); } rek.setPETCTKontrolskemaId(PETCTSkemaID); break; default: //Now store the requisition RekvisitionDao rekDao = new RekvisitionDaoImplExt(conn); try { rekDao.insert(rek); } catch (DaoException e) { // TODO Auto-generated catch block e.printStackTrace(); } //HopeFully it went well ;) //TODO - real page PrintWriter out = response.getWriter(); out.println("<HTML><BODY>Tak for din henvendelse - du kan følge med i status for din rekvisition i oversigten <BR>"); out.println("<A HREF='RekvisitionServlet'>Tilbage til rekvisitioner</A></BODY><HTML>"); break; } } private Integer storePatient(HttpServletRequest request, Connection conn, Bruger activeBruger) { Patient pt = new Patient(); // pt.setFoedselsdag(Timestamp.valueOf(parseCPRBirthday(request.getParameter(PATIENT_CPR)))); pt.setFoedselsdag(java.sql.Date.valueOf(parseCPRBirthday(request.getParameter(PATIENT_CPR)))); pt.setPatientCpr(request.getParameter(PATIENT_CPR)); pt.setPatientAdresse(request.getParameter(PATIENT_ADRESSE)); pt.setPatientNavn(request.getParameter(PATIENT_NAVN)); pt.setPatientTlf(request.getParameter(PATIENT_TLF)); pt.setStamafdeling(activeBruger.getBrugerNavn()); if (Const.DEBUG)System.out.println(pt); //Time to store patient Integer ptId = null; PatientDao ptDao = new PatientDaoImpl(conn); try { ptId = ptDao.insert(pt); } catch (DaoException e1) { e1.printStackTrace(); } return ptId; } private Integer storePETCTSkema(HttpServletRequest request, HttpServletResponse response) throws DaoException { Connection conn = null; try { conn = DataSourceConnector.getConnection(); } catch (ConnectionException e1) { e1.printStackTrace(); } //TODO remove if (request.getSession().getAttribute(Const.ACTIVE_USER) == null) { BrugerDao bDao = new BrugerDaoImpl(conn); Bruger abruger = bDao.findByPrimaryKey(1); request.getSession().setAttribute(Const.ACTIVE_USER, abruger); } PETCTKontrolskema pck = new PETCTKontrolskema(); pck.setFormaal(convertFormaalMetode(request)); pck.setFormaalTekst(request.getParameter("formaal_text")); pck.setKanPtLiggeStille30(Boolean.valueOf(request.getParameter("kanPtLiggeStille30"))); pck.setPtTaalerFaste(Boolean.valueOf(request.getParameter("ptTaalerFaste"))); pck.setDiabetes(Boolean.valueOf(request.getParameter("diabetes"))); pck.setDMBeh(request.getParameter("DM_Beh")); pck.setSmerter(Boolean.valueOf(request.getParameter("smerter"))); pck.setRespInsuff(Boolean.valueOf(request.getParameter("respInsuff"))); pck.setKlaustrofobi(Boolean.valueOf(request.getParameter("klaustrofobi"))); pck.setAllergi(Boolean.valueOf(request.getParameter("allergi"))); pck.setAllergiTekst(request.getParameter("allergi_tekst")); pck.setFedme(Boolean.valueOf(request.getParameter("fedme"))); pck.setVaegt(Integer.valueOf(request.getParameter("vaegt"))); pck.setBiopsi(Boolean.valueOf(request.getParameter("biopsi"))); pck.setBiopsiTekst(request.getParameter("biopsi_tekst")); pck.setOperation(Boolean.valueOf(request.getParameter("operation"))); pck.setOperationTekst(request.getParameter("operation_tekst")); pck.setKemoOgStraale(convertKemostraale(request)); pck.setSidstePKreatTimestamp(Timestamp.valueOf(request.getParameter("straaleDato"))); pck.setNedsatNyreFkt(Boolean.valueOf(request.getParameter("nedsatNyreFkt"))); pck.setSidstePKreatinin(Integer.valueOf(request.getParameter("sidstePKreatinin"))); pck.setSidstePKreatTimestamp(Timestamp.valueOf(request.getParameter("sidstePKreatTimestamp"))); PETCTKontrolskemaDao petctkDao = new PETCTKontrolskemaDaoImpl(conn); return petctkDao.insert(pck); } private Integer storeCTKSkema(HttpServletRequest request, HttpServletResponse response) throws DaoException { Connection conn = null; try { conn = DataSourceConnector.getConnection(); } catch (ConnectionException e1) { e1.printStackTrace(); } //TODO remove if (request.getSession().getAttribute(Const.ACTIVE_USER) == null) { BrugerDao bDao = new BrugerDaoImpl(conn); Bruger abruger = bDao.findByPrimaryKey(1); request.getSession().setAttribute(Const.ACTIVE_USER, abruger); } // Making CTTKontrolskema dto CtKontrastKontrolskema ctk = new CtKontrastKontrolskema(); ctk.setDiabetes(Boolean.valueOf(request.getParameter("diabetes"))); ctk.setNyrefunktion(Boolean.valueOf(request.getParameter("nyrefunktion"))); ctk.setNyreopereret(Boolean.valueOf(request.getParameter("nyreopereret"))); ctk.setHjertesygdom(Boolean.valueOf(request.getParameter("hjertesygdom"))); ctk.setMyokardieinfarkt(Boolean.valueOf(request.getParameter("myokardieinfarkt"))); ctk.setProteinuri(Boolean.valueOf(request.getParameter("proteinuri"))); ctk.setUrinsyregigt(Boolean.valueOf(request.getParameter("urinsyregigt"))); ctk.setOver70(Boolean.valueOf(request.getParameter("over70"))); ctk.setHypertension(Boolean.valueOf(request.getParameter("hypertension"))); ctk.setNsaidPraeparat(Boolean.valueOf(request.getParameter("NSAIDpræparat"))); ctk.setAllergi(Boolean.valueOf(request.getParameter("alergi"))); ctk.setKontraststofreaktion(Boolean.valueOf(request.getParameter("konstrastofreaktion"))); ctk.setAstma(Boolean.valueOf(request.getParameter("astma"))); ctk.setHyperthyreoidisme(Boolean.valueOf(request.getParameter("hyperthyreoidisme"))); ctk.setMetformin(Boolean.valueOf(request.getParameter("metformin"))); ctk.setInterleukin2(Boolean.valueOf(request.getParameter("interleukin"))); ctk.setBetaBlokkere(Boolean.valueOf(request.getParameter("betaBlokkere"))); ctk.setPKreatininVaerdi(request.getParameter("Værdi")); // setPKreatininTimestamp??? ctk.setPtHoejde(Integer.valueOf(request.getParameter("Højde"))); ctk.setPtVaegt(Integer.valueOf(request.getParameter("Vægt"))); CtKontrastKontrolskemaDao ctkDao = new CtKontrastKontrolskemaDaoImpl(conn); return ctkDao.insert(ctk); } private Integer storeMRSkema(HttpServletRequest request, HttpServletResponse response) throws DaoException { Connection conn = null; try { conn = DataSourceConnector.getConnection(); } catch (ConnectionException e1) { e1.printStackTrace(); } //TODO remove if (request.getSession().getAttribute(Const.ACTIVE_USER) == null) { BrugerDao bDao = new BrugerDaoImpl(conn); Bruger abruger = bDao.findByPrimaryKey(1); request.getSession().setAttribute(Const.ACTIVE_USER, abruger); } MRKontrolskema mrk = new MRKontrolskema(); mrk.setPacemaker(Boolean.valueOf(request.getParameter("pacemaker"))); mrk.setMetalImplantater(Boolean.valueOf(request.getParameter("metal_implantater"))); mrk.setMetalImplantaterBeskrivelse(request.getParameter("metal_implantater_beskrivelse")); mrk.setAndetMetalisk(Boolean.valueOf(request.getParameter("andet_metalisk"))); mrk.setAndetMetaliskBeskrivelse(request.getParameter("andet_metalisk_beskrivelse")); mrk.setNyresygdom(Boolean.valueOf(request.getParameter("nyresygdom"))); mrk.setNyresygdomKreatinin(Integer.valueOf(request.getParameter("nyresygdom_kreatinin"))); mrk.setGraviditet(Boolean.valueOf(request.getParameter("graviditet"))); mrk.setGraviditetUge(Integer.valueOf(request.getParameter("graviditet_uge"))); mrk.setKlaustrofobi(Boolean.valueOf(request.getParameter("klaustrofobi"))); mrk.setHoejde(Integer.valueOf(request.getParameter("hoejde"))); mrk.setVaegt(Integer.valueOf(request.getParameter("vaegt"))); mrk.setMRBoern(convertSederingBoern(request)); mrk.setMRVoksen(convertSederingVoksen(request)); mrk.setPraepForsyn(request.getParameter("praep_forsyn")); MRKontrolskemaDao mrkDao = new MRKontrolskemaDaoImpl(conn); return mrkDao.insert(mrk); } private Integer storeULInvKontrolSkema(HttpServletRequest request, HttpServletResponse response) { // TODO Auto-generated method stub return -1; } private String parseCPRBirthday(String foedselsdagString) { // String = request.getParameter(PATIENT_CPR); Integer foedeaar = Integer.valueOf(foedselsdagString.substring(4, 6)); String digit7String = foedselsdagString.substring(6,7); if (digit7String.equalsIgnoreCase("-") ) digit7String = foedselsdagString.substring(7, 8); Integer digit7 = Integer.valueOf(digit7String); if (digit7 <= 3 ){ foedeaar = 1900 + foedeaar; } else { if ((digit7 == 4 || digit7 == 9) && foedeaar >=37){ foedeaar = 1900 + foedeaar; } else { if (foedeaar >=58 && (digit7 !=4||digit7!=9)){ foedeaar = 1800 + foedeaar; } else { foedeaar = 2000 + foedeaar; } } } foedselsdagString = String.valueOf(foedeaar) + "-" + foedselsdagString.substring(2,4)+"-"+foedselsdagString.substring(0, 2); System.out.println("birthday from cpr: " + foedselsdagString); // Date d = new Date(); // System.out.println("Date format: " + d.toString()); // Timestamp t = Timestamp.valueOf(foedselsdagString); // new Date(foedselsdagString); // new Date(123); // System.out.println("come on: " + Date.parse(foedselsdagString)); // System.out.println("new format: " + java.sql.Date.valueOf(d.toString())); // System.out.println("second fomrat: " + Date.parse(d.toString())); // foedselsdagString = foedselsdagString + " 00:00:00.000000000"; return foedselsdagString; } private Boolean getBoolFromCheckbox(HttpServletRequest request, String boxname) { if("on".equals(request.getParameter(boxname))){ // check box is selected return true; } else{ // check box is not selected return false; } } private IndlaeggelseTransport convertIndlaeggelseTransport( HttpServletRequest request) { IndlaeggelseTransport indlTrans; String transString = request.getParameter("indlagt_transport"); if (transString==null) return null; switch (transString) { case "selv": indlTrans = RekvisitionExtended.IndlaeggelseTransport.GAA_UDEN_PORTOER; break; case "portoer": indlTrans = RekvisitionExtended.IndlaeggelseTransport.GAA_MED_PORTOER; break; case "koerestol": indlTrans = RekvisitionExtended.IndlaeggelseTransport.KOERESTOL; break; case "seng": indlTrans = RekvisitionExtended.IndlaeggelseTransport.SENG; break; default: indlTrans=null; break; } return indlTrans; } private AmbulantKoersel convertAmbulantKoersel(HttpServletRequest request) { AmbulantKoersel ambuTrans; String transString = request.getParameter("ambulant_transport"); if (transString==null) return null; switch (transString) { case "ingen": ambuTrans = RekvisitionExtended.AmbulantKoersel.INGEN; break; case "siddende": ambuTrans = RekvisitionExtended.AmbulantKoersel.SIDDENDE; break; case "liggende": ambuTrans = RekvisitionExtended.AmbulantKoersel.LIGGENDE; break; default: ambuTrans = null; break; } return ambuTrans; } private Prioritering convertPrioritering(HttpServletRequest request) { Prioritering prio; String prioString = request.getParameter("prioriterings_oenske"); if (prioString==null)return null; switch (prioString) { case "haste": prio = RekvisitionExtended.Prioritering.HASTE; break; case "fremskyndet": prio = RekvisitionExtended.Prioritering.FREMSKYNDET; break; case "rutine": prio = RekvisitionExtended.Prioritering.RUTINE; break; case "pakke": prio = RekvisitionExtended.Prioritering.PAKKEFORLOEB; break; default: prio = null; break; } return prio; } private HospitalOenske convertHospitalOenske(HttpServletRequest request) { HospitalOenske hospOensk; String hospOenskString = request.getParameter("hospitals_oenske"); if (hospOenskString==null) return null; switch (hospOenskString) { case "hilleroed": hospOensk = RekvisitionExtended.HospitalOenske.HILLEROED; break; case "frederikssund": hospOensk = RekvisitionExtended.HospitalOenske.FREDERIKSSUND; break; case "helsingoer": hospOensk = RekvisitionExtended.HospitalOenske.HELSINGOER; break; default: hospOensk=null; break; } return hospOensk; } private HenvistTil convertHenvistTil(HttpServletRequest request) { HenvistTil henv; String henvString = request.getParameter("henvist_til"); if (henvString==null) return null; switch (henvString) { case "radiologisk": henv = RekvisitionExtended.HenvistTil.RADIOLOGISK; break; case "klinfys": henv = RekvisitionExtended.HenvistTil.KLINISK; break; default: henv = null; break; } return henv; } private Samtykke convertSamtykke(HttpServletRequest request) { Samtykke samtykke; String samtykkeString = request.getParameter("samtykke"); if (samtykkeString == null) return null; switch (samtykkeString) { case "ja": samtykke = RekvisitionExtended.Samtykke.JA; break; case "nej": samtykke = RekvisitionExtended.Samtykke.NEJ; break; default: samtykke = RekvisitionExtended.Samtykke.UDEN_SAMTYKKE; break; } return samtykke; } private MRBoern convertSederingBoern(HttpServletRequest request){ MRBoern mrboern; String mrboernString = request.getParameter("sederingBoern"); if (mrboernString == null) return null; switch (mrboernString) { case "uden_sedering": mrboern = MRKontrolskema.MRBoern.UDEN_SEDERING; break; case "i_generel_anaestesi": mrboern = MRKontrolskema.MRBoern.I_GENEREL_ANAESTESI; break; default: mrboern = MRKontrolskema.MRBoern.UDEN_SEDERING; break; } return mrboern; } private MRVoksen convertSederingVoksen(HttpServletRequest request){ MRVoksen mrvoksen; String mrvoksenString = request.getParameter("sederingVoksne"); if (mrvoksenString == null) return null; switch (mrvoksenString) { case "uden_sedering": mrvoksen = MRKontrolskema.MRVoksen.UDEN_SEDERING; break; case "i_generel_anaestesi": mrvoksen = MRKontrolskema.MRVoksen.I_GENEREL_ANAESTESI; break; default: mrvoksen = MRKontrolskema.MRVoksen.UDEN_SEDERING; break; } return mrvoksen; } private KemoOgStraale convertKemostraale(HttpServletRequest request){ KemoOgStraale kemoOgStraale; String kemiOgStraaleString = request.getParameter("aldrigGivetKemo"); if (kemiOgStraaleString == null) return null; switch (kemiOgStraaleString) { case "aldrigGivetKemoJa": kemoOgStraale = PETCTKontrolskema.KemoOgStraale.ALDRIGGIVET; break; case "kemoterapiJa": case "stråleterapiNej": kemoOgStraale = PETCTKontrolskema.KemoOgStraale.KEMOTERAPI; break; case "kemoterapiNej": case "stråleterapiJa": kemoOgStraale = PETCTKontrolskema.KemoOgStraale.STRAALETERAPI; break; default: kemoOgStraale = PETCTKontrolskema.KemoOgStraale.KEMO_OG_STRAALE; break; } return kemoOgStraale; } private Formaal convertFormaalMetode(HttpServletRequest request){ Formaal formaal = null; String formaalString = request.getParameter("formaal"); if (formaalString == null) return null; switch (formaalString) { case "primardiag": formaal = PETCTKontrolskema.Formaal.PRIMAERDIAG; break; case "kontrolbeh": formaal = PETCTKontrolskema.Formaal.KONTROLBEH; break; case "kontrolremission": formaal = PETCTKontrolskema.Formaal.KONTROLREMISSION; break; case "kontrolrecidiv": formaal = PETCTKontrolskema.Formaal.KONTROLRECIDIV; break; } return formaal; } }
NU MED KONTROLSKEMAER - PS den er STOR
Xray/src/servlets/NyRekvisitionServlet.java
NU MED KONTROLSKEMAER - PS den er STOR
<ide><path>ray/src/servlets/NyRekvisitionServlet.java <ide> try { <ide> rek.setRekvirentId(Integer.valueOf(request.getParameter("rekvirent_id"))); <ide> } catch (NumberFormatException e){ <del> //Should never happen TODO - <add> //Should never happen TODO - Now handles by setting rekvirent to null - should give backend exception <ide> rek.setRekvirentId(null); <ide> e.printStackTrace(); <ide> } <ide> } catch (ConnectionException e1) { <ide> e1.printStackTrace(); <ide> } <del> //TODO remove <del> if (request.getSession().getAttribute(Const.ACTIVE_USER) == null) { <del> BrugerDao bDao = new BrugerDaoImpl(conn); <del> Bruger abruger = bDao.findByPrimaryKey(1); <del> request.getSession().setAttribute(Const.ACTIVE_USER, abruger); <del> } <del> <ide> PETCTKontrolskema pck = new PETCTKontrolskema(); <ide> pck.setFormaal(convertFormaalMetode(request)); <ide> pck.setFormaalTekst(request.getParameter("formaal_text")); <ide> } catch (ConnectionException e1) { <ide> e1.printStackTrace(); <ide> } <del> //TODO remove <del> if (request.getSession().getAttribute(Const.ACTIVE_USER) == null) { <del> BrugerDao bDao = new BrugerDaoImpl(conn); <del> Bruger abruger = bDao.findByPrimaryKey(1); <del> request.getSession().setAttribute(Const.ACTIVE_USER, abruger); <del> } <del> <ide> // Making CTTKontrolskema dto <ide> CtKontrastKontrolskema ctk = new CtKontrastKontrolskema(); <ide> ctk.setDiabetes(Boolean.valueOf(request.getParameter("diabetes"))); <ide> conn = DataSourceConnector.getConnection(); <ide> } catch (ConnectionException e1) { <ide> e1.printStackTrace(); <del> } <del> //TODO remove <del> if (request.getSession().getAttribute(Const.ACTIVE_USER) == null) { <del> BrugerDao bDao = new BrugerDaoImpl(conn); <del> Bruger abruger = bDao.findByPrimaryKey(1); <del> request.getSession().setAttribute(Const.ACTIVE_USER, abruger); <del> } <del> <add> } <ide> MRKontrolskema mrk = new MRKontrolskema(); <ide> mrk.setPacemaker(Boolean.valueOf(request.getParameter("pacemaker"))); <ide> mrk.setMetalImplantater(Boolean.valueOf(request.getParameter("metal_implantater")));
Java
apache-2.0
8fe17cd5f52444dcf0de3c7123feccc2604ecde1
0
jmostella/armeria,minwoox/armeria,kojilin/armeria,minwoox/armeria,minwoox/armeria,line/armeria,jonefeewang/armeria,imasahiro/armeria,kojilin/armeria,imasahiro/armeria,dongjinleekr/armeria,trustin/armeria,minwoox/armeria,line/armeria,imasahiro/armeria,dongjinleekr/armeria,line/armeria,line/armeria,kojilin/armeria,jmostella/armeria,minwoox/armeria,jonefeewang/armeria,anuraaga/armeria,minwoox/armeria,trustin/armeria,jonefeewang/armeria,jmostella/armeria,jonefeewang/armeria,anuraaga/armeria,trustin/armeria,anuraaga/armeria,imasahiro/armeria,kojilin/armeria,dongjinleekr/armeria,line/armeria,jmostella/armeria,kojilin/armeria,line/armeria,anuraaga/armeria,jmostella/armeria,dongjinleekr/armeria,anuraaga/armeria,kojilin/armeria,dongjinleekr/armeria,trustin/armeria,jonefeewang/armeria,imasahiro/armeria,trustin/armeria,anuraaga/armeria,trustin/armeria
/* * Copyright 2016 LINE Corporation * * LINE Corporation licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.linecorp.armeria.client.endpoint.zookeeper; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.io.File; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.Watcher.Event.KeeperState; import org.apache.zookeeper.ZooDefs; import org.apache.zookeeper.ZooKeeper; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Charsets; import com.google.common.collect.ImmutableList; import com.linecorp.armeria.client.Endpoint; import junitextensions.OptionAssert; import zookeeperjunit.ZKFactory; import zookeeperjunit.ZKInstance; import zookeeperjunit.ZooKeeperAssert; public class ZooKeeperEndpointGroupTest implements ZooKeeperAssert, OptionAssert { private static final Logger logger = LoggerFactory.getLogger(ZooKeeperEndpointGroup.class); private static final File ROOT_DIR = new File("build" + File.separator + "zookeeper"); static { ROOT_DIR.mkdirs(); } private static final Duration duration = Duration.ofSeconds(5); private static final ZKInstance zkInstance = ZKFactory.apply().withRootDir(ROOT_DIR).create(); private static final String zNode = "/testEndPoints"; private static final int sessionTimeout = 3000; private ZooKeeperEndpointGroup zkEndpointGroup; private static final List<Endpoint> initializedEndpointGroupList = new ArrayList<>(); private static final KeeperState[] expectedStates = { KeeperState.SyncConnected, KeeperState.Disconnected, KeeperState.Expired, KeeperState.SyncConnected }; @Override public ZKInstance instance() { return zkInstance; } @BeforeClass public static void start() { initializedEndpointGroupList.add(Endpoint.of("127.0.0.1", 1234, 2)); initializedEndpointGroupList.add(Endpoint.of("127.0.0.1", 2345, 4)); initializedEndpointGroupList.add(Endpoint.of("127.0.0.1", 3456, 2)); try { zkInstance.start().result(duration); } catch (Throwable throwable) { fail(); } } @AfterClass public static void stop() { try { zkInstance.stop().ready(duration); } catch (Exception e) { logger.warn("Failed to stop the ZooKeeper instance", e); } } @Before public void connectZk() { createOrUpdateZNode(endpointListToByteArray(initializedEndpointGroupList)); //forcing a get on the Option as we should be connected at this stage zkEndpointGroup = new ZooKeeperEndpointGroup( zkInstance.connectString().get(), zNode, sessionTimeout, true); } @After public void disconnectZk() { try { zkEndpointGroup.close(); } catch (Exception e) { fail(); } } @Test public void testUpdateEndpointGroup() { List<Endpoint> expected = ImmutableList.of(Endpoint.of("127.0.0.1", 8001, 2), Endpoint.of("127.0.0.1", 8002, 3)); createOrUpdateZNode(endpointListToByteArray(expected)); assertEquals(expected, zkEndpointGroup.endpoints()); } @Test public void testGetEndpointGroup() { assertEquals(initializedEndpointGroupList, zkEndpointGroup.endpoints()); } @Test public void testConnectionRecovery() throws Exception { ZooKeeper zkHandler1 = zkEndpointGroup.zkFuture().get(); CountDownLatch latch = new CountDownLatch(1); ZooKeeper zkHandler2; //create a new handler with the same sessionId and password zkHandler2 = new ZooKeeper(zkInstance.connectString().get(), sessionTimeout, event -> { if (event.getState() == KeeperState.SyncConnected) { latch.countDown(); } }, zkHandler1.getSessionId(), zkHandler1.getSessionPasswd()); latch.await(); //once connected, close the new handler to cause the original handler session expire zkHandler2.close(); for (KeeperState state : expectedStates) { assertEquals(state, zkEndpointGroup.stateQueue().take()); } } private void createOrUpdateZNode(byte[] nodeValue) { zkInstance.connect().map(closeableZooKeeper -> { if (closeableZooKeeper.exists(zNode).get()) { return closeableZooKeeper.setData(zNode, nodeValue, closeableZooKeeper.exists(zNode, false).getVersion()); } return closeableZooKeeper.create(zNode, nodeValue, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); }); assertExists(zNode); } private static byte[] endpointListToByteArray(List<Endpoint> endpointList) { return endpointList.stream() .map(endPointA -> endPointA.authority() + ':' + endPointA.weight()) .reduce((endPointAStr, endPointBStr) -> endPointAStr + ',' + endPointBStr) .orElse("").getBytes(Charsets.UTF_8); } }
zookeeper/src/test/java/com/linecorp/armeria/client/endpoint/zookeeper/ZooKeeperEndpointGroupTest.java
/* * Copyright 2016 LINE Corporation * * LINE Corporation licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.linecorp.armeria.client.endpoint.zookeeper; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.Watcher.Event.KeeperState; import org.apache.zookeeper.ZooDefs; import org.apache.zookeeper.ZooKeeper; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Charsets; import com.google.common.collect.ImmutableList; import com.linecorp.armeria.client.Endpoint; import junitextensions.OptionAssert; import zookeeperjunit.ZKFactory; import zookeeperjunit.ZKInstance; import zookeeperjunit.ZooKeeperAssert; public class ZooKeeperEndpointGroupTest implements ZooKeeperAssert, OptionAssert { private static final Logger logger = LoggerFactory.getLogger(ZooKeeperEndpointGroup.class); private static final Duration duration = Duration.ofSeconds(5); private static final ZKInstance zkInstance = ZKFactory.apply().create(); private static final String zNode = "/testEndPoints"; private static final int sessionTimeout = 3000; private ZooKeeperEndpointGroup zkEndpointGroup; private static final List<Endpoint> initializedEndpointGroupList = new ArrayList<>(); private static final KeeperState[] expectedStates = { KeeperState.SyncConnected, KeeperState.Disconnected, KeeperState.Expired, KeeperState.SyncConnected }; @Override public ZKInstance instance() { return zkInstance; } @BeforeClass public static void start() { initializedEndpointGroupList.add(Endpoint.of("127.0.0.1", 1234, 2)); initializedEndpointGroupList.add(Endpoint.of("127.0.0.1", 2345, 4)); initializedEndpointGroupList.add(Endpoint.of("127.0.0.1", 3456, 2)); try { zkInstance.start().result(duration); } catch (Throwable throwable) { fail(); } } @AfterClass public static void stop() { try { zkInstance.stop().ready(duration); } catch (Exception e) { logger.warn("Failed to stop the ZooKeeper instance", e); } } @Before public void connectZk() { createOrUpdateZNode(endpointListToByteArray(initializedEndpointGroupList)); //forcing a get on the Option as we should be connected at this stage zkEndpointGroup = new ZooKeeperEndpointGroup( zkInstance.connectString().get(), zNode, sessionTimeout, true); } @After public void disconnectZk() { try { zkEndpointGroup.close(); } catch (Exception e) { fail(); } } @Test public void testUpdateEndpointGroup() { List<Endpoint> expected = ImmutableList.of(Endpoint.of("127.0.0.1", 8001, 2), Endpoint.of("127.0.0.1", 8002, 3)); createOrUpdateZNode(endpointListToByteArray(expected)); assertEquals(expected, zkEndpointGroup.endpoints()); } @Test public void testGetEndpointGroup() { assertEquals(initializedEndpointGroupList, zkEndpointGroup.endpoints()); } @Test public void testConnectionRecovery() throws Exception { ZooKeeper zkHandler1 = zkEndpointGroup.zkFuture().get(); CountDownLatch latch = new CountDownLatch(1); ZooKeeper zkHandler2; //create a new handler with the same sessionId and password zkHandler2 = new ZooKeeper(zkInstance.connectString().get(), sessionTimeout, event -> { if (event.getState() == KeeperState.SyncConnected) { latch.countDown(); } }, zkHandler1.getSessionId(), zkHandler1.getSessionPasswd()); latch.await(); //once connected, close the new handler to cause the original handler session expire zkHandler2.close(); for (KeeperState state : expectedStates) { assertEquals(state, zkEndpointGroup.stateQueue().take()); } } private void createOrUpdateZNode(byte[] nodeValue) { zkInstance.connect().map(closeableZooKeeper -> { if (closeableZooKeeper.exists(zNode).get()) { return closeableZooKeeper.setData(zNode, nodeValue, closeableZooKeeper.exists(zNode, false).getVersion()); } return closeableZooKeeper.create(zNode, nodeValue, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); }); assertExists(zNode); } private static byte[] endpointListToByteArray(List<Endpoint> endpointList) { return endpointList.stream() .map(endPointA -> endPointA.authority() + ':' + endPointA.weight()) .reduce((endPointAStr, endPointBStr) -> endPointAStr + ',' + endPointBStr) .orElse("").getBytes(Charsets.UTF_8); } }
Change ZooKeeper test rootDir from target to build/zookeeper (#337) Motivation: ZooKeeperEndpointGroupTest creates the ZooKeeper work directory under 'target' dierctory. Gradle uses 'build' as the build output directory unlike Maven. As a result, the offending test case leaves the cruft files outside the 'build' directory. Modifications: - Change the rootDir from 'target' to 'build/zookeeper' Result: No more untracked files reported by Git after a build
zookeeper/src/test/java/com/linecorp/armeria/client/endpoint/zookeeper/ZooKeeperEndpointGroupTest.java
Change ZooKeeper test rootDir from target to build/zookeeper (#337)
<ide><path>ookeeper/src/test/java/com/linecorp/armeria/client/endpoint/zookeeper/ZooKeeperEndpointGroupTest.java <ide> import static org.junit.Assert.assertEquals; <ide> import static org.junit.Assert.fail; <ide> <add>import java.io.File; <ide> import java.time.Duration; <ide> import java.util.ArrayList; <ide> import java.util.List; <ide> public class ZooKeeperEndpointGroupTest implements ZooKeeperAssert, OptionAssert { <ide> private static final Logger logger = LoggerFactory.getLogger(ZooKeeperEndpointGroup.class); <ide> <add> private static final File ROOT_DIR = new File("build" + File.separator + "zookeeper"); <add> <add> static { <add> ROOT_DIR.mkdirs(); <add> } <add> <ide> private static final Duration duration = Duration.ofSeconds(5); <del> private static final ZKInstance zkInstance = ZKFactory.apply().create(); <add> private static final ZKInstance zkInstance = ZKFactory.apply().withRootDir(ROOT_DIR).create(); <ide> private static final String zNode = "/testEndPoints"; <ide> private static final int sessionTimeout = 3000; <ide> private ZooKeeperEndpointGroup zkEndpointGroup; <ide> private static final List<Endpoint> initializedEndpointGroupList = new ArrayList<>(); <del> private static final KeeperState[] expectedStates = <del> { <del> KeeperState.SyncConnected, KeeperState.Disconnected, KeeperState.Expired, <del> KeeperState.SyncConnected <del> }; <add> private static final KeeperState[] expectedStates = { <add> KeeperState.SyncConnected, KeeperState.Disconnected, <add> KeeperState.Expired, KeeperState.SyncConnected <add> }; <ide> <ide> @Override <ide> public ZKInstance instance() {
Java
apache-2.0
f6035be6f389f283cdd4042f6cfc581cdad92dfa
0
fengshao0907/bbossgroups-3.5,zofuthan/bbossgroups-3.5,fengshao0907/bbossgroups-3.5,fengshao0907/bbossgroups-3.5,WilliamRen/bbossgroups-3.5,shufudong/bboss,lewis-ing/bbossgroups-3.5,lewis-ing/bbossgroups-3.5,zofuthan/bbossgroups-3.5,WilliamRen/bbossgroups-3.5,ZJU-Shaonian-Biancheng-Tuan/bbossgroups-3.5,shufudong/bboss,shufudong/bboss,bbossgroups/bboss,lewis-ing/bbossgroups-3.5,WilliamRen/bbossgroups-3.5,bbossgroups/bboss,zofuthan/bbossgroups-3.5,lewis-ing/bbossgroups-3.5,WilliamRen/bbossgroups-3.5,shufudong/bboss,WilliamRen/bbossgroups-3.5,ZJU-Shaonian-Biancheng-Tuan/bbossgroups-3.5,bbossgroups/bbossgroups-3.5,WilliamRen/bbossgroups-3.5,WilliamRen/bbossgroups-3.5,ZJU-Shaonian-Biancheng-Tuan/bbossgroups-3.5,ZJU-Shaonian-Biancheng-Tuan/bbossgroups-3.5,zofuthan/bbossgroups-3.5,ZJU-Shaonian-Biancheng-Tuan/bbossgroups-3.5,zofuthan/bbossgroups-3.5,lewis-ing/bbossgroups-3.5,ZJU-Shaonian-Biancheng-Tuan/bbossgroups-3.5,fengshao0907/bbossgroups-3.5,lewis-ing/bbossgroups-3.5,lewis-ing/bbossgroups-3.5,fengshao0907/bbossgroups-3.5,bbossgroups/bbossgroups-3.5,bbossgroups/bbossgroups-3.5,fengshao0907/bbossgroups-3.5,fengshao0907/bbossgroups-3.5,lewis-ing/bbossgroups-3.5,shufudong/bboss,ZJU-Shaonian-Biancheng-Tuan/bbossgroups-3.5,zofuthan/bbossgroups-3.5,zofuthan/bbossgroups-3.5,bbossgroups/bboss,bbossgroups/bboss,bbossgroups/bbossgroups-3.5,WilliamRen/bbossgroups-3.5,zofuthan/bbossgroups-3.5,bbossgroups/bboss,bbossgroups/bbossgroups-3.5,ZJU-Shaonian-Biancheng-Tuan/bbossgroups-3.5,fengshao0907/bbossgroups-3.5
/***************************************************************************** * * * This file is part of the tna framework distribution. * * Documentation and updates may be get from biaoping.yin the author of * * this framework * * * * Sun Public License Notice: * * * * The contents of this file are subject to the Sun Public License Version * * 1.0 (the "License"); you may not use this file except in compliance with * * the License. A copy of the License is available at http://www.sun.com * * * * The Original Code is tag. The Initial Developer of the Original * * Code is biaoping yin. Portions created by biaoping yin are Copyright * * (C) 2000. All Rights Reserved. * * * * GNU Public License Notice: * * * * Alternatively, the contents of this file may be used under the terms of * * the GNU Lesser General Public License (the "LGPL"), in which case the * * provisions of LGPL are applicable instead of those above. If you wish to * * allow use of your version of this file only under the terms of the LGPL * * and not to allow others to use your version of this file under the SPL, * * indicate your decision by deleting the provisions above and replace * * them with the notice and other provisions required by the LGPL. If you * * do not delete the provisions above, a recipient may use your version of * * this file under either the SPL or the LGPL. * * * * biaoping.yin ([email protected]) * * Author of Learning Java * * * *****************************************************************************/ package com.frameworkset.common.tag.pager.tags; import java.util.Locale; import java.util.Stack; import java.util.UUID; import javax.servlet.http.HttpServletRequest; import javax.servlet.jsp.JspException; import org.apache.ecs.html.A; import org.apache.ecs.html.IMG; import org.apache.ecs.html.Input; import org.apache.ecs.html.Option; import org.apache.ecs.html.Script; import org.apache.ecs.html.Select; import org.frameworkset.spi.ApplicationContext; import org.frameworkset.web.servlet.support.RequestContextUtils; import com.frameworkset.common.tag.TagUtil; import com.frameworkset.common.tag.pager.config.PageConfig; import com.frameworkset.platform.cms.driver.jsp.CMSServletRequest; import com.frameworkset.util.StringUtil; /** * * ɵť磺һҳһҳҳβҳȵ * * @author biaoping.yin * @version 1.0 */ public final class IndexTag extends PagerTagSupport { /** * չԣťǷʹͼƬ */ private boolean useimage = false; private boolean usegoimage = false; public static final String[] _sizescope = new String[] {"5","10","20","30","40","50","60","70","80","90","100"}; private String sizescope = null; private static boolean enable_page_size_set = ApplicationContext.getApplicationContext().getBooleanProperty("enable_page_size_set",true); private static boolean enable_page_total_size = ApplicationContext.getApplicationContext().getBooleanProperty("enable_page_total_size",true); /** * ·ҳûʱǷa * trueĬֵ ӣfalse */ private boolean aindex = false; /** * ҳǰ׺ */ private String numberpre ; /** * ҳ׺ */ private String numberend; // /** // * jquery // */ // private String containerid ; // // /** // * jqueryѡ // */ // private String selector; public String getImagedir() { return imagedir; } public void setImagedir(String imagedir) { // if(imagedir != null) // { // this.imagedir = StringUtil.getRealPath(request, imagedir); // } this.imagedir = imagedir; } public void setUseimage(boolean useimage) { this.useimage = useimage; } /** * ͼƬչԴ */ private String imageextend = " border=0 "; /** * ͼƬչԴ */ private String centerextend ; public String getCenterextend() { return centerextend; } public void setCenterextend(String centerextend) { this.centerextend = centerextend; } /** * * @return */ public String getImageextend() { return imageextend; } public void setImageextend(String imageextend) { if(imageextend != null && !imageextend.equals("")) this.imageextend = imageextend; } /** * չԣťͼƬӦĿ¼ */ private String imagedir = "/include/images"; public static final String first_image = "first.gif"; public static final String next_image = "next.gif"; public static final String pre_image = "pre.gif"; public static final String last_image = "last.gif"; public static final String go_image = "go.jpg"; /**ԿƷҳǩЩťҳ*/ private String export = null; private String style = "V"; /** * Զתлʶ * ΪtruejspҳбһΪ * com.frameworkset.goformformҪָactionmethodΪpost */ private boolean custom = false; public final void setExport(String value) throws JspException { this.export = value; } public void setStyle(String style) { this.style = style; } public final String getExport() { return export; } public String getStyle() { return style; } /** * Ϊ7byteֽڣÿֽڵֵΪ01 * ֱƶӦλϵİťǷ * 0ʾӦλϵİť֣�� */ protected byte[] switchcase = new byte[9]; /** * мҳǸΪ-1ʱûмҳ */ private int tagnumber = -1; public int getTagnumber() { return tagnumber; } public void setTagnumber(int tagnumber) { this.tagnumber = tagnumber; } /** * мҳʽ */ private String classname; public String getClassname() { return classname; } public void setClassname(String classname) { this.classname = classname; } protected void parser() { if(getExport() != null) { String temp = getExport(); for (int i = 0; i <switchcase.length && i < temp.length(); i++) switchcase[i] = (byte)(temp.charAt(i) - 48); } } private boolean skip() { return (switchcase[0] & switchcase[1] & switchcase[2] & switchcase[3] & switchcase[4] & switchcase[5] & switchcase[6]& switchcase[7]& switchcase[8]) == 1; } public int doStartTag() throws JspException { super.doStartTag(); if(this.pagerContext == null) { String t_id = "pagerContext." ; HttpServletRequest request = this.getHttpServletRequest(); if(request instanceof CMSServletRequest) { CMSServletRequest cmsRequest = (CMSServletRequest)request; t_id += cmsRequest.getContext().getID() ; } else if(this.id != null && !id.trim().equals("")) { t_id += id; } else t_id += PagerContext.DEFAULT_ID; this.pagerContext = (PagerContext)request.getAttribute(t_id); } //indexhelper = new IndexHelper(pagerContext); if (pagerContext == null || pagerContext.ListMode()) { return SKIP_BODY; } //ҳЩťҪʾexport parser(); if(imagedir != null) { this.imagedir = StringUtil.getRealPath(request, imagedir); } if(!skip()) try { String output = generateContent(); // System.out.println(output); this.getJspWriter().print(output); } catch (Exception e) { throw new JspException(e.getMessage()); } return SKIP_BODY; } // public static void main(String[] args) // { // byte[] switchcase = new byte[7]; // String test = "1000000"; // System.out.println("test:"+test.charAt(0)); // switchcase[0] = (byte)(test.charAt(0) - 48); // System.out.println(switchcase[0]); // } public int doEndTag() throws JspException { // if (indexTagExport != null) { // String name; // if ((name = indexTagExport.getItemCount()) != null) { // restoreAttribute(name, oldItemCount); // oldItemCount = null; // } // // if ((name = indexTagExport.getPageCount()) != null) { // restoreAttribute(name, oldPageCount); // oldPageCount = null; // } // } // super.doEndTag();//Ƿ⣬biaoping.yin20081121 this.custom = false; export = null; style = "V"; switchcase = new byte[9]; this.pageContext = null; imagedir = "/include/images"; this.imageextend = " border=0 "; this.useimage = false; this.tagnumber = -1; this.classname = null; this.centerextend = null; // pagerContext.getContainerid() = null; // pagerContext.getSelector() = null; this.sizescope = null; this.usegoimage = false; this.numberend = null; this.numberpre = null; this.aindex = false; return EVAL_PAGE; } public void release() { export = null; super.release(); } /* (non-Javadoc) * @see com.frameworkset.common.tag.BaseTag#generateContent() */ /** * */ public String generateContent() { StringBuffer ret = new StringBuffer(); //webӦjavascriptűļwapӦ boolean needScript = (pagerContext.indexs == null || pagerContext.indexs.isEmpty()); if(needScript) { if(!pagerContext.isWapflag()) ret.append(this.getScript()); } Locale locale = RequestContextUtils.getRequestContextLocal(request); String total_label = TagUtil.tagmessageSource.getMessage("bboss.tag.pager.total",locale) ; String total_page_label = TagUtil.tagmessageSource.getMessage("bboss.tag.pager.total.page",locale) ; String total_records_label = TagUtil.tagmessageSource.getMessage("bboss.tag.pager.total.records",locale) ; // ret.append( // "<table width=\"100%\" border=\"0\" align=\"center\" cellpadding=\"0\" cellspacing=\"1\">"); //ret.append("<tr class='TableHead1'>"); //ret.append("<td align='center' colspan=100>"); if(!pagerContext.isWapflag()) { if (needScript && pagerContext.getForm() != null) { String name = pagerContext.getId() + ".PAGE_QUERY_STRING"; ret.append("<input type=\"hidden\" id=\"" + name + "\" name=\"" + name + "\"/>"); } } if( switchcase[8] == 0) { if(enable_page_total_size) ret.append(total_label)// .append("<span class='Total'>").append(!pagerContext.ListMode()?pagerContext.getItemCount():pagerContext.getDataSize()).append("</span>").append(total_records_label);//¼ } //ret.append("<div align=\"right\">"); if (switchcase[0] == 0) { long serial = Math.min(pagerContext.getPageNumber() + 1, pagerContext.getPageCount()); if(!pagerContext.isWapflag()) ret.append("<span class='current'>" + serial + "</span>/"); else ret.append("<span class='current'>" + serial + "</span>/"); } if (switchcase[1] == 0) { if(!pagerContext.isWapflag()) ret.append( pagerContext.getPageCount()).append(total_page_label);//" ҳ" else ret.append( pagerContext.getPageCount()).append(total_page_label);//" ҳ" } if (switchcase[2] == 0) { if(!pagerContext.isWapflag() ) ret.append("<span class='next'>"+this.getFirstContent()).append("</span>"); else ret.append(this.getWapFirstContent()).append(" "); } if (switchcase[3] == 0) { if(!pagerContext.isWapflag()) ret.append("<span class='next'>"+this.getPrevContent()).append("</span> "); else ret.append(this.getWapPrevContent()).append(" "); } if(this.tagnumber > 0) { StringBuffer center = new StringBuffer(); this.getCenterContent((int)pagerContext.getPageNumber(), (int)pagerContext.getPageCount(), center); String temp = center.toString(); ret.append(temp); } if (switchcase[4] == 0) if(!pagerContext.isWapflag()) ret.append("<span class='next'>"+this.getNextContent()).append("</span>"); else ret.append(this.getWapNextContent()).append(" "); if (switchcase[5] == 0) if(!pagerContext.isWapflag()) ret.append("<span class='next'>"+this.getLastContent()).append("</span>"); else ret.append(this.getWapLastContent()).append(" "); if (switchcase[6] == 0) if(!pagerContext.isWapflag()) ret.append(this.getGoContent()); else ret.append(this.getWapGoContent()); if (switchcase.length > 7 ) { if( switchcase[7] == 0) ret.append(this.getMaxPageItem()); } else { if(enable_page_size_set) ret.append(this.getMaxPageItem()); } // else // ret.append(this.getWapGoContent()); /* мҳ */ // ret.append("</div>"); // ret.append("</td>"); // ret.append("</tr>"); // ret.append("</table>"); //ǩջԱҳǩи push(); return ret.toString(); } public String getMaxPageItem() { String defaultsize = pagerContext.getMaxPageItems() + ""; Select select = new Select(); select.setID("__max_page_size"); select.setName("__max_page_size"); if(pagerContext.getContainerid() == null || pagerContext.getContainerid().equals("")) { select.setOnChange("javascript:__chagePageSize(event,'" + pagerContext.getCookieid() + "','__max_page_size','" + pagerContext.getTruePageUrl() + "')"); } else { select.setOnChange("javascript:__chagePageSize(event,'" + pagerContext.getCookieid() + "','__max_page_size','" + pagerContext.getTruePageUrl() + "','"+ pagerContext.getSelector() + "','"+ pagerContext.getContainerid() + "')"); } // Option option = new Option(); // option.setValue(defaultsize); // option.setTagText("¼"); // select.addElement(option); Option option = null; String[] ops = null; if(this.sizescope == null || this.sizescope.equals("")) ops = _sizescope; else ops = this.sizescope.split(","); ops = sortitems(ops,pagerContext.getCustomMaxPageItems()); for(int i =0; i < ops.length; i ++) { option = new Option(); option.setValue(ops[i]); option.setTagText(ops[i]); if(defaultsize.equals(ops[i])) { option.setSelected(true); } select.addElement(option); } Locale locale = RequestContextUtils.getRequestContextLocal(request); String everypage_label = TagUtil.tagmessageSource.getMessage("bboss.tag.pager.everypageshow",locale) ; String everypagerecords_label = TagUtil.tagmessageSource.getMessage("bboss.tag.pager.everypageshow.records",locale) ; return new StringBuffer(" <span class='pages1'>").append(everypage_label)//ÿҳʾ .append(select.toString()).append(everypagerecords_label)// .append("</span>").toString(); } private String[] sortitems(String[] ops,int pagesize) { if(pagesize <= 0 ) return ops; if(ops == null || ops.length <= 0) { return new String[]{pagesize + ""}; } for(int i = 0 ; i < ops.length ; i ++) { String size = ops[i]; try { int size_ = Integer.parseInt(size); if (pagesize == size_) return ops; } catch (Exception e) { continue; } } String[] ret = new String[ops.length + 1]; ret[0] = pagesize + ""; for(int i = 1 ;i< ret.length; i ++) { ret[i] = ops[i - 1]; } return ret; } // /** // * notified by biaoping.yin on 2005-02-16 // * עԭѾƵpagerContext // * Description:Զķҳӵַ // * @param formName // * @param params // * @param promotion // * @param forwardUrl // * @return // * String // */ // private String getCustomUrl(String formName,String params,boolean promotion,String forwardUrl) // { // String customFirstUrl = "javascript:pageSubmit('" // + formName // + "','" // + params // + "','" // + forwardUrl // + "'," // + promotion + ")"; // return customFirstUrl; // // } private String getWapFirstContent() { String firstUrl = pagerContext.getPageUrl(getJumpPage(PagerConst.FIRST_PAGE)); if (firstUrl.equals("")) return ""; String customFirstUrl = null; customFirstUrl = firstUrl; customFirstUrl = StringUtil.replace(customFirstUrl,"&","&amp;"); if(this.getStyle().equals("V")) return "<br/>" + new A().setHref(customFirstUrl).setTagText("ҳ").toString(); else return " " + new A().setHref(customFirstUrl).setTagText("ҳ").toString(); } private static String buildPath(String dir,String fileName) { if(dir == null || dir.equals("")) return fileName; if(dir.endsWith("/")) { return dir + fileName; } else { return dir + "/" + fileName; } } public static String getJqueryUrl(String url,String containerid,String selector) { StringBuffer ret = new StringBuffer(); if(selector != null) ret.append("javascript:loadPageContent('").append(url).append("','").append(containerid).append("','").append(selector).append("');"); else ret.append("javascript:loadPageContent('").append(url).append("','").append(containerid).append("',null);"); return ret.toString(); } private String getFirstContent() { String firstUrl = pagerContext.getPageUrl(getJumpPage(PagerConst.FIRST_PAGE)); Locale locale = RequestContextUtils.getRequestContextLocal(request); String firstpage_label = TagUtil.tagmessageSource.getMessage("bboss.tag.pager.firstpage",locale) ; if (firstUrl.equals("")) { if(!this.useimage) { if(this.aindex) { return new StringBuffer("<a href='#'>") .append(firstpage_label)// ҳ .append("</a>").toString(); } else { return firstpage_label; } } else { IMG image = new IMG(); image.setSrc(buildPath(this.getImagedir(), first_image)); image.setAlt(firstpage_label);// ҳ if(this.imageextend != null) { image.setExtend(this.imageextend); } return image.toString(); } } String customFirstUrl = null; if(pagerContext.getForm() != null) { String params = pagerContext.getQueryString(0,pagerContext.getSortKey(),pagerContext.getDesc()); customFirstUrl = pagerContext.getCustomUrl(pagerContext.getForm(), params, pagerContext.getPromotion(),firstUrl,pagerContext.getId()); } else { customFirstUrl = firstUrl; } if(!this.useimage) { A a = new A(); a.setTagText(firstpage_label);// ҳ; if(pagerContext.getContainerid() == null || pagerContext.getContainerid().equals("")) { a.setHref(customFirstUrl); } else { a.setHref("#"); a.setOnClick(this.getJqueryUrl(customFirstUrl,pagerContext.getContainerid(),pagerContext.getSelector())); } return a.toString(); } else { IMG image = new IMG(); image.setSrc(buildPath(this.getImagedir(), first_image)); image.setAlt(firstpage_label);// ҳ if(this.imageextend != null) { image.setExtend(this.imageextend); } A a = new A(); if(pagerContext.getContainerid() == null || pagerContext.getContainerid().equals("")) { a.setHref(customFirstUrl); } else { a.setOnClick(this.getJqueryUrl(customFirstUrl,pagerContext.getContainerid(),pagerContext.getSelector())); } a.addElement(image); return a.toString(); } //1ҳ ҳһҳһҳβҳ ת ҳ //return ret.toString(); } // private String getFirstContent() { // String firstUrl = pagerContext.getPageUrl(getJumpPage(PagerConst.FIRST_PAGE)); // // if (firstUrl.equals("")) // { // if(!this.useimage) // return " ҳ"; // else // { // IMG image = new IMG(); // // image.setSrc(buildPath(this.getImagedir(), first_image)); // image.setAlt(" ҳ"); // if(this.imageextend != null) // { // // image.setExtend(this.imageextend); // } // // return image.toString(); // } // } // String customFirstUrl = null; // if(pagerContext.getForm() != null) // { // String params = pagerContext.getQueryString(0,pagerContext.getSortKey(),pagerContext.getDesc()); // customFirstUrl = pagerContext.getCustomUrl(pagerContext.getForm(), // params, // pagerContext.getPromotion(),firstUrl,pagerContext.getId()); // } // else // { // customFirstUrl = firstUrl; // } // // if(!this.useimage) // { // return new A().setHref(customFirstUrl).setTagText(" ҳ").toString(); // } // else // { // IMG image = new IMG(); // // image.setSrc(buildPath(this.getImagedir(), first_image)); // image.setAlt(" ҳ"); // if(this.imageextend != null) // { // image.setExtend(this.imageextend); // } // return new A().setHref(customFirstUrl).addElement(image).toString(); // // } // // //1ҳ ҳһҳһҳβҳ ת ҳ // // //return ret.toString(); // } public static void main(String args[]) { // IMG image = new IMG(); // image.setSrc(buildPath("aaa", "bbb.gif")); // image.setAlt("ҳ"); // image.setExtend(" border=0 "); // System.out.println(new A().setHref("www.sina.com.cn").addElement(image).toString()); System.out.println(UUID.randomUUID().toString()); long start = System.currentTimeMillis(); String gotopageid = UUID.randomUUID().toString(); long end = System.currentTimeMillis(); System.out.println(gotopageid + ":"+ (end - start)); // UUIDGenerator generator = UUIDGenerator.getInstance(); // gotopageid = generator.generateRandomBasedUUID().toString(); start = System.currentTimeMillis(); // gotopageid = generator.generateRandomBasedUUID().toString(); end = System.currentTimeMillis(); System.out.println(gotopageid + ":"+ (end - start)); } // private String getNavigationUrl(int offset,String sortKey) // { // String forwardUrl = pagerContext.getOffsetUrl(offset,sortKey); // String customUrl = null; // if(pagerContext.getForm() != null) // { // customUrl = pagerContext.getCustomUrl(pagerContext.getForm(), // pagerContext.getQueryString(offset,sortKey), // pagerContext.getPromotion(), // forwardUrl); // // } // else // customUrl = forwardUrl; // return customUrl; // } /** * ȡһҳhtml * @return String */ private String getWapPrevContent() { StringBuffer ret = new StringBuffer(); if (!pagerContext.hasPrevPage()) return ""; long offset = pagerContext.getPrevOffset(); String sortKey = pagerContext.getSortKey(); String prevurl = pagerContext.getOffsetUrl(offset,sortKey,pagerContext.getDesc()); String customPrevutl = null; customPrevutl = prevurl; //String prevurl = pagerContext.getPageUrl(getJumpPage(PagerConst.PRE_PAGE)); customPrevutl = StringUtil.replace(customPrevutl,"&","&amp;"); if(this.getStyle().equals("V")) return "<br/>" + new A().setHref(customPrevutl).setTagText("һҳ"); else return " " + new A().setHref(customPrevutl).setTagText("һҳ"); } private String getPrevContent() { Locale locale = RequestContextUtils.getRequestContextLocal(request); String prepage_label = TagUtil.tagmessageSource.getMessage("bboss.tag.pager.prepage",locale) ; if (!pagerContext.hasPrevPage()) { // return "һҳ"; if(!this.useimage) { if(this.aindex) { return new StringBuffer("<a href='#'>") .append(prepage_label)//һҳ .append("</a>").toString(); } else { return prepage_label//һҳ ; } } else { IMG image = new IMG(); image.setSrc(buildPath(this.getImagedir(), this.pre_image)); image.setAlt(prepage_label);//һҳ if(this.imageextend != null) { image.setExtend(this.imageextend); } return image.toString(); } } long offset = pagerContext.getPrevOffset(); String sortKey = pagerContext.getSortKey(); String prevurl = pagerContext.getOffsetUrl(offset,sortKey,pagerContext.getDesc()); String customPrevutl = null; if(pagerContext.getForm() != null) { customPrevutl = pagerContext.getCustomUrl(pagerContext.getForm(), pagerContext.getQueryString(offset,sortKey,pagerContext.getDesc()), pagerContext.getPromotion(), prevurl,pagerContext.getId()); } else customPrevutl = prevurl; //String prevurl = pagerContext.getPageUrl(getJumpPage(PagerConst.PRE_PAGE)); if(!this.useimage) { A a = new A(); a.setTagText(prepage_label);//һҳ if(pagerContext.getContainerid() == null || pagerContext.getContainerid().equals("")) { a.setHref(customPrevutl); } else { a.setHref("#"); a.setOnClick(this.getJqueryUrl(customPrevutl,pagerContext.getContainerid(),pagerContext.getSelector())); } return a.toString(); // return "" + new A().setHref(customPrevutl).setTagText("һҳ"); } else { IMG image = new IMG(); image.setSrc(buildPath(this.getImagedir(), pre_image)); image.setAlt(prepage_label);//һҳ if(this.imageextend != null) { image.setExtend(this.imageextend); } A a = new A(); if(pagerContext.getContainerid() == null || pagerContext.getContainerid().equals("")) { a.setHref(customPrevutl); } else { a.setOnClick(this.getJqueryUrl(customPrevutl,pagerContext.getContainerid(),pagerContext.getSelector())); } a.addElement(image); return "" + a.toString(); // return "" + new A().setHref(customPrevutl).addElement(image).toString(); // return new A().setHref(customFirstUrl).addElement(image).toString(); } } private String getCenterPageUrl(long offset,String sortKey) { StringBuffer ret = new StringBuffer(); // long offset = pagerContext.getPrevOffset(); // String sortKey = pagerContext.getSortKey(); String prevurl = pagerContext.getOffsetUrl(offset,sortKey,pagerContext.getDesc()); String customPrevutl = null; if(pagerContext.getForm() != null) { customPrevutl = pagerContext.getCustomUrl(pagerContext.getForm(), pagerContext.getQueryString(offset,sortKey,pagerContext.getDesc()), pagerContext.getPromotion(), prevurl,pagerContext.getId()); } else customPrevutl = prevurl; return customPrevutl; } /** * ȡwapһҳַ * @return String */ private String getWapNextContent() { if (pagerContext.hasNextPage()) { long offset = pagerContext.getNextOffset(); String sortKey = pagerContext.getSortKey(); String nextUrl = pagerContext.getOffsetUrl(offset,pagerContext.getSortKey(),pagerContext.getDesc()); //String prevurl = pagerContext.getOffsetUrl(offset,sortKey); String customNextUrl = null; customNextUrl = nextUrl; customNextUrl = StringUtil.replace(customNextUrl,"&","&amp;"); //String nextUrl = pagerContext.getPageUrl(getJumpPage(PagerConst.NEXT_PAGE)); if(this.getStyle().equals("V")) return "<br/>" + new A().setHref(customNextUrl).setTagText("һҳ"); else return " " + new A().setHref(customNextUrl).setTagText("һҳ"); } return ""; } /** * ȡһҳhtml * * To change the template for this generated type comment go to * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments */ private String getNextContent() { Locale locale = RequestContextUtils.getRequestContextLocal(request); String nextpage_label = TagUtil.tagmessageSource.getMessage("bboss.tag.pager.nextpage",locale) ; if (pagerContext.hasNextPage()) { long offset = pagerContext.getNextOffset(); String sortKey = pagerContext.getSortKey(); String nextUrl = pagerContext.getOffsetUrl(offset,pagerContext.getSortKey(),pagerContext.getDesc()); //String prevurl = pagerContext.getOffsetUrl(offset,sortKey); String customNextUrl = null; if(pagerContext.getForm() != null) { customNextUrl = pagerContext.getCustomUrl(pagerContext.getForm(), pagerContext.getQueryString(offset,sortKey,pagerContext.getDesc()), pagerContext.getPromotion(), nextUrl,pagerContext.getId()); } else customNextUrl = nextUrl; if(!this.useimage) { A a = new A(); a.setTagText(nextpage_label);//"һҳ" if(pagerContext.getContainerid() == null || pagerContext.getContainerid().equals("")) { a.setHref(customNextUrl); } else { a.setHref("#"); a.setOnClick(this.getJqueryUrl(customNextUrl,pagerContext.getContainerid(),pagerContext.getSelector())); } return a.toString(); } else { IMG image = new IMG(); image.setSrc(buildPath(this.getImagedir(), this.next_image)); image.setAlt(nextpage_label);//"һҳ" if(this.imageextend != null) { image.setExtend(this.imageextend); } A a = new A(); if(pagerContext.getContainerid() == null || pagerContext.getContainerid().equals("")) { a.setHref(customNextUrl); } else { a.setOnClick(this.getJqueryUrl(customNextUrl,pagerContext.getContainerid(),pagerContext.getSelector())); } a.addElement(image); return a.toString(); // return new A().setHref(customNextUrl).addElement(image).toString(); // return new A().setHref(customFirstUrl).addElement(image).toString(); } } if(!this.useimage) { if(this.aindex) { return new StringBuffer("<a href='#'>").append(nextpage_label)//"һҳ" .append("</a>").toString(); } else { return nextpage_label//"һҳ" ; } } else { IMG image = new IMG(); image.setSrc(buildPath(this.getImagedir(), next_image)); image.setAlt(nextpage_label);//"һҳ" if(this.imageextend != null) { image.setExtend(this.imageextend); } return image.toString(); } // return "һҳ"; } /** * ȡwapβҳť * @return String */ private String getWapLastContent() { String lastUrl = pagerContext.getPageUrl(getJumpPage(PagerConst.LAST_PAGE)); if (lastUrl.equals("")) return ""; long offset = pagerContext.getLastOffset(); String sortKey = pagerContext.getSortKey(); String customLastUrl = null; customLastUrl = lastUrl; customLastUrl = StringUtil.replaceAll(customLastUrl,"&","&amp;"); if(this.getStyle().equals("V")) return "<br/>" + new A().setHref(customLastUrl).setTagText("β ҳ"); else return " " + new A().setHref(customLastUrl).setTagText("β ҳ"); } /** * мҳַ * @param tagnumber * @param currentPage * @param totalPage * @param output * @return */ private void getCenterContent(int currentPage,int totalPage,StringBuffer output) { /* ʼҳ */ // System.out.println("currentPage:"+currentPage); // System.out.println("totalPage:"+totalPage); if(tagnumber >0){ int start = 1; int end = 1; if(tagnumber<=2) tagnumber = 3; // if(tagnumber>3) { if(currentPage>tagnumber){ start = (int)currentPage-(int)Math.floor(tagnumber/2); }else{ if((currentPage%tagnumber)>=(int)Math.floor(tagnumber/2) || currentPage%tagnumber==0 ) start = (int)currentPage-(int)Math.floor(tagnumber/2); } start = start<=0?1:start; /* βҳ */ end = (int)this.tagnumber + start ; if(end > totalPage) { //ҳǴ1ʼ end = (int)totalPage + 1; start = end - (int)this.tagnumber; if(start<=0) start = 1; } } // else{ // if(tagnumber<=2) tagnumber = 3; // start = (int)currentPage-1; // if(start<=0) start = 1 ; // // if(currentPage == 1) end = (int)currentPage + (int)this.tagnumber ; // else end = (int)currentPage + (int)this.tagnumber - 1 ; // if(end>totalPage){ // end = (int)totalPage + 1; // start = end - (int)tagnumber; // if(start<=0) start = 1; // } // } for(int i=start;i<end;i++){ if(totalPage>1){ if((i - 1) ==currentPage){ if(aindex) { if(this.numberpre == null) output.append("<span class='current_page'><a href='#'>").append(i).append("</a></span> "); else output.append("<span class='current_page'><a href='#'>").append(this.numberpre).append(i).append(this.numberend).append("</a></span> "); } else { if(this.numberpre == null) output.append("<span class='current_page'>").append(i).append("</span> "); else output.append("<span class='current_page'>").append(this.numberpre).append(i).append(this.numberend).append("</span> "); } }else{ // Context loop = new VelocityContext(); A a = new A(); if(this.numberpre == null) { a.setTagText(String.valueOf(i)); } else { a.setTagText(this.numberpre +i+this.numberend); } String url = getCenterPageUrl((i-1) * this.pagerContext.getMaxPageItems(),this.pagerContext.getSortKey()); if(pagerContext.getForm() != null) { a.setHref(url); } else { if(pagerContext.getContainerid() != null && !pagerContext.getContainerid().equals("")) { a.setHref("#"); a.setOnClick(getJqueryUrl(url,pagerContext.getContainerid(),pagerContext.getSelector())); } else { a.setHref(url); } } if(centerextend != null) a.setExtend(centerextend); if(this.classname != null && !this.classname.equals("")) a.setClass(classname); // if(this.style != null && !this.style.equals("")) // a.setStyle(style); // loop.put("count",i+""); // long off = (i-1) * this.pagerContext.getMaxPageItems(); // loop.put("currentpath",); // loop.put("classname",this.classname); // loop.put("style",this.style); // output.append(CMSTagUtil.loadTemplate("publish/newsTurnPage/content-loop.vm",loop)); output.append(a); } }else{ // Context loop = new VelocityContext(); // loop.put("count"," "); // loop.put("currentpath",getCurrentPath(i)); // output.append(CMSTagUtil.loadTemplate("publish/newsTurnPage/content-loop.vm",loop)); } } } } /** * ȡβҳť * @return String */ private String getLastContent() { String lastpage_label = TagUtil.tagmessageSource.getMessage("bboss.tag.pager.lastpage",RequestContextUtils.getRequestContextLocal(request)) ; String lastUrl = pagerContext.getPageUrl(getJumpPage(PagerConst.LAST_PAGE)); if (lastUrl.equals("")) { // return "β ҳ"; if(!this.useimage) { if(this.aindex) { return new StringBuffer().append(" <a href='#'>") .append(lastpage_label)//βҳ .append("</a>").toString(); } else { return lastpage_label; } } else { IMG image = new IMG(); image.setSrc(buildPath(this.getImagedir(), last_image)); image.setAlt(lastpage_label);//βҳ if(this.imageextend != null) { image.setExtend(this.imageextend); } return image.toString(); } } long offset = pagerContext.getLastOffset(); String sortKey = pagerContext.getSortKey(); String customLastUrl = null; if(pagerContext.getForm() != null) { customLastUrl = pagerContext.getCustomUrl(pagerContext.getForm(), pagerContext.getQueryString(offset,sortKey,pagerContext.getDesc()), pagerContext.getPromotion(), lastUrl,pagerContext.getId()); } else customLastUrl = lastUrl; if(!this.useimage) { A a = new A(); a.setTagText(lastpage_label);//βҳ if(pagerContext.getContainerid() == null || pagerContext.getContainerid().equals("")) { a.setHref(customLastUrl); } else { a.setHref("#"); a.setOnClick(this.getJqueryUrl(customLastUrl,pagerContext.getContainerid(),pagerContext.getSelector())); } return a.toString(); // return "" + new A().setHref(customLastUrl).setTagText("β ҳ"); } else { IMG image = new IMG(); image.setSrc(buildPath(this.getImagedir(), this.last_image)); image.setAlt(lastpage_label);//βҳ if(this.imageextend != null) { image.setExtend(this.imageextend); } A a = new A(); if(pagerContext.getContainerid() == null || pagerContext.getContainerid().equals("")) { a.setHref(customLastUrl); } else { a.setOnClick(this.getJqueryUrl(customLastUrl,pagerContext.getContainerid(),pagerContext.getSelector())); } a.addElement(image); return a.toString(); // return new A().setHref(customLastUrl).addElement(image).toString(); // return new A().setHref(customFirstUrl).addElement(image).toString(); } } /** * <a id="bridge"></a> * function goTo(url,maxPageItem,hasParam) * { * * var go = document.all.item("go").value; * var goPage = parserInt(go); * if(isNaN(goPage)) * { * alert("תҳ"); * return; * } * var offset = (goPage - 1) * maxPageItems; * document.bridge.href = url + (hasParam?"&":"?" + "pager.offset=" + offset); * document.bridge.onClick(); * } * @return String */ private String getScript() { StringBuffer script = new StringBuffer(); HttpServletRequest request = this.getHttpServletRequest(); if(!this.isCustom()) { // script.append(new Script() // .setSrc(StringUtil.getRealPath(request, "/include/pager.js")) // .setLanguage("javascript") // .toString()); if(pagerContext.getContainerid() == null || pagerContext.getContainerid().equals("")) { script.append(PageConfig.getPagerConfig(request)); //jquery script.append(PageConfig.getPagerCss(request)); //jquery } else { request.setAttribute(PageConfig.jqueryscript_set_flag,"true"); } } else { script.append(new Script() .setSrc(StringUtil.getRealPath(request, "/include/pager_custom.js")) .setLanguage("javascript") .toString()); script.append(PageConfig.getPagerCss(request)); //jquery } if(this.pagerContext.getCommitevent() != null) { if(this.pagerContext.getCommitevent().startsWith("'") || this.pagerContext.getCommitevent().startsWith("\"")) { script .append(new Script().setTagText("commitevent = "+ this.pagerContext.getCommitevent() + ";")); } else { script .append(new Script().setTagText("commitevent = \"" + this.pagerContext.getCommitevent() + "\";")); } } return script.toString(); } // public static void main(String[] args ) // // { // // System.out.println(new Script().setTagText("commitevent = \"turnPageSumbmitSet()\";").toString()); // } /** * ȡwapתť * @return String */ private String getWapGoContent() { StringBuffer ret = new StringBuffer(); //.append("ת"); //ret.append("<a id=\"bridge\"></a>"); //ret.append(this.getScript()); long pages = pagerContext.getPageCount(); HttpServletRequest request = this.getHttpServletRequest(); //System.out.println("pagerContext.getPageCount():"+pagerContext.getPageCount()); if (pages > 1) { String goTo = null; goTo = request.getContextPath() + "/include/pager.wmls#goTo('" + pagerContext.getUri() + "'," + pages + "," + pagerContext.getMaxPageItems() + "," + String.valueOf(pagerContext.getParams() > 0) + ","; if(pagerContext.getSortKey() == null) goTo += "null"; else goTo += "'" + pagerContext.getSortKey() + "'"; goTo += "," + pagerContext.getDesc() + ",'" + pagerContext.getId() + "')"; // validator.wmlsеⲿvalidate()ЧԼ String doEvent = "<do type=\"accept\" label=\"ת\">" + "<go href=\"" + goTo + "\"/>" + "</do>"; //a.setStyle("cursor:hand"); ret.append(doEvent); ret .append("<input name='gotopage' type='text' size='2'/>") .append("ҳ"); } else { // ret // .append("ת ") // .append( // new Input() // .setName("gotopage") // .setType("text") // .setSize(2) // .setDisabled(true) // ) // .append(" ҳ"); } //<input name="txtName2" type="text" size="4" attrib="editor"> // <a href="#">ҳ</a> if(this.getStyle().equals("V")) return "<br/>" + ret.toString(); else return " " + ret.toString(); } // /** // * ȡתť // * @return String // */ // private String getGoContent() { // StringBuffer ret = new StringBuffer(); //.append("ת"); // //ret.append("<a id=\"bridge\"></a>"); // //ret.append(this.getScript()); // long pages = pagerContext.getPageCount(); // //System.out.println("pagerContext.getPageCount():"+pagerContext.getPageCount()); // if (pages > 1) { // // // String goTo = null; // StringBuffer gogo = new StringBuffer(); // if(pagerContext.getForm() == null) // { // if(pagerContext.getSortKey() != null) // { // goTo = "goTo('" // + pagerContext.getUri() // + "'," // + pages // + "," // + pagerContext.getMaxPageItems() // + "," // + pagerContext.hasParams() // + ",'" // + pagerContext.getSortKey() // + "'," // + pagerContext.getDesc() // + ",'" // + pagerContext.getId() // + "')"; // } // else // { // goTo = "goTo('" // + pagerContext.getUri() // + "'," // + pages // + "," // + pagerContext.getMaxPageItems() // + "," // + pagerContext.hasParams() // + ",null," // + pagerContext.getDesc() // + ",'" // + pagerContext.getId() // + "')"; // } // } // else // { // if(pagerContext.getSortKey() != null) // { // // // goTo = "goTo('" // + pagerContext.getUri() // + "'," // + pages // + "," // + pagerContext.getMaxPageItems() // + "," // + pagerContext.hasParams() // + ",'" // + pagerContext.getSortKey() // + "'," // + pagerContext.getDesc() // + ",'" // + pagerContext.getId() // + "','" // + pagerContext.getForm() // + "','" // + pagerContext.getQueryString() // + "'," // + pagerContext.getPromotion() // + ")"; // } // else // { // goTo = "goTo('" // + pagerContext.getUri() // + "'," // + pages // + "," // + pagerContext.getMaxPageItems() // + "," // + pagerContext.hasParams() // + ",null," // + pagerContext.getDesc() // + ",'" // + pagerContext.getId() // + "','" // + pagerContext.getForm() // + "','" // + pagerContext.getQueryString() // + "'," // + pagerContext.getPromotion() // + ")"; // } // } // // /** // * goTo(url, // pages, // maxPageItem, // hasParam, // sortKey, // formName, // params, // promotion) // */ // // // A a = new A(); // // if(!this.useimage) // { // a.setOnClick(goTo); // // a.setTagText("ת "); // } // else // { // IMG image = new IMG(); // image.setSrc(buildPath(this.getImagedir(), this.go_image)); // image.setAlt("ת"); // if(this.imageextend != null) // { // // image.setExtend(this.imageextend); // } // image.setOnClick(goTo); // // a.addElement(image); // } // a.setName("pager.jumpto"); // a.setID("pager.jumpto"); // a.setHref("#"); // ///a.setStyle("cursor:hand"); // ret.append(a.toString()); // Input go = new Input() // // .setName("gotopage") // .setType("text") // .setSize(2); // // go.setOnKeyDown("keydowngo('pager.jumpto')"); // ret // .append( // go.toString()) // .append(" ҳ"); // } else { // if(!this.useimage) // { // Input go = new Input() // // .setName("gotopage") // .setType("text") // .setSize(2) // .setDisabled(true); // // ret // .append("ת ") // .append( // go.toString() // ) // .append(" ҳ"); // } // else // { // IMG image = new IMG(); // image.setSrc(buildPath(this.getImagedir(), this.go_image)); // image.setAlt("ת"); // if(this.imageextend != null) // { // // image.setExtend(this.imageextend); // } // // Input go = new Input() // // .setName("gotopage") // .setType("text") // .setSize(2) // .setDisabled(true); // // ret // .append(image.toString()) // .append( // go.toString() // ) // .append(" ҳ"); // } // // } // // //<input name="txtName2" type="text" size="4" attrib="editor"> // // <a href="#">ҳ</a> //// if(pagerContext.indexs == null || pagerContext.indexs.isEmpty()) //// { //// //// ret.append("<form action='' name='com.frameworkset.goform' method='post'></form>" ); //// } // return ret.toString(); // } private static final String gopageerror_msg = "תҳתҳΪ"; /** * ȡתť * @return String */ private String getGoContent() { StringBuffer ret = new StringBuffer(); //.append("ת"); //ret.append("<a id=\"bridge\"></a>"); //ret.append(this.getScript()); long pages = pagerContext.getPageCount(); //System.out.println("pagerContext.getPageCount():"+pagerContext.getPageCount()); String uuid = UUID.randomUUID().toString(); String gotopageid = uuid+".go"; Locale locale = RequestContextUtils.getRequestContextLocal(request); String gotopage_label = TagUtil.tagmessageSource.getMessage("bboss.tag.pager.gotopage",locale) ; String page_label = TagUtil.tagmessageSource.getMessage("bboss.tag.pager.page",locale) ; String gopageerror_msg = TagUtil.tagmessageSource.getMessage("bboss.tag.pager.gopageerror_msg",locale) ; if (pages > 1) { String goTo = null; StringBuffer gogo = new StringBuffer(); if(pagerContext.getForm() == null) { if(pagerContext.getSortKey() != null) { gogo.append("goTo('").append(gotopageid).append("','").append(gopageerror_msg).append("',"); if(pagerContext.getContainerid() != null && !pagerContext.getContainerid().equals("")) { gogo.append("'").append(pagerContext.getContainerid()).append("'"); } else { gogo.append("null"); } gogo.append(","); if(pagerContext.getSelector() != null && !pagerContext.getSelector().equals("")) { gogo.append("'").append(pagerContext.getSelector()).append("'"); } else { gogo.append("null"); } gogo.append(",'"); gogo.append(pagerContext.getUri()) .append("',") .append(pages) .append(",") .append(pagerContext.getMaxPageItems()) .append(",") .append(pagerContext.hasParams()) .append(",'") .append(pagerContext.getSortKey()) .append("',") .append(pagerContext.getDesc()) .append(",'") .append(pagerContext.getId()) .append("')"); } else { gogo.append("goTo('").append(gotopageid).append("','").append(gopageerror_msg).append("',"); if(pagerContext.getContainerid() != null && !pagerContext.getContainerid().equals("")) { gogo.append("'").append(pagerContext.getContainerid()).append("'"); } else { gogo.append("null"); } gogo.append(","); if(pagerContext.getSelector() != null && !pagerContext.getSelector().equals("")) { gogo.append("'").append(pagerContext.getSelector()).append("'"); } else { gogo.append("null"); } gogo.append(",'"); gogo.append(pagerContext.getUri()) .append("',") .append(pages) .append(",") .append(pagerContext.getMaxPageItems()) .append(",") .append(pagerContext.hasParams()) .append(",null,") .append(pagerContext.getDesc()) .append(",'") .append(pagerContext.getId()) .append("')"); } } else { if(pagerContext.getSortKey() != null) { gogo.append("goTo('").append(gotopageid).append("','").append(gopageerror_msg).append("',"); if(pagerContext.getContainerid() != null && !pagerContext.getContainerid().equals("")) { gogo.append("'").append(pagerContext.getContainerid()).append("'"); } else { gogo.append("null"); } gogo.append(","); if(pagerContext.getSelector() != null && !pagerContext.getSelector().equals("")) { gogo.append("'").append(pagerContext.getSelector()).append("'"); } else { gogo.append("null"); } gogo.append(",'"); gogo.append(pagerContext.getUri()) .append("',") .append(pages) .append( ",") .append( pagerContext.getMaxPageItems()) .append(",") .append(pagerContext.hasParams()) .append(",'") .append(pagerContext.getSortKey()) .append("',") .append(pagerContext.getDesc()) .append(",'") .append(pagerContext.getId()) .append("','") .append(pagerContext.getForm()) .append("','") .append(pagerContext.getQueryString()) .append("',") .append(pagerContext.getPromotion()) .append(")"); } else { gogo.append("goTo('").append(gotopageid).append("','").append(gopageerror_msg).append("',"); if(pagerContext.getContainerid() != null && !pagerContext.getContainerid().equals("")) { gogo.append("'").append(pagerContext.getContainerid()).append("'"); } else { gogo.append("null"); } gogo.append(","); if(pagerContext.getSelector() != null && !pagerContext.getSelector().equals("")) { gogo.append("'").append(pagerContext.getSelector()).append("'"); } else { gogo.append("null"); } gogo.append(",'"); gogo.append(pagerContext.getUri()) .append("',") .append(pages) .append( ",") .append( pagerContext.getMaxPageItems()) .append(",") .append(pagerContext.hasParams()) .append(",null,") .append(pagerContext.getDesc()) .append(",'") .append(pagerContext.getId()) .append("','") .append(pagerContext.getForm()) .append("','") .append(pagerContext.getQueryString()) .append("',") .append(pagerContext.getPromotion()) .append(")"); } } goTo = gogo.toString(); /** * goTo(url, pages, maxPageItem, hasParam, sortKey, formName, params, promotion) */ String pagerjumpto = uuid+".go"; Input go = (Input) new Input() .setName(gotopageid) .setType("text") .setSize(2) .setClass("page_input"); go.setID(gotopageid); go.setOnKeyDown("keydowngo(event,'"+ pagerjumpto + "')"); if(this.usegoimage){ ret.append(" ") .append(gotopage_label)//ת .append(go.toString()) .append(page_label); //ҳ IMG image = new IMG(); image.setSrc(buildPath(this.getImagedir(), this.go_image)); image.setAlt(gotopage_label); if(this.imageextend != null) { image.setExtend(this.imageextend); } image.setOnClick(goTo); ret.append(image.toString()); }else{ A a = new A(); a.setOnClick(goTo); a.setTagText(gotopage_label);//ת ret.append(a.toString()).append(go.toString()).append(page_label); //ҳ } } else { if(this.usegoimage){ Input go = ((Input) new Input() .setName(gotopageid) .setType("text") .setSize(2) .setClass("page_input")) .setDisabled(true); ret.append(" ") .append(gotopage_label)//ת .append(go.toString()) .append(page_label); //ҳ IMG image = new IMG(); image.setSrc(buildPath(this.getImagedir(), this.go_image)); image.setAlt(gotopage_label);//ת if(this.imageextend != null) { image.setExtend(this.imageextend); } // image.setOnClick(goTo); ret.append(image.toString()); }else{ Input go = ((Input) new Input() .setName(gotopageid) .setType("text") .setSize(2) .setClass("page_input")) .setDisabled(true); ret.append(" ") .append(gotopage_label)//ת .append(go.toString() ) .append(page_label); //ҳ } } //<input name="txtName2" type="text" size="4" attrib="editor"> // <a href="#">ҳ</a> // if(pagerContext.indexs == null || pagerContext.indexs.isEmpty()) // { // // ret.append("<form action='' name='com.frameworkset.goform' method='post'></form>" ); // } return ret.toString(); } private long getJumpPage(int type) { switch (type) { case PagerConst.FIRST_PAGE : return 0; // case PagerConst.PRE_PAGE://ؼ֣Ŀǰûʹ // return pagerContext.getPrevOffset(); // case PagerConst.INDEX_PAGE://ؼ֣Ŀǰûʹ // return 2; // case PagerConst.NEXT_PAGE: // return pagerContext.getNextOffset(); case PagerConst.LAST_PAGE : return pagerContext.getLastPageNumber(); // case PagerConst.GO_PAGE://ؼ֣Ŀǰûʹ // return 2; default : return 2; } } /** * Indexǩʵѹջ * Description: * @return * Object */ public Object push() { if(pagerContext.indexs == null) pagerContext.indexs = new Stack(); return pagerContext.indexs.push(this); } public boolean isCustom() { return custom; } public void setCustom(boolean custom) { this.custom = custom; } /** * @return the sizescope */ public String getSizescope() { return sizescope; } /** * @param sizescope the sizescope to set */ public void setSizescope(String sizescope) { this.sizescope = sizescope; } public boolean isUsegoimage() { return usegoimage; } public void setUsegoimage(boolean usegoimage) { this.usegoimage = usegoimage; } public boolean isAindex() { return aindex; } public void setAindex(boolean aindex) { this.aindex = aindex; } public String getNumberpre() { return numberpre; } public void setNumberpre(String numberpre) { this.numberpre = numberpre; } public String getNumberend() { return numberend; } public void setNumberend(String numberend) { this.numberend = numberend; } // public String getContainerid() // { // return containerid; // } // // // public void setContainerid(String containerid) // { // pagerContext.getContainerid() = containerid; // } // // // public String getSelector() // { // return selector; // } // // // public void setSelector(String selector) // { // pagerContext.getSelector() = selector; // } } /* vim:set ts=4 sw=4: */
bboss-taglib/src/com/frameworkset/common/tag/pager/tags/IndexTag.java
/***************************************************************************** * * * This file is part of the tna framework distribution. * * Documentation and updates may be get from biaoping.yin the author of * * this framework * * * * Sun Public License Notice: * * * * The contents of this file are subject to the Sun Public License Version * * 1.0 (the "License"); you may not use this file except in compliance with * * the License. A copy of the License is available at http://www.sun.com * * * * The Original Code is tag. The Initial Developer of the Original * * Code is biaoping yin. Portions created by biaoping yin are Copyright * * (C) 2000. All Rights Reserved. * * * * GNU Public License Notice: * * * * Alternatively, the contents of this file may be used under the terms of * * the GNU Lesser General Public License (the "LGPL"), in which case the * * provisions of LGPL are applicable instead of those above. If you wish to * * allow use of your version of this file only under the terms of the LGPL * * and not to allow others to use your version of this file under the SPL, * * indicate your decision by deleting the provisions above and replace * * them with the notice and other provisions required by the LGPL. If you * * do not delete the provisions above, a recipient may use your version of * * this file under either the SPL or the LGPL. * * * * biaoping.yin ([email protected]) * * Author of Learning Java * * * *****************************************************************************/ package com.frameworkset.common.tag.pager.tags; import java.util.Locale; import java.util.Stack; import java.util.UUID; import javax.servlet.http.HttpServletRequest; import javax.servlet.jsp.JspException; import org.apache.ecs.html.A; import org.apache.ecs.html.IMG; import org.apache.ecs.html.Input; import org.apache.ecs.html.Option; import org.apache.ecs.html.Script; import org.apache.ecs.html.Select; import org.frameworkset.spi.ApplicationContext; import org.frameworkset.web.servlet.support.RequestContextUtils; import com.frameworkset.common.tag.TagUtil; import com.frameworkset.common.tag.pager.config.PageConfig; import com.frameworkset.platform.cms.driver.jsp.CMSServletRequest; import com.frameworkset.util.StringUtil; /** * * ɵť磺һҳһҳҳβҳȵ * * @author biaoping.yin * @version 1.0 */ public final class IndexTag extends PagerTagSupport { /** * չԣťǷʹͼƬ */ private boolean useimage = false; private boolean usegoimage = false; public static final String[] _sizescope = new String[] {"5","10","20","30","40","50","60","70","80","90","100"}; private String sizescope = null; private static boolean enable_page_size_set = ApplicationContext.getApplicationContext().getBooleanProperty("enable_page_size_set",true); private static boolean enable_page_total_size = ApplicationContext.getApplicationContext().getBooleanProperty("enable_page_total_size",true); /** * ·ҳûʱǷa * trueĬֵ ӣfalse */ private boolean aindex = false; /** * ҳǰ׺ */ private String numberpre ; /** * ҳ׺ */ private String numberend; // /** // * jquery // */ // private String containerid ; // // /** // * jqueryѡ // */ // private String selector; public String getImagedir() { return imagedir; } public void setImagedir(String imagedir) { // if(imagedir != null) // { // this.imagedir = StringUtil.getRealPath(request, imagedir); // } this.imagedir = imagedir; } public void setUseimage(boolean useimage) { this.useimage = useimage; } /** * ͼƬչԴ */ private String imageextend = " border=0 "; /** * ͼƬչԴ */ private String centerextend ; public String getCenterextend() { return centerextend; } public void setCenterextend(String centerextend) { this.centerextend = centerextend; } /** * * @return */ public String getImageextend() { return imageextend; } public void setImageextend(String imageextend) { if(imageextend != null && !imageextend.equals("")) this.imageextend = imageextend; } /** * չԣťͼƬӦĿ¼ */ private String imagedir = "/include/images"; public static final String first_image = "first.gif"; public static final String next_image = "next.gif"; public static final String pre_image = "pre.gif"; public static final String last_image = "last.gif"; public static final String go_image = "go.jpg"; /**ԿƷҳǩЩťҳ*/ private String export = null; private String style = "V"; /** * Զתлʶ * ΪtruejspҳбһΪ * com.frameworkset.goformformҪָactionmethodΪpost */ private boolean custom = false; public final void setExport(String value) throws JspException { this.export = value; } public void setStyle(String style) { this.style = style; } public final String getExport() { return export; } public String getStyle() { return style; } /** * Ϊ7byteֽڣÿֽڵֵΪ01 * ֱƶӦλϵİťǷ * 0ʾӦλϵİť֣�� */ protected byte[] switchcase = new byte[9]; /** * мҳǸΪ-1ʱûмҳ */ private int tagnumber = -1; public int getTagnumber() { return tagnumber; } public void setTagnumber(int tagnumber) { this.tagnumber = tagnumber; } /** * мҳʽ */ private String classname; public String getClassname() { return classname; } public void setClassname(String classname) { this.classname = classname; } protected void parser() { if(getExport() != null) { String temp = getExport(); for (int i = 0; i <switchcase.length && i < temp.length(); i++) switchcase[i] = (byte)(temp.charAt(i) - 48); } } private boolean skip() { return (switchcase[0] & switchcase[1] & switchcase[2] & switchcase[3] & switchcase[4] & switchcase[5] & switchcase[6]& switchcase[7]& switchcase[8]) == 1; } public int doStartTag() throws JspException { super.doStartTag(); if(this.pagerContext == null) { String t_id = "pagerContext." ; HttpServletRequest request = this.getHttpServletRequest(); if(request instanceof CMSServletRequest) { CMSServletRequest cmsRequest = (CMSServletRequest)request; t_id += cmsRequest.getContext().getID() ; } else if(this.id != null && !id.trim().equals("")) { t_id += id; } else t_id += PagerContext.DEFAULT_ID; this.pagerContext = (PagerContext)request.getAttribute(t_id); } //indexhelper = new IndexHelper(pagerContext); if (pagerContext == null || pagerContext.ListMode()) { return SKIP_BODY; } //ҳЩťҪʾexport parser(); if(imagedir != null) { this.imagedir = StringUtil.getRealPath(request, imagedir); } if(!skip()) try { String output = generateContent(); // System.out.println(output); this.getJspWriter().print(output); } catch (Exception e) { throw new JspException(e.getMessage()); } return SKIP_BODY; } // public static void main(String[] args) // { // byte[] switchcase = new byte[7]; // String test = "1000000"; // System.out.println("test:"+test.charAt(0)); // switchcase[0] = (byte)(test.charAt(0) - 48); // System.out.println(switchcase[0]); // } public int doEndTag() throws JspException { // if (indexTagExport != null) { // String name; // if ((name = indexTagExport.getItemCount()) != null) { // restoreAttribute(name, oldItemCount); // oldItemCount = null; // } // // if ((name = indexTagExport.getPageCount()) != null) { // restoreAttribute(name, oldPageCount); // oldPageCount = null; // } // } // super.doEndTag();//Ƿ⣬biaoping.yin20081121 this.custom = false; export = null; style = "V"; switchcase = new byte[9]; this.pageContext = null; imagedir = "/include/images"; this.imageextend = " border=0 "; this.useimage = false; this.tagnumber = -1; this.classname = null; this.centerextend = null; // pagerContext.getContainerid() = null; // pagerContext.getSelector() = null; this.sizescope = null; this.usegoimage = false; this.numberend = null; this.numberpre = null; this.aindex = false; return EVAL_PAGE; } public void release() { export = null; super.release(); } /* (non-Javadoc) * @see com.frameworkset.common.tag.BaseTag#generateContent() */ /** * */ public String generateContent() { StringBuffer ret = new StringBuffer(); //webӦjavascriptűļwapӦ boolean needScript = (pagerContext.indexs == null || pagerContext.indexs.isEmpty()); if(needScript) { if(!pagerContext.isWapflag()) ret.append(this.getScript()); } Locale locale = RequestContextUtils.getRequestContextLocal(request); String total_label = TagUtil.tagmessageSource.getMessage("bboss.tag.pager.total",locale) ; String total_page_label = TagUtil.tagmessageSource.getMessage("bboss.tag.pager.total.page",locale) ; String total_records_label = TagUtil.tagmessageSource.getMessage("bboss.tag.pager.total.records",locale) ; // ret.append( // "<table width=\"100%\" border=\"0\" align=\"center\" cellpadding=\"0\" cellspacing=\"1\">"); //ret.append("<tr class='TableHead1'>"); //ret.append("<td align='center' colspan=100>"); if(!pagerContext.isWapflag()) { if (needScript && pagerContext.getForm() != null) { String name = pagerContext.getId() + ".PAGE_QUERY_STRING"; ret.append("<input type=\"hidden\" id=\"" + name + "\" name=\"" + name + "\"/>"); } } if( switchcase[8] == 0) { if(enable_page_total_size) ret.append(total_label)// .append("<span class='Total'>").append(!pagerContext.ListMode()?pagerContext.getItemCount():pagerContext.getDataSize()).append("</span>").append(total_records_label);//¼ } //ret.append("<div align=\"right\">"); if (switchcase[0] == 0) { long serial = Math.min(pagerContext.getPageNumber() + 1, pagerContext.getPageCount()); if(!pagerContext.isWapflag()) ret.append("<span class='current'>" + serial + "</span>/"); else ret.append("<span class='current'>" + serial + "</span>/"); } if (switchcase[1] == 0) { if(!pagerContext.isWapflag()) ret.append( pagerContext.getPageCount()).append(total_page_label);//" ҳ" else ret.append( pagerContext.getPageCount()).append(total_page_label);//" ҳ" } if (switchcase[2] == 0) { if(!pagerContext.isWapflag() ) ret.append("<span class='next'>"+this.getFirstContent()).append("</span>"); else ret.append(this.getWapFirstContent()).append(" "); } if (switchcase[3] == 0) { if(!pagerContext.isWapflag()) ret.append("<span class='next'>"+this.getPrevContent()).append("</span> "); else ret.append(this.getWapPrevContent()).append(" "); } if(this.tagnumber > 0) { StringBuffer center = new StringBuffer(); this.getCenterContent((int)pagerContext.getPageNumber(), (int)pagerContext.getPageCount(), center); String temp = center.toString(); ret.append(temp); } if (switchcase[4] == 0) if(!pagerContext.isWapflag()) ret.append("<span class='next'>"+this.getNextContent()).append("</span>"); else ret.append(this.getWapNextContent()).append(" "); if (switchcase[5] == 0) if(!pagerContext.isWapflag()) ret.append("<span class='next'>"+this.getLastContent()).append("</span>"); else ret.append(this.getWapLastContent()).append(" "); if (switchcase[6] == 0) if(!pagerContext.isWapflag()) ret.append(this.getGoContent()); else ret.append(this.getWapGoContent()); if (switchcase.length > 7 ) { if( switchcase[7] == 0) ret.append(this.getMaxPageItem()); } else { if(enable_page_size_set) ret.append(this.getMaxPageItem()); } // else // ret.append(this.getWapGoContent()); /* мҳ */ // ret.append("</div>"); // ret.append("</td>"); // ret.append("</tr>"); // ret.append("</table>"); //ǩջԱҳǩи push(); return ret.toString(); } public String getMaxPageItem() { String defaultsize = pagerContext.getMaxPageItems() + ""; Select select = new Select(); select.setID("__max_page_size"); select.setName("__max_page_size"); if(pagerContext.getContainerid() == null || pagerContext.getContainerid().equals("")) { select.setOnChange("javascript:__chagePageSize(event,'" + pagerContext.getCookieid() + "','__max_page_size','" + pagerContext.getTruePageUrl() + "')"); } else { select.setOnChange("javascript:__chagePageSize(event,'" + pagerContext.getCookieid() + "','__max_page_size','" + pagerContext.getTruePageUrl() + "','"+ pagerContext.getSelector() + "','"+ pagerContext.getContainerid() + "')"); } // Option option = new Option(); // option.setValue(defaultsize); // option.setTagText("¼"); // select.addElement(option); Option option = null; String[] ops = null; if(this.sizescope == null || this.sizescope.equals("")) ops = _sizescope; else ops = this.sizescope.split(","); ops = sortitems(ops,pagerContext.getCustomMaxPageItems()); for(int i =0; i < ops.length; i ++) { option = new Option(); option.setValue(ops[i]); option.setTagText(ops[i]); if(defaultsize.equals(ops[i])) { option.setSelected(true); } select.addElement(option); } Locale locale = RequestContextUtils.getRequestContextLocal(request); String everypage_label = TagUtil.tagmessageSource.getMessage("bboss.tag.pager.everypageshow",locale) ; String everypagerecords_label = TagUtil.tagmessageSource.getMessage("bboss.tag.pager.everypageshow.records",locale) ; return new StringBuffer(" <span class='pages1'>").append(everypage_label)//ÿҳʾ .append(select.toString()).append(everypagerecords_label)// .append("</span>").toString(); } private String[] sortitems(String[] ops,int pagesize) { if(pagesize <= 0 ) return ops; if(ops == null || ops.length <= 0) { return new String[]{pagesize + ""}; } for(int i = 0 ; i < ops.length ; i ++) { String size = ops[i]; try { int size_ = Integer.parseInt(size); if (pagesize == size_) return ops; } catch (Exception e) { continue; } } String[] ret = new String[ops.length + 1]; ret[0] = pagesize + ""; for(int i = 1 ;i< ret.length; i ++) { ret[i] = ops[i - 1]; } return ret; } // /** // * notified by biaoping.yin on 2005-02-16 // * עԭѾƵpagerContext // * Description:Զķҳӵַ // * @param formName // * @param params // * @param promotion // * @param forwardUrl // * @return // * String // */ // private String getCustomUrl(String formName,String params,boolean promotion,String forwardUrl) // { // String customFirstUrl = "javascript:pageSubmit('" // + formName // + "','" // + params // + "','" // + forwardUrl // + "'," // + promotion + ")"; // return customFirstUrl; // // } private String getWapFirstContent() { String firstUrl = pagerContext.getPageUrl(getJumpPage(PagerConst.FIRST_PAGE)); if (firstUrl.equals("")) return ""; String customFirstUrl = null; customFirstUrl = firstUrl; customFirstUrl = StringUtil.replace(customFirstUrl,"&","&amp;"); if(this.getStyle().equals("V")) return "<br/>" + new A().setHref(customFirstUrl).setTagText("ҳ").toString(); else return " " + new A().setHref(customFirstUrl).setTagText("ҳ").toString(); } private static String buildPath(String dir,String fileName) { if(dir == null || dir.equals("")) return fileName; if(dir.endsWith("/")) { return dir + fileName; } else { return dir + "/" + fileName; } } public static String getJqueryUrl(String url,String containerid,String selector) { StringBuffer ret = new StringBuffer(); if(selector != null) ret.append("javascript:loadPageContent('").append(url).append("','").append(containerid).append("','").append(selector).append("');"); else ret.append("javascript:loadPageContent('").append(url).append("','").append(containerid).append("',null);"); return ret.toString(); } private String getFirstContent() { String firstUrl = pagerContext.getPageUrl(getJumpPage(PagerConst.FIRST_PAGE)); Locale locale = RequestContextUtils.getRequestContextLocal(request); String firstpage_label = TagUtil.tagmessageSource.getMessage("bboss.tag.pager.firstpage",locale) ; if (firstUrl.equals("")) { if(!this.useimage) { if(this.aindex) { return new StringBuffer("<a href='#'>") .append(firstpage_label)// ҳ .append("</a>").toString(); } else { return firstpage_label; } } else { IMG image = new IMG(); image.setSrc(buildPath(this.getImagedir(), first_image)); image.setAlt(firstpage_label);// ҳ if(this.imageextend != null) { image.setExtend(this.imageextend); } return image.toString(); } } String customFirstUrl = null; if(pagerContext.getForm() != null) { String params = pagerContext.getQueryString(0,pagerContext.getSortKey(),pagerContext.getDesc()); customFirstUrl = pagerContext.getCustomUrl(pagerContext.getForm(), params, pagerContext.getPromotion(),firstUrl,pagerContext.getId()); } else { customFirstUrl = firstUrl; } if(!this.useimage) { A a = new A(); a.setTagText(firstpage_label);// ҳ; if(pagerContext.getContainerid() == null || pagerContext.getContainerid().equals("")) { a.setHref(customFirstUrl); } else { a.setHref("#"); a.setOnClick(this.getJqueryUrl(customFirstUrl,pagerContext.getContainerid(),pagerContext.getSelector())); } return a.toString(); } else { IMG image = new IMG(); image.setSrc(buildPath(this.getImagedir(), first_image)); image.setAlt(firstpage_label);// ҳ if(this.imageextend != null) { image.setExtend(this.imageextend); } A a = new A(); if(pagerContext.getContainerid() == null || pagerContext.getContainerid().equals("")) { a.setHref(customFirstUrl); } else { a.setOnClick(this.getJqueryUrl(customFirstUrl,pagerContext.getContainerid(),pagerContext.getSelector())); } a.addElement(image); return a.toString(); } //1ҳ ҳһҳһҳβҳ ת ҳ //return ret.toString(); } // private String getFirstContent() { // String firstUrl = pagerContext.getPageUrl(getJumpPage(PagerConst.FIRST_PAGE)); // // if (firstUrl.equals("")) // { // if(!this.useimage) // return " ҳ"; // else // { // IMG image = new IMG(); // // image.setSrc(buildPath(this.getImagedir(), first_image)); // image.setAlt(" ҳ"); // if(this.imageextend != null) // { // // image.setExtend(this.imageextend); // } // // return image.toString(); // } // } // String customFirstUrl = null; // if(pagerContext.getForm() != null) // { // String params = pagerContext.getQueryString(0,pagerContext.getSortKey(),pagerContext.getDesc()); // customFirstUrl = pagerContext.getCustomUrl(pagerContext.getForm(), // params, // pagerContext.getPromotion(),firstUrl,pagerContext.getId()); // } // else // { // customFirstUrl = firstUrl; // } // // if(!this.useimage) // { // return new A().setHref(customFirstUrl).setTagText(" ҳ").toString(); // } // else // { // IMG image = new IMG(); // // image.setSrc(buildPath(this.getImagedir(), first_image)); // image.setAlt(" ҳ"); // if(this.imageextend != null) // { // image.setExtend(this.imageextend); // } // return new A().setHref(customFirstUrl).addElement(image).toString(); // // } // // //1ҳ ҳһҳһҳβҳ ת ҳ // // //return ret.toString(); // } public static void main(String args[]) { // IMG image = new IMG(); // image.setSrc(buildPath("aaa", "bbb.gif")); // image.setAlt("ҳ"); // image.setExtend(" border=0 "); // System.out.println(new A().setHref("www.sina.com.cn").addElement(image).toString()); System.out.println(UUID.randomUUID().toString()); long start = System.currentTimeMillis(); String gotopageid = UUID.randomUUID().toString(); long end = System.currentTimeMillis(); System.out.println(gotopageid + ":"+ (end - start)); // UUIDGenerator generator = UUIDGenerator.getInstance(); // gotopageid = generator.generateRandomBasedUUID().toString(); start = System.currentTimeMillis(); // gotopageid = generator.generateRandomBasedUUID().toString(); end = System.currentTimeMillis(); System.out.println(gotopageid + ":"+ (end - start)); } // private String getNavigationUrl(int offset,String sortKey) // { // String forwardUrl = pagerContext.getOffsetUrl(offset,sortKey); // String customUrl = null; // if(pagerContext.getForm() != null) // { // customUrl = pagerContext.getCustomUrl(pagerContext.getForm(), // pagerContext.getQueryString(offset,sortKey), // pagerContext.getPromotion(), // forwardUrl); // // } // else // customUrl = forwardUrl; // return customUrl; // } /** * ȡһҳhtml * @return String */ private String getWapPrevContent() { StringBuffer ret = new StringBuffer(); if (!pagerContext.hasPrevPage()) return ""; long offset = pagerContext.getPrevOffset(); String sortKey = pagerContext.getSortKey(); String prevurl = pagerContext.getOffsetUrl(offset,sortKey,pagerContext.getDesc()); String customPrevutl = null; customPrevutl = prevurl; //String prevurl = pagerContext.getPageUrl(getJumpPage(PagerConst.PRE_PAGE)); customPrevutl = StringUtil.replace(customPrevutl,"&","&amp;"); if(this.getStyle().equals("V")) return "<br/>" + new A().setHref(customPrevutl).setTagText("һҳ"); else return " " + new A().setHref(customPrevutl).setTagText("һҳ"); } private String getPrevContent() { Locale locale = RequestContextUtils.getRequestContextLocal(request); String prepage_label = TagUtil.tagmessageSource.getMessage("bboss.tag.pager.prepage",locale) ; if (!pagerContext.hasPrevPage()) { // return "һҳ"; if(!this.useimage) { if(this.aindex) { return new StringBuffer("<a href='#'>") .append(prepage_label)//һҳ .append("</a>").toString(); } else { return prepage_label//һҳ ; } } else { IMG image = new IMG(); image.setSrc(buildPath(this.getImagedir(), this.pre_image)); image.setAlt(prepage_label);//һҳ if(this.imageextend != null) { image.setExtend(this.imageextend); } return image.toString(); } } long offset = pagerContext.getPrevOffset(); String sortKey = pagerContext.getSortKey(); String prevurl = pagerContext.getOffsetUrl(offset,sortKey,pagerContext.getDesc()); String customPrevutl = null; if(pagerContext.getForm() != null) { customPrevutl = pagerContext.getCustomUrl(pagerContext.getForm(), pagerContext.getQueryString(offset,sortKey,pagerContext.getDesc()), pagerContext.getPromotion(), prevurl,pagerContext.getId()); } else customPrevutl = prevurl; //String prevurl = pagerContext.getPageUrl(getJumpPage(PagerConst.PRE_PAGE)); if(!this.useimage) { A a = new A(); a.setTagText(prepage_label);//һҳ if(pagerContext.getContainerid() == null || pagerContext.getContainerid().equals("")) { a.setHref(customPrevutl); } else { a.setHref("#"); a.setOnClick(this.getJqueryUrl(customPrevutl,pagerContext.getContainerid(),pagerContext.getSelector())); } return a.toString(); // return "" + new A().setHref(customPrevutl).setTagText("һҳ"); } else { IMG image = new IMG(); image.setSrc(buildPath(this.getImagedir(), pre_image)); image.setAlt(prepage_label);//һҳ if(this.imageextend != null) { image.setExtend(this.imageextend); } A a = new A(); if(pagerContext.getContainerid() == null || pagerContext.getContainerid().equals("")) { a.setHref(customPrevutl); } else { a.setOnClick(this.getJqueryUrl(customPrevutl,pagerContext.getContainerid(),pagerContext.getSelector())); } a.addElement(image); return "" + a.toString(); // return "" + new A().setHref(customPrevutl).addElement(image).toString(); // return new A().setHref(customFirstUrl).addElement(image).toString(); } } private String getCenterPageUrl(long offset,String sortKey) { StringBuffer ret = new StringBuffer(); // long offset = pagerContext.getPrevOffset(); // String sortKey = pagerContext.getSortKey(); String prevurl = pagerContext.getOffsetUrl(offset,sortKey,pagerContext.getDesc()); String customPrevutl = null; if(pagerContext.getForm() != null) { customPrevutl = pagerContext.getCustomUrl(pagerContext.getForm(), pagerContext.getQueryString(offset,sortKey,pagerContext.getDesc()), pagerContext.getPromotion(), prevurl,pagerContext.getId()); } else customPrevutl = prevurl; return customPrevutl; } /** * ȡwapһҳַ * @return String */ private String getWapNextContent() { if (pagerContext.hasNextPage()) { long offset = pagerContext.getNextOffset(); String sortKey = pagerContext.getSortKey(); String nextUrl = pagerContext.getOffsetUrl(offset,pagerContext.getSortKey(),pagerContext.getDesc()); //String prevurl = pagerContext.getOffsetUrl(offset,sortKey); String customNextUrl = null; customNextUrl = nextUrl; customNextUrl = StringUtil.replace(customNextUrl,"&","&amp;"); //String nextUrl = pagerContext.getPageUrl(getJumpPage(PagerConst.NEXT_PAGE)); if(this.getStyle().equals("V")) return "<br/>" + new A().setHref(customNextUrl).setTagText("һҳ"); else return " " + new A().setHref(customNextUrl).setTagText("һҳ"); } return ""; } /** * ȡһҳhtml * * To change the template for this generated type comment go to * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments */ private String getNextContent() { Locale locale = RequestContextUtils.getRequestContextLocal(request); String nextpage_label = TagUtil.tagmessageSource.getMessage("bboss.tag.pager.nextpage",locale) ; if (pagerContext.hasNextPage()) { long offset = pagerContext.getNextOffset(); String sortKey = pagerContext.getSortKey(); String nextUrl = pagerContext.getOffsetUrl(offset,pagerContext.getSortKey(),pagerContext.getDesc()); //String prevurl = pagerContext.getOffsetUrl(offset,sortKey); String customNextUrl = null; if(pagerContext.getForm() != null) { customNextUrl = pagerContext.getCustomUrl(pagerContext.getForm(), pagerContext.getQueryString(offset,sortKey,pagerContext.getDesc()), pagerContext.getPromotion(), nextUrl,pagerContext.getId()); } else customNextUrl = nextUrl; if(!this.useimage) { A a = new A(); a.setTagText(nextpage_label);//"һҳ" if(pagerContext.getContainerid() == null || pagerContext.getContainerid().equals("")) { a.setHref(customNextUrl); } else { a.setHref("#"); a.setOnClick(this.getJqueryUrl(customNextUrl,pagerContext.getContainerid(),pagerContext.getSelector())); } return a.toString(); } else { IMG image = new IMG(); image.setSrc(buildPath(this.getImagedir(), this.next_image)); image.setAlt(nextpage_label);//"һҳ" if(this.imageextend != null) { image.setExtend(this.imageextend); } A a = new A(); if(pagerContext.getContainerid() == null || pagerContext.getContainerid().equals("")) { a.setHref(customNextUrl); } else { a.setOnClick(this.getJqueryUrl(customNextUrl,pagerContext.getContainerid(),pagerContext.getSelector())); } a.addElement(image); return a.toString(); // return new A().setHref(customNextUrl).addElement(image).toString(); // return new A().setHref(customFirstUrl).addElement(image).toString(); } } if(!this.useimage) { if(this.aindex) { return new StringBuffer("<a href='#'>").append(nextpage_label)//"һҳ" .append("</a>").toString(); } else { return nextpage_label//"һҳ" ; } } else { IMG image = new IMG(); image.setSrc(buildPath(this.getImagedir(), next_image)); image.setAlt(nextpage_label);//"һҳ" if(this.imageextend != null) { image.setExtend(this.imageextend); } return image.toString(); } // return "һҳ"; } /** * ȡwapβҳť * @return String */ private String getWapLastContent() { String lastUrl = pagerContext.getPageUrl(getJumpPage(PagerConst.LAST_PAGE)); if (lastUrl.equals("")) return ""; long offset = pagerContext.getLastOffset(); String sortKey = pagerContext.getSortKey(); String customLastUrl = null; customLastUrl = lastUrl; customLastUrl = StringUtil.replaceAll(customLastUrl,"&","&amp;"); if(this.getStyle().equals("V")) return "<br/>" + new A().setHref(customLastUrl).setTagText("β ҳ"); else return " " + new A().setHref(customLastUrl).setTagText("β ҳ"); } /** * мҳַ * @param tagnumber * @param currentPage * @param totalPage * @param output * @return */ private void getCenterContent(int currentPage,int totalPage,StringBuffer output) { /* ʼҳ */ // System.out.println("currentPage:"+currentPage); // System.out.println("totalPage:"+totalPage); if(tagnumber >0){ int start = 1; int end = 1; if(tagnumber<=2) tagnumber = 3; // if(tagnumber>3) { if(currentPage>tagnumber){ start = (int)currentPage-(int)Math.floor(tagnumber/2); }else{ if((currentPage%tagnumber)>=(int)Math.floor(tagnumber/2) || currentPage%tagnumber==0 ) start = (int)currentPage-(int)Math.floor(tagnumber/2); } start = start<=0?1:start; /* βҳ */ end = (int)this.tagnumber + start ; if(end > totalPage) { //ҳǴ1ʼ end = (int)totalPage + 1; start = end - (int)this.tagnumber; if(start<=0) start = 1; } } // else{ // if(tagnumber<=2) tagnumber = 3; // start = (int)currentPage-1; // if(start<=0) start = 1 ; // // if(currentPage == 1) end = (int)currentPage + (int)this.tagnumber ; // else end = (int)currentPage + (int)this.tagnumber - 1 ; // if(end>totalPage){ // end = (int)totalPage + 1; // start = end - (int)tagnumber; // if(start<=0) start = 1; // } // } for(int i=start;i<end;i++){ if(totalPage>1){ if((i - 1) ==currentPage){ if(aindex) { if(this.numberpre == null) output.append("<span class='current_page'><a href='#'>").append(i).append("</a></span> "); else output.append("<span class='current_page'><a href='#'>").append(this.numberpre).append(i).append(this.numberend).append("</a></span> "); } else { if(this.numberpre == null) output.append("<span class='current_page'>").append(i).append("</span> "); else output.append("<span class='current_page'>").append(this.numberpre).append(i).append(this.numberend).append("</span> "); } }else{ // Context loop = new VelocityContext(); A a = new A(); if(this.numberpre == null) { a.setTagText(String.valueOf(i)); } else { a.setTagText(this.numberpre +i+this.numberend); } String url = getCenterPageUrl((i-1) * this.pagerContext.getMaxPageItems(),this.pagerContext.getSortKey()); if(pagerContext.getForm() != null) { a.setHref(url); } else { if(pagerContext.getContainerid() != null && !pagerContext.getContainerid().equals("")) { a.setHref("#"); a.setOnClick(getJqueryUrl(url,pagerContext.getContainerid(),pagerContext.getSelector())); } else { a.setHref(url); } } if(centerextend != null) a.setExtend(centerextend); if(this.classname != null && !this.classname.equals("")) a.setClass(classname); // if(this.style != null && !this.style.equals("")) // a.setStyle(style); // loop.put("count",i+""); // long off = (i-1) * this.pagerContext.getMaxPageItems(); // loop.put("currentpath",); // loop.put("classname",this.classname); // loop.put("style",this.style); // output.append(CMSTagUtil.loadTemplate("publish/newsTurnPage/content-loop.vm",loop)); output.append(a); } }else{ // Context loop = new VelocityContext(); // loop.put("count"," "); // loop.put("currentpath",getCurrentPath(i)); // output.append(CMSTagUtil.loadTemplate("publish/newsTurnPage/content-loop.vm",loop)); } } } } /** * ȡβҳť * @return String */ private String getLastContent() { String lastpage_label = TagUtil.tagmessageSource.getMessage("bboss.tag.pager.lastpage",RequestContextUtils.getRequestContextLocal(request)) ; String lastUrl = pagerContext.getPageUrl(getJumpPage(PagerConst.LAST_PAGE)); if (lastUrl.equals("")) { // return "β ҳ"; if(!this.useimage) { if(this.aindex) { return new StringBuffer().append(" <a href='#'>") .append(lastpage_label)//βҳ .append("</a>").toString(); } else { return lastpage_label; } } else { IMG image = new IMG(); image.setSrc(buildPath(this.getImagedir(), last_image)); image.setAlt(lastpage_label);//βҳ if(this.imageextend != null) { image.setExtend(this.imageextend); } return image.toString(); } } long offset = pagerContext.getLastOffset(); String sortKey = pagerContext.getSortKey(); String customLastUrl = null; if(pagerContext.getForm() != null) { customLastUrl = pagerContext.getCustomUrl(pagerContext.getForm(), pagerContext.getQueryString(offset,sortKey,pagerContext.getDesc()), pagerContext.getPromotion(), lastUrl,pagerContext.getId()); } else customLastUrl = lastUrl; if(!this.useimage) { A a = new A(); a.setTagText(lastpage_label);//βҳ if(pagerContext.getContainerid() == null || pagerContext.getContainerid().equals("")) { a.setHref(customLastUrl); } else { a.setHref("#"); a.setOnClick(this.getJqueryUrl(customLastUrl,pagerContext.getContainerid(),pagerContext.getSelector())); } return a.toString(); // return "" + new A().setHref(customLastUrl).setTagText("β ҳ"); } else { IMG image = new IMG(); image.setSrc(buildPath(this.getImagedir(), this.last_image)); image.setAlt(lastpage_label);//βҳ if(this.imageextend != null) { image.setExtend(this.imageextend); } A a = new A(); if(pagerContext.getContainerid() == null || pagerContext.getContainerid().equals("")) { a.setHref(customLastUrl); } else { a.setOnClick(this.getJqueryUrl(customLastUrl,pagerContext.getContainerid(),pagerContext.getSelector())); } a.addElement(image); return a.toString(); // return new A().setHref(customLastUrl).addElement(image).toString(); // return new A().setHref(customFirstUrl).addElement(image).toString(); } } /** * <a id="bridge"></a> * function goTo(url,maxPageItem,hasParam) * { * * var go = document.all.item("go").value; * var goPage = parserInt(go); * if(isNaN(goPage)) * { * alert("תҳ"); * return; * } * var offset = (goPage - 1) * maxPageItems; * document.bridge.href = url + (hasParam?"&":"?" + "pager.offset=" + offset); * document.bridge.onClick(); * } * @return String */ private String getScript() { StringBuffer script = new StringBuffer(); HttpServletRequest request = this.getHttpServletRequest(); if(!this.isCustom()) { // script.append(new Script() // .setSrc(StringUtil.getRealPath(request, "/include/pager.js")) // .setLanguage("javascript") // .toString()); if(pagerContext.getContainerid() == null || pagerContext.getContainerid().equals("")) { script.append(PageConfig.getPagerConfig(request)); //jquery script.append(PageConfig.getPagerCss(request)); //jquery } else { request.setAttribute(PageConfig.jqueryscript_set_flag,"true"); } } else { script.append(new Script() .setSrc(StringUtil.getRealPath(request, "/include/pager_custom.js")) .setLanguage("javascript") .toString()); script.append(PageConfig.getPagerCss(request)); //jquery } if(this.pagerContext.getCommitevent() != null) { if(this.pagerContext.getCommitevent().startsWith("'") || this.pagerContext.getCommitevent().startsWith("\"")) { script .append(new Script().setTagText("commitevent = "+ this.pagerContext.getCommitevent() + ";")); } else { script .append(new Script().setTagText("commitevent = \"" + this.pagerContext.getCommitevent() + "\";")); } } return script.toString(); } // public static void main(String[] args ) // // { // // System.out.println(new Script().setTagText("commitevent = \"turnPageSumbmitSet()\";").toString()); // } /** * ȡwapתť * @return String */ private String getWapGoContent() { StringBuffer ret = new StringBuffer(); //.append("ת"); //ret.append("<a id=\"bridge\"></a>"); //ret.append(this.getScript()); long pages = pagerContext.getPageCount(); HttpServletRequest request = this.getHttpServletRequest(); //System.out.println("pagerContext.getPageCount():"+pagerContext.getPageCount()); if (pages > 1) { String goTo = null; goTo = request.getContextPath() + "/include/pager.wmls#goTo('" + pagerContext.getUri() + "'," + pages + "," + pagerContext.getMaxPageItems() + "," + String.valueOf(pagerContext.getParams() > 0) + ","; if(pagerContext.getSortKey() == null) goTo += "null"; else goTo += "'" + pagerContext.getSortKey() + "'"; goTo += "," + pagerContext.getDesc() + ",'" + pagerContext.getId() + "')"; // validator.wmlsеⲿvalidate()ЧԼ String doEvent = "<do type=\"accept\" label=\"ת\">" + "<go href=\"" + goTo + "\"/>" + "</do>"; //a.setStyle("cursor:hand"); ret.append(doEvent); ret .append("<input name='gotopage' type='text' size='2'/>") .append("ҳ"); } else { // ret // .append("ת ") // .append( // new Input() // .setName("gotopage") // .setType("text") // .setSize(2) // .setDisabled(true) // ) // .append(" ҳ"); } //<input name="txtName2" type="text" size="4" attrib="editor"> // <a href="#">ҳ</a> if(this.getStyle().equals("V")) return "<br/>" + ret.toString(); else return " " + ret.toString(); } // /** // * ȡתť // * @return String // */ // private String getGoContent() { // StringBuffer ret = new StringBuffer(); //.append("ת"); // //ret.append("<a id=\"bridge\"></a>"); // //ret.append(this.getScript()); // long pages = pagerContext.getPageCount(); // //System.out.println("pagerContext.getPageCount():"+pagerContext.getPageCount()); // if (pages > 1) { // // // String goTo = null; // StringBuffer gogo = new StringBuffer(); // if(pagerContext.getForm() == null) // { // if(pagerContext.getSortKey() != null) // { // goTo = "goTo('" // + pagerContext.getUri() // + "'," // + pages // + "," // + pagerContext.getMaxPageItems() // + "," // + pagerContext.hasParams() // + ",'" // + pagerContext.getSortKey() // + "'," // + pagerContext.getDesc() // + ",'" // + pagerContext.getId() // + "')"; // } // else // { // goTo = "goTo('" // + pagerContext.getUri() // + "'," // + pages // + "," // + pagerContext.getMaxPageItems() // + "," // + pagerContext.hasParams() // + ",null," // + pagerContext.getDesc() // + ",'" // + pagerContext.getId() // + "')"; // } // } // else // { // if(pagerContext.getSortKey() != null) // { // // // goTo = "goTo('" // + pagerContext.getUri() // + "'," // + pages // + "," // + pagerContext.getMaxPageItems() // + "," // + pagerContext.hasParams() // + ",'" // + pagerContext.getSortKey() // + "'," // + pagerContext.getDesc() // + ",'" // + pagerContext.getId() // + "','" // + pagerContext.getForm() // + "','" // + pagerContext.getQueryString() // + "'," // + pagerContext.getPromotion() // + ")"; // } // else // { // goTo = "goTo('" // + pagerContext.getUri() // + "'," // + pages // + "," // + pagerContext.getMaxPageItems() // + "," // + pagerContext.hasParams() // + ",null," // + pagerContext.getDesc() // + ",'" // + pagerContext.getId() // + "','" // + pagerContext.getForm() // + "','" // + pagerContext.getQueryString() // + "'," // + pagerContext.getPromotion() // + ")"; // } // } // // /** // * goTo(url, // pages, // maxPageItem, // hasParam, // sortKey, // formName, // params, // promotion) // */ // // // A a = new A(); // // if(!this.useimage) // { // a.setOnClick(goTo); // // a.setTagText("ת "); // } // else // { // IMG image = new IMG(); // image.setSrc(buildPath(this.getImagedir(), this.go_image)); // image.setAlt("ת"); // if(this.imageextend != null) // { // // image.setExtend(this.imageextend); // } // image.setOnClick(goTo); // // a.addElement(image); // } // a.setName("pager.jumpto"); // a.setID("pager.jumpto"); // a.setHref("#"); // ///a.setStyle("cursor:hand"); // ret.append(a.toString()); // Input go = new Input() // // .setName("gotopage") // .setType("text") // .setSize(2); // // go.setOnKeyDown("keydowngo('pager.jumpto')"); // ret // .append( // go.toString()) // .append(" ҳ"); // } else { // if(!this.useimage) // { // Input go = new Input() // // .setName("gotopage") // .setType("text") // .setSize(2) // .setDisabled(true); // // ret // .append("ת ") // .append( // go.toString() // ) // .append(" ҳ"); // } // else // { // IMG image = new IMG(); // image.setSrc(buildPath(this.getImagedir(), this.go_image)); // image.setAlt("ת"); // if(this.imageextend != null) // { // // image.setExtend(this.imageextend); // } // // Input go = new Input() // // .setName("gotopage") // .setType("text") // .setSize(2) // .setDisabled(true); // // ret // .append(image.toString()) // .append( // go.toString() // ) // .append(" ҳ"); // } // // } // // //<input name="txtName2" type="text" size="4" attrib="editor"> // // <a href="#">ҳ</a> //// if(pagerContext.indexs == null || pagerContext.indexs.isEmpty()) //// { //// //// ret.append("<form action='' name='com.frameworkset.goform' method='post'></form>" ); //// } // return ret.toString(); // } private static final String gopageerror_msg = "תҳתҳΪ"; /** * ȡתť * @return String */ private String getGoContent() { StringBuffer ret = new StringBuffer(); //.append("ת"); //ret.append("<a id=\"bridge\"></a>"); //ret.append(this.getScript()); long pages = pagerContext.getPageCount(); //System.out.println("pagerContext.getPageCount():"+pagerContext.getPageCount()); String uuid = UUID.randomUUID().toString(); String gotopageid = uuid+".go"; Locale locale = RequestContextUtils.getRequestContextLocal(request); String gotopage_label = TagUtil.tagmessageSource.getMessage("bboss.tag.pager.gotopage",locale) ; String page_label = TagUtil.tagmessageSource.getMessage("bboss.tag.pager.page",locale) ; String gopageerror_msg = TagUtil.tagmessageSource.getMessage("bboss.tag.pager.gopageerror_msg",locale) ; if (pages > 1) { String goTo = null; StringBuffer gogo = new StringBuffer(); if(pagerContext.getForm() == null) { if(pagerContext.getSortKey() != null) { gogo.append("goTo('").append(gotopageid).append("','").append(gopageerror_msg).append("',"); if(pagerContext.getContainerid() != null && !pagerContext.getContainerid().equals("")) { gogo.append("'").append(pagerContext.getContainerid()).append("'"); } else { gogo.append("null"); } gogo.append(","); if(pagerContext.getSelector() != null && !pagerContext.getSelector().equals("")) { gogo.append("'").append(pagerContext.getSelector()).append("'"); } else { gogo.append("null"); } gogo.append(",'"); gogo.append(pagerContext.getUri()) .append("',") .append(pages) .append(",") .append(pagerContext.getMaxPageItems()) .append(",") .append(pagerContext.hasParams()) .append(",'") .append(pagerContext.getSortKey()) .append("',") .append(pagerContext.getDesc()) .append(",'") .append(pagerContext.getId()) .append("')"); } else { gogo.append("goTo('").append(gotopageid).append("','").append(gopageerror_msg).append("',"); if(pagerContext.getContainerid() != null && !pagerContext.getContainerid().equals("")) { gogo.append("'").append(pagerContext.getContainerid()).append("'"); } else { gogo.append("null"); } gogo.append(","); if(pagerContext.getSelector() != null && !pagerContext.getSelector().equals("")) { gogo.append("'").append(pagerContext.getSelector()).append("'"); } else { gogo.append("null"); } gogo.append(",'"); gogo.append(pagerContext.getUri()) .append("',") .append(pages) .append(",") .append(pagerContext.getMaxPageItems()) .append(",") .append(pagerContext.hasParams()) .append(",null,") .append(pagerContext.getDesc()) .append(",'") .append(pagerContext.getId()) .append("')"); } } else { if(pagerContext.getSortKey() != null) { gogo.append("goTo('").append(gotopageid).append("','").append(gopageerror_msg).append("',"); if(pagerContext.getContainerid() != null && !pagerContext.getContainerid().equals("")) { gogo.append("'").append(pagerContext.getContainerid()).append("'"); } else { gogo.append("null"); } gogo.append(","); if(pagerContext.getSelector() != null && !pagerContext.getSelector().equals("")) { gogo.append("'").append(pagerContext.getSelector()).append("'"); } else { gogo.append("null"); } gogo.append(",'"); gogo.append(pagerContext.getUri()) .append("',") .append(pages) .append( ",") .append( pagerContext.getMaxPageItems()) .append(",") .append(pagerContext.hasParams()) .append(",'") .append(pagerContext.getSortKey()) .append("',") .append(pagerContext.getDesc()) .append(",'") .append(pagerContext.getId()) .append("','") .append(pagerContext.getForm()) .append("','") .append(pagerContext.getQueryString()) .append("',") .append(pagerContext.getPromotion()) .append(")"); } else { gogo.append("goTo('").append(gotopageid).append("','").append(gopageerror_msg).append("',"); if(pagerContext.getContainerid() != null && !pagerContext.getContainerid().equals("")) { gogo.append("'").append(pagerContext.getContainerid()).append("'"); } else { gogo.append("null"); } gogo.append(","); if(pagerContext.getSelector() != null && !pagerContext.getSelector().equals("")) { gogo.append("'").append(pagerContext.getSelector()).append("'"); } else { gogo.append("null"); } gogo.append(",'"); gogo.append(pagerContext.getUri()) .append("',") .append(pages) .append( ",") .append( pagerContext.getMaxPageItems()) .append(",") .append(pagerContext.hasParams()) .append(",null,") .append(pagerContext.getDesc()) .append(",'") .append(pagerContext.getId()) .append("','") .append(pagerContext.getForm()) .append("','") .append(pagerContext.getQueryString()) .append("',") .append(pagerContext.getPromotion()) .append(")"); } } goTo = gogo.toString(); /** * goTo(url, pages, maxPageItem, hasParam, sortKey, formName, params, promotion) */ String pagerjumpto = uuid+".jumpto"; Input go = (Input) new Input() .setName(gotopageid) .setType("text") .setSize(2) .setClass("page_input"); go.setID(gotopageid); go.setOnKeyDown("keydowngo(event,'"+ pagerjumpto + "')"); if(this.usegoimage){ ret.append(" ") .append(gotopage_label)//ת .append(go.toString()) .append(page_label); //ҳ IMG image = new IMG(); image.setSrc(buildPath(this.getImagedir(), this.go_image)); image.setAlt(gotopage_label); if(this.imageextend != null) { image.setExtend(this.imageextend); } image.setOnClick(goTo); ret.append(image.toString()); }else{ A a = new A(); a.setOnClick(goTo); a.setTagText(gotopage_label);//ת ret.append(a.toString()).append(go.toString()).append(page_label); //ҳ } } else { if(this.usegoimage){ Input go = ((Input) new Input() .setName(gotopageid) .setType("text") .setSize(2) .setClass("page_input")) .setDisabled(true); ret.append(" ") .append(gotopage_label)//ת .append(go.toString()) .append(page_label); //ҳ IMG image = new IMG(); image.setSrc(buildPath(this.getImagedir(), this.go_image)); image.setAlt(gotopage_label);//ת if(this.imageextend != null) { image.setExtend(this.imageextend); } // image.setOnClick(goTo); ret.append(image.toString()); }else{ Input go = ((Input) new Input() .setName(gotopageid) .setType("text") .setSize(2) .setClass("page_input")) .setDisabled(true); ret.append(" ") .append(gotopage_label)//ת .append(go.toString() ) .append(page_label); //ҳ } } //<input name="txtName2" type="text" size="4" attrib="editor"> // <a href="#">ҳ</a> // if(pagerContext.indexs == null || pagerContext.indexs.isEmpty()) // { // // ret.append("<form action='' name='com.frameworkset.goform' method='post'></form>" ); // } return ret.toString(); } private long getJumpPage(int type) { switch (type) { case PagerConst.FIRST_PAGE : return 0; // case PagerConst.PRE_PAGE://ؼ֣Ŀǰûʹ // return pagerContext.getPrevOffset(); // case PagerConst.INDEX_PAGE://ؼ֣Ŀǰûʹ // return 2; // case PagerConst.NEXT_PAGE: // return pagerContext.getNextOffset(); case PagerConst.LAST_PAGE : return pagerContext.getLastPageNumber(); // case PagerConst.GO_PAGE://ؼ֣Ŀǰûʹ // return 2; default : return 2; } } /** * Indexǩʵѹջ * Description: * @return * Object */ public Object push() { if(pagerContext.indexs == null) pagerContext.indexs = new Stack(); return pagerContext.indexs.push(this); } public boolean isCustom() { return custom; } public void setCustom(boolean custom) { this.custom = custom; } /** * @return the sizescope */ public String getSizescope() { return sizescope; } /** * @param sizescope the sizescope to set */ public void setSizescope(String sizescope) { this.sizescope = sizescope; } public boolean isUsegoimage() { return usegoimage; } public void setUsegoimage(boolean usegoimage) { this.usegoimage = usegoimage; } public boolean isAindex() { return aindex; } public void setAindex(boolean aindex) { this.aindex = aindex; } public String getNumberpre() { return numberpre; } public void setNumberpre(String numberpre) { this.numberpre = numberpre; } public String getNumberend() { return numberend; } public void setNumberend(String numberend) { this.numberend = numberend; } // public String getContainerid() // { // return containerid; // } // // // public void setContainerid(String containerid) // { // pagerContext.getContainerid() = containerid; // } // // // public String getSelector() // { // return selector; // } // // // public void setSelector(String selector) // { // pagerContext.getSelector() = selector; // } } /* vim:set ts=4 sw=4: */
分页导航标签index输入调整页时跳转不起做用问题修复
bboss-taglib/src/com/frameworkset/common/tag/pager/tags/IndexTag.java
分页导航标签index输入调整页时跳转不起做用问题修复
<ide><path>boss-taglib/src/com/frameworkset/common/tag/pager/tags/IndexTag.java <ide> promotion) <ide> */ <ide> <del> String pagerjumpto = uuid+".jumpto"; <add> String pagerjumpto = uuid+".go"; <ide> <ide> Input go = (Input) new Input() <ide> .setName(gotopageid)
Java
apache-2.0
6679c45590c3a7a1b5acc3adf44289fcffd720b3
0
AndroidX/androidx,androidx/androidx,androidx/androidx,androidx/androidx,AndroidX/androidx,androidx/androidx,AndroidX/androidx,androidx/androidx,AndroidX/androidx,AndroidX/androidx,AndroidX/androidx,androidx/androidx,AndroidX/androidx,androidx/androidx,AndroidX/androidx,androidx/androidx,AndroidX/androidx,androidx/androidx,androidx/androidx,AndroidX/androidx
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.wear.input; import android.content.Context; import android.graphics.Point; import android.graphics.drawable.Drawable; import android.graphics.drawable.RotateDrawable; import android.os.Bundle; import android.provider.Settings; import android.view.Surface; import android.view.WindowManager; import androidx.annotation.IntDef; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RestrictTo; import androidx.annotation.VisibleForTesting; import com.google.android.wearable.input.WearableInputDevice; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** Class containing helpers for managing wearable buttons. */ public final class WearableButtons { private static WearableButtonsProvider sButtonsProvider = new DeviceWearableButtonsProvider(); /** Represents that the count of available device buttons. */ private static volatile int sButtonCount = -1; private WearableButtons() { throw new RuntimeException("WearableButtons should not be instantiated"); } /** * Testing call to allow the underlying {@link WearableButtonsProvider} to be substituted in * test code. * * @param provider The new {@link WearableButtonsProvider} to use. */ @VisibleForTesting(otherwise = VisibleForTesting.NONE) public static void setWearableButtonsProvider(@NonNull WearableButtonsProvider provider) { sButtonsProvider = provider; } /** @hide */ @Retention(RetentionPolicy.SOURCE) @RestrictTo(RestrictTo.Scope.LIBRARY) @IntDef({ LOCATION_UNKNOWN, LOCATION_EAST, LOCATION_ENE, LOCATION_NE, LOCATION_NNE, LOCATION_NORTH, LOCATION_NNW, LOCATION_NW, LOCATION_WNW, LOCATION_WEST, LOCATION_WSW, LOCATION_SW, LOCATION_SSW, LOCATION_SOUTH, LOCATION_SSE, LOCATION_SE, LOCATION_ESE, LOCATION_TOP_RIGHT, LOCATION_TOP_CENTER, LOCATION_TOP_LEFT, LOCATION_LEFT_TOP, LOCATION_LEFT_CENTER, LOCATION_LEFT_BOTTOM, LOCATION_BOTTOM_LEFT, LOCATION_BOTTOM_CENTER, LOCATION_BOTTOM_RIGHT, LOCATION_RIGHT_BOTTOM, LOCATION_RIGHT_CENTER, LOCATION_RIGHT_TOP }) public @interface ButtonLocation {} /** Represents that the location zone is unknown. */ public static final int LOCATION_UNKNOWN = -1; /** Represents the east position on a round device. */ public static final int LOCATION_EAST = 0; /** Represents the east-northeast position on a round device. */ public static final int LOCATION_ENE = 1; /** Represents the northeast position on a round device. */ public static final int LOCATION_NE = 2; /** Represents the north-northeast position on a round device. */ public static final int LOCATION_NNE = 3; /** Represents the north position on a round device. */ public static final int LOCATION_NORTH = 4; /** Represents the north-northwest position on a round device. */ public static final int LOCATION_NNW = 5; /** Represents the northwest position on a round device. */ public static final int LOCATION_NW = 6; /** Represents the west-northwest position on a round device. */ public static final int LOCATION_WNW = 7; /** Represents the west position on a round device. */ public static final int LOCATION_WEST = 8; /** Represents the west-southwest position on a round device. */ public static final int LOCATION_WSW = 9; /** Represents the southwest position on a round device. */ public static final int LOCATION_SW = 10; /** Represents the south-southwest position on a round device. */ public static final int LOCATION_SSW = 11; /** Represents the south position on a round device. */ public static final int LOCATION_SOUTH = 12; /** Represents the south-southeast position on a round device. */ public static final int LOCATION_SSE = 13; /** Represents the southeast position on a round device. */ public static final int LOCATION_SE = 14; /** Represents the east-southeast position on a round device. */ public static final int LOCATION_ESE = 15; private static final int LOCATION_ROUND_COUNT = 16; /** Represents the right third of the top side on a square device. */ public static final int LOCATION_TOP_RIGHT = 100; /** Represents the center third of the top side on a square device. */ public static final int LOCATION_TOP_CENTER = 101; /** Represents the left third of the top side on a square device. */ public static final int LOCATION_TOP_LEFT = 102; /** Represents the top third of the left side on a square device. */ public static final int LOCATION_LEFT_TOP = 103; /** Represents the center third of the left side on a square device. */ public static final int LOCATION_LEFT_CENTER = 104; /** Represents the bottom third of the left side on a square device. */ public static final int LOCATION_LEFT_BOTTOM = 105; /** Represents the left third of the bottom side on a square device. */ public static final int LOCATION_BOTTOM_LEFT = 106; /** Represents the center third of the bottom side on a square device. */ public static final int LOCATION_BOTTOM_CENTER = 107; /** Represents the right third of the bottom side on a square device. */ public static final int LOCATION_BOTTOM_RIGHT = 108; /** Represents the bottom third of the right side on a square device. */ public static final int LOCATION_RIGHT_BOTTOM = 109; /** Represents the center third of the right side on a square device. */ public static final int LOCATION_RIGHT_CENTER = 110; /** Represents the top third of the right side on a square device. */ public static final int LOCATION_RIGHT_TOP = 111; /** * Key used with the bundle returned by {@link #getButtonInfo}} to retrieve the x coordinate of * a button when the screen is rotated 180 degrees. (temporary copy from WearableInputDevice) */ private static final String X_KEY_ROTATED = "x_key_rotated"; /** * Key used with the bundle returned by {@link #getButtonInfo}} to retrieve the y coordinate of * a button when the screen is rotated 180 degrees. (temporary copy from WearableInputDevice) */ private static final String Y_KEY_ROTATED = "y_key_rotated"; /** * Returns a {@link ButtonInfo} containing the metadata for a specific button. * * <p>The location will be populated in the following manner: * * <ul> * <li>The provided point will be on the screen, or more typically, on the edge of the screen. * <li>The point won't be off the edge of the screen. * <li>The location returned is a screen coordinate. The unit of measurement is in pixels. The * coordinates do not take rotation into account and assume that the device is in the * standard upright position. * </ul> * * <p>Additionally, a location zone will be provided for the button, which will be one of the * {@code LOCATION_*} constants. This defines the general area of the button on the device, and * can be passed to {@link #getButtonLabel} to provide a human-understandable name for the * location. There are two sets of locations for a device, depending on whether it is a circular * or rectilinear device. * * <p>The "compass" locations (e.g. {@link #LOCATION_ENE}) are used on a circular device. The * locations for each are shown in the following image: * * <img src="https://developer.android.com/images/reference/androidx/wear/wear-input/buttons_round.png" alt="Image detailing the locations of compass locations on a Wear device. North is at the top, followed by north-north-east, north-east, east-north-east, east, and so on."> * * <p>The other locations (e.g. {@link #LOCATION_BOTTOM_CENTER}) are used on a rectilinear * device. The locations for each are shown in the following image: * * <img src="https://developer.android.com/images/reference/androidx/wear/wear-input/buttons_square.png" alt="Image detailing the locations of other buttons on a Wear device. The first word details the side of the device the button is on, then the second word details where on that side the button is (e.g. 'TOP LEFT' means on the top edge, at the left hand side, and 'RIGHT BOTTOM' means on the right edge, at the bottom)."> * * <p>Common keycodes to use are {@link android.view.KeyEvent#KEYCODE_STEM_PRIMARY}, {@link * android.view.KeyEvent#KEYCODE_STEM_1}, {@link android.view.KeyEvent#KEYCODE_STEM_2}, and * {@link android.view.KeyEvent#KEYCODE_STEM_3}. * * @param context The context of the current activity * @param keycode The keycode associated with the hardware button of interest * @return A {@link ButtonInfo} containing the metadata for the given keycode or null if the * information is not available */ @SuppressWarnings("deprecation") @Nullable public static ButtonInfo getButtonInfo(@NonNull Context context, int keycode) { Bundle bundle = sButtonsProvider.getButtonInfo(context, keycode); if (bundle == null) { return null; } // If the information is not available, return null if (!bundle.containsKey(WearableInputDevice.X_KEY) || !bundle.containsKey(WearableInputDevice.Y_KEY)) { return null; } float screenLocationX = bundle.getFloat(WearableInputDevice.X_KEY); float screenLocationY = bundle.getFloat(WearableInputDevice.Y_KEY); // Get the screen size for the locationZone WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); Point screenSize = new Point(); wm.getDefaultDisplay().getSize(screenSize); if (isLeftyModeEnabled(context)) { // By default, the rotated placement is exactly the opposite. // This may be overridden if there is a remapping of buttons applied as well. float screenRotatedX = screenSize.x - screenLocationX; float screenRotatedY = screenSize.y - screenLocationY; if (bundle.containsKey(X_KEY_ROTATED) && bundle.containsKey(Y_KEY_ROTATED)) { screenRotatedX = bundle.getFloat(X_KEY_ROTATED); screenRotatedY = bundle.getFloat(Y_KEY_ROTATED); } screenLocationX = screenRotatedX; screenLocationY = screenRotatedY; } boolean isRound = context.getResources().getConfiguration().isScreenRound(); ButtonInfo info = new ButtonInfo( keycode, screenLocationX, screenLocationY, getLocationZone(isRound, screenSize, screenLocationX, screenLocationY)); return info; } /** * Get the number of hardware buttons available. This count includes the primary stem key as * well as any secondary stem keys available. * * @param context The context of the current activity * @return The number of buttons available, or the information is not available. */ public static int getButtonCount(@NonNull Context context) { if (sButtonCount == -1) { int[] buttonCodes = sButtonsProvider.getAvailableButtonKeyCodes(context); if (buttonCodes == null) { return -1; } sButtonCount = buttonCodes.length; } return sButtonCount; } /** * Returns an icon that can be used to represent the location of a button. * * @param context The context of the current activity * @param keycode The keycode associated with the hardware button of interest * @return A drawable representing the location of a button, or null if unavailable */ @Nullable public static Drawable getButtonIcon(@NonNull Context context, int keycode) { ButtonInfo info = getButtonInfo(context, keycode); if (info == null) { return null; } return getButtonIconFromLocationZone(context, info.getLocationZone()); } @VisibleForTesting static RotateDrawable getButtonIconFromLocationZone( Context context, @ButtonLocation int locationZone) { // To save memory for assets, we are using 4 icons to represent the 20+ possible // configurations. These 4 base icons can be rotated to fit any configuration needed. // id is the drawable id for the base icon // degrees is the number of degrees the icon needs to be rotated to match the wanted // position int id; int degrees; switch (locationZone) { // Round constants case LOCATION_EAST: id = R.drawable.ic_cc_settings_button_e; degrees = 0; break; case LOCATION_ENE: case LOCATION_NE: case LOCATION_NNE: id = R.drawable.ic_cc_settings_button_e; degrees = -45; break; case LOCATION_NORTH: id = R.drawable.ic_cc_settings_button_e; degrees = -90; break; case LOCATION_NNW: case LOCATION_NW: case LOCATION_WNW: id = R.drawable.ic_cc_settings_button_e; degrees = -135; break; case LOCATION_WEST: id = R.drawable.ic_cc_settings_button_e; degrees = 180; break; case LOCATION_WSW: case LOCATION_SW: case LOCATION_SSW: id = R.drawable.ic_cc_settings_button_e; degrees = 135; break; case LOCATION_SOUTH: id = R.drawable.ic_cc_settings_button_e; degrees = 90; break; case LOCATION_SSE: case LOCATION_SE: case LOCATION_ESE: id = R.drawable.ic_cc_settings_button_e; degrees = 45; break; // Rectangular constants case LOCATION_LEFT_TOP: id = R.drawable.ic_cc_settings_button_bottom; degrees = 180; break; case LOCATION_LEFT_CENTER: id = R.drawable.ic_cc_settings_button_center; degrees = 180; break; case LOCATION_LEFT_BOTTOM: id = R.drawable.ic_cc_settings_button_top; degrees = 180; break; case LOCATION_RIGHT_TOP: id = R.drawable.ic_cc_settings_button_top; degrees = 0; break; case LOCATION_RIGHT_CENTER: id = R.drawable.ic_cc_settings_button_center; degrees = 0; break; case LOCATION_RIGHT_BOTTOM: id = R.drawable.ic_cc_settings_button_bottom; degrees = 0; break; case LOCATION_TOP_LEFT: id = R.drawable.ic_cc_settings_button_top; degrees = -90; break; case LOCATION_TOP_CENTER: id = R.drawable.ic_cc_settings_button_center; degrees = -90; break; case LOCATION_TOP_RIGHT: id = R.drawable.ic_cc_settings_button_bottom; degrees = -90; break; case LOCATION_BOTTOM_LEFT: id = R.drawable.ic_cc_settings_button_bottom; degrees = 90; break; case LOCATION_BOTTOM_CENTER: id = R.drawable.ic_cc_settings_button_center; degrees = 90; break; case LOCATION_BOTTOM_RIGHT: id = R.drawable.ic_cc_settings_button_top; degrees = 90; break; default: throw new IllegalArgumentException("Unexpected location zone"); } RotateDrawable rotateIcon = new RotateDrawable(); rotateIcon.setDrawable(context.getDrawable(id)); rotateIcon.setFromDegrees(degrees); rotateIcon.setToDegrees(degrees); rotateIcon.setLevel(1); return rotateIcon; } /** * Returns a CharSequence that describes the placement location of a button. An example might be * "Top right" or "Bottom". * * @param context The context of the current activity * @param keycode The keycode associated with the hardware button of interest * @return A CharSequence describing the placement location of the button, or null if no * location is available for that button. */ @Nullable public static CharSequence getButtonLabel(@NonNull Context context, int keycode) { // 4 length array where the index uses the standard quadrant counting system (minus 1 for // 0 index) int[] buttonsInQuadrantCount = new int[4]; // Retrieve ButtonInfo objects and count how many buttons are in a quadrant. This is only // needed for round devices but will help us come up with friendly strings to show to the // user. // TODO(ahugh): We can cache quadrant counts to optimize. These values should be static for // each // device. int[] buttonCodes = sButtonsProvider.getAvailableButtonKeyCodes(context); if (buttonCodes == null) { return null; } for (int key : buttonCodes) { ButtonInfo info = getButtonInfo(context, key); if (info != null) { int quadrantIndex = getQuadrantIndex(info.getLocationZone()); if (quadrantIndex != -1) { ++buttonsInQuadrantCount[quadrantIndex]; } } } ButtonInfo info = getButtonInfo(context, keycode); int quadrantIndex = (info != null ? getQuadrantIndex(info.getLocationZone()) : -1); return info == null ? null : context.getString( getFriendlyLocationZoneStringId( info.getLocationZone(), (quadrantIndex == -1 ? 0 : buttonsInQuadrantCount[quadrantIndex]))); } /** * Returns quadrant index if locationZone is for a round device. Follows the conventional * quadrant system with the top right quadrant being 0, incrementing the index by 1 going * counter-clockwise around. */ private static int getQuadrantIndex(@ButtonLocation int locationZone) { switch (locationZone) { case LOCATION_ENE: case LOCATION_NE: case LOCATION_NNE: return 0; case LOCATION_NNW: case LOCATION_NW: case LOCATION_WNW: return 1; case LOCATION_WSW: case LOCATION_SW: case LOCATION_SSW: return 2; case LOCATION_SSE: case LOCATION_SE: case LOCATION_ESE: return 3; default: return -1; } } /** * If the screen is round, there is special logic we use to determine the string that should * show on the screen. Simple strings are broad descriptors like "top right". Detailed strings * are narrow descriptors like, "top right, upper" 1) If there are exactly 2 buttons in a * quadrant, use detailed strings to describe button locations. 2) Otherwise, use simple strings * to describe the button locations. * * @param locationZone The location zone to get a string id for * @param buttonsInQuadrantCount The number of buttons in the quadrant of the button * @return The string id to use to represent this button zone */ @VisibleForTesting static int getFriendlyLocationZoneStringId( @ButtonLocation int locationZone, int buttonsInQuadrantCount) { if (buttonsInQuadrantCount == 2) { switch (locationZone) { case LOCATION_ENE: return R.string.buttons_round_top_right_lower; case LOCATION_NE: case LOCATION_NNE: return R.string.buttons_round_top_right_upper; case LOCATION_NNW: case LOCATION_NW: return R.string.buttons_round_top_left_upper; case LOCATION_WNW: return R.string.buttons_round_top_left_lower; case LOCATION_ESE: case LOCATION_SE: return R.string.buttons_round_bottom_left_upper; case LOCATION_SSE: return R.string.buttons_round_bottom_left_lower; case LOCATION_SSW: return R.string.buttons_round_bottom_right_lower; case LOCATION_SW: case LOCATION_WSW: return R.string.buttons_round_bottom_right_upper; default: // fall out } } // If we couldn't find a detailed string, or we need a simple string switch (locationZone) { // Round constants case LOCATION_EAST: return R.string.buttons_round_center_right; case LOCATION_ENE: case LOCATION_NE: case LOCATION_NNE: return R.string.buttons_round_top_right; case LOCATION_NORTH: return R.string.buttons_round_top_center; case LOCATION_NNW: case LOCATION_NW: case LOCATION_WNW: return R.string.buttons_round_top_left; case LOCATION_WEST: return R.string.buttons_round_center_left; case LOCATION_WSW: case LOCATION_SW: case LOCATION_SSW: return R.string.buttons_round_bottom_left; case LOCATION_SOUTH: return R.string.buttons_round_bottom_center; case LOCATION_SSE: case LOCATION_SE: case LOCATION_ESE: return R.string.buttons_round_bottom_right; // Rectangular constants case LOCATION_LEFT_TOP: return R.string.buttons_rect_left_top; case LOCATION_LEFT_CENTER: return R.string.buttons_rect_left_center; case LOCATION_LEFT_BOTTOM: return R.string.buttons_rect_left_bottom; case LOCATION_RIGHT_TOP: return R.string.buttons_rect_right_top; case LOCATION_RIGHT_CENTER: return R.string.buttons_rect_right_center; case LOCATION_RIGHT_BOTTOM: return R.string.buttons_rect_right_bottom; case LOCATION_TOP_LEFT: return R.string.buttons_rect_top_left; case LOCATION_TOP_CENTER: return R.string.buttons_rect_top_center; case LOCATION_TOP_RIGHT: return R.string.buttons_rect_top_right; case LOCATION_BOTTOM_LEFT: return R.string.buttons_rect_bottom_left; case LOCATION_BOTTOM_CENTER: return R.string.buttons_rect_bottom_center; case LOCATION_BOTTOM_RIGHT: return R.string.buttons_rect_bottom_right; default: throw new IllegalArgumentException("Unexpected location zone"); } } /** * For round devices, the location zone is defined using 16 points in a compass arrangement. If * a button falls between anchor points, this method will return the closest anchor. * * <p>For rectangular devices, the location zone is defined by splitting each side into thirds. * If a button falls anywhere within a zone, the method will return that zone. The constants for * these zones are named LOCATION_[side in question]_[which third is affected]. E.g. * LOCATION_TOP_RIGHT would refer to the right third of the top side of the device. */ @VisibleForTesting /* package */ static int getLocationZone( boolean isRound, Point screenSize, float screenLocationX, float screenLocationY) { if (screenLocationX == Float.MAX_VALUE || screenLocationY == Float.MAX_VALUE) { return LOCATION_UNKNOWN; } return isRound ? getLocationZoneRound(screenSize, screenLocationX, screenLocationY) : getLocationZoneRectangular(screenSize, screenLocationX, screenLocationY); } private static int getLocationZoneRound( Point screenSize, float screenLocationX, float screenLocationY) { // Convert screen coordinate to Cartesian coordinate float cartesianX = screenLocationX - screenSize.x / 2; float cartesianY = screenSize.y / 2 - screenLocationY; // Use polar coordinates to figure out which zone the point is in double angle = Math.atan2(cartesianY, cartesianX); // Convert angle to all positive values if (angle < 0) { angle += 2 * Math.PI; } // Return the associated section rounded to the nearest anchor. // Using some clever math tricks and enum declaration, we can reduce this calculation // down to a single formula that converts angle to enum value. return Math.round((float) (angle / (Math.PI / 8))) % LOCATION_ROUND_COUNT; } private static int getLocationZoneRectangular( Point screenSize, float screenLocationX, float screenLocationY) { // Calculate distance to each edge. float deltaFromLeft = screenLocationX; float deltaFromRight = screenSize.x - screenLocationX; float deltaFromTop = screenLocationY; float deltaFromBottom = screenSize.y - screenLocationY; float minDelta = Math.min( deltaFromLeft, Math.min(deltaFromRight, Math.min(deltaFromTop, deltaFromBottom))); // Prioritize ties to left and right sides of watch since they're more likely to be placed // on the side. Buttons directly on the corner are not accounted for with this API. if (minDelta == deltaFromLeft) { // Left is the primary side switch (whichThird(screenSize.y, screenLocationY)) { case 0: return LOCATION_LEFT_TOP; case 1: return LOCATION_LEFT_CENTER; default: return LOCATION_LEFT_BOTTOM; } } else if (minDelta == deltaFromRight) { // Right is primary side switch (whichThird(screenSize.y, screenLocationY)) { case 0: return LOCATION_RIGHT_TOP; case 1: return LOCATION_RIGHT_CENTER; default: return LOCATION_RIGHT_BOTTOM; } } else if (minDelta == deltaFromTop) { // Top is primary side switch (whichThird(screenSize.x, screenLocationX)) { case 0: return LOCATION_TOP_LEFT; case 1: return LOCATION_TOP_CENTER; default: return LOCATION_TOP_RIGHT; } } else /* if (minDelta == deltaFromBottom) */ { // Bottom is primary side switch (whichThird(screenSize.x, screenLocationX)) { case 0: return LOCATION_BOTTOM_LEFT; case 1: return LOCATION_BOTTOM_CENTER; default: return LOCATION_BOTTOM_RIGHT; } } } // Returns 0, 1, or 2 which correspond to the index of the third the screen point lies in // from 'left to right' or 'top to bottom'. private static int whichThird(float screenLength, float screenLocation) { if (screenLocation <= screenLength / 3) { return 0; } else if (screenLocation <= screenLength * 2 / 3) { return 1; } else { return 2; } } private static boolean isLeftyModeEnabled(Context context) { return Settings.System.getInt( context.getContentResolver(), Settings.System.USER_ROTATION, Surface.ROTATION_0) == Surface.ROTATION_180; } /** Metadata for a specific button. */ public static final class ButtonInfo { private final int mKeycode; private final float mX; private final float mY; /** * The location zone of the button as defined in the {@link #getButtonInfo(Context, int)} * method. The intended use is to help developers attach a friendly String to the button * location. This value is LOCATION_UNKNOWN if the information is not available. * * */ @ButtonLocation private final int mLocationZone; /** * Gets the keycode this {@code ButtonInfo} provides information for. * * @return The keycode this {@code ButtonInfo} provides information for */ public int getKeycode() { return mKeycode; } /** The x coordinate of the button in screen coordinates. */ public float getX() { return mX; } /** The y coordinate of the button in screen coordinates. */ public float getY() { return mY; } /** The location zone of the button (e.g. LOCATION_EAST) */ @ButtonLocation public int getLocationZone() { return mLocationZone; } /** @hide */ @RestrictTo(RestrictTo.Scope.LIBRARY) @VisibleForTesting public ButtonInfo(int keycode, float x, float y, @ButtonLocation int locationZone) { this.mKeycode = keycode; this.mX = x; this.mY = y; this.mLocationZone = locationZone; } } }
wear/wear-input/src/main/java/androidx/wear/input/WearableButtons.java
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.wear.input; import android.content.Context; import android.graphics.Point; import android.graphics.drawable.Drawable; import android.graphics.drawable.RotateDrawable; import android.os.Bundle; import android.provider.Settings; import android.view.Surface; import android.view.WindowManager; import androidx.annotation.IntDef; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RestrictTo; import androidx.annotation.VisibleForTesting; import com.google.android.wearable.input.WearableInputDevice; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** Class containing helpers for managing wearable buttons. */ public final class WearableButtons { private static WearableButtonsProvider sButtonsProvider = new DeviceWearableButtonsProvider(); /** Represents that the count of available device buttons. */ private static volatile int sButtonCount = -1; private WearableButtons() { throw new RuntimeException("WearableButtons should not be instantiated"); } /** * Testing call to allow the underlying {@link WearableButtonsProvider} to be substituted in * test code. * * @param provider The new {@link WearableButtonsProvider} to use. */ @VisibleForTesting(otherwise = VisibleForTesting.NONE) public static void setWearableButtonsProvider(@NonNull WearableButtonsProvider provider) { sButtonsProvider = provider; } /** @hide */ @Retention(RetentionPolicy.SOURCE) @RestrictTo(RestrictTo.Scope.LIBRARY) @IntDef({ LOCATION_UNKNOWN, LOCATION_EAST, LOCATION_ENE, LOCATION_NE, LOCATION_NNE, LOCATION_NORTH, LOCATION_NNW, LOCATION_NW, LOCATION_WNW, LOCATION_WEST, LOCATION_WSW, LOCATION_SW, LOCATION_SSW, LOCATION_SOUTH, LOCATION_SSE, LOCATION_SE, LOCATION_ESE, LOCATION_TOP_RIGHT, LOCATION_TOP_CENTER, LOCATION_TOP_LEFT, LOCATION_LEFT_TOP, LOCATION_LEFT_CENTER, LOCATION_LEFT_BOTTOM, LOCATION_BOTTOM_LEFT, LOCATION_BOTTOM_CENTER, LOCATION_BOTTOM_RIGHT, LOCATION_RIGHT_BOTTOM, LOCATION_RIGHT_CENTER, LOCATION_RIGHT_TOP }) public @interface ButtonLocation {} /** Represents that the location zone is unknown. */ public static final int LOCATION_UNKNOWN = -1; /** Represents the east position on a round device. */ public static final int LOCATION_EAST = 0; /** Represents the east-northeast position on a round device. */ public static final int LOCATION_ENE = 1; /** Represents the northeast position on a round device. */ public static final int LOCATION_NE = 2; /** Represents the north-northeast position on a round device. */ public static final int LOCATION_NNE = 3; /** Represents the north position on a round device. */ public static final int LOCATION_NORTH = 4; /** Represents the north-northwest position on a round device. */ public static final int LOCATION_NNW = 5; /** Represents the northwest position on a round device. */ public static final int LOCATION_NW = 6; /** Represents the west-northwest position on a round device. */ public static final int LOCATION_WNW = 7; /** Represents the west position on a round device. */ public static final int LOCATION_WEST = 8; /** Represents the west-southwest position on a round device. */ public static final int LOCATION_WSW = 9; /** Represents the southwest position on a round device. */ public static final int LOCATION_SW = 10; /** Represents the south-southwest position on a round device. */ public static final int LOCATION_SSW = 11; /** Represents the south position on a round device. */ public static final int LOCATION_SOUTH = 12; /** Represents the south-southeast position on a round device. */ public static final int LOCATION_SSE = 13; /** Represents the southeast position on a round device. */ public static final int LOCATION_SE = 14; /** Represents the east-southeast position on a round device. */ public static final int LOCATION_ESE = 15; private static final int LOCATION_ROUND_COUNT = 16; /** Represents the right third of the top side on a square device. */ public static final int LOCATION_TOP_RIGHT = 100; /** Represents the center third of the top side on a square device. */ public static final int LOCATION_TOP_CENTER = 101; /** Represents the left third of the top side on a square device. */ public static final int LOCATION_TOP_LEFT = 102; /** Represents the top third of the left side on a square device. */ public static final int LOCATION_LEFT_TOP = 103; /** Represents the center third of the left side on a square device. */ public static final int LOCATION_LEFT_CENTER = 104; /** Represents the bottom third of the left side on a square device. */ public static final int LOCATION_LEFT_BOTTOM = 105; /** Represents the left third of the bottom side on a square device. */ public static final int LOCATION_BOTTOM_LEFT = 106; /** Represents the center third of the bottom side on a square device. */ public static final int LOCATION_BOTTOM_CENTER = 107; /** Represents the right third of the bottom side on a square device. */ public static final int LOCATION_BOTTOM_RIGHT = 108; /** Represents the bottom third of the right side on a square device. */ public static final int LOCATION_RIGHT_BOTTOM = 109; /** Represents the center third of the right side on a square device. */ public static final int LOCATION_RIGHT_CENTER = 110; /** Represents the top third of the right side on a square device. */ public static final int LOCATION_RIGHT_TOP = 111; /** * Key used with the bundle returned by {@link #getButtonInfo}} to retrieve the x coordinate of * a button when the screen is rotated 180 degrees. (temporary copy from WearableInputDevice) */ private static final String X_KEY_ROTATED = "x_key_rotated"; /** * Key used with the bundle returned by {@link #getButtonInfo}} to retrieve the y coordinate of * a button when the screen is rotated 180 degrees. (temporary copy from WearableInputDevice) */ private static final String Y_KEY_ROTATED = "y_key_rotated"; /** * Returns a {@link ButtonInfo} containing the metadata for a specific button. * * <p>The location will be populated in the following manner: * * <ul> * <li>The provided point will be on the screen, or more typically, on the edge of the screen. * <li>The point won't be off the edge of the screen. * <li>The location returned is a screen coordinate. The unit of measurement is in pixels. The * coordinates do not take rotation into account and assume that the device is in the * standard upright position. * </ul> * * <p>Common keycodes to use are {@link android.view.KeyEvent#KEYCODE_STEM_PRIMARY}, {@link * android.view.KeyEvent#KEYCODE_STEM_1}, {@link android.view.KeyEvent#KEYCODE_STEM_2}, and * {@link android.view.KeyEvent#KEYCODE_STEM_3}. * * @param context The context of the current activity * @param keycode The keycode associated with the hardware button of interest * @return A {@link ButtonInfo} containing the metadata for the given keycode or null if the * information is not available */ @SuppressWarnings("deprecation") @Nullable public static ButtonInfo getButtonInfo(@NonNull Context context, int keycode) { Bundle bundle = sButtonsProvider.getButtonInfo(context, keycode); if (bundle == null) { return null; } // If the information is not available, return null if (!bundle.containsKey(WearableInputDevice.X_KEY) || !bundle.containsKey(WearableInputDevice.Y_KEY)) { return null; } float screenLocationX = bundle.getFloat(WearableInputDevice.X_KEY); float screenLocationY = bundle.getFloat(WearableInputDevice.Y_KEY); // Get the screen size for the locationZone WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); Point screenSize = new Point(); wm.getDefaultDisplay().getSize(screenSize); if (isLeftyModeEnabled(context)) { // By default, the rotated placement is exactly the opposite. // This may be overridden if there is a remapping of buttons applied as well. float screenRotatedX = screenSize.x - screenLocationX; float screenRotatedY = screenSize.y - screenLocationY; if (bundle.containsKey(X_KEY_ROTATED) && bundle.containsKey(Y_KEY_ROTATED)) { screenRotatedX = bundle.getFloat(X_KEY_ROTATED); screenRotatedY = bundle.getFloat(Y_KEY_ROTATED); } screenLocationX = screenRotatedX; screenLocationY = screenRotatedY; } boolean isRound = context.getResources().getConfiguration().isScreenRound(); ButtonInfo info = new ButtonInfo( keycode, screenLocationX, screenLocationY, getLocationZone(isRound, screenSize, screenLocationX, screenLocationY)); return info; } /** * Get the number of hardware buttons available. This count includes the primary stem key as * well as any secondary stem keys available. * * @param context The context of the current activity * @return The number of buttons available, or the information is not available. */ public static int getButtonCount(@NonNull Context context) { if (sButtonCount == -1) { int[] buttonCodes = sButtonsProvider.getAvailableButtonKeyCodes(context); if (buttonCodes == null) { return -1; } sButtonCount = buttonCodes.length; } return sButtonCount; } /** * Returns an icon that can be used to represent the location of a button. * * @param context The context of the current activity * @param keycode The keycode associated with the hardware button of interest * @return A drawable representing the location of a button, or null if unavailable */ @Nullable public static Drawable getButtonIcon(@NonNull Context context, int keycode) { ButtonInfo info = getButtonInfo(context, keycode); if (info == null) { return null; } return getButtonIconFromLocationZone(context, info.getLocationZone()); } @VisibleForTesting static RotateDrawable getButtonIconFromLocationZone( Context context, @ButtonLocation int locationZone) { // To save memory for assets, we are using 4 icons to represent the 20+ possible // configurations. These 4 base icons can be rotated to fit any configuration needed. // id is the drawable id for the base icon // degrees is the number of degrees the icon needs to be rotated to match the wanted // position int id; int degrees; switch (locationZone) { // Round constants case LOCATION_EAST: id = R.drawable.ic_cc_settings_button_e; degrees = 0; break; case LOCATION_ENE: case LOCATION_NE: case LOCATION_NNE: id = R.drawable.ic_cc_settings_button_e; degrees = -45; break; case LOCATION_NORTH: id = R.drawable.ic_cc_settings_button_e; degrees = -90; break; case LOCATION_NNW: case LOCATION_NW: case LOCATION_WNW: id = R.drawable.ic_cc_settings_button_e; degrees = -135; break; case LOCATION_WEST: id = R.drawable.ic_cc_settings_button_e; degrees = 180; break; case LOCATION_WSW: case LOCATION_SW: case LOCATION_SSW: id = R.drawable.ic_cc_settings_button_e; degrees = 135; break; case LOCATION_SOUTH: id = R.drawable.ic_cc_settings_button_e; degrees = 90; break; case LOCATION_SSE: case LOCATION_SE: case LOCATION_ESE: id = R.drawable.ic_cc_settings_button_e; degrees = 45; break; // Rectangular constants case LOCATION_LEFT_TOP: id = R.drawable.ic_cc_settings_button_bottom; degrees = 180; break; case LOCATION_LEFT_CENTER: id = R.drawable.ic_cc_settings_button_center; degrees = 180; break; case LOCATION_LEFT_BOTTOM: id = R.drawable.ic_cc_settings_button_top; degrees = 180; break; case LOCATION_RIGHT_TOP: id = R.drawable.ic_cc_settings_button_top; degrees = 0; break; case LOCATION_RIGHT_CENTER: id = R.drawable.ic_cc_settings_button_center; degrees = 0; break; case LOCATION_RIGHT_BOTTOM: id = R.drawable.ic_cc_settings_button_bottom; degrees = 0; break; case LOCATION_TOP_LEFT: id = R.drawable.ic_cc_settings_button_top; degrees = -90; break; case LOCATION_TOP_CENTER: id = R.drawable.ic_cc_settings_button_center; degrees = -90; break; case LOCATION_TOP_RIGHT: id = R.drawable.ic_cc_settings_button_bottom; degrees = -90; break; case LOCATION_BOTTOM_LEFT: id = R.drawable.ic_cc_settings_button_bottom; degrees = 90; break; case LOCATION_BOTTOM_CENTER: id = R.drawable.ic_cc_settings_button_center; degrees = 90; break; case LOCATION_BOTTOM_RIGHT: id = R.drawable.ic_cc_settings_button_top; degrees = 90; break; default: throw new IllegalArgumentException("Unexpected location zone"); } RotateDrawable rotateIcon = new RotateDrawable(); rotateIcon.setDrawable(context.getDrawable(id)); rotateIcon.setFromDegrees(degrees); rotateIcon.setToDegrees(degrees); rotateIcon.setLevel(1); return rotateIcon; } /** * Returns a CharSequence that describes the placement location of a button. An example might be * "Top right" or "Bottom". * * @param context The context of the current activity * @param keycode The keycode associated with the hardware button of interest * @return A CharSequence describing the placement location of the button, or null if no * location is available for that button. */ @Nullable public static CharSequence getButtonLabel(@NonNull Context context, int keycode) { // 4 length array where the index uses the standard quadrant counting system (minus 1 for // 0 index) int[] buttonsInQuadrantCount = new int[4]; // Retrieve ButtonInfo objects and count how many buttons are in a quadrant. This is only // needed for round devices but will help us come up with friendly strings to show to the // user. // TODO(ahugh): We can cache quadrant counts to optimize. These values should be static for // each // device. int[] buttonCodes = sButtonsProvider.getAvailableButtonKeyCodes(context); if (buttonCodes == null) { return null; } for (int key : buttonCodes) { ButtonInfo info = getButtonInfo(context, key); if (info != null) { int quadrantIndex = getQuadrantIndex(info.getLocationZone()); if (quadrantIndex != -1) { ++buttonsInQuadrantCount[quadrantIndex]; } } } ButtonInfo info = getButtonInfo(context, keycode); int quadrantIndex = (info != null ? getQuadrantIndex(info.getLocationZone()) : -1); return info == null ? null : context.getString( getFriendlyLocationZoneStringId( info.getLocationZone(), (quadrantIndex == -1 ? 0 : buttonsInQuadrantCount[quadrantIndex]))); } /** * Returns quadrant index if locationZone is for a round device. Follows the conventional * quadrant system with the top right quadrant being 0, incrementing the index by 1 going * counter-clockwise around. */ private static int getQuadrantIndex(@ButtonLocation int locationZone) { switch (locationZone) { case LOCATION_ENE: case LOCATION_NE: case LOCATION_NNE: return 0; case LOCATION_NNW: case LOCATION_NW: case LOCATION_WNW: return 1; case LOCATION_WSW: case LOCATION_SW: case LOCATION_SSW: return 2; case LOCATION_SSE: case LOCATION_SE: case LOCATION_ESE: return 3; default: return -1; } } /** * If the screen is round, there is special logic we use to determine the string that should * show on the screen. Simple strings are broad descriptors like "top right". Detailed strings * are narrow descriptors like, "top right, upper" 1) If there are exactly 2 buttons in a * quadrant, use detailed strings to describe button locations. 2) Otherwise, use simple strings * to describe the button locations. * * @param locationZone The location zone to get a string id for * @param buttonsInQuadrantCount The number of buttons in the quadrant of the button * @return The string id to use to represent this button zone */ @VisibleForTesting static int getFriendlyLocationZoneStringId( @ButtonLocation int locationZone, int buttonsInQuadrantCount) { if (buttonsInQuadrantCount == 2) { switch (locationZone) { case LOCATION_ENE: return R.string.buttons_round_top_right_lower; case LOCATION_NE: case LOCATION_NNE: return R.string.buttons_round_top_right_upper; case LOCATION_NNW: case LOCATION_NW: return R.string.buttons_round_top_left_upper; case LOCATION_WNW: return R.string.buttons_round_top_left_lower; case LOCATION_ESE: case LOCATION_SE: return R.string.buttons_round_bottom_left_upper; case LOCATION_SSE: return R.string.buttons_round_bottom_left_lower; case LOCATION_SSW: return R.string.buttons_round_bottom_right_lower; case LOCATION_SW: case LOCATION_WSW: return R.string.buttons_round_bottom_right_upper; default: // fall out } } // If we couldn't find a detailed string, or we need a simple string switch (locationZone) { // Round constants case LOCATION_EAST: return R.string.buttons_round_center_right; case LOCATION_ENE: case LOCATION_NE: case LOCATION_NNE: return R.string.buttons_round_top_right; case LOCATION_NORTH: return R.string.buttons_round_top_center; case LOCATION_NNW: case LOCATION_NW: case LOCATION_WNW: return R.string.buttons_round_top_left; case LOCATION_WEST: return R.string.buttons_round_center_left; case LOCATION_WSW: case LOCATION_SW: case LOCATION_SSW: return R.string.buttons_round_bottom_left; case LOCATION_SOUTH: return R.string.buttons_round_bottom_center; case LOCATION_SSE: case LOCATION_SE: case LOCATION_ESE: return R.string.buttons_round_bottom_right; // Rectangular constants case LOCATION_LEFT_TOP: return R.string.buttons_rect_left_top; case LOCATION_LEFT_CENTER: return R.string.buttons_rect_left_center; case LOCATION_LEFT_BOTTOM: return R.string.buttons_rect_left_bottom; case LOCATION_RIGHT_TOP: return R.string.buttons_rect_right_top; case LOCATION_RIGHT_CENTER: return R.string.buttons_rect_right_center; case LOCATION_RIGHT_BOTTOM: return R.string.buttons_rect_right_bottom; case LOCATION_TOP_LEFT: return R.string.buttons_rect_top_left; case LOCATION_TOP_CENTER: return R.string.buttons_rect_top_center; case LOCATION_TOP_RIGHT: return R.string.buttons_rect_top_right; case LOCATION_BOTTOM_LEFT: return R.string.buttons_rect_bottom_left; case LOCATION_BOTTOM_CENTER: return R.string.buttons_rect_bottom_center; case LOCATION_BOTTOM_RIGHT: return R.string.buttons_rect_bottom_right; default: throw new IllegalArgumentException("Unexpected location zone"); } } /** * For round devices, the location zone is defined using 16 points in a compass arrangement. If * a button falls between anchor points, this method will return the closest anchor. * * <p>For rectangular devices, the location zone is defined by splitting each side into thirds. * If a button falls anywhere within a zone, the method will return that zone. The constants for * these zones are named LOCATION_[side in question]_[which third is affected]. E.g. * LOCATION_TOP_RIGHT would refer to the right third of the top side of the device. */ @VisibleForTesting /* package */ static int getLocationZone( boolean isRound, Point screenSize, float screenLocationX, float screenLocationY) { if (screenLocationX == Float.MAX_VALUE || screenLocationY == Float.MAX_VALUE) { return LOCATION_UNKNOWN; } return isRound ? getLocationZoneRound(screenSize, screenLocationX, screenLocationY) : getLocationZoneRectangular(screenSize, screenLocationX, screenLocationY); } private static int getLocationZoneRound( Point screenSize, float screenLocationX, float screenLocationY) { // Convert screen coordinate to Cartesian coordinate float cartesianX = screenLocationX - screenSize.x / 2; float cartesianY = screenSize.y / 2 - screenLocationY; // Use polar coordinates to figure out which zone the point is in double angle = Math.atan2(cartesianY, cartesianX); // Convert angle to all positive values if (angle < 0) { angle += 2 * Math.PI; } // Return the associated section rounded to the nearest anchor. // Using some clever math tricks and enum declaration, we can reduce this calculation // down to a single formula that converts angle to enum value. return Math.round((float) (angle / (Math.PI / 8))) % LOCATION_ROUND_COUNT; } private static int getLocationZoneRectangular( Point screenSize, float screenLocationX, float screenLocationY) { // Calculate distance to each edge. float deltaFromLeft = screenLocationX; float deltaFromRight = screenSize.x - screenLocationX; float deltaFromTop = screenLocationY; float deltaFromBottom = screenSize.y - screenLocationY; float minDelta = Math.min( deltaFromLeft, Math.min(deltaFromRight, Math.min(deltaFromTop, deltaFromBottom))); // Prioritize ties to left and right sides of watch since they're more likely to be placed // on the side. Buttons directly on the corner are not accounted for with this API. if (minDelta == deltaFromLeft) { // Left is the primary side switch (whichThird(screenSize.y, screenLocationY)) { case 0: return LOCATION_LEFT_TOP; case 1: return LOCATION_LEFT_CENTER; default: return LOCATION_LEFT_BOTTOM; } } else if (minDelta == deltaFromRight) { // Right is primary side switch (whichThird(screenSize.y, screenLocationY)) { case 0: return LOCATION_RIGHT_TOP; case 1: return LOCATION_RIGHT_CENTER; default: return LOCATION_RIGHT_BOTTOM; } } else if (minDelta == deltaFromTop) { // Top is primary side switch (whichThird(screenSize.x, screenLocationX)) { case 0: return LOCATION_TOP_LEFT; case 1: return LOCATION_TOP_CENTER; default: return LOCATION_TOP_RIGHT; } } else /* if (minDelta == deltaFromBottom) */ { // Bottom is primary side switch (whichThird(screenSize.x, screenLocationX)) { case 0: return LOCATION_BOTTOM_LEFT; case 1: return LOCATION_BOTTOM_CENTER; default: return LOCATION_BOTTOM_RIGHT; } } } // Returns 0, 1, or 2 which correspond to the index of the third the screen point lies in // from 'left to right' or 'top to bottom'. private static int whichThird(float screenLength, float screenLocation) { if (screenLocation <= screenLength / 3) { return 0; } else if (screenLocation <= screenLength * 2 / 3) { return 1; } else { return 2; } } private static boolean isLeftyModeEnabled(Context context) { return Settings.System.getInt( context.getContentResolver(), Settings.System.USER_ROTATION, Surface.ROTATION_0) == Surface.ROTATION_180; } /** Metadata for a specific button. */ public static final class ButtonInfo { private final int mKeycode; private final float mX; private final float mY; /** * The location zone of the button as defined in the {@link #getButtonInfo(Context, int)} * method. The intended use is to help developers attach a friendly String to the button * location. This value is LOCATION_UNKNOWN if the information is not available. */ @ButtonLocation private final int mLocationZone; /** * Gets the keycode this {@code ButtonInfo} provides information for. * * @return The keycode this {@code ButtonInfo} provides information for */ public int getKeycode() { return mKeycode; } /** The x coordinate of the button in screen coordinates. */ public float getX() { return mX; } /** The y coordinate of the button in screen coordinates. */ public float getY() { return mY; } /** The location zone of the button (e.g. LOCATION_EAST) */ @ButtonLocation public int getLocationZone() { return mLocationZone; } /** @hide */ @RestrictTo(RestrictTo.Scope.LIBRARY) @VisibleForTesting public ButtonInfo(int keycode, float x, float y, @ButtonLocation int locationZone) { this.mKeycode = keycode; this.mX = x; this.mY = y; this.mLocationZone = locationZone; } } }
Added images to Javadocs on WearableButtons. Test: It's just documentation. Bug: 193669509 Change-Id: I6b5c3770be455810a077a9abe80815b161f58601
wear/wear-input/src/main/java/androidx/wear/input/WearableButtons.java
Added images to Javadocs on WearableButtons.
<ide><path>ear/wear-input/src/main/java/androidx/wear/input/WearableButtons.java <ide> * coordinates do not take rotation into account and assume that the device is in the <ide> * standard upright position. <ide> * </ul> <add> * <add> * <p>Additionally, a location zone will be provided for the button, which will be one of the <add> * {@code LOCATION_*} constants. This defines the general area of the button on the device, and <add> * can be passed to {@link #getButtonLabel} to provide a human-understandable name for the <add> * location. There are two sets of locations for a device, depending on whether it is a circular <add> * or rectilinear device. <add> * <add> * <p>The "compass" locations (e.g. {@link #LOCATION_ENE}) are used on a circular device. The <add> * locations for each are shown in the following image: <add> * <add> * <img src="https://developer.android.com/images/reference/androidx/wear/wear-input/buttons_round.png" alt="Image detailing the locations of compass locations on a Wear device. North is at the top, followed by north-north-east, north-east, east-north-east, east, and so on."> <add> * <add> * <p>The other locations (e.g. {@link #LOCATION_BOTTOM_CENTER}) are used on a rectilinear <add> * device. The locations for each are shown in the following image: <add> * <add> * <img src="https://developer.android.com/images/reference/androidx/wear/wear-input/buttons_square.png" alt="Image detailing the locations of other buttons on a Wear device. The first word details the side of the device the button is on, then the second word details where on that side the button is (e.g. 'TOP LEFT' means on the top edge, at the left hand side, and 'RIGHT BOTTOM' means on the right edge, at the bottom)."> <ide> * <ide> * <p>Common keycodes to use are {@link android.view.KeyEvent#KEYCODE_STEM_PRIMARY}, {@link <ide> * android.view.KeyEvent#KEYCODE_STEM_1}, {@link android.view.KeyEvent#KEYCODE_STEM_2}, and <ide> * The location zone of the button as defined in the {@link #getButtonInfo(Context, int)} <ide> * method. The intended use is to help developers attach a friendly String to the button <ide> * location. This value is LOCATION_UNKNOWN if the information is not available. <add> * <add> * <ide> */ <ide> @ButtonLocation private final int mLocationZone; <ide>
Java
apache-2.0
40c3e798b0bc0a444af014f8ad16720f03d104cb
0
luoxiaoshenghustedu/AndEngine,Munazza/AndEngine,viacheslavokolitiy/AndEngine,parthipanramesh/AndEngine,pongo710/AndEngine,viacheslavokolitiy/AndEngine,shiguang1120/AndEngine,yudhir/AndEngine,chautn/AndEngine,zhidew/AndEngine,nicolasgramlich/AndEngine,viacheslavokolitiy/AndEngine,pongo710/AndEngine,chautn/AndEngine,jduberville/AndEngine,godghdai/AndEngine,pongo710/AndEngine,Munazza/AndEngine,godghdai/AndEngine,msdgwzhy6/AndEngine,viacheslavokolitiy/AndEngine,luoxiaoshenghustedu/AndEngine,yudhir/AndEngine,shiguang1120/AndEngine,Munazza/AndEngine,shiguang1120/AndEngine,chautn/AndEngine,zhidew/AndEngine,zhidew/AndEngine,yudhir/AndEngine,ericlaro/AndEngineLibrary,yudhir/AndEngine,yaye729125/gles,zcwk/AndEngine,chautn/AndEngine,borrom/AndEngine,shiguang1120/AndEngine,jduberville/AndEngine,nicolasgramlich/AndEngine,duchien85/AndEngine,borrom/AndEngine,zhidew/AndEngine,jduberville/AndEngine,godghdai/AndEngine,zcwk/AndEngine,nicolasgramlich/AndEngine,parthipanramesh/AndEngine,msdgwzhy6/AndEngine,borrom/AndEngine,luoxiaoshenghustedu/AndEngine,zcwk/AndEngine,ericlaro/AndEngineLibrary,ericlaro/AndEngineLibrary,borrom/AndEngine,yaye729125/gles,zcwk/AndEngine,yaye729125/gles,nicolasgramlich/AndEngine,msdgwzhy6/AndEngine,godghdai/AndEngine,jduberville/AndEngine,parthipanramesh/AndEngine,luoxiaoshenghustedu/AndEngine,duchien85/AndEngine,parthipanramesh/AndEngine,msdgwzhy6/AndEngine,yaye729125/gles,pongo710/AndEngine,Munazza/AndEngine,ericlaro/AndEngineLibrary
package org.anddev.andengine.entity.text; import javax.microedition.khronos.opengles.GL10; import javax.microedition.khronos.opengles.GL11; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.entity.shape.RectangularShape; import org.anddev.andengine.opengl.buffer.BufferObjectManager; import org.anddev.andengine.opengl.font.Font; import org.anddev.andengine.opengl.texture.buffer.TextTextureBuffer; import org.anddev.andengine.opengl.util.GLHelper; import org.anddev.andengine.opengl.vertex.TextVertexBuffer; import org.anddev.andengine.util.HorizontalAlign; import org.anddev.andengine.util.StringUtils; /** * @author Nicolas Gramlich * @since 10:54:59 - 03.04.2010 */ public class Text extends RectangularShape { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final TextTextureBuffer mTextTextureBuffer; private String mText; private String[] mLines; private int[] mWidths; private final Font mFont; private int mMaximumLineWidth; protected final int mCharactersMaximum; protected final int mVertexCount; // =========================================================== // Constructors // =========================================================== public Text(final float pX, final float pY, final Font pFont, final String pText) { this(pX, pY, pFont, pText, HorizontalAlign.LEFT); } public Text(final float pX, final float pY, final Font pFont, final String pText, final HorizontalAlign pHorizontalAlign) { this(pX, pY, pFont, pText, pHorizontalAlign, pText.length() - StringUtils.countOccurrences(pText, '\n')); } protected Text(final float pX, final float pY, final Font pFont, final String pText, final HorizontalAlign pHorizontalAlign, final int pCharactersMaximum) { super(pX, pY, 0, 0, new TextVertexBuffer(pCharactersMaximum, pHorizontalAlign, GL11.GL_STATIC_DRAW)); this.mCharactersMaximum = pCharactersMaximum; this.mVertexCount = TextVertexBuffer.VERTICES_PER_CHARACTER * this.mCharactersMaximum; this.mTextTextureBuffer = new TextTextureBuffer(2 * this.mVertexCount, GL11.GL_STATIC_DRAW); BufferObjectManager.getActiveInstance().loadBufferObject(this.mTextTextureBuffer); this.mFont = pFont; this.updateText(pText); this.initBlendFunction(); } protected void updateText(final String pText) { this.mText = pText; final Font font = this.mFont; this.mLines = StringUtils.split(this.mText, '\n', this.mLines); final String[] lines = this.mLines; final int lineCount = lines.length; final boolean widthsReusable = this.mWidths != null && this.mWidths.length == lineCount; if(widthsReusable == false) { this.mWidths = new int[lineCount]; } final int[] widths = this.mWidths; int maximumLineWidth = 0; for (int i = lineCount - 1; i >= 0; i--) { widths[i] = font.getStringWidth(lines[i]); maximumLineWidth = Math.max(maximumLineWidth, widths[i]); } this.mMaximumLineWidth = maximumLineWidth; super.mWidth = this.mMaximumLineWidth; final float width = super.mWidth; super.mBaseWidth = width; super.mHeight = lineCount * font.getLineHeight() + (lineCount - 1) * font.getLineGap(); final float height = super.mHeight; super.mBaseHeight = height; this.mRotationCenterX = width * 0.5f; this.mRotationCenterY = height * 0.5f; this.mScaleCenterX = this.mRotationCenterX; this.mScaleCenterY = this.mRotationCenterY; this.mTextTextureBuffer.update(font, lines); this.updateVertexBuffer(); } // =========================================================== // Getter & Setter // =========================================================== public int getCharacterCount() { return this.mCharactersMaximum; } @Override public TextVertexBuffer getVertexBuffer() { return (TextVertexBuffer)super.getVertexBuffer(); } public String getText() { return this.mText; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override protected void onInitDraw(final GL10 pGL) { super.onInitDraw(pGL); GLHelper.enableTextures(pGL); GLHelper.enableTexCoordArray(pGL); } @Override protected void drawVertices(final GL10 pGL, final Camera pCamera) { pGL.glDrawArrays(GL10.GL_TRIANGLES, 0, this.mVertexCount); } @Override protected void onUpdateVertexBuffer() { final Font font = this.mFont; if(font != null) { this.getVertexBuffer().update(font, this.mMaximumLineWidth, this.mWidths, this.mLines); } } @Override protected void onApplyTransformations(final GL10 pGL) { super.onApplyTransformations(pGL); this.applyTexture(pGL); } // =========================================================== // Methods // =========================================================== private void initBlendFunction() { if(this.mFont.getTexture().getTextureOptions().mPreMultipyAlpha) { this.setBlendFunction(BLENDFUNCTION_SOURCE_PREMULTIPLYALPHA_DEFAULT, BLENDFUNCTION_DESTINATION_PREMULTIPLYALPHA_DEFAULT); } } private void applyTexture(final GL10 pGL) { if(GLHelper.EXTENSIONS_VERTEXBUFFEROBJECTS) { final GL11 gl11 = (GL11)pGL; this.mTextTextureBuffer.selectOnHardware(gl11); GLHelper.bindTexture(pGL, this.mFont.getTexture().getHardwareTextureID()); GLHelper.texCoordZeroPointer(gl11); } else { GLHelper.bindTexture(pGL, this.mFont.getTexture().getHardwareTextureID()); GLHelper.texCoordPointer(pGL, this.mTextTextureBuffer.getFloatBuffer()); } } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
src/org/anddev/andengine/entity/text/Text.java
package org.anddev.andengine.entity.text; import javax.microedition.khronos.opengles.GL10; import javax.microedition.khronos.opengles.GL11; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.entity.shape.RectangularShape; import org.anddev.andengine.opengl.buffer.BufferObjectManager; import org.anddev.andengine.opengl.font.Font; import org.anddev.andengine.opengl.texture.buffer.TextTextureBuffer; import org.anddev.andengine.opengl.util.GLHelper; import org.anddev.andengine.opengl.vertex.TextVertexBuffer; import org.anddev.andengine.util.HorizontalAlign; import org.anddev.andengine.util.StringUtils; /** * @author Nicolas Gramlich * @since 10:54:59 - 03.04.2010 */ public class Text extends RectangularShape { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final TextTextureBuffer mTextTextureBuffer; private String mText; private String[] mLines; private int[] mWidths; private final Font mFont; private int mMaximumLineWidth; protected final int mCharactersMaximum; protected final int mVertexCount; // =========================================================== // Constructors // =========================================================== public Text(final float pX, final float pY, final Font pFont, final String pText) { this(pX, pY, pFont, pText, HorizontalAlign.LEFT); } public Text(final float pX, final float pY, final Font pFont, final String pText, final HorizontalAlign pHorizontalAlign) { this(pX, pY, pFont, pText, pHorizontalAlign, pText.length() - StringUtils.countOccurrences(pText, '\n')); } protected Text(final float pX, final float pY, final Font pFont, final String pText, final HorizontalAlign pHorizontalAlign, final int pCharactersMaximum) { super(pX, pY, 0, 0, new TextVertexBuffer(pCharactersMaximum, pHorizontalAlign, GL11.GL_STATIC_DRAW)); this.mCharactersMaximum = pCharactersMaximum; this.mVertexCount = TextVertexBuffer.VERTICES_PER_CHARACTER * this.mCharactersMaximum; this.mTextTextureBuffer = new TextTextureBuffer(2 * this.mVertexCount, GL11.GL_STATIC_DRAW); BufferObjectManager.getActiveInstance().loadBufferObject(this.mTextTextureBuffer); this.mFont = pFont; this.updateText(pText); this.initBlendFunction(); } protected void updateText(final String pText) { this.mText = pText; final Font font = this.mFont; this.mLines = StringUtils.split(this.mText, '\n', this.mLines); final String[] lines = this.mLines; final int lineCount = lines.length; final boolean widthsReusable = this.mWidths != null && this.mWidths.length == lineCount; if(widthsReusable == false) { this.mWidths = new int[lineCount]; } final int[] widths = this.mWidths; int maximumLineWidth = 0; for (int i = lineCount - 1; i >= 0; i--) { widths[i] = font.getStringWidth(lines[i]); maximumLineWidth = Math.max(maximumLineWidth, widths[i]); } this.mMaximumLineWidth = maximumLineWidth; super.mWidth = this.mMaximumLineWidth; final float width = super.mWidth; super.mBaseWidth = width; super.mHeight = lineCount * font.getLineHeight() + (lineCount - 1) * font.getLineGap(); final float height = super.mHeight; super.mBaseHeight = height; this.mRotationCenterX = width * 0.5f; this.mRotationCenterY = height * 0.5f; this.mScaleCenterX = this.mRotationCenterX; this.mScaleCenterY = this.mRotationCenterY; this.mTextTextureBuffer.update(font, lines); this.updateVertexBuffer(); } // =========================================================== // Getter & Setter // =========================================================== public int getCharacterCount() { return this.mCharactersMaximum; } @Override public TextVertexBuffer getVertexBuffer() { return (TextVertexBuffer)super.getVertexBuffer(); } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override protected void onInitDraw(final GL10 pGL) { super.onInitDraw(pGL); GLHelper.enableTextures(pGL); GLHelper.enableTexCoordArray(pGL); } @Override protected void drawVertices(final GL10 pGL, final Camera pCamera) { pGL.glDrawArrays(GL10.GL_TRIANGLES, 0, this.mVertexCount); } @Override protected void onUpdateVertexBuffer() { final Font font = this.mFont; if(font != null) { this.getVertexBuffer().update(font, this.mMaximumLineWidth, this.mWidths, this.mLines); } } @Override protected void onApplyTransformations(final GL10 pGL) { super.onApplyTransformations(pGL); this.applyTexture(pGL); } // =========================================================== // Methods // =========================================================== private void initBlendFunction() { if(this.mFont.getTexture().getTextureOptions().mPreMultipyAlpha) { this.setBlendFunction(BLENDFUNCTION_SOURCE_PREMULTIPLYALPHA_DEFAULT, BLENDFUNCTION_DESTINATION_PREMULTIPLYALPHA_DEFAULT); } } private void applyTexture(final GL10 pGL) { if(GLHelper.EXTENSIONS_VERTEXBUFFEROBJECTS) { final GL11 gl11 = (GL11)pGL; this.mTextTextureBuffer.selectOnHardware(gl11); GLHelper.bindTexture(pGL, this.mFont.getTexture().getHardwareTextureID()); GLHelper.texCoordZeroPointer(gl11); } else { GLHelper.bindTexture(pGL, this.mFont.getTexture().getHardwareTextureID()); GLHelper.texCoordPointer(pGL, this.mTextTextureBuffer.getFloatBuffer()); } } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Added a getText() method to the Text class. (Requested by: Tahakki, AlexNunn and others).
src/org/anddev/andengine/entity/text/Text.java
Added a getText() method to the Text class. (Requested by: Tahakki, AlexNunn and others).
<ide><path>rc/org/anddev/andengine/entity/text/Text.java <ide> public TextVertexBuffer getVertexBuffer() { <ide> return (TextVertexBuffer)super.getVertexBuffer(); <ide> } <add> <add> public String getText() { <add> return this.mText; <add> } <ide> <ide> // =========================================================== <ide> // Methods for/from SuperClass/Interfaces
Java
agpl-3.0
200ab14d732010e8f98d1b0a56d5d4d15d3f824b
0
ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools
package de.unituebingen.ub.ubtools.solrmarcMixin; import java.text.Collator; import java.util.*; import org.marc4j.marc.DataField; import org.marc4j.marc.Record; import org.marc4j.marc.Subfield; import org.marc4j.marc.VariableField; import org.solrmarc.index.SolrIndexerMixin; import de.unituebingen.ub.ubtools.solrmarcMixin.*; public class IxTheoKeywordChains extends SolrIndexerMixin { private final static String KEYWORD_DELIMITER = "/"; private final static String SUBFIELD_CODES = "abctnpz"; private final static TuelibMixin tuelibMixin = new TuelibMixin(); public Set<String> getKeyWordChain(final Record record, final String fieldSpec, final String lang) { final List<VariableField> variableFields = record.getVariableFields(fieldSpec); final Map<Character, List<String>> keyWordChains = new HashMap<>(); for (final VariableField variableField : variableFields) { final DataField dataField = (DataField) variableField; processField(dataField, keyWordChains, lang); } return concatenateKeyWordsToChains(keyWordChains); } /** * Create set version of the terms contained in the keyword chains */ public Set<String> getKeyWordChainBag(final Record record, final String fieldSpec, final String lang) { final List<VariableField> variableFields = record.getVariableFields(fieldSpec); final Map<Character, List<String>> keyWordChains = new HashMap<>(); final Set<String> keyWordChainBag = new HashSet<>(); for (final VariableField variableField : variableFields) { final DataField dataField = (DataField) variableField; processField(dataField, keyWordChains, lang); } for (List<String> keyWordChain : keyWordChains.values()) { keyWordChainBag.addAll(keyWordChain); } return keyWordChainBag; } public Set<String> getKeyWordChainSorted(final Record record, final String fieldSpec, final String lang) { final List<VariableField> variableFields = record.getVariableFields(fieldSpec); final Map<Character, List<String>> keyWordChains = new HashMap<>(); for (final VariableField variableField : variableFields) { final DataField dataField = (DataField) variableField; processField(dataField, keyWordChains, lang); // Sort keyword chain final char chainID = dataField.getIndicator1(); final List<String> keyWordChain = getKeyWordChain(keyWordChains, chainID); Collator collator = Collator.getInstance(Locale.forLanguageTag(lang)); Collections.sort(keyWordChain, collator); } return concatenateKeyWordsToChains(keyWordChains); } /** * Extracts the keyword from data field and inserts it into the right * keyword chain. */ private void processField(final DataField dataField, final Map<Character, List<String>> keyWordChains, String lang) { final char chainID = dataField.getIndicator1(); final List<String> keyWordChain = getKeyWordChain(keyWordChains, chainID); boolean gnd_seen = false; StringBuilder keyword = new StringBuilder(); for (final Subfield subfield : dataField.getSubfields()) { if (gnd_seen) { if (SUBFIELD_CODES.indexOf(subfield.getCode()) != -1) { if (keyword.length() > 0) { if (subfield.getCode() == 'z') { keyword.append(" (" + tuelibMixin.translateTopic(subfield.getData(), lang) + ")"); continue; } else if (subfield.getCode() == 'n') keyword.append(" "); else if (subfield.getCode() == 'p') keyword.append(". "); else keyword.append(", "); } keyword.append(tuelibMixin.translateTopic(subfield.getData(), lang)); } else if (subfield.getCode() == '9' && keyword.length() > 0 && subfield.getData().startsWith("g:")) { // For Ixtheo-translations the specification in the g:-Subfield is appended in angle // brackets, so this is a special case where we have to begin from scratch final String specification = subfield.getData().substring(2); final Subfield germanASubfield = dataField.getSubfield('a'); if (germanASubfield != null) { final String translationCandidate = germanASubfield.getData() + " <" + specification + ">"; final String translation = tuelibMixin.translateTopic(translationCandidate, lang); keyword.setLength(0); keyword.append(translation.replaceAll("<", "(").replaceAll(">", ")")); } else { keyword.append(" ("); keyword.append(tuelibMixin.translateTopic(specification, lang)); keyword.append(')'); } } } else if (subfield.getCode() == '2' && subfield.getData().equals("gnd")) gnd_seen = true; } if (keyword.length() > 0) { String keywordString = keyword.toString().replace("/", "\\/"); keyWordChain.add(keywordString); } } /** * Finds the right keyword chain for a given chain id. * * @return A map containing the keywords of the chain (id -> keyword), or an * empty map. */ private List<String> getKeyWordChain(final Map<Character, List<String>> keyWordChains, final char chainID) { List<String> keyWordChain = keyWordChains.get(chainID); if (keyWordChain == null) { keyWordChain = new ArrayList<>(); keyWordChains.put(chainID, keyWordChain); } return keyWordChain; } private Set<String> concatenateKeyWordsToChains(final Map<Character, List<String>> keyWordChains) { final List<Character> chainIDs = new ArrayList<>(keyWordChains.keySet()); Collections.sort(chainIDs); final Set<String> chainSet = new LinkedHashSet<>(); for (final Character chainID : chainIDs) { chainSet.add(keyChainToString(keyWordChains.get(chainID))); } return chainSet; } private String keyChainToString(final List<String> keyWordChain) { final StringBuilder buffer = new StringBuilder(); for (final String keyWord : keyWordChain) { buffer.append(KEYWORD_DELIMITER); buffer.append(keyWord); } if (buffer.length() == 0) { return ""; } // Discard leading keyword delimiter. return buffer.toString().substring(1); } }
solrmarc_mixin/src/de/unituebingen/ub/ubtools/solrmarcMixin/IxTheoKeywordChains.java
package de.unituebingen.ub.ubtools.solrmarcMixin; import java.util.*; import org.marc4j.marc.DataField; import org.marc4j.marc.Record; import org.marc4j.marc.Subfield; import org.marc4j.marc.VariableField; import org.solrmarc.index.SolrIndexerMixin; import de.unituebingen.ub.ubtools.solrmarcMixin.*; public class IxTheoKeywordChains extends SolrIndexerMixin { private final static String KEYWORD_DELIMITER = "/"; private final static String SUBFIELD_CODES = "abctnpz"; private final static TuelibMixin tuelibMixin = new TuelibMixin(); public Set<String> getKeyWordChain(final Record record, final String fieldSpec, final String lang) { final List<VariableField> variableFields = record.getVariableFields(fieldSpec); final Map<Character, List<String>> keyWordChains = new HashMap<>(); for (final VariableField variableField : variableFields) { final DataField dataField = (DataField) variableField; processField(dataField, keyWordChains, lang); } return concatenateKeyWordsToChains(keyWordChains); } /** * Create set version of the terms contained in the keyword chains */ public Set<String> getKeyWordChainBag(final Record record, final String fieldSpec, final String lang) { final List<VariableField> variableFields = record.getVariableFields(fieldSpec); final Map<Character, List<String>> keyWordChains = new HashMap<>(); final Set<String> keyWordChainBag = new HashSet<>(); for (final VariableField variableField : variableFields) { final DataField dataField = (DataField) variableField; processField(dataField, keyWordChains, lang); } for (List<String> keyWordChain : keyWordChains.values()) { keyWordChainBag.addAll(keyWordChain); } return keyWordChainBag; } public Set<String> getKeyWordChainSorted(final Record record, final String fieldSpec, final String lang) { final List<VariableField> variableFields = record.getVariableFields(fieldSpec); final Map<Character, List<String>> keyWordChains = new HashMap<>(); for (final VariableField variableField : variableFields) { final DataField dataField = (DataField) variableField; processField(dataField, keyWordChains, lang); // Sort keyword chain final char chainID = dataField.getIndicator1(); final List<String> keyWordChain = getKeyWordChain(keyWordChains, chainID); Collections.sort(keyWordChain, String.CASE_INSENSITIVE_ORDER); } return concatenateKeyWordsToChains(keyWordChains); } /** * Extracts the keyword from data field and inserts it into the right * keyword chain. */ private void processField(final DataField dataField, final Map<Character, List<String>> keyWordChains, String lang) { final char chainID = dataField.getIndicator1(); final List<String> keyWordChain = getKeyWordChain(keyWordChains, chainID); boolean gnd_seen = false; StringBuilder keyword = new StringBuilder(); for (final Subfield subfield : dataField.getSubfields()) { if (gnd_seen) { if (SUBFIELD_CODES.indexOf(subfield.getCode()) != -1) { if (keyword.length() > 0) { if (subfield.getCode() == 'z') { keyword.append(" (" + tuelibMixin.translateTopic(subfield.getData(), lang) + ")"); continue; } else if (subfield.getCode() == 'n') keyword.append(" "); else if (subfield.getCode() == 'p') keyword.append(". "); else keyword.append(", "); } keyword.append(tuelibMixin.translateTopic(subfield.getData(), lang)); } else if (subfield.getCode() == '9' && keyword.length() > 0 && subfield.getData().startsWith("g:")) { // For Ixtheo-translations the specification in the g:-Subfield is appended in angle // brackets, so this is a special case where we have to begin from scratch final String specification = subfield.getData().substring(2); final Subfield germanASubfield = dataField.getSubfield('a'); if (germanASubfield != null) { final String translationCandidate = germanASubfield.getData() + " <" + specification + ">"; final String translation = tuelibMixin.translateTopic(translationCandidate, lang); keyword.setLength(0); keyword.append(translation.replaceAll("<", "(").replaceAll(">", ")")); } else { keyword.append(" ("); keyword.append(tuelibMixin.translateTopic(specification, lang)); keyword.append(')'); } } } else if (subfield.getCode() == '2' && subfield.getData().equals("gnd")) gnd_seen = true; } if (keyword.length() > 0) { String keywordString = keyword.toString().replace("/", "\\/"); keyWordChain.add(keywordString); } } /** * Finds the right keyword chain for a given chain id. * * @return A map containing the keywords of the chain (id -> keyword), or an * empty map. */ private List<String> getKeyWordChain(final Map<Character, List<String>> keyWordChains, final char chainID) { List<String> keyWordChain = keyWordChains.get(chainID); if (keyWordChain == null) { keyWordChain = new ArrayList<>(); keyWordChains.put(chainID, keyWordChain); } return keyWordChain; } private Set<String> concatenateKeyWordsToChains(final Map<Character, List<String>> keyWordChains) { final List<Character> chainIDs = new ArrayList<>(keyWordChains.keySet()); Collections.sort(chainIDs); final Set<String> chainSet = new LinkedHashSet<>(); for (final Character chainID : chainIDs) { chainSet.add(keyChainToString(keyWordChains.get(chainID))); } return chainSet; } private String keyChainToString(final List<String> keyWordChain) { final StringBuilder buffer = new StringBuilder(); for (final String keyWord : keyWordChain) { buffer.append(KEYWORD_DELIMITER); buffer.append(keyWord); } if (buffer.length() == 0) { return ""; } // Discard leading keyword delimiter. return buffer.toString().substring(1); } }
Make sorting KWCs locale dependent
solrmarc_mixin/src/de/unituebingen/ub/ubtools/solrmarcMixin/IxTheoKeywordChains.java
Make sorting KWCs locale dependent
<ide><path>olrmarc_mixin/src/de/unituebingen/ub/ubtools/solrmarcMixin/IxTheoKeywordChains.java <ide> package de.unituebingen.ub.ubtools.solrmarcMixin; <ide> <add>import java.text.Collator; <ide> import java.util.*; <ide> import org.marc4j.marc.DataField; <ide> import org.marc4j.marc.Record; <ide> // Sort keyword chain <ide> final char chainID = dataField.getIndicator1(); <ide> final List<String> keyWordChain = getKeyWordChain(keyWordChains, chainID); <del> Collections.sort(keyWordChain, String.CASE_INSENSITIVE_ORDER); <add> Collator collator = Collator.getInstance(Locale.forLanguageTag(lang)); <add> Collections.sort(keyWordChain, collator); <ide> } <ide> return concatenateKeyWordsToChains(keyWordChains); <ide> }
JavaScript
apache-2.0
acd809db1d3541d6d4f801f9750df7c1ee51ebc2
0
tymiles003/metrics-dashboard,tymiles003/metrics-dashboard
(function(){ // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // Dashboard Settings // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- var settings = { ssl : true, subscribe_key : 'sub-c-44d3418c-4855-11e4-8a5b-02ee2ddab7fe', publish_key : 'pub-c-eae49ba3-b1ee-46c4-8674-27ce042e7ab3', channel : urlsetting() }; var pubnub = PUBNUB(settings); var starttime = now(); var genstarttime = now(); var salebellwait = 3000; // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // Startup Metrics Default Dashboard Position // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- var startupmetrics = JSON.parse(PUBNUB.db.get(settings.channel)) || { // Whitelable title : "Startup", subtitle : "Weekly Goals", logo_img : "img/pubnub.png", // Vanity Labels vanity_one : 'MENTIONS', vanity_two : 'FOLLOWERS', vanity_three : 'COMMENTS', vanity_four : 'STACKOVERFLOW', // Acquisition acquisition : 55, acquisition_goal : 100, // Activation activation : 10, activation_goal : 20, // Retention retention : 189, retention_goal : 250, // Revenue revenue : 890, revenue_goal : 1200, // Referrals mentions : 342, attendees : 89, articles : 45, stackoverflow : 8 }; // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // Bootstrap Startup Metrics // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- pubnub.history({ limit : 1, channel : settings.channel, callback : function(msgs) { save(msgs[0][0] || {}) } }); // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // Live Startup Metrics // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- pubnub.subscribe({ channel : settings.channel, message : function(msg) { save(msg) } }); // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // Update Startup Metrics // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- update_metrics(startupmetrics); function update_metrics(startup) { PUBNUB.each( startup, function( metric, value ) { // Update Metric Display var display = PUBNUB.$(metric); if (!display) return; // Logo Whitelabel if (metric.indexOf('_img') > 0) return PUBNUB.css( display, { 'background-image' : 'url('+value+')' } ); // Revenue Money Sales Bell if ( metric === 'revenue' && +value && +display.innerHTML && +value != (+display.innerHTML) && +value != (+PUBNUB.attr( display, 'upcoming' )) ) ring_bell( +value < (+display.innerHTML) ); // Set Display for Awesome? update_display( display, value ); // Generic Update Sound update_sound(metric); // Percentage Display if Relevant if (metric.indexOf('_goal') < 0) return; var metric_name = metric.split('_goal')[0] , metric_value = startup[metric_name] , metric_goal = value; // Update GUI Percent Circle Metrics update_circle_metrics( metric_name, metric_value, metric_goal ); } ); } // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // Visually Update Startup Metrics with Maybe Animations // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- function update_display( display, value ) { var original = display.innerHTML , upcoming = PUBNUB.attr( display, 'upcoming' ); // Save Upcoming Value if (upcoming == value) return; PUBNUB.attr( display, 'upcoming', value ); // Render Display if (!!(+original+ +value) && original != value) (function(){ var frame = 1.0 , total = 15 , ori = +original , val = +value; function updater(frame) { setTimeout( function() { display.innerHTML = Math.floor( ori + (val - ori) * (frame / total) ); }, frame * 180 ) } while (frame <= total) updater(frame++); })(); else display.innerHTML = value; } // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // Save Startup Metrics // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- function save( modification, broadcast ) { PUBNUB.each( modification, function( k, v ) { startupmetrics[k] = v } ); PUBNUB.db.set( settings.channel, JSON.stringify(startupmetrics) ); update_metrics(startupmetrics); if (!broadcast) return; pubnub.publish({ channel : settings.channel, message : startupmetrics }); } // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // Update Startup Metrics Circles // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- function update_circle_metrics( name, value, goal ) { var circle = PUBNUB.$('pc_'+name) , percent = PUBNUB.$('percent_'+name) , result = Math.floor( (+value / (+goal||1)) * 100 ) , resmax = (result > 999 ? 999 : result) , pclass = ' p' + (result > 100 ? 100 : result); circle.className = circle.className.replace( / p[^ ]+/, ' p00' ); circle.className = circle.className.replace( / p[^ ]+/, pclass ); update_display( percent, resmax ) } // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // Change UI Element - Update the Values Visually // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- PUBNUB.bind( 'mousedown,touchstart', document, function(element) { var target = (element.target || element.srcElement) , id = PUBNUB.attr( target, 'id' ) , input = PUBNUB.$('editor-input') , editor = PUBNUB.$('editor'); // Ignore Clicking Editor Controls if (!id || id.indexOf('editor') >= 0) return true; // Show Editor GUI PUBNUB.attr( input, 'directive', id ); show_editor(true); input.value = startupmetrics[id] || target.innerHTML.replace(/^\s+|\s+$/g,''); setTimeout( function(){input.focus();input.select()}, 250 ); return true; } ); // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // Show Editor // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- function show_editor(yes) { PUBNUB.css( PUBNUB.$('editor'), { display : (yes ? 'block' : 'none') } ); } // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // Generic Update Sound // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- function update_sound(metric) { if (genstarttime + salebellwait > now()) return; if ( metric === 'acquisition' || metric === 'activation' || metric === 'retention' || metric === 'mentions' || metric === 'attendees' || metric === 'articles' || metric === 'stackoverflow' ) { sounds.play( 'sounds/success', 2000 ); genstarttime = now(); } } // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // Sales Bell // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- window.ring_bell = ring_bell; function ring_bell(downd) { // Prevent Early Sales Bell on Boot if (starttime + salebellwait > now()) return; starttime = now(); // Play Sales Bell Sound "money.mp3" or "money.ogg" if (!downd) sounds.play( 'sounds/money', 16000 ); else return sounds.play( 'sounds/decrement', 2000 ); // Display Animation var bell = PUBNUB.$('salesbell'); PUBNUB.css( bell, { opacity : 0.0, display : 'block' } ); setTimeout( function() { PUBNUB.css( bell, { opacity : 1.0 } ); }, 500 ); setTimeout( function() { PUBNUB.css( bell, { opacity : 0.0 } ); }, 12000 ); setTimeout( function() { PUBNUB.css( bell, { display : 'none' } ); }, 14000 ); } // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // Editor Controls - SAVE // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- PUBNUB.bind( 'click', PUBNUB.$('editor-save'), save_edits ); PUBNUB.bind( 'keydown', PUBNUB.$('editor-input'), function(e) { var charcode = (e.keyCode || e.charCode); if (charcode === 27) return show_editor(false); if (charcode !== 13) return true; return save_edits(); } ); function save_edits() { var input = PUBNUB.$('editor-input') , id = PUBNUB.attr( input, 'directive' ) , target = PUBNUB.$(id) , value = PUBNUB.$('editor-input').value , modify = {}; if (!value) return; // Save Change modify[id] = value; save( modify, true ); show_editor(false); return false; } // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // Editor Controls - CANCEL // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- PUBNUB.bind( 'click', PUBNUB.$('editor-cancel'), function() { show_editor(false); } ); // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // Offset // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- function offset( node, what ) { var pos = 0 , what = what || 'Top'; while (node) { pos += node['offset'+what]; node = node.offsetParent; } return pos; } // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // Right Now // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- function now() { return+new Date() } // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // URL Param Setting // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- function urlsetting() { var standard = 'standard-' + now() , spliter = '?company='; if (location.href.indexOf(spliter) < 0) return standard; return location.href.split(spliter)[1].split('&')[0] || standard; } })();
js/startup-metrics.js
(function(){ // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // Dashboard Settings // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- var settings = { ssl : true, subscribe_key : 'sub-c-44d3418c-4855-11e4-8a5b-02ee2ddab7fe', publish_key : 'pub-c-eae49ba3-b1ee-46c4-8674-27ce042e7ab3', channel : urlsetting() }; var pubnub = PUBNUB(settings); var starttime = now(); var genstarttime = now(); var salebellwait = 3000; // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // Startup Metrics Default Dashboard Position // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- var startupmetrics = JSON.parse(PUBNUB.db.get(settings.channel)) || { // Whitelable title : "Startup", subtitle : "Weekly Goals", logo_img : "img/pubnub.png", // Vanity Labels vanity_one : 'MENTIONS', vanity_two : 'ATTENDEES', vanity_three : 'ARTICLES', vanity_four : 'STACKOVERFLOW', // Acquisition acquisition : 55, acquisition_goal : 100, // Activation activation : 1, activation_goal : 1, // Retention retention : 1, retention_goal : 1, // Revenue revenue : 1, revenue_goal : 1, // Referrals mentions : 1, attendees : 1, articles : 1, stackoverflow : 1 }; // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // Bootstrap Startup Metrics // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- pubnub.history({ limit : 1, channel : settings.channel, callback : function(msgs) { save(msgs[0][0] || {}) } }); // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // Live Startup Metrics // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- pubnub.subscribe({ channel : settings.channel, message : function(msg) { save(msg) } }); // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // Update Startup Metrics // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- update_metrics(startupmetrics); function update_metrics(startup) { PUBNUB.each( startup, function( metric, value ) { // Update Metric Display var display = PUBNUB.$(metric); if (!display) return; // Logo Whitelabel if (metric.indexOf('_img') > 0) return PUBNUB.css( display, { 'background-image' : 'url('+value+')' } ); // Revenue Money Sales Bell if ( metric === 'revenue' && +value && +display.innerHTML && +value != (+display.innerHTML) && +value != (+PUBNUB.attr( display, 'upcoming' )) ) ring_bell( +value < (+display.innerHTML) ); // Set Display for Awesome? update_display( display, value ); // Generic Update Sound update_sound(metric); // Percentage Display if Relevant if (metric.indexOf('_goal') < 0) return; var metric_name = metric.split('_goal')[0] , metric_value = startup[metric_name] , metric_goal = value; // Update GUI Percent Circle Metrics update_circle_metrics( metric_name, metric_value, metric_goal ); } ); } // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // Visually Update Startup Metrics with Maybe Animations // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- function update_display( display, value ) { var original = display.innerHTML , upcoming = PUBNUB.attr( display, 'upcoming' ); // Save Upcoming Value if (upcoming == value) return; PUBNUB.attr( display, 'upcoming', value ); // Render Display if (!!(+original+ +value) && original != value) (function(){ var frame = 1.0 , total = 15 , ori = +original , val = +value; function updater(frame) { setTimeout( function() { display.innerHTML = Math.floor( ori + (val - ori) * (frame / total) ); }, frame * 180 ) } while (frame <= total) updater(frame++); })(); else display.innerHTML = value; } // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // Save Startup Metrics // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- function save( modification, broadcast ) { PUBNUB.each( modification, function( k, v ) { startupmetrics[k] = v } ); PUBNUB.db.set( settings.channel, JSON.stringify(startupmetrics) ); update_metrics(startupmetrics); if (!broadcast) return; pubnub.publish({ channel : settings.channel, message : startupmetrics }); } // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // Update Startup Metrics Circles // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- function update_circle_metrics( name, value, goal ) { var circle = PUBNUB.$('pc_'+name) , percent = PUBNUB.$('percent_'+name) , result = Math.floor( (+value / (+goal||1)) * 100 ) , resmax = (result > 999 ? 999 : result) , pclass = ' p' + (result > 100 ? 100 : result); circle.className = circle.className.replace( / p[^ ]+/, ' p00' ); circle.className = circle.className.replace( / p[^ ]+/, pclass ); update_display( percent, resmax ) } // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // Change UI Element - Update the Values Visually // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- PUBNUB.bind( 'mousedown,touchstart', document, function(element) { var target = (element.target || element.srcElement) , id = PUBNUB.attr( target, 'id' ) , input = PUBNUB.$('editor-input') , editor = PUBNUB.$('editor'); // Ignore Clicking Editor Controls if (!id || id.indexOf('editor') >= 0) return true; // Show Editor GUI PUBNUB.attr( input, 'directive', id ); show_editor(true); input.value = startupmetrics[id] || target.innerHTML.replace(/^\s+|\s+$/g,''); setTimeout( function(){input.focus();input.select()}, 250 ); return true; } ); // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // Show Editor // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- function show_editor(yes) { PUBNUB.css( PUBNUB.$('editor'), { display : (yes ? 'block' : 'none') } ); } // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // Generic Update Sound // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- function update_sound(metric) { if (genstarttime + salebellwait > now()) return; if ( metric === 'acquisition' || metric === 'activation' || metric === 'retention' || metric === 'mentions' || metric === 'attendees' || metric === 'articles' || metric === 'stackoverflow' ) { sounds.play( 'sounds/success', 2000 ); genstarttime = now(); } } // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // Sales Bell // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- window.ring_bell = ring_bell; function ring_bell(downd) { // Prevent Early Sales Bell on Boot if (starttime + salebellwait > now()) return; starttime = now(); // Play Sales Bell Sound "money.mp3" or "money.ogg" if (!downd) sounds.play( 'sounds/money', 16000 ); else return sounds.play( 'sounds/decrement', 2000 ); // Display Animation var bell = PUBNUB.$('salesbell'); PUBNUB.css( bell, { opacity : 0.0, display : 'block' } ); setTimeout( function() { PUBNUB.css( bell, { opacity : 1.0 } ); }, 500 ); setTimeout( function() { PUBNUB.css( bell, { opacity : 0.0 } ); }, 12000 ); setTimeout( function() { PUBNUB.css( bell, { display : 'none' } ); }, 14000 ); } // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // Editor Controls - SAVE // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- PUBNUB.bind( 'click', PUBNUB.$('editor-save'), save_edits ); PUBNUB.bind( 'keydown', PUBNUB.$('editor-input'), function(e) { var charcode = (e.keyCode || e.charCode); if (charcode === 27) return show_editor(false); if (charcode !== 13) return true; return save_edits(); } ); function save_edits() { var input = PUBNUB.$('editor-input') , id = PUBNUB.attr( input, 'directive' ) , target = PUBNUB.$(id) , value = PUBNUB.$('editor-input').value , modify = {}; if (!value) return; // Save Change modify[id] = value; save( modify, true ); show_editor(false); return false; } // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // Editor Controls - CANCEL // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- PUBNUB.bind( 'click', PUBNUB.$('editor-cancel'), function() { show_editor(false); } ); // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // Offset // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- function offset( node, what ) { var pos = 0 , what = what || 'Top'; while (node) { pos += node['offset'+what]; node = node.offsetParent; } return pos; } // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // Right Now // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- function now() { return+new Date() } // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // URL Param Setting // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- function urlsetting() { var standard = 'standard-' + now() , spliter = '?company='; if (location.href.indexOf(spliter) < 0) return standard; return location.href.split(spliter)[1].split('&')[0] || standard; } })();
Update startup-metrics.js
js/startup-metrics.js
Update startup-metrics.js
<ide><path>s/startup-metrics.js <ide> <ide> // Vanity Labels <ide> vanity_one : 'MENTIONS', <del> vanity_two : 'ATTENDEES', <del> vanity_three : 'ARTICLES', <add> vanity_two : 'FOLLOWERS', <add> vanity_three : 'COMMENTS', <ide> vanity_four : 'STACKOVERFLOW', <ide> <ide> // Acquisition <ide> acquisition_goal : 100, <ide> <ide> // Activation <del> activation : 1, <del> activation_goal : 1, <add> activation : 10, <add> activation_goal : 20, <ide> <ide> // Retention <del> retention : 1, <del> retention_goal : 1, <add> retention : 189, <add> retention_goal : 250, <ide> <ide> // Revenue <del> revenue : 1, <del> revenue_goal : 1, <add> revenue : 890, <add> revenue_goal : 1200, <ide> <ide> // Referrals <del> mentions : 1, <del> attendees : 1, <del> articles : 1, <del> stackoverflow : 1 <add> mentions : 342, <add> attendees : 89, <add> articles : 45, <add> stackoverflow : 8 <ide> <ide> }; <ide>
Java
mit
afea536174ae2f2cf4e2aa57e551b89d46057815
0
conveyal/r5,conveyal/r5,conveyal/r5,conveyal/r5,conveyal/r5
package com.conveyal.r5.streets; import com.conveyal.gtfs.model.Stop; import com.conveyal.osmlib.Node; import com.conveyal.osmlib.OSM; import com.conveyal.osmlib.OSMEntity; import com.conveyal.osmlib.Relation; import com.conveyal.osmlib.Way; import com.conveyal.r5.api.util.BikeRentalStation; import com.conveyal.r5.api.util.ParkRideParking; import com.conveyal.r5.common.GeometryUtils; import com.conveyal.r5.labeling.LevelOfTrafficStressLabeler; import com.conveyal.r5.labeling.RoadPermission; import com.conveyal.r5.labeling.SpeedConfigurator; import com.conveyal.r5.labeling.TraversalPermissionLabeler; import com.conveyal.r5.labeling.TypeOfEdgeLabeler; import com.conveyal.r5.labeling.USTraversalPermissionLabeler; import com.conveyal.r5.point_to_point.builder.TNBuilderConfig; import com.conveyal.r5.streets.EdgeStore.Edge; import com.conveyal.r5.transit.TransitLayer; import com.conveyal.r5.transit.TransportNetwork; import com.vividsolutions.jts.geom.*; import com.conveyal.r5.profile.StreetMode; import com.vividsolutions.jts.operation.union.UnaryUnionOp; import gnu.trove.list.TIntList; import gnu.trove.list.array.TIntArrayList; import gnu.trove.map.TIntObjectMap; import gnu.trove.map.TLongIntMap; import gnu.trove.map.hash.TIntObjectHashMap; import gnu.trove.map.hash.TLongIntHashMap; import gnu.trove.set.TIntSet; import org.geotools.geojson.geom.GeometryJSON; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.EnumSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Random; import java.util.stream.Collectors; import java.util.stream.LongStream; import static com.conveyal.r5.streets.VertexStore.fixedDegreeGeometryToFloating; import static com.conveyal.r5.streets.VertexStore.fixedDegreesToFloating; /** * This stores the street layer of OTP routing data. * * Is is currently using a column store. * An advantage of disk-backing this (FSTStructs, MapDB optimized for zero-based * integer keys) would be that we can remove any logic about loading/unloading graphs. * We could route over a whole continent without using much memory. * * Any data that's not used by Analyst workers (street names and geometries for example) * should be optional so we can have fast-loading, small transportation network files to pass around. * It can even be loaded from the OSM MapDB on demand. * * There's also https://github.com/RichardWarburton/slab * which seems simpler to use. * * TODO Morton-code-sort vertices, then sort edges by from-vertex. */ public class StreetLayer implements Serializable, Cloneable { private static final Logger LOG = LoggerFactory.getLogger(StreetLayer.class); /** * Minimum allowable size (in number of vertices) for a disconnected subgraph; subgraphs smaller than these will be removed. * There are several reasons why one might have a disconnected subgraph. The most common is poor quality * OSM data. However, they also could be due to areas that really are disconnected in the street graph, * and are connected only by transit. These could be literal islands (Vashon Island near Seattle comes * to mind), or islands that are isolated by infrastructure (for example, airport terminals reachable * only by transit or driving, for instance BWI or SFO). */ public static final int MIN_SUBGRAPH_SIZE = 40; private static final int SNAP_RADIUS_MM = 5 * 1000; /** * The radius of a circle in meters within which to search for nearby streets. * This should not necessarily be a constant, but even if it's made settable it should be a field to avoid * cluttering method signatures. Generally you'd set this once at startup and always use the same value afterward. */ public static final double LINK_RADIUS_METERS = 300; // Edge lists should be constructed after the fact from edges. This minimizes serialized size too. public transient List<TIntList> outgoingEdges; public transient List<TIntList> incomingEdges; public transient IntHashGrid spatialIndex = new IntHashGrid(); /** Spatial index of temporary edges from a scenario */ private transient IntHashGrid temporaryEdgeIndex; // Key is street vertex index, value is BikeRentalStation (with name, number of bikes, spaces id etc.) public TIntObjectMap<BikeRentalStation> bikeRentalStationMap; public TIntObjectMap<ParkRideParking> parkRideLocationsMap; // TODO these are only needed when building the network, should we really be keeping them here in the layer? // TODO don't hardwire to US private transient TraversalPermissionLabeler permissions = new USTraversalPermissionLabeler(); private transient LevelOfTrafficStressLabeler stressLabeler = new LevelOfTrafficStressLabeler(); private transient TypeOfEdgeLabeler typeOfEdgeLabeler = new TypeOfEdgeLabeler(); private transient SpeedConfigurator speedConfigurator; // This is only used when loading from OSM, and is then nulled to save memory. transient OSM osm; /** Envelope of this street layer, in decimal degrees (floating, not fixed-point) */ public Envelope envelope = new Envelope(); TLongIntMap vertexIndexForOsmNode = new TLongIntHashMap(100_000, 0.75f, -1, -1); // Initialize these when we have an estimate of the number of expected edges. public VertexStore vertexStore = new VertexStore(100_000); public EdgeStore edgeStore = new EdgeStore(vertexStore, this, 200_000); /** * Turn restrictions can potentially have a large number of affected edges, so store them once and reference them. * TODO clarify documentation: what does "store them once and reference them" mean? Why? */ public List<TurnRestriction> turnRestrictions = new ArrayList<>(); /** * The TransportNetwork containing this StreetLayer. This link up the object tree also allows us to access the * TransitLayer associated with this StreetLayer of the same TransportNetwork without maintaining bidirectional * references between the two layers. */ public TransportNetwork parentNetwork = null; /** * A string uniquely identifying the contents of this StreetLayer among all StreetLayers. * When no scenario has been applied, this field will contain the ID of the enclosing TransportNetwork. * When a scenario has modified this StreetLayer, this field will be changed to that scenario's ID. * We need a way to know what information is in the network independent of object identity, which is lost in a * round trip through serialization. This also allows re-using cached linkages for several scenarios as long as * they don't modify the street network. */ public String scenarioId; /** * Some StreetLayers are created by applying a scenario to an existing StreetLayer. All the contents of the base * StreetLayer are not copied, they are wrapped to make them extensible. These are called "scenario copies". * If this StreetLayer is such a scenario copy, this field points to the original StreetLayer it was based upon. * Otherwise this field should be null. */ public StreetLayer baseStreetLayer = null; public static final EnumSet<EdgeStore.EdgeFlag> ALL_PERMISSIONS = EnumSet .of(EdgeStore.EdgeFlag.ALLOWS_BIKE, EdgeStore.EdgeFlag.ALLOWS_CAR, EdgeStore.EdgeFlag.ALLOWS_PEDESTRIAN, EdgeStore.EdgeFlag.NO_THRU_TRAFFIC, EdgeStore.EdgeFlag.NO_THRU_TRAFFIC_BIKE, EdgeStore.EdgeFlag.NO_THRU_TRAFFIC_PEDESTRIAN, EdgeStore.EdgeFlag.NO_THRU_TRAFFIC_CAR); public boolean bikeSharing = false; public StreetLayer(TNBuilderConfig tnBuilderConfig) { speedConfigurator = new SpeedConfigurator(tnBuilderConfig.speeds); } /** Load street layer from an OSM-lib OSM DB */ public void loadFromOsm(OSM osm) { loadFromOsm(osm, true, false); } /** * Returns true if way can be used for routing * * Routable ways are highways (unless they are raceways or highway rest_area/services since those are similar to landuse tags * Or public_transport platform or railway platform unless its usage tag is tourism * * In both cases roads need to exists in reality aka don't have: * - construction, * - proposed, * - removed, * - abandoned * - unbuilt * tags * * Both construction tagging schemes are supported tag construction=anything and highway/cycleway=construction * same with proposed. * @param way * @return */ private static boolean isWayRoutable(Way way) { boolean isRoutable = false; String highway = way.getTag("highway"); if ( //Way is routable if it is highway (way.hasTag("highway") && !( //Unless it is raceway or rest area //Those two are areas which are places around highway (similar to landuse tags they aren't routable) highway.equals("services") || highway.equals("rest_area") //highway=conveyor is obsoleted tag for escalator and is actually routable || highway.equals("raceway"))) //or it is public transport platform or railway platform || (way.hasTag("public_transport", "platform") || way.hasTag("railway", "platform") //unless it's usage is tourism && !way.hasTag("usage", "tourism"))) { isRoutable = actuallyExistsInReality(highway, way); } if (isRoutable && way.hasTag("cycleway")) { //highway tag is already checked String cycleway = way.getTag("cycleway"); isRoutable = actuallyExistsInReality(cycleway, way); } return isRoutable; } /** * Returns true if road is not in construction, abandoned, removed or proposed * @param highway value of highway or cycleway tag * @param way * @return */ private static boolean actuallyExistsInReality(String highway, Way way) { return !("construction".equals(highway) || "abandoned".equals(highway)|| "removed".equals(highway) || "proposed".equals(highway) || "propossed".equals(highway) || "unbuilt".equals(highway) || way.hasTag("construction") || way.hasTag("proposed")); } /** Load OSM, optionally removing floating subgraphs (recommended) */ void loadFromOsm (OSM osm, boolean removeIslands, boolean saveVertexIndex) { if (!osm.intersectionDetection) throw new IllegalArgumentException("Intersection detection not enabled on OSM source"); LOG.info("Making street edges from OSM ways..."); this.osm = osm; // keep track of ways that need to later become park and rides List<Way> parkAndRideWays = new ArrayList<>(); for (Map.Entry<Long, Way> entry : osm.ways.entrySet()) { Way way = entry.getValue(); if (way.hasTag("park_ride", "yes")) parkAndRideWays.add(way); if (!isWayRoutable(way)) { continue; } int nEdgesCreated = 0; int beginIdx = 0; // Break each OSM way into topological segments between intersections, and make one edge per segment. for (int n = 1; n < way.nodes.length; n++) { if (osm.intersectionNodes.contains(way.nodes[n]) || n == (way.nodes.length - 1)) { makeEdge(way, beginIdx, n, entry.getKey()); nEdgesCreated += 1; beginIdx = n; } } } stressLabeler.logErrors(); // summarize LTS statistics Edge cursor = edgeStore.getCursor(); cursor.seek(0); int lts1 = 0, lts2 = 0, lts3 = 0, lts4 = 0, ltsUnknown = 0; do { if (cursor.getFlag(EdgeStore.EdgeFlag.BIKE_LTS_1)) lts1++; else if (cursor.getFlag(EdgeStore.EdgeFlag.BIKE_LTS_2)) lts2++; else if (cursor.getFlag(EdgeStore.EdgeFlag.BIKE_LTS_3)) lts3++; else if (cursor.getFlag(EdgeStore.EdgeFlag.BIKE_LTS_4)) lts4++; else ltsUnknown++; } while (cursor.advance()); LOG.info("Surrogate LTS:\n 1: {} edges\n 2: {} edges\n 3: {} edges\n 4: {} edges\n Unknown: {} edges", lts1, lts2, lts3, lts4, ltsUnknown); List<Node> parkAndRideNodes = new ArrayList<>(); for (Node node : osm.nodes.values()) { if (node.hasTag("park_ride", "yes")) parkAndRideNodes.add(node); } LOG.info("Done making street edges."); LOG.info("Made {} vertices and {} edges.", vertexStore.getVertexCount(), edgeStore.nEdges()); LOG.info("Found {} P+R node candidates", parkAndRideNodes.size()); // We need edge lists to apply intersection costs. buildEdgeLists(); stressLabeler.applyIntersectionCosts(this); if (removeIslands) { new TarjanIslandPruner(this, MIN_SUBGRAPH_SIZE, StreetMode.CAR).run(); // due to bike walking, walk must go before bike, see comment in TarjanIslandPruner javadoc new TarjanIslandPruner(this, MIN_SUBGRAPH_SIZE, StreetMode.WALK).run(); new TarjanIslandPruner(this, MIN_SUBGRAPH_SIZE, StreetMode.BICYCLE).run(); } // index the streets, we need the index to connect things to them. this.indexStreets(); buildParkAndRideAreas(parkAndRideWays); buildParkAndRideNodes(parkAndRideNodes); VertexStore.Vertex vertex = vertexStore.getCursor(); long numOfParkAndRides = 0; while (vertex.advance()) { if (vertex.getFlag(VertexStore.VertexFlag.PARK_AND_RIDE)) { numOfParkAndRides++; } } LOG.info("Made {} P+R vertices", numOfParkAndRides); // create turn restrictions. // TODO transit splitting is going to mess this up osm.relations.entrySet().stream().filter(e -> e.getValue().hasTag("type", "restriction")).forEach(e -> this.applyTurnRestriction(e.getKey(), e.getValue())); LOG.info("Created {} turn restrictions", turnRestrictions.size()); //edgesPerWayHistogram.display(); //pointsPerEdgeHistogram.display(); // Clear unneeded indexes, allow them to be gc'ed if (!saveVertexIndex) vertexIndexForOsmNode = null; osm = null; } /** * TODO Javadoc. What is this for? */ public void openOSM(File file) { osm = new OSM(file.getPath()); LOG.info("Read OSM"); } /** * Gets way name from OSM name tag * * It uses OSM Mapdb * * Uses {@link #getName(long, Locale)} * * @param edgeIdx edgeStore EdgeIDX * @param locale which locale to use * @return null if edge doesn't have name tag or if OSM data isn't loaded */ public String getNameEdgeIdx(int edgeIdx, Locale locale) { if (osm == null) { return null; } EdgeStore.Edge edge = edgeStore.getCursor(edgeIdx); String name = getName(edge.getOSMID(), locale); if (name == null) { //TODO: localize generated street names if (edge.getFlag(EdgeStore.EdgeFlag.STAIRS)) { return "stairs"; } else if (edge.getFlag(EdgeStore.EdgeFlag.CROSSING)) { return "street crossing"; } else if (edge.getFlag(EdgeStore.EdgeFlag.BIKE_PATH)) { return "bike path"; } else if (edge.getFlag(EdgeStore.EdgeFlag.SIDEWALK)) { return "sidewalk"; } } return name; } /** * Gets way name from OSM name tag * * TODO: generate name on unnamed ways (sidewalks, cycleways etc.) * @param OSMid OSM ID of a way * @param locale which locale to use * @return */ private String getName(long OSMid, Locale locale) { String name = null; Way way = osm.ways.get(OSMid); if (way != null) { name = way.getTag("name"); } return name; } /** * Gets all the OSM tags of specified OSM way * * Tags are returned as tag=value separated with ; * * AKA same format that {@link Way#setTagsFromString(String)} accepts * * @param edge for which to get tags * @return String with all the tags or null */ public String getWayTags(EdgeStore.Edge edge) { if (osm == null) { return null; } Way way = osm.ways.get(edge.getOSMID()); if (way != null && !way.hasNoTags()) { return way.tags.stream() .map(OSMEntity.Tag::toString) .collect(Collectors.joining(";")); } return null; } /** Connect areal park and rides to the graph */ private void buildParkAndRideAreas(List<Way> parkAndRideWays) { VertexStore.Vertex v = this.vertexStore.getCursor(); EdgeStore.Edge e = this.edgeStore.getCursor(); parkRideLocationsMap = new TIntObjectHashMap<>(); for (Way way : parkAndRideWays) { Coordinate[] coords = LongStream.of(way.nodes).mapToObj(nid -> { Node n = osm.nodes.get(nid); return new Coordinate(n.getLon(), n.getLat()); }).toArray(s -> new Coordinate[s]); // nb using linestring not polygon so all found intersections are at edges. LineString g = GeometryUtils.geometryFactory.createLineString(coords); // create a vertex in the middle of the lot to reflect the park and ride Coordinate centroid = g.getCentroid().getCoordinate(); int centerVertex = vertexStore.addVertex(centroid.y, centroid.x); v.seek(centerVertex); v.setFlag(VertexStore.VertexFlag.PARK_AND_RIDE); ParkRideParking parkRideParking = new ParkRideParking(centerVertex, centroid.y, centroid.x, way); parkRideLocationsMap.put(centerVertex, parkRideParking); // find nearby edges Envelope env = g.getEnvelopeInternal(); TIntSet nearbyEdges = this.spatialIndex.query(VertexStore.envelopeToFixed(env)); nearbyEdges.forEach(eidx -> { e.seek(eidx); // Connect only to edges that are good to link to (This skips tunnels) // and skips link edges (that were used to link other stuff) if (!e.getFlag(EdgeStore.EdgeFlag.LINKABLE) || e.getFlag(EdgeStore.EdgeFlag.LINK)) { return true; } LineString edgeGeometry = e.getGeometry(); if (edgeGeometry.intersects(g)) { // we found an intersection! yay! Geometry intersection = edgeGeometry.intersection(g); for (int i = 0; i < intersection.getNumGeometries(); i++) { Geometry single = intersection.getGeometryN(i); if (single instanceof Point) { connectParkAndRide(centerVertex, single.getCoordinate(), e); } else if (single instanceof LineString) { // coincident segments. TODO can this even happen? // just connect start and end of coincident segment Coordinate[] singleCoords = single.getCoordinates(); if (singleCoords.length > 0) { connectParkAndRide(centerVertex, coords[0], e); // TODO is conditional even necessary? if (singleCoords.length > 1) { connectParkAndRide(centerVertex, coords[coords.length - 1], e); } } } } } return true; }); // TODO check if we didn't connect anything and fall back to proximity based connection } } private void buildParkAndRideNodes (List<Node> nodes) { VertexStore.Vertex v = vertexStore.getCursor(); for (Node node : nodes) { int vidx = vertexStore.addVertex(node.getLat(), node.getLon()); v.seek(vidx); v.setFlag(VertexStore.VertexFlag.PARK_AND_RIDE); ParkRideParking parkRideParking = new ParkRideParking(vidx, node.getLat(), node.getLon(), node); parkRideLocationsMap.put(vidx, parkRideParking); int targetWalking = getOrCreateVertexNear(node.getLat(), node.getLon(), StreetMode.WALK); if (targetWalking == -1) { LOG.warn("Could not link park and ride node at ({}, {}) to the street network.", node.getLat(), node.getLon()); continue; } EdgeStore.Edge created = edgeStore.addStreetPair(vidx, targetWalking, 1, -1); // allow link edges to be traversed by all, access is controlled by connected edges created.allowAllModes(); created.setFlag(EdgeStore.EdgeFlag.LINK); // and the back edge created.advance(); created.allowAllModes(); created.setFlag(EdgeStore.EdgeFlag.LINK); int targetDriving = getOrCreateVertexNear(node.getLat(), node.getLon(), StreetMode.CAR); //If both CAR and WALK links would connect to the same edge we can skip new useless edge if (targetDriving == targetWalking) { continue; } created = edgeStore.addStreetPair(vidx, targetDriving, 1, -1); // allow link edges to be traversed by all, access is controlled by connected edges created.allowAllModes(); created.setFlag(EdgeStore.EdgeFlag.LINK); // and the back edge created.advance(); created.allowAllModes(); created.setFlag(EdgeStore.EdgeFlag.LINK); } } /** Connect a park and ride vertex to the street network at a particular location and edge */ private void connectParkAndRide (int centerVertex, Coordinate coord, EdgeStore.Edge edge) { Split split = Split.findOnEdge(coord.y, coord.x, edge); int targetVertex = splitEdge(split); EdgeStore.Edge created = edgeStore.addStreetPair(centerVertex, targetVertex, 1, -1); // basically free to enter/leave P&R for now. // allow link edges to be traversed by all, access is controlled by connected edges created.allowAllModes(); created.setFlag(EdgeStore.EdgeFlag.LINK); // and the back edge created.advance(); created.allowAllModes(); created.setFlag(EdgeStore.EdgeFlag.LINK); } private void applyTurnRestriction (long id, Relation restriction) { boolean only; if (!restriction.hasTag("restriction")) { LOG.error("Restriction {} has no restriction tag, skipping", id); return; } if (restriction.getTag("restriction").startsWith("no_")) only = false; else if (restriction.getTag("restriction").startsWith("only_")) only = true; else { LOG.error("Restriction {} has invalid restriction tag {}, skipping", id, restriction.getTag("restriction")); return; } TurnRestriction out = new TurnRestriction(); out.only = only; // sort out the members Relation.Member from = null, to = null; List<Relation.Member> via = new ArrayList<>(); for (Relation.Member member : restriction.members) { if ("from".equals(member.role)) { if (from != null) { LOG.error("Turn restriction {} has multiple 'from' members, skipping.", id); return; } if (member.type != OSMEntity.Type.WAY) { LOG.error("Turn restriction {} has a 'from' member that is not a way, skipping.", id); return; } from = member; } else if ("to".equals(member.role)) { if (to != null) { LOG.error("Turn restriction {} has multiple 'to' members, skipping.", id); return; } if (member.type != OSMEntity.Type.WAY) { LOG.error("Turn restriction {} has a 'to' member that is not a way, skipping.", id); return; } to = member; } else if ("via".equals(member.role)) { via.add(member); } // Osmosis may produce situations where referential integrity is violated, probably at the edge of the // bounding box where half a turn restriction is outside the box. if (member.type == OSMEntity.Type.WAY) { if (!osm.ways.containsKey(member.id)) { LOG.warn("Turn restriction relation {} references nonexistent way {}, dropping this relation", id, member.id); return; } } else if (member.type == OSMEntity.Type.NODE) { if (!osm.nodes.containsKey(member.id)) { LOG.warn("Turn restriction relation {} references nonexistent node {}, dropping this relation", id, member.id); return; } } } if (from == null || to == null || via.isEmpty()) { LOG.error("Invalid turn restriction {}, does not have from, to and via, skipping", id); return; } boolean hasViaWays = false, hasViaNodes = false; for (Relation.Member m : via) { if (m.type == OSMEntity.Type.WAY) hasViaWays = true; else if (m.type == OSMEntity.Type.NODE) hasViaNodes = true; else { LOG.error("via must be node or way, skipping restriction {}", id); return; } } if ((hasViaWays && hasViaNodes) || (hasViaNodes && via.size() > 1)) { LOG.error("via must be single node or one or more ways, skipping restriction {}", id); return; } EdgeStore.Edge e = edgeStore.getCursor(); if (hasViaNodes) { // Turn restriction passes via a single node. This is a fairly simple turn restriction. // First find the relevant vertex. int vertex = vertexIndexForOsmNode.get(via.get(0).id); if (vertex == -1) { LOG.warn("Vertex {} not found to use as via node for restriction {}, skipping this restriction", via.get(0).id, id); return; } // use array to dodge Java closure "effectively final" nonsense final int[] fromEdge = new int[] { -1 }; final long fromWayId = from.id; // more effectively final nonsense final boolean[] bad = new boolean[] { false }; // find the edges incomingEdges.get(vertex).forEach(eidx -> { e.seek(eidx); if (e.getOSMID() == fromWayId) { if (fromEdge[0] != -1) { LOG.error("From way enters vertex {} twice, restriction {} is therefore ambiguous, skipping", vertex, id); bad[0] = true; return false; } fromEdge[0] = eidx; } return true; // iteration should continue }); final int[] toEdge = new int[] { -1 }; final long toWayId = to.id; // more effectively final nonsense outgoingEdges.get(vertex).forEach(eidx -> { e.seek(eidx); if (e.getOSMID() == toWayId) { if (toEdge[0] != -1) { LOG.error("To way exits vertex {} twice, restriction {} is therefore ambiguous, skipping", vertex, id); bad[0] = true; return false; } toEdge[0] = eidx; } return true; // iteration should continue }); if (bad[0]) return; // log message already printed if (fromEdge[0] == -1 || toEdge[0] == -1) { LOG.error("Did not find from/to edges for restriction {}, skipping", id); return; } // phew. create the restriction and apply it where needed out.fromEdge = fromEdge[0]; out.toEdge = toEdge[0]; int index = turnRestrictions.size(); turnRestrictions.add(out); edgeStore.turnRestrictions.put(out.fromEdge, index); addReverseTurnRestriction(out, index); } else { // via member(s) are ways, which is more tricky // do a little street search constrained to the ways in question Way fromWay = osm.ways.get(from.id); long[][] viaNodes = via.stream().map(m -> osm.ways.get(m.id).nodes).toArray(i -> new long[i][]); Way toWay = osm.ways.get(to.id); // We do a little search, keeping in mind that there must be the same number of ways as there are via members List<long[]> nodes = new ArrayList<>(); List<long[]> ways = new ArrayList<>(); // loop over from way to initialize search for (long node : fromWay.nodes) { for (int viaPos = 0; viaPos < viaNodes.length; viaPos++) { for (long viaNode : viaNodes[viaPos]) { if (node == viaNode) { nodes.add(new long[] { node }); ways.add(new long[] { via.get(viaPos).id }); } } } } List<long[]> previousNodes; List<long[]> previousWays; // via.size() - 1 because we've already explored one via way where we transferred from the the from way for (int round = 0; round < via.size() - 1; round++) { previousNodes = nodes; previousWays = ways; nodes = new ArrayList<>(); ways = new ArrayList<>(); for (int statePos = 0; statePos < previousNodes.size(); statePos++) { // get the way we are on and search all its nodes long wayId = previousWays.get(statePos)[round]; Way way = osm.ways.get(wayId); for (long node : way.nodes) { VIA: for (int viaPos = 0; viaPos < viaNodes.length; viaPos++) { long viaWayId = via.get(viaPos).id; // don't do looping searches for (long prevWay : previousWays.get(statePos)) { if (viaWayId == prevWay) continue VIA; } for (long viaNode : osm.ways.get(viaWayId).nodes) { if (viaNode == node) { long[] newNodes = Arrays.copyOf(previousNodes.get(statePos), round + 2); long[] newWays = Arrays.copyOf(previousWays.get(statePos), round + 2); newNodes[round + 1] = node; newWays[round + 1] = viaWayId; nodes.add(newNodes); ways.add(newWays); } } } } } } // now filter them to just ones that reach the to way long[] pathNodes = null; long[] pathWays = null; for (int statePos = 0; statePos < nodes.size(); statePos++) { long[] theseWays = ways.get(statePos); Way finalWay = osm.ways.get(theseWays[theseWays.length - 1]); for (long node : finalWay.nodes) { for (long toNode : toWay.nodes) { if (node == toNode) { if (pathNodes != null) { LOG.error("Turn restriction {} has ambiguous via ways (multiple paths through via ways between from and to), skipping", id); return; } pathNodes = Arrays.copyOf(nodes.get(statePos), theseWays.length + 1); pathNodes[pathNodes.length - 1] = node; pathWays = theseWays; } } } } if (pathNodes == null) { LOG.error("Invalid turn restriction {}, no way from from to to via via, skipping", id); return; } // convert OSM nodes and ways into IDs // first find the fromEdge and toEdge. dodge effectively final nonsense final int[] fromEdge = new int[] { -1 }; final long fromWayId = from.id; // more effectively final nonsense final boolean[] bad = new boolean[] { false }; int fromVertex = vertexIndexForOsmNode.get(pathNodes[0]); // find the edges incomingEdges.get(fromVertex).forEach(eidx -> { e.seek(eidx); if (e.getOSMID() == fromWayId) { if (fromEdge[0] != -1) { LOG.error("From way enters vertex {} twice, restriction {} is therefore ambiguous, skipping", fromVertex, id); bad[0] = true; return false; } fromEdge[0] = eidx; } return true; // iteration should continue }); int toVertex = vertexIndexForOsmNode.get(pathNodes[pathNodes.length - 1]); final int[] toEdge = new int[] { -1 }; final long toWayId = to.id; // more effectively final nonsense outgoingEdges.get(toVertex).forEach(eidx -> { e.seek(eidx); if (e.getOSMID() == toWayId) { if (toEdge[0] != -1) { LOG.error("To way exits vertex {} twice, restriction {} is therefore ambiguous, skipping", toVertex, id); bad[0] = true; return false; } toEdge[0] = eidx; } return true; // iteration should continue }); if (bad[0]) return; // log message already printed if (fromEdge[0] == -1 || toEdge[0] == -1) { LOG.error("Did not find from/to edges for restriction {}, skipping", id); return; } out.fromEdge = fromEdge[0]; out.toEdge = toEdge[0]; // edges affected by this turn restriction. Make a list in case something goes awry when trying to find edges TIntList affectedEdges = new TIntArrayList(); // now apply to all via ways. // > 0 is intentional. pathNodes[0] is the node on the from edge for (int nidx = pathNodes.length - 1; nidx > 0; nidx--) { final int[] edge = new int[] { -1 }; // fencepost problem: one more node than ways final long wayId = pathWays[nidx - 1]; // more effectively final nonsense int vertex = vertexIndexForOsmNode.get(pathNodes[nidx]); incomingEdges.get(vertex).forEach(eidx -> { e.seek(eidx); if (e.getOSMID() == wayId) { if (edge[0] != -1) { // TODO we've already started messing with data structures! LOG.error("To way exits vertex {} twice, restriction {} is therefore ambiguous, skipping", vertex, id); bad[0] = true; return false; } edge[0] = eidx; } return true; // iteration should continue }); if (bad[0]) return; // log message already printed if (edge[0] == -1) { LOG.warn("Did not find via way {} for restriction {}, skipping", wayId, id); return; } affectedEdges.add(edge[0]); } affectedEdges.reverse(); out.viaEdges = affectedEdges.toArray(); int index = turnRestrictions.size(); turnRestrictions.add(out); edgeStore.turnRestrictions.put(out.fromEdge, index); addReverseTurnRestriction(out, index); // take a deep breath } } /** * Adding turn restrictions for reverse search is a little tricky. * * First because we are adding toEdge to turnRestrictionReverse map and second because ONLY TURNs aren't supported * * Since ONLY TURN restrictions aren't supported ONLY TURN restrictions * are created with NO TURN restrictions and added to turnRestrictions and edgeStore turnRestrictionsReverse * * if NO TURN restriction is added it's just added with correct toEdge (instead of from since * we are searching from the back) * @param turnRestriction * @param index */ void addReverseTurnRestriction(TurnRestriction turnRestriction, int index) { if (turnRestriction.only) { //From Only turn restrictions create multiple NO TURN restrictions which means the same //Since only turn restrictions aren't supported in reverse street search List<TurnRestriction> remapped = turnRestriction.remap(this); for (TurnRestriction remapped_restriction: remapped) { index = turnRestrictions.size(); turnRestrictions.add(remapped_restriction); edgeStore.turnRestrictionsReverse.put(remapped_restriction.toEdge, index); } } else { edgeStore.turnRestrictionsReverse.put(turnRestriction.toEdge, index); } } /** * Get or create mapping from a global long OSM ID to an internal street vertex ID, creating the vertex as needed. * @return the internal ID for the street vertex that was found or created, or -1 if there was no such OSM node. */ private int getVertexIndexForOsmNode(long osmNodeId) { int vertexIndex = vertexIndexForOsmNode.get(osmNodeId); if (vertexIndex == -1) { // Register a new vertex, incrementing the index starting from zero. // Store node coordinates for this new street vertex Node node = osm.nodes.get(osmNodeId); if (node == null) { LOG.warn("OSM data references an undefined node. This is often the result of extracting a bounding box in Osmosis without the completeWays option."); } else { vertexIndex = vertexStore.addVertex(node.getLat(), node.getLon()); VertexStore.Vertex v = vertexStore.getCursor(vertexIndex); if (node.hasTag("highway", "traffic_signals")) v.setFlag(VertexStore.VertexFlag.TRAFFIC_SIGNAL); vertexIndexForOsmNode.put(osmNodeId, vertexIndex); } } return vertexIndex; } /** * Calculate length from a list of nodes. This is done in advance of creating an edge pair because we need to catch * potential length overflows before we ever reserve space for the edges. * @return the length of the edge in millimeters, or -1 if that length will overflow a 32 bit int */ private int getEdgeLengthMillimeters (List<Node> nodes) { double lengthMeters = 0; Node prevNode = nodes.get(0); for (Node node : nodes.subList(1, nodes.size())) { lengthMeters += GeometryUtils .distance(prevNode.getLat(), prevNode.getLon(), node.getLat(), node.getLon()); prevNode = node; } if (lengthMeters * 1000 > Integer.MAX_VALUE) { return -1; } return (int)(lengthMeters * 1000); } private static short speedToShort(Float speed) { return (short) Math.round(speed * 100); } /** * Make an edge for a sub-section of an OSM way, typically between two intersections or leading up to a dead end. */ private void makeEdge(Way way, int beginIdx, int endIdx, Long osmID) { long beginOsmNodeId = way.nodes[beginIdx]; long endOsmNodeId = way.nodes[endIdx]; // Will create mapping if it doesn't exist yet. int beginVertexIndex = getVertexIndexForOsmNode(beginOsmNodeId); int endVertexIndex = getVertexIndexForOsmNode(endOsmNodeId); // Fetch the OSM node objects for this subsection of the OSM way. int nNodes = endIdx - beginIdx + 1; List<Node> nodes = new ArrayList<>(nNodes); for (int n = beginIdx; n <= endIdx; n++) { long nodeId = way.nodes[n]; Node node = osm.nodes.get(nodeId); if (node == null) { LOG.warn("Not creating street segment that references an undefined node."); return; } envelope.expandToInclude(node.getLon(), node.getLat()); nodes.add(node); } // Compute edge length and check that it can be properly represented. int edgeLengthMillimeters = getEdgeLengthMillimeters(nodes); if (edgeLengthMillimeters < 0) { LOG.warn("Street segment was too long to be represented, skipping."); return; } // FIXME this encoded speed should probably never be exposed outside the edge object short forwardSpeed = speedToShort(speedConfigurator.getSpeedMS(way, false)); short backwardSpeed = speedToShort(speedConfigurator.getSpeedMS(way, true)); RoadPermission roadPermission = permissions.getPermissions(way); // Create and store the forward and backward edge // FIXME these sets of flags should probably not leak outside the permissions/stress/etc. labeler methods EnumSet<EdgeStore.EdgeFlag> forwardFlags = roadPermission.forward; EnumSet<EdgeStore.EdgeFlag> backFlags = roadPermission.backward; // Doesn't insert edges which don't have any permissions forward and backward if (Collections.disjoint(forwardFlags, ALL_PERMISSIONS) && Collections.disjoint(backFlags, ALL_PERMISSIONS)) { LOG.debug("Way has no permissions skipping!"); return; } stressLabeler.label(way, forwardFlags, backFlags); typeOfEdgeLabeler.label(way, forwardFlags, backFlags); Edge newEdge = edgeStore.addStreetPair(beginVertexIndex, endVertexIndex, edgeLengthMillimeters, osmID); // newEdge is first pointing to the forward edge in the pair. // Geometries apply to both edges in a pair. newEdge.setGeometry(nodes); newEdge.setFlags(forwardFlags); newEdge.setSpeed(forwardSpeed); // Step ahead to the backward edge in the same pair. newEdge.advance(); newEdge.setFlags(backFlags); newEdge.setSpeed(backwardSpeed); } public void indexStreets () { LOG.info("Indexing streets..."); spatialIndex = new IntHashGrid(); // Skip by twos, we only need to index forward (even) edges. Their odd companions have the same geometry. Edge edge = edgeStore.getCursor(); for (int e = 0; e < edgeStore.nEdges(); e += 2) { edge.seek(e); spatialIndex.insert(edge.getGeometry(), e); } LOG.info("Done indexing streets."); } /** * Rather than querying the spatial index directly, going through this method will ensure that any temporary edges * not in the index are also visible. Temporary edges, created when applying a scenario in a single thread, are * not added to the spatial index, which is read by all threads. * Note: the spatial index can and will return false positives, but should not produce false negatives. * We return the unfiltered results including false positives because calculating the true distance to each edge * is quite a slow operation. The caller must post-filter the set of edges if more distance information is needed, * including knowledge of whether an edge passes inside the query envelope at all. */ public TIntSet findEdgesInEnvelope (Envelope envelope) { TIntSet candidates = spatialIndex.query(envelope); // Include temporary edges if (temporaryEdgeIndex != null) { TIntSet temporaryCandidates = temporaryEdgeIndex.query(envelope); candidates.addAll(temporaryCandidates); } // Remove any edges that were temporarily deleted in a scenario. // This allows properly re-splitting the same edge in multiple places. if (edgeStore.temporarilyDeletedEdges != null) { candidates.removeAll(edgeStore.temporarilyDeletedEdges); } return candidates; } /** After JIT this appears to scale almost linearly with number of cores. */ public void testRouting (boolean withDestinations, TransitLayer transitLayer) { LOG.info("Routing from random vertices in the graph..."); LOG.info("{} goal direction.", withDestinations ? "Using" : "Not using"); StreetRouter router = new StreetRouter(this); long startTime = System.currentTimeMillis(); final int N = 1_000; final int nVertices = outgoingEdges.size(); Random random = new Random(); for (int n = 0; n < N; n++) { int from = random.nextInt(nVertices); VertexStore.Vertex vertex = vertexStore.getCursor(from); // LOG.info("Routing from ({}, {}).", vertex.getLat(), vertex.getLon()); router.setOrigin(from); router.toVertex = withDestinations ? random.nextInt(nVertices) : StreetRouter.ALL_VERTICES; if (n != 0 && n % 100 == 0) { LOG.info(" {}/{} searches", n, N); } } double eTime = System.currentTimeMillis() - startTime; LOG.info("average response time {} msec", eTime / N); } /** * The edge lists (which edges go out of and come into each vertex) are derived from the edges in the EdgeStore. * So any time you add edges or change their endpoints, you need to rebuild the edge index. * TODO some way to signal that a few new edges have been added, rather than rebuilding the whole lists. */ public void buildEdgeLists() { LOG.info("Building edge lists from edges..."); outgoingEdges = new ArrayList<>(vertexStore.getVertexCount()); incomingEdges = new ArrayList<>(vertexStore.getVertexCount()); for (int v = 0; v < vertexStore.getVertexCount(); v++) { outgoingEdges.add(new TIntArrayList(4)); incomingEdges.add(new TIntArrayList(4)); } Edge edge = edgeStore.getCursor(); while (edge.advance()) { outgoingEdges.get(edge.getFromVertex()).add(edge.edgeIndex); incomingEdges.get(edge.getToVertex()).add(edge.edgeIndex); } LOG.info("Done building edge lists."); } /** * Find an existing street vertex near the supplied coordinates, or create a new one if there are no vertices * near enough. Note that calling this method is potentially destructive (it can modify the street network). * * This uses {@link #findSplit(double, double, double, StreetMode)} and {@link Split} which need filled spatialIndex * In other works {@link #indexStreets()} needs to be called before this is used. Otherwise no near vertex is found. * * TODO maybe use X and Y everywhere for fixed point, and lat/lon for double precision degrees. * TODO maybe move this into Split.perform(), store streetLayer ref in Split. * @param lat latitude in floating point geographic (not fixed point) degrees. * @param lon longitude in floating point geographic (not fixed point) degrees. * @param streetMode Link to edges which have permission for StreetMode * @return the index of a street vertex very close to the supplied location, * or -1 if no such vertex could be found or created. */ public int getOrCreateVertexNear(double lat, double lon, StreetMode streetMode) { Split split = findSplit(lat, lon, LINK_RADIUS_METERS, streetMode); if (split == null) { // No linking site was found within range. return -1; } // We have a linking site on a street edge. Find or make a suitable vertex at that site. // It is not necessary to reuse the Edge cursor object created inside the findSplit call, // one additional object instantiation is harmless. Edge edge = edgeStore.getCursor(split.edge); // Check for cases where we don't need to create a new vertex: // The linking site is very near an intersection, or the edge is reached end-wise. if (split.distance0_mm < SNAP_RADIUS_MM || split.distance1_mm < SNAP_RADIUS_MM) { if (split.distance0_mm < split.distance1_mm) { // Very close to the beginning of the edge. Return that existing vertex. return edge.getFromVertex(); } else { // Very close to the end of the edge. Return that existing vertex. return edge.getToVertex(); } } // The split is somewhere along a street away from an existing intersection vertex. Make a new splitter vertex. int newVertexIndex = vertexStore.addVertexFixed((int) split.fixedLat, (int) split.fixedLon); int oldToVertex = edge.getToVertex(); // Hold a copy of the to vertex index, because it may be modified below. if (edge.isMutable()) { // The edge we are going to split is mutable. // We're either building a baseline graph, or modifying an edge created within the same scenario. // Modify the existing bidirectional edge pair to serve as the first segment leading up to the split point. // Its spatial index entry is still valid, since the edge's envelope will only shrink. edge.setLengthMm(split.distance0_mm); edge.setToVertex(newVertexIndex); // Turn the edge into a straight line. // FIXME split edges and new edges should have geometries! edge.setGeometry(Collections.EMPTY_LIST); } else { // The edge we are going to split is immutable, and should be left as-is. // We must be applying a scenario, and this edge is part of the baseline graph shared between threads. // Preserve the existing edge pair, creating a new edge pair to lead up to the split. // The new edge will be added to the edge lists later (the edge lists are a transient index). // We don't add it to the spatial index, which is shared between all threads. EdgeStore.Edge newEdge0 = edgeStore.addStreetPair(edge.getFromVertex(), newVertexIndex, split.distance0_mm, edge.getOSMID()); // Copy the flags and speeds for both directions, making the new edge like the existing one. newEdge0.copyPairFlagsAndSpeeds(edge); // add to temp spatial index // we need to build this on the fly so that it is possible to split a street multiple times; otherwise, // once a street had been split once, the original edge would be removed from consideration // (StreetLayer#getEdgesNear filters out edges that have been deleted) and the new edge would not yet be in // the spatial index for consideration. Havoc would ensue. temporaryEdgeIndex.insert(newEdge0.getEnvelope(), newEdge0.edgeIndex); // Exclude the original split edge from all future spatial index queries on this scenario copy. // This should allow proper re-splitting of a single edge for multiple new transit stops. edgeStore.temporarilyDeletedEdges.add(edge.edgeIndex); } // Make a new bidirectional edge pair for the segment after the split. // The new edge will be added to the edge lists later (the edge lists are a transient index). EdgeStore.Edge newEdge1 = edgeStore.addStreetPair(newVertexIndex, oldToVertex, split.distance1_mm, edge.getOSMID()); // Copy the flags and speeds for both directions, making newEdge1 like the existing edge. newEdge1.copyPairFlagsAndSpeeds(edge); // Insert the new edge into the spatial index if (!edgeStore.isExtendOnlyCopy()) { spatialIndex.insert(newEdge1.getEnvelope(), newEdge1.edgeIndex); } else { temporaryEdgeIndex.insert(newEdge1.getEnvelope(), newEdge1.edgeIndex); } // don't allow the router to make ill-advised U-turns at splitter vertices // Return the splitter vertex ID return newVertexIndex; } /** perform destructive splitting of edges * FIXME: currently used only in P+R it should probably be changed to use getOrCreateVertexNear */ public int splitEdge(Split split) { // We have a linking site. Find or make a suitable vertex at that site. // Retaining the original Edge cursor object inside findSplit is not necessary, one object creation is harmless. Edge edge = edgeStore.getCursor(split.edge); // Check for cases where we don't need to create a new vertex (the edge is reached end-wise) if (split.distance0_mm < SNAP_RADIUS_MM || split.distance1_mm < SNAP_RADIUS_MM) { if (split.distance0_mm < split.distance1_mm) { // Very close to the beginning of the edge. return edge.getFromVertex(); } else { // Very close to the end of the edge. return edge.getToVertex(); } } // The split is somewhere away from an existing intersection vertex. Make a new vertex. int newVertexIndex = vertexStore.addVertexFixed((int)split.fixedLat, (int)split.fixedLon); // Modify the existing bidirectional edge pair to lead up to the split. // Its spatial index entry is still valid, its envelope has only shrunk. int oldToVertex = edge.getToVertex(); edge.setLengthMm(split.distance0_mm); edge.setToVertex(newVertexIndex); edge.setGeometry(Collections.EMPTY_LIST); // Turn it into a straight line for now. FIXME split edges should have geometries // Make a second, new bidirectional edge pair after the split and add it to the spatial index. // New edges will be added to edge lists later (the edge list is a transient index). EdgeStore.Edge newEdge = edgeStore.addStreetPair(newVertexIndex, oldToVertex, split.distance1_mm, edge.getOSMID()); spatialIndex.insert(newEdge.getEnvelope(), newEdge.edgeIndex); // Copy the flags and speeds for both directions, making the new edge like the existing one. newEdge.copyPairFlagsAndSpeeds(edge); // clean up any turn restrictions that exist // turn restrictions on the forward edge go to the new edge's forward edge. Turn restrictions on the back edge stay // where they are edgeStore.turnRestrictions.removeAll(split.edge).forEach(ridx -> edgeStore.turnRestrictions.put(newEdge.edgeIndex, ridx)); return newVertexIndex; // TODO store street-to-stop distance in a table in TransitLayer. This also allows adjusting for subway entrances etc. } /** * Create a street-layer vertex representing a transit stop, and connect that new vertex to the street network if * possible. The vertex will be created and assigned an index whether or not it is successfully linked to the streets. * This is intended for transit stop linking. It always creates a new vertex in the street layer exactly at the * coordinates provided. You can be sure to receive a unique vertex index each time it's called on the same street layer. * Once it has created this new vertex, it will look for the nearest edge in the street network and link the newly * created vertex to the closest point on that nearby edge. * The process of linking to that edge may or may not create a second new splitter vertex along that edge. * If the newly created vertex is near an intersection or another splitter vertex, the existing vertex will be * reused. So in sum, this will create one or two new vertices, and all necessary edge pairs to properly connect * these new vertices. * TODO store street-to-stop distance in a table in TransitLayer, or change the link edge length. This also allows adjusting for subway entrances etc. * @return the vertex of the newly created vertex at the supplied coordinates. */ public int createAndLinkVertex (double lat, double lon) { int stopVertex = vertexStore.addVertex(lat, lon); int streetVertex = getOrCreateVertexNear(lat, lon, StreetMode.WALK); if (streetVertex == -1) { return -1; // Unlinked } // TODO give link edges a length. // Set OSM way ID is -1 because this edge is not derived from any OSM way. Edge e = edgeStore.addStreetPair(stopVertex, streetVertex, 1, -1); // Allow all modes to traverse street-to-transit link edges. // In practice, mode permissions will be controlled by whatever street edges lead up to these link edges. e.allowAllModes(); // forward edge e.setFlag(EdgeStore.EdgeFlag.LINK); e.advance(); e.allowAllModes(); // backward edge e.setFlag(EdgeStore.EdgeFlag.LINK); return stopVertex; } /** * Find a split. Deprecated in favor of finding a split for a particular mode, below. */ @Deprecated public Split findSplit (double lat, double lon, double radiusMeters) { return findSplit(lat, lon, radiusMeters, null); } /** * Find a location on an existing street near the given point, without actually creating any vertices or edges. * The search radius can be specified freely here because we use this function to link transit stops to streets but * also to link pointsets to streets, and currently we use different distances for these two things. * This is a nondestructive operation: it simply finds a candidate split point without modifying anything. * This function starts with a small search envelope and expands it as needed under the assumption that most * search envelopes will be close to a road. * TODO favor platforms and pedestrian paths when requested * @param lat latitude in floating point geographic coordinates (not fixed point int coordinates) * @param lon longitude in floating point geographic coordinates (not fixed point int coordinates) * @return a Split object representing a point along a sub-segment of a specific edge, or null if there are no streets nearby. */ public Split findSplit(double lat, double lon, double radiusMeters, StreetMode streetMode) { Split split = null; if (radiusMeters > 300) { split = Split.find(lat, lon, 150, this, streetMode); } if (split == null) { split = Split.find(lat, lon, radiusMeters, this, streetMode); } return split; } /** * For every stop in a TransitLayer, find or create a nearby vertex in the street layer and record the connection * between the two. */ public void associateStops (TransitLayer transitLayer) { for (Stop stop : transitLayer.stopForIndex) { int stopVertex = createAndLinkVertex(stop.stop_lat, stop.stop_lon); transitLayer.streetVertexForStop.add(stopVertex); // This is always a valid, unique vertex index. // The inverse stopForStreetVertex map is a transient, derived index and will be built later. } } public int getVertexCount() { return vertexStore.getVertexCount(); } public Envelope getEnvelope() { return envelope; } /** * We intentionally avoid using clone() on EdgeStore and VertexStore so all field copying is explicit and we can * clearly see whether we are accidentally shallow-copying any collections or data structures from the base graph. * StreetLayer has a lot more fields and most of them can be shallow-copied, so here we use clone() for convenience. * @param willBeModified must be true if the scenario to be applied will make any changes to the new StreetLayer * copy. This allows some optimizations (the lists in the StreetLayer will not be wrapped). * @return a copy of this StreetLayer to which Scenarios can be applied without affecting the original StreetLayer. * * It's questionable whether the willBeModified optimization actually affects routing speed, but in theory it * saves a comparison and an extra dereference every time we use the edge/vertex stores. * TODO check whether this actually affects speed. If not, just wrap the lists in every scenario copy. */ public StreetLayer scenarioCopy(TransportNetwork newScenarioNetwork, boolean willBeModified) { StreetLayer copy = this.clone(); if (willBeModified) { // Wrap all the edge and vertex storage in classes that make them extensible. // Indicate that the content of the new StreetLayer will be changed by giving it the scenario's scenarioId. // If the copy will not be modified, scenarioId remains unchanged to allow cached pointset linkage reuse. copy.scenarioId = newScenarioNetwork.scenarioId; copy.edgeStore = edgeStore.extendOnlyCopy(copy); // The extend-only copy of the EdgeStore also contains a new extend-only copy of the VertexStore. copy.vertexStore = copy.edgeStore.vertexStore; copy.temporaryEdgeIndex = new IntHashGrid(); } copy.parentNetwork = newScenarioNetwork; copy.baseStreetLayer = this; return copy; } // FIXME radiusMeters is now set project-wide public void associateBikeSharing(TNBuilderConfig tnBuilderConfig, int radiusMeters) { LOG.info("Builder file:{}", tnBuilderConfig.bikeRentalFile); BikeRentalBuilder bikeRentalBuilder = new BikeRentalBuilder(new File(tnBuilderConfig.bikeRentalFile)); List<BikeRentalStation> bikeRentalStations = bikeRentalBuilder.getRentalStations(); bikeRentalStationMap = new TIntObjectHashMap<>(bikeRentalStations.size()); LOG.info("Bike rental stations:{}", bikeRentalStations.size()); int numAddedStations = 0; for (BikeRentalStation bikeRentalStation: bikeRentalStations) { int streetVertexIndex = getOrCreateVertexNear(bikeRentalStation.lat, bikeRentalStation.lon, StreetMode.WALK); if (streetVertexIndex > -1) { numAddedStations++; VertexStore.Vertex vertex = vertexStore.getCursor(streetVertexIndex); vertex.setFlag(VertexStore.VertexFlag.BIKE_SHARING); bikeRentalStationMap.put(streetVertexIndex, bikeRentalStation); } } if (numAddedStations > 0) { this.bikeSharing = true; } LOG.info("Added {} out of {} stations ratio:{}", numAddedStations, bikeRentalStations.size(), numAddedStations/bikeRentalStations.size()); } public StreetLayer clone () { try { return (StreetLayer) super.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException("This exception cannot happen. This is why I love checked exceptions."); } } /** @return true iff this StreetLayer was created by a scenario, and is therefore wrapping a base StreetLayer. */ public boolean isScenarioCopy() { return baseStreetLayer != null; } /** * Create a geometry in FIXED POINT DEGREES containing all the points on all edges created or removed by the * scenario that produced this StreetLayer, buffered by radiusMeters. This is a MultiPolygon or GeometryCollection. * When there are no created or removed edges, returns an empty geometry rather than null, because we test whether * transit stops are contained within the resulting geometry. */ public Geometry scenarioEdgesBoundingGeometry(int radiusMeters) { List<Polygon> geoms = new ArrayList<>(); Edge edge = edgeStore.getCursor(); edgeStore.forEachTemporarilyAddedOrDeletedEdge(e -> { edge.seek(e); Envelope envelope = edge.getEnvelope(); GeometryUtils.expandEnvelopeFixed(envelope, radiusMeters); geoms.add((Polygon)GeometryUtils.geometryFactory.toGeometry(envelope)); }); // We can't just make a multipolygon as the component polygons may not be disjoint. Unions are pretty quick though. // The UnaryUnionOp gets its geometryFactory from the geometries it's operating on. // We need to supply one in case the list is empty, so it can return an empty geometry instead of null. Geometry result = new UnaryUnionOp(geoms, GeometryUtils.geometryFactory).union(); // logFixedPointGeometry("Unioned buffered streets", result); return result; } /** * Given a JTS Geometry in fixed-point latitude and longitude, log it as floating-point GeoJSON. */ public static void logFixedPointGeometry (String label, Geometry fixedPointGeometry) { if (fixedPointGeometry == null){ LOG.info("{} is null.", label); } else if (fixedPointGeometry.isEmpty()) { LOG.info("{} is empty.", label); } else { String geoJson = new GeometryJSON().toString(fixedDegreeGeometryToFloating(fixedPointGeometry)); if (geoJson == null) { LOG.info("Could not convert non-null geometry to GeoJSON"); } else { LOG.info("{} {}", label, geoJson); } } } /** * Finds all the P+R stations in given envelope * * Returns empty list if none are found or no P+R stations are in graph * * @param env Envelope in float degrees * @return */ public List<ParkRideParking> findParkRidesInEnvelope(Envelope env) { List<ParkRideParking> parkingRides = new ArrayList<>(); if (parkRideLocationsMap != null) { EdgeStore.Edge e = edgeStore.getCursor(); VertexStore.Vertex v = vertexStore.getCursor(); TIntSet nearbyEdges = spatialIndex.query(VertexStore.envelopeToFixed(env)); nearbyEdges.forEach(eidx -> { e.seek(eidx); if (e.getFlag(EdgeStore.EdgeFlag.LINK)) { v.seek(e.getFromVertex()); if (v.getFlag(VertexStore.VertexFlag.PARK_AND_RIDE)) { ParkRideParking parkRideParking = parkRideLocationsMap.get(e.getFromVertex()); parkingRides.add(parkRideParking); } } return true; }); } return parkingRides; } /** * Finds all the bike share stations in given envelope * * Returns empty list if none are found or no bike stations are in graph * * @param env Envelope in float degrees * @return */ public List<BikeRentalStation> findBikeSharesInEnvelope(Envelope env) { List<BikeRentalStation> bikeRentalStations = new ArrayList<>(); if (bikeRentalStationMap != null) { EdgeStore.Edge e = edgeStore.getCursor(); VertexStore.Vertex v = vertexStore.getCursor(); TIntSet nearbyEdges = spatialIndex.query(VertexStore.envelopeToFixed(env)); nearbyEdges.forEach(eidx -> { e.seek(eidx); //TODO: for now bikeshares aren't connected with link edges to the graph //if (e.getFlag(EdgeStore.EdgeFlag.LINK)) { v.seek(e.getFromVertex()); if (v.getFlag(VertexStore.VertexFlag.BIKE_SHARING)) { BikeRentalStation bikeRentalStation = bikeRentalStationMap.get(e.getFromVertex()); bikeRentalStations.add(bikeRentalStation); } //} return true; }); } return bikeRentalStations; } }
src/main/java/com/conveyal/r5/streets/StreetLayer.java
package com.conveyal.r5.streets; import com.conveyal.gtfs.model.Stop; import com.conveyal.osmlib.Node; import com.conveyal.osmlib.OSM; import com.conveyal.osmlib.OSMEntity; import com.conveyal.osmlib.Relation; import com.conveyal.osmlib.Way; import com.conveyal.r5.api.util.BikeRentalStation; import com.conveyal.r5.api.util.ParkRideParking; import com.conveyal.r5.common.GeometryUtils; import com.conveyal.r5.labeling.LevelOfTrafficStressLabeler; import com.conveyal.r5.labeling.RoadPermission; import com.conveyal.r5.labeling.SpeedConfigurator; import com.conveyal.r5.labeling.TraversalPermissionLabeler; import com.conveyal.r5.labeling.TypeOfEdgeLabeler; import com.conveyal.r5.labeling.USTraversalPermissionLabeler; import com.conveyal.r5.point_to_point.builder.TNBuilderConfig; import com.conveyal.r5.streets.EdgeStore.Edge; import com.conveyal.r5.transit.TransitLayer; import com.conveyal.r5.transit.TransportNetwork; import com.vividsolutions.jts.geom.*; import com.conveyal.r5.profile.StreetMode; import com.vividsolutions.jts.operation.union.UnaryUnionOp; import gnu.trove.list.TIntList; import gnu.trove.list.array.TIntArrayList; import gnu.trove.map.TIntObjectMap; import gnu.trove.map.TLongIntMap; import gnu.trove.map.hash.TIntObjectHashMap; import gnu.trove.map.hash.TLongIntHashMap; import gnu.trove.set.TIntSet; import org.geotools.geojson.geom.GeometryJSON; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.EnumSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Random; import java.util.stream.Collectors; import java.util.stream.LongStream; import static com.conveyal.r5.streets.VertexStore.fixedDegreeGeometryToFloating; import static com.conveyal.r5.streets.VertexStore.fixedDegreesToFloating; /** * This stores the street layer of OTP routing data. * * Is is currently using a column store. * An advantage of disk-backing this (FSTStructs, MapDB optimized for zero-based * integer keys) would be that we can remove any logic about loading/unloading graphs. * We could route over a whole continent without using much memory. * * Any data that's not used by Analyst workers (street names and geometries for example) * should be optional so we can have fast-loading, small transportation network files to pass around. * It can even be loaded from the OSM MapDB on demand. * * There's also https://github.com/RichardWarburton/slab * which seems simpler to use. * * TODO Morton-code-sort vertices, then sort edges by from-vertex. */ public class StreetLayer implements Serializable, Cloneable { private static final Logger LOG = LoggerFactory.getLogger(StreetLayer.class); /** * Minimum allowable size (in number of vertices) for a disconnected subgraph; subgraphs smaller than these will be removed. * There are several reasons why one might have a disconnected subgraph. The most common is poor quality * OSM data. However, they also could be due to areas that really are disconnected in the street graph, * and are connected only by transit. These could be literal islands (Vashon Island near Seattle comes * to mind), or islands that are isolated by infrastructure (for example, airport terminals reachable * only by transit or driving, for instance BWI or SFO). */ public static final int MIN_SUBGRAPH_SIZE = 40; private static final int SNAP_RADIUS_MM = 5 * 1000; /** * The radius of a circle in meters within which to search for nearby streets. * This should not necessarily be a constant, but even if it's made settable it should be a field to avoid * cluttering method signatures. Generally you'd set this once at startup and always use the same value afterward. */ public static final double LINK_RADIUS_METERS = 300; // Edge lists should be constructed after the fact from edges. This minimizes serialized size too. public transient List<TIntList> outgoingEdges; public transient List<TIntList> incomingEdges; public transient IntHashGrid spatialIndex = new IntHashGrid(); /** Spatial index of temporary edges from a scenario */ private transient IntHashGrid temporaryEdgeIndex; // Key is street vertex index, value is BikeRentalStation (with name, number of bikes, spaces id etc.) public TIntObjectMap<BikeRentalStation> bikeRentalStationMap; public TIntObjectMap<ParkRideParking> parkRideLocationsMap; // TODO these are only needed when building the network, should we really be keeping them here in the layer? // TODO don't hardwire to US private transient TraversalPermissionLabeler permissions = new USTraversalPermissionLabeler(); private transient LevelOfTrafficStressLabeler stressLabeler = new LevelOfTrafficStressLabeler(); private transient TypeOfEdgeLabeler typeOfEdgeLabeler = new TypeOfEdgeLabeler(); private transient SpeedConfigurator speedConfigurator; // This is only used when loading from OSM, and is then nulled to save memory. transient OSM osm; /** Envelope of this street layer, in decimal degrees (floating, not fixed-point) */ public Envelope envelope = new Envelope(); TLongIntMap vertexIndexForOsmNode = new TLongIntHashMap(100_000, 0.75f, -1, -1); // Initialize these when we have an estimate of the number of expected edges. public VertexStore vertexStore = new VertexStore(100_000); public EdgeStore edgeStore = new EdgeStore(vertexStore, this, 200_000); /** * Turn restrictions can potentially have a large number of affected edges, so store them once and reference them. * TODO clarify documentation: what does "store them once and reference them" mean? Why? */ public List<TurnRestriction> turnRestrictions = new ArrayList<>(); /** * The TransportNetwork containing this StreetLayer. This link up the object tree also allows us to access the * TransitLayer associated with this StreetLayer of the same TransportNetwork without maintaining bidirectional * references between the two layers. */ public TransportNetwork parentNetwork = null; /** * A string uniquely identifying the contents of this StreetLayer among all StreetLayers. * When no scenario has been applied, this field will contain the ID of the enclosing TransportNetwork. * When a scenario has modified this StreetLayer, this field will be changed to that scenario's ID. * We need a way to know what information is in the network independent of object identity, which is lost in a * round trip through serialization. This also allows re-using cached linkages for several scenarios as long as * they don't modify the street network. */ public String scenarioId; /** * Some StreetLayers are created by applying a scenario to an existing StreetLayer. All the contents of the base * StreetLayer are not copied, they are wrapped to make them extensible. These are called "scenario copies". * If this StreetLayer is such a scenario copy, this field points to the original StreetLayer it was based upon. * Otherwise this field should be null. */ public StreetLayer baseStreetLayer = null; public static final EnumSet<EdgeStore.EdgeFlag> ALL_PERMISSIONS = EnumSet .of(EdgeStore.EdgeFlag.ALLOWS_BIKE, EdgeStore.EdgeFlag.ALLOWS_CAR, EdgeStore.EdgeFlag.ALLOWS_PEDESTRIAN, EdgeStore.EdgeFlag.NO_THRU_TRAFFIC, EdgeStore.EdgeFlag.NO_THRU_TRAFFIC_BIKE, EdgeStore.EdgeFlag.NO_THRU_TRAFFIC_PEDESTRIAN, EdgeStore.EdgeFlag.NO_THRU_TRAFFIC_CAR); public boolean bikeSharing = false; public StreetLayer(TNBuilderConfig tnBuilderConfig) { speedConfigurator = new SpeedConfigurator(tnBuilderConfig.speeds); } /** Load street layer from an OSM-lib OSM DB */ public void loadFromOsm(OSM osm) { loadFromOsm(osm, true, false); } /** * Returns true if way can be used for routing * * Routable ways are highways (unless they are raceways or highway rest_area/services since those are similar to landuse tags * Or public_transport platform or railway platform unless its usage tag is tourism * * In both cases roads need to exists in reality aka don't have: * - construction, * - proposed, * - removed, * - abandoned * - unbuilt * tags * * Both construction tagging schemes are supported tag construction=anything and highway/cycleway=construction * same with proposed. * @param way * @return */ private static boolean isWayRoutable(Way way) { boolean isRoutable = false; String highway = way.getTag("highway"); if ( //Way is routable if it is highway (way.hasTag("highway") && !( //Unless it is raceway or rest area //Those two are areas which are places around highway (similar to landuse tags they aren't routable) highway.equals("services") || highway.equals("rest_area") //highway=conveyor is obsoleted tag for escalator and is actually routable || highway.equals("raceway"))) //or it is public transport platform or railway platform || (way.hasTag("public_transport", "platform") || way.hasTag("railway", "platform") //unless it's usage is tourism && !way.hasTag("usage", "tourism"))) { isRoutable = actuallyExistsInReality(highway, way); } if (isRoutable && way.hasTag("cycleway")) { //highway tag is already checked String cycleway = way.getTag("cycleway"); isRoutable = actuallyExistsInReality(cycleway, way); } return isRoutable; } /** * Returns true if road is not in construction, abandoned, removed or proposed * @param highway value of highway or cycleway tag * @param way * @return */ private static boolean actuallyExistsInReality(String highway, Way way) { return !("construction".equals(highway) || "abandoned".equals(highway)|| "removed".equals(highway) || "proposed".equals(highway) || "propossed".equals(highway) || "unbuilt".equals(highway) || way.hasTag("construction") || way.hasTag("proposed")); } /** Load OSM, optionally removing floating subgraphs (recommended) */ void loadFromOsm (OSM osm, boolean removeIslands, boolean saveVertexIndex) { if (!osm.intersectionDetection) throw new IllegalArgumentException("Intersection detection not enabled on OSM source"); LOG.info("Making street edges from OSM ways..."); this.osm = osm; // keep track of ways that need to later become park and rides List<Way> parkAndRideWays = new ArrayList<>(); for (Map.Entry<Long, Way> entry : osm.ways.entrySet()) { Way way = entry.getValue(); if (way.hasTag("park_ride", "yes")) parkAndRideWays.add(way); if (!isWayRoutable(way)) { continue; } int nEdgesCreated = 0; int beginIdx = 0; // Break each OSM way into topological segments between intersections, and make one edge per segment. for (int n = 1; n < way.nodes.length; n++) { if (osm.intersectionNodes.contains(way.nodes[n]) || n == (way.nodes.length - 1)) { makeEdge(way, beginIdx, n, entry.getKey()); nEdgesCreated += 1; beginIdx = n; } } } stressLabeler.logErrors(); // summarize LTS statistics Edge cursor = edgeStore.getCursor(); cursor.seek(0); int lts1 = 0, lts2 = 0, lts3 = 0, lts4 = 0, ltsUnknown = 0; do { if (cursor.getFlag(EdgeStore.EdgeFlag.BIKE_LTS_1)) lts1++; else if (cursor.getFlag(EdgeStore.EdgeFlag.BIKE_LTS_2)) lts2++; else if (cursor.getFlag(EdgeStore.EdgeFlag.BIKE_LTS_3)) lts3++; else if (cursor.getFlag(EdgeStore.EdgeFlag.BIKE_LTS_4)) lts4++; else ltsUnknown++; } while (cursor.advance()); LOG.info("Surrogate LTS:\n 1: {} edges\n 2: {} edges\n 3: {} edges\n 4: {} edges\n Unknown: {} edges", lts1, lts2, lts3, lts4, ltsUnknown); List<Node> parkAndRideNodes = new ArrayList<>(); for (Node node : osm.nodes.values()) { if (node.hasTag("park_ride", "yes")) parkAndRideNodes.add(node); } LOG.info("Done making street edges."); LOG.info("Made {} vertices and {} edges.", vertexStore.getVertexCount(), edgeStore.nEdges()); LOG.info("Found {} P+R node candidates", parkAndRideNodes.size()); // We need edge lists to apply intersection costs. buildEdgeLists(); stressLabeler.applyIntersectionCosts(this); if (removeIslands) { new TarjanIslandPruner(this, MIN_SUBGRAPH_SIZE, StreetMode.CAR).run(); // due to bike walking, walk must go before bike, see comment in TarjanIslandPruner javadoc new TarjanIslandPruner(this, MIN_SUBGRAPH_SIZE, StreetMode.WALK).run(); new TarjanIslandPruner(this, MIN_SUBGRAPH_SIZE, StreetMode.BICYCLE).run(); } // index the streets, we need the index to connect things to them. this.indexStreets(); buildParkAndRideAreas(parkAndRideWays); buildParkAndRideNodes(parkAndRideNodes); VertexStore.Vertex vertex = vertexStore.getCursor(); long numOfParkAndRides = 0; while (vertex.advance()) { if (vertex.getFlag(VertexStore.VertexFlag.PARK_AND_RIDE)) { numOfParkAndRides++; } } LOG.info("Made {} P+R vertices", numOfParkAndRides); // create turn restrictions. // TODO transit splitting is going to mess this up osm.relations.entrySet().stream().filter(e -> e.getValue().hasTag("type", "restriction")).forEach(e -> this.applyTurnRestriction(e.getKey(), e.getValue())); LOG.info("Created {} turn restrictions", turnRestrictions.size()); //edgesPerWayHistogram.display(); //pointsPerEdgeHistogram.display(); // Clear unneeded indexes, allow them to be gc'ed if (!saveVertexIndex) vertexIndexForOsmNode = null; osm = null; } /** * TODO Javadoc. What is this for? */ public void openOSM(File file) { osm = new OSM(file.getPath()); LOG.info("Read OSM"); } /** * Gets way name from OSM name tag * * It uses OSM Mapdb * * Uses {@link #getName(long, Locale)} * * @param edgeIdx edgeStore EdgeIDX * @param locale which locale to use * @return null if edge doesn't have name tag or if OSM data isn't loaded */ public String getNameEdgeIdx(int edgeIdx, Locale locale) { if (osm == null) { return null; } EdgeStore.Edge edge = edgeStore.getCursor(edgeIdx); String name = getName(edge.getOSMID(), locale); if (name == null) { //TODO: localize generated street names if (edge.getFlag(EdgeStore.EdgeFlag.STAIRS)) { return "stairs"; } else if (edge.getFlag(EdgeStore.EdgeFlag.CROSSING)) { return "street crossing"; } else if (edge.getFlag(EdgeStore.EdgeFlag.BIKE_PATH)) { return "bike path"; } else if (edge.getFlag(EdgeStore.EdgeFlag.SIDEWALK)) { return "sidewalk"; } } return name; } /** * Gets way name from OSM name tag * * TODO: generate name on unnamed ways (sidewalks, cycleways etc.) * @param OSMid OSM ID of a way * @param locale which locale to use * @return */ private String getName(long OSMid, Locale locale) { String name = null; Way way = osm.ways.get(OSMid); if (way != null) { name = way.getTag("name"); } return name; } /** * Gets all the OSM tags of specified OSM way * * Tags are returned as tag=value separated with ; * * AKA same format that {@link Way#setTagsFromString(String)} accepts * * @param edge for which to get tags * @return String with all the tags or null */ public String getWayTags(EdgeStore.Edge edge) { if (osm == null) { return null; } Way way = osm.ways.get(edge.getOSMID()); if (way != null && !way.hasNoTags()) { return way.tags.stream() .map(OSMEntity.Tag::toString) .collect(Collectors.joining(";")); } return null; } /** Connect areal park and rides to the graph */ private void buildParkAndRideAreas(List<Way> parkAndRideWays) { VertexStore.Vertex v = this.vertexStore.getCursor(); EdgeStore.Edge e = this.edgeStore.getCursor(); parkRideLocationsMap = new TIntObjectHashMap<>(); for (Way way : parkAndRideWays) { Coordinate[] coords = LongStream.of(way.nodes).mapToObj(nid -> { Node n = osm.nodes.get(nid); return new Coordinate(n.getLon(), n.getLat()); }).toArray(s -> new Coordinate[s]); // nb using linestring not polygon so all found intersections are at edges. LineString g = GeometryUtils.geometryFactory.createLineString(coords); // create a vertex in the middle of the lot to reflect the park and ride Coordinate centroid = g.getCentroid().getCoordinate(); int centerVertex = vertexStore.addVertex(centroid.y, centroid.x); v.seek(centerVertex); v.setFlag(VertexStore.VertexFlag.PARK_AND_RIDE); ParkRideParking parkRideParking = new ParkRideParking(centerVertex, centroid.y, centroid.x, way); parkRideLocationsMap.put(centerVertex, parkRideParking); // find nearby edges Envelope env = g.getEnvelopeInternal(); TIntSet nearbyEdges = this.spatialIndex.query(VertexStore.envelopeToFixed(env)); nearbyEdges.forEach(eidx -> { e.seek(eidx); // Connect only to edges that are good to link to (This skips tunnels) // and skips link edges (that were used to link other stuff) if (!e.getFlag(EdgeStore.EdgeFlag.LINKABLE) || e.getFlag(EdgeStore.EdgeFlag.LINK)) { return true; } LineString edgeGeometry = e.getGeometry(); if (edgeGeometry.intersects(g)) { // we found an intersection! yay! Geometry intersection = edgeGeometry.intersection(g); for (int i = 0; i < intersection.getNumGeometries(); i++) { Geometry single = intersection.getGeometryN(i); if (single instanceof Point) { connectParkAndRide(centerVertex, single.getCoordinate(), e); } else if (single instanceof LineString) { // coincident segments. TODO can this even happen? // just connect start and end of coincident segment Coordinate[] singleCoords = single.getCoordinates(); if (singleCoords.length > 0) { connectParkAndRide(centerVertex, coords[0], e); // TODO is conditional even necessary? if (singleCoords.length > 1) { connectParkAndRide(centerVertex, coords[coords.length - 1], e); } } } } } return true; }); // TODO check if we didn't connect anything and fall back to proximity based connection } } private void buildParkAndRideNodes (List<Node> nodes) { VertexStore.Vertex v = vertexStore.getCursor(); for (Node node : nodes) { int vidx = vertexStore.addVertex(node.getLat(), node.getLon()); v.seek(vidx); v.setFlag(VertexStore.VertexFlag.PARK_AND_RIDE); ParkRideParking parkRideParking = new ParkRideParking(vidx, node.getLat(), node.getLon(), node); parkRideLocationsMap.put(vidx, parkRideParking); int targetWalking = getOrCreateVertexNear(node.getLat(), node.getLon(), StreetMode.WALK); if (targetWalking == -1) { LOG.warn("Could not link park and ride node at ({}, {}) to the street network.", node.getLat(), node.getLon()); continue; } EdgeStore.Edge created = edgeStore.addStreetPair(vidx, targetWalking, 1, -1); // allow link edges to be traversed by all, access is controlled by connected edges created.allowAllModes(); created.setFlag(EdgeStore.EdgeFlag.LINK); // and the back edge created.advance(); created.allowAllModes(); created.setFlag(EdgeStore.EdgeFlag.LINK); int targetDriving = getOrCreateVertexNear(node.getLat(), node.getLon(), StreetMode.CAR); //If both CAR and WALK links would connect to the same edge we can skip new useless edge if (targetDriving == targetWalking) { continue; } created = edgeStore.addStreetPair(vidx, targetDriving, 1, -1); // allow link edges to be traversed by all, access is controlled by connected edges created.allowAllModes(); created.setFlag(EdgeStore.EdgeFlag.LINK); // and the back edge created.advance(); created.allowAllModes(); created.setFlag(EdgeStore.EdgeFlag.LINK); } } /** Connect a park and ride vertex to the street network at a particular location and edge */ private void connectParkAndRide (int centerVertex, Coordinate coord, EdgeStore.Edge edge) { Split split = Split.findOnEdge(coord.y, coord.x, edge); int targetVertex = splitEdge(split); EdgeStore.Edge created = edgeStore.addStreetPair(centerVertex, targetVertex, 1, -1); // basically free to enter/leave P&R for now. // allow link edges to be traversed by all, access is controlled by connected edges created.allowAllModes(); created.setFlag(EdgeStore.EdgeFlag.LINK); // and the back edge created.advance(); created.allowAllModes(); created.setFlag(EdgeStore.EdgeFlag.LINK); } private void applyTurnRestriction (long id, Relation restriction) { boolean only; if (!restriction.hasTag("restriction")) { LOG.error("Restriction {} has no restriction tag, skipping", id); return; } if (restriction.getTag("restriction").startsWith("no_")) only = false; else if (restriction.getTag("restriction").startsWith("only_")) only = true; else { LOG.error("Restriction {} has invalid restriction tag {}, skipping", id, restriction.getTag("restriction")); return; } TurnRestriction out = new TurnRestriction(); out.only = only; // sort out the members Relation.Member from = null, to = null; List<Relation.Member> via = new ArrayList<>(); for (Relation.Member member : restriction.members) { if ("from".equals(member.role)) { if (from != null) { LOG.error("Turn restriction {} has multiple from members, skipping", id); return; } from = member; } else if ("to".equals(member.role)) { if (to != null) { LOG.error("Turn restriction {} has multiple to members, skipping", id); return; } to = member; } else if ("via".equals(member.role)) { via.add(member); } // Osmosis may produce situations where referential integrity is violated, probably at the edge of the // bounding box where half a turn restriction is outside the box. if (member.type == OSMEntity.Type.WAY) { if (!osm.ways.containsKey(member.id)) { LOG.warn("Turn restriction relation {} references nonexistent way {}, dropping this relation", id, member.id); return; } } else if (member.type == OSMEntity.Type.NODE) { if (!osm.nodes.containsKey(member.id)) { LOG.warn("Turn restriction relation {} references nonexistent node {}, dropping this relation", id, member.id); return; } } } if (from == null || to == null || via.isEmpty()) { LOG.error("Invalid turn restriction {}, does not have from, to and via, skipping", id); return; } boolean hasWays = false, hasNodes = false; for (Relation.Member m : via) { if (m.type == OSMEntity.Type.WAY) hasWays = true; else if (m.type == OSMEntity.Type.NODE) hasNodes = true; else { LOG.error("via must be node or way, skipping restriction {}", id); return; } } if (hasWays && hasNodes || hasNodes && via.size() > 1) { LOG.error("via must be single node or one or more ways, skipping restriction {}", id); return; } EdgeStore.Edge e = edgeStore.getCursor(); if (hasNodes) { // via node, this is a fairly simple turn restriction. First find the relevant vertex. int vertex = vertexIndexForOsmNode.get(via.get(0).id); if (vertex == -1) { LOG.warn("Vertex {} not found to use as via node for restriction {}, skipping this restriction", via.get(0).id, id); return; } // use array to dodge effectively final nonsense final int[] fromEdge = new int[] { -1 }; final long fromWayId = from.id; // more effectively final nonsense final boolean[] bad = new boolean[] { false }; // find the edges incomingEdges.get(vertex).forEach(eidx -> { e.seek(eidx); if (e.getOSMID() == fromWayId) { if (fromEdge[0] != -1) { LOG.error("From way enters vertex {} twice, restriction {} is therefore ambiguous, skipping", vertex, id); bad[0] = true; return false; } fromEdge[0] = eidx; } return true; // iteration should continue }); final int[] toEdge = new int[] { -1 }; final long toWayId = to.id; // more effectively final nonsense outgoingEdges.get(vertex).forEach(eidx -> { e.seek(eidx); if (e.getOSMID() == toWayId) { if (toEdge[0] != -1) { LOG.error("To way exits vertex {} twice, restriction {} is therefore ambiguous, skipping", vertex, id); bad[0] = true; return false; } toEdge[0] = eidx; } return true; // iteration should continue }); if (bad[0]) return; // log message already printed if (fromEdge[0] == -1 || toEdge[0] == -1) { LOG.error("Did not find from/to edges for restriction {}, skipping", id); return; } // phew. create the restriction and apply it where needed out.fromEdge = fromEdge[0]; out.toEdge = toEdge[0]; int index = turnRestrictions.size(); turnRestrictions.add(out); edgeStore.turnRestrictions.put(out.fromEdge, index); addReverseTurnRestriction(out, index); } else { // via member(s) are ways, which is more tricky // do a little street search constrained to the ways in question Way fromWay = osm.ways.get(from.id); long[][] viaNodes = via.stream().map(m -> osm.ways.get(m.id).nodes).toArray(i -> new long[i][]); Way toWay = osm.ways.get(to.id); // We do a little search, keeping in mind that there must be the same number of ways as there are via members List<long[]> nodes = new ArrayList<>(); List<long[]> ways = new ArrayList<>(); // loop over from way to initialize search for (long node : fromWay.nodes) { for (int viaPos = 0; viaPos < viaNodes.length; viaPos++) { for (long viaNode : viaNodes[viaPos]) { if (node == viaNode) { nodes.add(new long[] { node }); ways.add(new long[] { via.get(viaPos).id }); } } } } List<long[]> previousNodes; List<long[]> previousWays; // via.size() - 1 because we've already explored one via way where we transferred from the the from way for (int round = 0; round < via.size() - 1; round++) { previousNodes = nodes; previousWays = ways; nodes = new ArrayList<>(); ways = new ArrayList<>(); for (int statePos = 0; statePos < previousNodes.size(); statePos++) { // get the way we are on and search all its nodes long wayId = previousWays.get(statePos)[round]; Way way = osm.ways.get(wayId); for (long node : way.nodes) { VIA: for (int viaPos = 0; viaPos < viaNodes.length; viaPos++) { long viaWayId = via.get(viaPos).id; // don't do looping searches for (long prevWay : previousWays.get(statePos)) { if (viaWayId == prevWay) continue VIA; } for (long viaNode : osm.ways.get(viaWayId).nodes) { if (viaNode == node) { long[] newNodes = Arrays.copyOf(previousNodes.get(statePos), round + 2); long[] newWays = Arrays.copyOf(previousWays.get(statePos), round + 2); newNodes[round + 1] = node; newWays[round + 1] = viaWayId; nodes.add(newNodes); ways.add(newWays); } } } } } } // now filter them to just ones that reach the to way long[] pathNodes = null; long[] pathWays = null; for (int statePos = 0; statePos < nodes.size(); statePos++) { long[] theseWays = ways.get(statePos); Way finalWay = osm.ways.get(theseWays[theseWays.length - 1]); for (long node : finalWay.nodes) { for (long toNode : toWay.nodes) { if (node == toNode) { if (pathNodes != null) { LOG.error("Turn restriction {} has ambiguous via ways (multiple paths through via ways between from and to), skipping", id); return; } pathNodes = Arrays.copyOf(nodes.get(statePos), theseWays.length + 1); pathNodes[pathNodes.length - 1] = node; pathWays = theseWays; } } } } if (pathNodes == null) { LOG.error("Invalid turn restriction {}, no way from from to to via via, skipping", id); return; } // convert OSM nodes and ways into IDs // first find the fromEdge and toEdge. dodge effectively final nonsense final int[] fromEdge = new int[] { -1 }; final long fromWayId = from.id; // more effectively final nonsense final boolean[] bad = new boolean[] { false }; int fromVertex = vertexIndexForOsmNode.get(pathNodes[0]); // find the edges incomingEdges.get(fromVertex).forEach(eidx -> { e.seek(eidx); if (e.getOSMID() == fromWayId) { if (fromEdge[0] != -1) { LOG.error("From way enters vertex {} twice, restriction {} is therefore ambiguous, skipping", fromVertex, id); bad[0] = true; return false; } fromEdge[0] = eidx; } return true; // iteration should continue }); int toVertex = vertexIndexForOsmNode.get(pathNodes[pathNodes.length - 1]); final int[] toEdge = new int[] { -1 }; final long toWayId = to.id; // more effectively final nonsense outgoingEdges.get(toVertex).forEach(eidx -> { e.seek(eidx); if (e.getOSMID() == toWayId) { if (toEdge[0] != -1) { LOG.error("To way exits vertex {} twice, restriction {} is therefore ambiguous, skipping", toVertex, id); bad[0] = true; return false; } toEdge[0] = eidx; } return true; // iteration should continue }); if (bad[0]) return; // log message already printed if (fromEdge[0] == -1 || toEdge[0] == -1) { LOG.error("Did not find from/to edges for restriction {}, skipping", id); return; } out.fromEdge = fromEdge[0]; out.toEdge = toEdge[0]; // edges affected by this turn restriction. Make a list in case something goes awry when trying to find edges TIntList affectedEdges = new TIntArrayList(); // now apply to all via ways. // > 0 is intentional. pathNodes[0] is the node on the from edge for (int nidx = pathNodes.length - 1; nidx > 0; nidx--) { final int[] edge = new int[] { -1 }; // fencepost problem: one more node than ways final long wayId = pathWays[nidx - 1]; // more effectively final nonsense int vertex = vertexIndexForOsmNode.get(pathNodes[nidx]); incomingEdges.get(vertex).forEach(eidx -> { e.seek(eidx); if (e.getOSMID() == wayId) { if (edge[0] != -1) { // TODO we've already started messing with data structures! LOG.error("To way exits vertex {} twice, restriction {} is therefore ambiguous, skipping", vertex, id); bad[0] = true; return false; } edge[0] = eidx; } return true; // iteration should continue }); if (bad[0]) return; // log message already printed if (edge[0] == -1) { LOG.warn("Did not find via way {} for restriction {}, skipping", wayId, id); return; } affectedEdges.add(edge[0]); } affectedEdges.reverse(); out.viaEdges = affectedEdges.toArray(); int index = turnRestrictions.size(); turnRestrictions.add(out); edgeStore.turnRestrictions.put(out.fromEdge, index); addReverseTurnRestriction(out, index); // take a deep breath } } /** * Adding turn restrictions for reverse search is a little tricky. * * First because we are adding toEdge to turnRestrictionReverse map and second because ONLY TURNs aren't supported * * Since ONLY TURN restrictions aren't supported ONLY TURN restrictions * are created with NO TURN restrictions and added to turnRestrictions and edgeStore turnRestrictionsReverse * * if NO TURN restriction is added it's just added with correct toEdge (instead of from since * we are searching from the back) * @param turnRestriction * @param index */ void addReverseTurnRestriction(TurnRestriction turnRestriction, int index) { if (turnRestriction.only) { //From Only turn restrictions create multiple NO TURN restrictions which means the same //Since only turn restrictions aren't supported in reverse street search List<TurnRestriction> remapped = turnRestriction.remap(this); for (TurnRestriction remapped_restriction: remapped) { index = turnRestrictions.size(); turnRestrictions.add(remapped_restriction); edgeStore.turnRestrictionsReverse.put(remapped_restriction.toEdge, index); } } else { edgeStore.turnRestrictionsReverse.put(turnRestriction.toEdge, index); } } /** * Get or create mapping from a global long OSM ID to an internal street vertex ID, creating the vertex as needed. * @return the internal ID for the street vertex that was found or created, or -1 if there was no such OSM node. */ private int getVertexIndexForOsmNode(long osmNodeId) { int vertexIndex = vertexIndexForOsmNode.get(osmNodeId); if (vertexIndex == -1) { // Register a new vertex, incrementing the index starting from zero. // Store node coordinates for this new street vertex Node node = osm.nodes.get(osmNodeId); if (node == null) { LOG.warn("OSM data references an undefined node. This is often the result of extracting a bounding box in Osmosis without the completeWays option."); } else { vertexIndex = vertexStore.addVertex(node.getLat(), node.getLon()); VertexStore.Vertex v = vertexStore.getCursor(vertexIndex); if (node.hasTag("highway", "traffic_signals")) v.setFlag(VertexStore.VertexFlag.TRAFFIC_SIGNAL); vertexIndexForOsmNode.put(osmNodeId, vertexIndex); } } return vertexIndex; } /** * Calculate length from a list of nodes. This is done in advance of creating an edge pair because we need to catch * potential length overflows before we ever reserve space for the edges. * @return the length of the edge in millimeters, or -1 if that length will overflow a 32 bit int */ private int getEdgeLengthMillimeters (List<Node> nodes) { double lengthMeters = 0; Node prevNode = nodes.get(0); for (Node node : nodes.subList(1, nodes.size())) { lengthMeters += GeometryUtils .distance(prevNode.getLat(), prevNode.getLon(), node.getLat(), node.getLon()); prevNode = node; } if (lengthMeters * 1000 > Integer.MAX_VALUE) { return -1; } return (int)(lengthMeters * 1000); } private static short speedToShort(Float speed) { return (short) Math.round(speed * 100); } /** * Make an edge for a sub-section of an OSM way, typically between two intersections or leading up to a dead end. */ private void makeEdge(Way way, int beginIdx, int endIdx, Long osmID) { long beginOsmNodeId = way.nodes[beginIdx]; long endOsmNodeId = way.nodes[endIdx]; // Will create mapping if it doesn't exist yet. int beginVertexIndex = getVertexIndexForOsmNode(beginOsmNodeId); int endVertexIndex = getVertexIndexForOsmNode(endOsmNodeId); // Fetch the OSM node objects for this subsection of the OSM way. int nNodes = endIdx - beginIdx + 1; List<Node> nodes = new ArrayList<>(nNodes); for (int n = beginIdx; n <= endIdx; n++) { long nodeId = way.nodes[n]; Node node = osm.nodes.get(nodeId); if (node == null) { LOG.warn("Not creating street segment that references an undefined node."); return; } envelope.expandToInclude(node.getLon(), node.getLat()); nodes.add(node); } // Compute edge length and check that it can be properly represented. int edgeLengthMillimeters = getEdgeLengthMillimeters(nodes); if (edgeLengthMillimeters < 0) { LOG.warn("Street segment was too long to be represented, skipping."); return; } // FIXME this encoded speed should probably never be exposed outside the edge object short forwardSpeed = speedToShort(speedConfigurator.getSpeedMS(way, false)); short backwardSpeed = speedToShort(speedConfigurator.getSpeedMS(way, true)); RoadPermission roadPermission = permissions.getPermissions(way); // Create and store the forward and backward edge // FIXME these sets of flags should probably not leak outside the permissions/stress/etc. labeler methods EnumSet<EdgeStore.EdgeFlag> forwardFlags = roadPermission.forward; EnumSet<EdgeStore.EdgeFlag> backFlags = roadPermission.backward; // Doesn't insert edges which don't have any permissions forward and backward if (Collections.disjoint(forwardFlags, ALL_PERMISSIONS) && Collections.disjoint(backFlags, ALL_PERMISSIONS)) { LOG.debug("Way has no permissions skipping!"); return; } stressLabeler.label(way, forwardFlags, backFlags); typeOfEdgeLabeler.label(way, forwardFlags, backFlags); Edge newEdge = edgeStore.addStreetPair(beginVertexIndex, endVertexIndex, edgeLengthMillimeters, osmID); // newEdge is first pointing to the forward edge in the pair. // Geometries apply to both edges in a pair. newEdge.setGeometry(nodes); newEdge.setFlags(forwardFlags); newEdge.setSpeed(forwardSpeed); // Step ahead to the backward edge in the same pair. newEdge.advance(); newEdge.setFlags(backFlags); newEdge.setSpeed(backwardSpeed); } public void indexStreets () { LOG.info("Indexing streets..."); spatialIndex = new IntHashGrid(); // Skip by twos, we only need to index forward (even) edges. Their odd companions have the same geometry. Edge edge = edgeStore.getCursor(); for (int e = 0; e < edgeStore.nEdges(); e += 2) { edge.seek(e); spatialIndex.insert(edge.getGeometry(), e); } LOG.info("Done indexing streets."); } /** * Rather than querying the spatial index directly, going through this method will ensure that any temporary edges * not in the index are also visible. Temporary edges, created when applying a scenario in a single thread, are * not added to the spatial index, which is read by all threads. * Note: the spatial index can and will return false positives, but should not produce false negatives. * We return the unfiltered results including false positives because calculating the true distance to each edge * is quite a slow operation. The caller must post-filter the set of edges if more distance information is needed, * including knowledge of whether an edge passes inside the query envelope at all. */ public TIntSet findEdgesInEnvelope (Envelope envelope) { TIntSet candidates = spatialIndex.query(envelope); // Include temporary edges if (temporaryEdgeIndex != null) { TIntSet temporaryCandidates = temporaryEdgeIndex.query(envelope); candidates.addAll(temporaryCandidates); } // Remove any edges that were temporarily deleted in a scenario. // This allows properly re-splitting the same edge in multiple places. if (edgeStore.temporarilyDeletedEdges != null) { candidates.removeAll(edgeStore.temporarilyDeletedEdges); } return candidates; } /** After JIT this appears to scale almost linearly with number of cores. */ public void testRouting (boolean withDestinations, TransitLayer transitLayer) { LOG.info("Routing from random vertices in the graph..."); LOG.info("{} goal direction.", withDestinations ? "Using" : "Not using"); StreetRouter router = new StreetRouter(this); long startTime = System.currentTimeMillis(); final int N = 1_000; final int nVertices = outgoingEdges.size(); Random random = new Random(); for (int n = 0; n < N; n++) { int from = random.nextInt(nVertices); VertexStore.Vertex vertex = vertexStore.getCursor(from); // LOG.info("Routing from ({}, {}).", vertex.getLat(), vertex.getLon()); router.setOrigin(from); router.toVertex = withDestinations ? random.nextInt(nVertices) : StreetRouter.ALL_VERTICES; if (n != 0 && n % 100 == 0) { LOG.info(" {}/{} searches", n, N); } } double eTime = System.currentTimeMillis() - startTime; LOG.info("average response time {} msec", eTime / N); } /** * The edge lists (which edges go out of and come into each vertex) are derived from the edges in the EdgeStore. * So any time you add edges or change their endpoints, you need to rebuild the edge index. * TODO some way to signal that a few new edges have been added, rather than rebuilding the whole lists. */ public void buildEdgeLists() { LOG.info("Building edge lists from edges..."); outgoingEdges = new ArrayList<>(vertexStore.getVertexCount()); incomingEdges = new ArrayList<>(vertexStore.getVertexCount()); for (int v = 0; v < vertexStore.getVertexCount(); v++) { outgoingEdges.add(new TIntArrayList(4)); incomingEdges.add(new TIntArrayList(4)); } Edge edge = edgeStore.getCursor(); while (edge.advance()) { outgoingEdges.get(edge.getFromVertex()).add(edge.edgeIndex); incomingEdges.get(edge.getToVertex()).add(edge.edgeIndex); } LOG.info("Done building edge lists."); } /** * Find an existing street vertex near the supplied coordinates, or create a new one if there are no vertices * near enough. Note that calling this method is potentially destructive (it can modify the street network). * * This uses {@link #findSplit(double, double, double, StreetMode)} and {@link Split} which need filled spatialIndex * In other works {@link #indexStreets()} needs to be called before this is used. Otherwise no near vertex is found. * * TODO maybe use X and Y everywhere for fixed point, and lat/lon for double precision degrees. * TODO maybe move this into Split.perform(), store streetLayer ref in Split. * @param lat latitude in floating point geographic (not fixed point) degrees. * @param lon longitude in floating point geographic (not fixed point) degrees. * @param streetMode Link to edges which have permission for StreetMode * @return the index of a street vertex very close to the supplied location, * or -1 if no such vertex could be found or created. */ public int getOrCreateVertexNear(double lat, double lon, StreetMode streetMode) { Split split = findSplit(lat, lon, LINK_RADIUS_METERS, streetMode); if (split == null) { // No linking site was found within range. return -1; } // We have a linking site on a street edge. Find or make a suitable vertex at that site. // It is not necessary to reuse the Edge cursor object created inside the findSplit call, // one additional object instantiation is harmless. Edge edge = edgeStore.getCursor(split.edge); // Check for cases where we don't need to create a new vertex: // The linking site is very near an intersection, or the edge is reached end-wise. if (split.distance0_mm < SNAP_RADIUS_MM || split.distance1_mm < SNAP_RADIUS_MM) { if (split.distance0_mm < split.distance1_mm) { // Very close to the beginning of the edge. Return that existing vertex. return edge.getFromVertex(); } else { // Very close to the end of the edge. Return that existing vertex. return edge.getToVertex(); } } // The split is somewhere along a street away from an existing intersection vertex. Make a new splitter vertex. int newVertexIndex = vertexStore.addVertexFixed((int) split.fixedLat, (int) split.fixedLon); int oldToVertex = edge.getToVertex(); // Hold a copy of the to vertex index, because it may be modified below. if (edge.isMutable()) { // The edge we are going to split is mutable. // We're either building a baseline graph, or modifying an edge created within the same scenario. // Modify the existing bidirectional edge pair to serve as the first segment leading up to the split point. // Its spatial index entry is still valid, since the edge's envelope will only shrink. edge.setLengthMm(split.distance0_mm); edge.setToVertex(newVertexIndex); // Turn the edge into a straight line. // FIXME split edges and new edges should have geometries! edge.setGeometry(Collections.EMPTY_LIST); } else { // The edge we are going to split is immutable, and should be left as-is. // We must be applying a scenario, and this edge is part of the baseline graph shared between threads. // Preserve the existing edge pair, creating a new edge pair to lead up to the split. // The new edge will be added to the edge lists later (the edge lists are a transient index). // We don't add it to the spatial index, which is shared between all threads. EdgeStore.Edge newEdge0 = edgeStore.addStreetPair(edge.getFromVertex(), newVertexIndex, split.distance0_mm, edge.getOSMID()); // Copy the flags and speeds for both directions, making the new edge like the existing one. newEdge0.copyPairFlagsAndSpeeds(edge); // add to temp spatial index // we need to build this on the fly so that it is possible to split a street multiple times; otherwise, // once a street had been split once, the original edge would be removed from consideration // (StreetLayer#getEdgesNear filters out edges that have been deleted) and the new edge would not yet be in // the spatial index for consideration. Havoc would ensue. temporaryEdgeIndex.insert(newEdge0.getEnvelope(), newEdge0.edgeIndex); // Exclude the original split edge from all future spatial index queries on this scenario copy. // This should allow proper re-splitting of a single edge for multiple new transit stops. edgeStore.temporarilyDeletedEdges.add(edge.edgeIndex); } // Make a new bidirectional edge pair for the segment after the split. // The new edge will be added to the edge lists later (the edge lists are a transient index). EdgeStore.Edge newEdge1 = edgeStore.addStreetPair(newVertexIndex, oldToVertex, split.distance1_mm, edge.getOSMID()); // Copy the flags and speeds for both directions, making newEdge1 like the existing edge. newEdge1.copyPairFlagsAndSpeeds(edge); // Insert the new edge into the spatial index if (!edgeStore.isExtendOnlyCopy()) { spatialIndex.insert(newEdge1.getEnvelope(), newEdge1.edgeIndex); } else { temporaryEdgeIndex.insert(newEdge1.getEnvelope(), newEdge1.edgeIndex); } // don't allow the router to make ill-advised U-turns at splitter vertices // Return the splitter vertex ID return newVertexIndex; } /** perform destructive splitting of edges * FIXME: currently used only in P+R it should probably be changed to use getOrCreateVertexNear */ public int splitEdge(Split split) { // We have a linking site. Find or make a suitable vertex at that site. // Retaining the original Edge cursor object inside findSplit is not necessary, one object creation is harmless. Edge edge = edgeStore.getCursor(split.edge); // Check for cases where we don't need to create a new vertex (the edge is reached end-wise) if (split.distance0_mm < SNAP_RADIUS_MM || split.distance1_mm < SNAP_RADIUS_MM) { if (split.distance0_mm < split.distance1_mm) { // Very close to the beginning of the edge. return edge.getFromVertex(); } else { // Very close to the end of the edge. return edge.getToVertex(); } } // The split is somewhere away from an existing intersection vertex. Make a new vertex. int newVertexIndex = vertexStore.addVertexFixed((int)split.fixedLat, (int)split.fixedLon); // Modify the existing bidirectional edge pair to lead up to the split. // Its spatial index entry is still valid, its envelope has only shrunk. int oldToVertex = edge.getToVertex(); edge.setLengthMm(split.distance0_mm); edge.setToVertex(newVertexIndex); edge.setGeometry(Collections.EMPTY_LIST); // Turn it into a straight line for now. FIXME split edges should have geometries // Make a second, new bidirectional edge pair after the split and add it to the spatial index. // New edges will be added to edge lists later (the edge list is a transient index). EdgeStore.Edge newEdge = edgeStore.addStreetPair(newVertexIndex, oldToVertex, split.distance1_mm, edge.getOSMID()); spatialIndex.insert(newEdge.getEnvelope(), newEdge.edgeIndex); // Copy the flags and speeds for both directions, making the new edge like the existing one. newEdge.copyPairFlagsAndSpeeds(edge); // clean up any turn restrictions that exist // turn restrictions on the forward edge go to the new edge's forward edge. Turn restrictions on the back edge stay // where they are edgeStore.turnRestrictions.removeAll(split.edge).forEach(ridx -> edgeStore.turnRestrictions.put(newEdge.edgeIndex, ridx)); return newVertexIndex; // TODO store street-to-stop distance in a table in TransitLayer. This also allows adjusting for subway entrances etc. } /** * Create a street-layer vertex representing a transit stop, and connect that new vertex to the street network if * possible. The vertex will be created and assigned an index whether or not it is successfully linked to the streets. * This is intended for transit stop linking. It always creates a new vertex in the street layer exactly at the * coordinates provided. You can be sure to receive a unique vertex index each time it's called on the same street layer. * Once it has created this new vertex, it will look for the nearest edge in the street network and link the newly * created vertex to the closest point on that nearby edge. * The process of linking to that edge may or may not create a second new splitter vertex along that edge. * If the newly created vertex is near an intersection or another splitter vertex, the existing vertex will be * reused. So in sum, this will create one or two new vertices, and all necessary edge pairs to properly connect * these new vertices. * TODO store street-to-stop distance in a table in TransitLayer, or change the link edge length. This also allows adjusting for subway entrances etc. * @return the vertex of the newly created vertex at the supplied coordinates. */ public int createAndLinkVertex (double lat, double lon) { int stopVertex = vertexStore.addVertex(lat, lon); int streetVertex = getOrCreateVertexNear(lat, lon, StreetMode.WALK); if (streetVertex == -1) { return -1; // Unlinked } // TODO give link edges a length. // Set OSM way ID is -1 because this edge is not derived from any OSM way. Edge e = edgeStore.addStreetPair(stopVertex, streetVertex, 1, -1); // Allow all modes to traverse street-to-transit link edges. // In practice, mode permissions will be controlled by whatever street edges lead up to these link edges. e.allowAllModes(); // forward edge e.setFlag(EdgeStore.EdgeFlag.LINK); e.advance(); e.allowAllModes(); // backward edge e.setFlag(EdgeStore.EdgeFlag.LINK); return stopVertex; } /** * Find a split. Deprecated in favor of finding a split for a particular mode, below. */ @Deprecated public Split findSplit (double lat, double lon, double radiusMeters) { return findSplit(lat, lon, radiusMeters, null); } /** * Find a location on an existing street near the given point, without actually creating any vertices or edges. * The search radius can be specified freely here because we use this function to link transit stops to streets but * also to link pointsets to streets, and currently we use different distances for these two things. * This is a nondestructive operation: it simply finds a candidate split point without modifying anything. * This function starts with a small search envelope and expands it as needed under the assumption that most * search envelopes will be close to a road. * TODO favor platforms and pedestrian paths when requested * @param lat latitude in floating point geographic coordinates (not fixed point int coordinates) * @param lon longitude in floating point geographic coordinates (not fixed point int coordinates) * @return a Split object representing a point along a sub-segment of a specific edge, or null if there are no streets nearby. */ public Split findSplit(double lat, double lon, double radiusMeters, StreetMode streetMode) { Split split = null; if (radiusMeters > 300) { split = Split.find(lat, lon, 150, this, streetMode); } if (split == null) { split = Split.find(lat, lon, radiusMeters, this, streetMode); } return split; } /** * For every stop in a TransitLayer, find or create a nearby vertex in the street layer and record the connection * between the two. */ public void associateStops (TransitLayer transitLayer) { for (Stop stop : transitLayer.stopForIndex) { int stopVertex = createAndLinkVertex(stop.stop_lat, stop.stop_lon); transitLayer.streetVertexForStop.add(stopVertex); // This is always a valid, unique vertex index. // The inverse stopForStreetVertex map is a transient, derived index and will be built later. } } public int getVertexCount() { return vertexStore.getVertexCount(); } public Envelope getEnvelope() { return envelope; } /** * We intentionally avoid using clone() on EdgeStore and VertexStore so all field copying is explicit and we can * clearly see whether we are accidentally shallow-copying any collections or data structures from the base graph. * StreetLayer has a lot more fields and most of them can be shallow-copied, so here we use clone() for convenience. * @param willBeModified must be true if the scenario to be applied will make any changes to the new StreetLayer * copy. This allows some optimizations (the lists in the StreetLayer will not be wrapped). * @return a copy of this StreetLayer to which Scenarios can be applied without affecting the original StreetLayer. * * It's questionable whether the willBeModified optimization actually affects routing speed, but in theory it * saves a comparison and an extra dereference every time we use the edge/vertex stores. * TODO check whether this actually affects speed. If not, just wrap the lists in every scenario copy. */ public StreetLayer scenarioCopy(TransportNetwork newScenarioNetwork, boolean willBeModified) { StreetLayer copy = this.clone(); if (willBeModified) { // Wrap all the edge and vertex storage in classes that make them extensible. // Indicate that the content of the new StreetLayer will be changed by giving it the scenario's scenarioId. // If the copy will not be modified, scenarioId remains unchanged to allow cached pointset linkage reuse. copy.scenarioId = newScenarioNetwork.scenarioId; copy.edgeStore = edgeStore.extendOnlyCopy(copy); // The extend-only copy of the EdgeStore also contains a new extend-only copy of the VertexStore. copy.vertexStore = copy.edgeStore.vertexStore; copy.temporaryEdgeIndex = new IntHashGrid(); } copy.parentNetwork = newScenarioNetwork; copy.baseStreetLayer = this; return copy; } // FIXME radiusMeters is now set project-wide public void associateBikeSharing(TNBuilderConfig tnBuilderConfig, int radiusMeters) { LOG.info("Builder file:{}", tnBuilderConfig.bikeRentalFile); BikeRentalBuilder bikeRentalBuilder = new BikeRentalBuilder(new File(tnBuilderConfig.bikeRentalFile)); List<BikeRentalStation> bikeRentalStations = bikeRentalBuilder.getRentalStations(); bikeRentalStationMap = new TIntObjectHashMap<>(bikeRentalStations.size()); LOG.info("Bike rental stations:{}", bikeRentalStations.size()); int numAddedStations = 0; for (BikeRentalStation bikeRentalStation: bikeRentalStations) { int streetVertexIndex = getOrCreateVertexNear(bikeRentalStation.lat, bikeRentalStation.lon, StreetMode.WALK); if (streetVertexIndex > -1) { numAddedStations++; VertexStore.Vertex vertex = vertexStore.getCursor(streetVertexIndex); vertex.setFlag(VertexStore.VertexFlag.BIKE_SHARING); bikeRentalStationMap.put(streetVertexIndex, bikeRentalStation); } } if (numAddedStations > 0) { this.bikeSharing = true; } LOG.info("Added {} out of {} stations ratio:{}", numAddedStations, bikeRentalStations.size(), numAddedStations/bikeRentalStations.size()); } public StreetLayer clone () { try { return (StreetLayer) super.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException("This exception cannot happen. This is why I love checked exceptions."); } } /** @return true iff this StreetLayer was created by a scenario, and is therefore wrapping a base StreetLayer. */ public boolean isScenarioCopy() { return baseStreetLayer != null; } /** * Create a geometry in FIXED POINT DEGREES containing all the points on all edges created or removed by the * scenario that produced this StreetLayer, buffered by radiusMeters. This is a MultiPolygon or GeometryCollection. * When there are no created or removed edges, returns an empty geometry rather than null, because we test whether * transit stops are contained within the resulting geometry. */ public Geometry scenarioEdgesBoundingGeometry(int radiusMeters) { List<Polygon> geoms = new ArrayList<>(); Edge edge = edgeStore.getCursor(); edgeStore.forEachTemporarilyAddedOrDeletedEdge(e -> { edge.seek(e); Envelope envelope = edge.getEnvelope(); GeometryUtils.expandEnvelopeFixed(envelope, radiusMeters); geoms.add((Polygon)GeometryUtils.geometryFactory.toGeometry(envelope)); }); // We can't just make a multipolygon as the component polygons may not be disjoint. Unions are pretty quick though. // The UnaryUnionOp gets its geometryFactory from the geometries it's operating on. // We need to supply one in case the list is empty, so it can return an empty geometry instead of null. Geometry result = new UnaryUnionOp(geoms, GeometryUtils.geometryFactory).union(); // logFixedPointGeometry("Unioned buffered streets", result); return result; } /** * Given a JTS Geometry in fixed-point latitude and longitude, log it as floating-point GeoJSON. */ public static void logFixedPointGeometry (String label, Geometry fixedPointGeometry) { if (fixedPointGeometry == null){ LOG.info("{} is null.", label); } else if (fixedPointGeometry.isEmpty()) { LOG.info("{} is empty.", label); } else { String geoJson = new GeometryJSON().toString(fixedDegreeGeometryToFloating(fixedPointGeometry)); if (geoJson == null) { LOG.info("Could not convert non-null geometry to GeoJSON"); } else { LOG.info("{} {}", label, geoJson); } } } /** * Finds all the P+R stations in given envelope * * Returns empty list if none are found or no P+R stations are in graph * * @param env Envelope in float degrees * @return */ public List<ParkRideParking> findParkRidesInEnvelope(Envelope env) { List<ParkRideParking> parkingRides = new ArrayList<>(); if (parkRideLocationsMap != null) { EdgeStore.Edge e = edgeStore.getCursor(); VertexStore.Vertex v = vertexStore.getCursor(); TIntSet nearbyEdges = spatialIndex.query(VertexStore.envelopeToFixed(env)); nearbyEdges.forEach(eidx -> { e.seek(eidx); if (e.getFlag(EdgeStore.EdgeFlag.LINK)) { v.seek(e.getFromVertex()); if (v.getFlag(VertexStore.VertexFlag.PARK_AND_RIDE)) { ParkRideParking parkRideParking = parkRideLocationsMap.get(e.getFromVertex()); parkingRides.add(parkRideParking); } } return true; }); } return parkingRides; } /** * Finds all the bike share stations in given envelope * * Returns empty list if none are found or no bike stations are in graph * * @param env Envelope in float degrees * @return */ public List<BikeRentalStation> findBikeSharesInEnvelope(Envelope env) { List<BikeRentalStation> bikeRentalStations = new ArrayList<>(); if (bikeRentalStationMap != null) { EdgeStore.Edge e = edgeStore.getCursor(); VertexStore.Vertex v = vertexStore.getCursor(); TIntSet nearbyEdges = spatialIndex.query(VertexStore.envelopeToFixed(env)); nearbyEdges.forEach(eidx -> { e.seek(eidx); //TODO: for now bikeshares aren't connected with link edges to the graph //if (e.getFlag(EdgeStore.EdgeFlag.LINK)) { v.seek(e.getFromVertex()); if (v.getFlag(VertexStore.VertexFlag.BIKE_SHARING)) { BikeRentalStation bikeRentalStation = bikeRentalStationMap.get(e.getFromVertex()); bikeRentalStations.add(bikeRentalStation); } //} return true; }); } return bikeRentalStations; } }
check that turn restriction from and to members are ways, addresses #276 also added some comments and clarified a variable name
src/main/java/com/conveyal/r5/streets/StreetLayer.java
check that turn restriction from and to members are ways, addresses #276
<ide><path>rc/main/java/com/conveyal/r5/streets/StreetLayer.java <ide> for (Relation.Member member : restriction.members) { <ide> if ("from".equals(member.role)) { <ide> if (from != null) { <del> LOG.error("Turn restriction {} has multiple from members, skipping", id); <add> LOG.error("Turn restriction {} has multiple 'from' members, skipping.", id); <ide> return; <ide> } <del> <add> if (member.type != OSMEntity.Type.WAY) { <add> LOG.error("Turn restriction {} has a 'from' member that is not a way, skipping.", id); <add> return; <add> } <ide> from = member; <ide> } <ide> else if ("to".equals(member.role)) { <ide> if (to != null) { <del> LOG.error("Turn restriction {} has multiple to members, skipping", id); <add> LOG.error("Turn restriction {} has multiple 'to' members, skipping.", id); <ide> return; <ide> } <del> <add> if (member.type != OSMEntity.Type.WAY) { <add> LOG.error("Turn restriction {} has a 'to' member that is not a way, skipping.", id); <add> return; <add> } <ide> to = member; <ide> } <ide> else if ("via".equals(member.role)) { <ide> return; <ide> } <ide> <del> boolean hasWays = false, hasNodes = false; <add> boolean hasViaWays = false, hasViaNodes = false; <ide> <ide> for (Relation.Member m : via) { <del> if (m.type == OSMEntity.Type.WAY) hasWays = true; <del> else if (m.type == OSMEntity.Type.NODE) hasNodes = true; <add> if (m.type == OSMEntity.Type.WAY) hasViaWays = true; <add> else if (m.type == OSMEntity.Type.NODE) hasViaNodes = true; <ide> else { <ide> LOG.error("via must be node or way, skipping restriction {}", id); <ide> return; <ide> } <ide> } <ide> <del> if (hasWays && hasNodes || hasNodes && via.size() > 1) { <add> if ((hasViaWays && hasViaNodes) || (hasViaNodes && via.size() > 1)) { <ide> LOG.error("via must be single node or one or more ways, skipping restriction {}", id); <ide> return; <ide> } <ide> <ide> EdgeStore.Edge e = edgeStore.getCursor(); <ide> <del> if (hasNodes) { <del> // via node, this is a fairly simple turn restriction. First find the relevant vertex. <add> if (hasViaNodes) { <add> // Turn restriction passes via a single node. This is a fairly simple turn restriction. <add> // First find the relevant vertex. <ide> int vertex = vertexIndexForOsmNode.get(via.get(0).id); <ide> <ide> if (vertex == -1) { <ide> return; <ide> } <ide> <del> // use array to dodge effectively final nonsense <add> // use array to dodge Java closure "effectively final" nonsense <ide> final int[] fromEdge = new int[] { -1 }; <ide> final long fromWayId = from.id; // more effectively final nonsense <ide> final boolean[] bad = new boolean[] { false };
Java
apache-2.0
c6aff1b7f0edf085d1e5e4fdc9d98a72c377315b
0
naritta/hivemall,daijyc/hivemall,NaokiStones/hivemall,NaokiStones/hivemall,tempbottle/hivemall,naritta/hivemall,daijyc/hivemall,NaokiStones/hivemall,tempbottle/hivemall,daijyc/hivemall,naritta/hivemall,tempbottle/hivemall
package hivemall.utils.lang.mutable; import hivemall.utils.lang.Copyable; import java.io.Serializable; public final class MutableInt extends Number implements Copyable<MutableInt>, Comparable<MutableInt>, Serializable { private static final long serialVersionUID = -3289272606407100628L; private int value; public MutableInt() { super(); } public MutableInt(int value) { super(); this.value = value; } public MutableInt(Number value) { super(); this.value = value.intValue(); } public int getValue() { return value; } public void setValue(int value) { this.value = value; } public void setValue(Number value) { this.value = value.intValue(); } @Override public int intValue() { return value; } @Override public long longValue() { return value; } @Override public float floatValue() { return value; } @Override public double doubleValue() { return value; } @Override public void copyTo(MutableInt another) { another.setValue(value); } @Override public void copyFrom(MutableInt another) { this.value = another.value; } @Override public int compareTo(MutableInt other) { return compare(value, other.value); } private static int compare(final int x, final int y) { return (x < y) ? -1 : ((x == y) ? 0 : 1); } @Override public boolean equals(Object obj) { if(obj instanceof MutableInt) { return value == ((MutableInt) obj).intValue(); } return false; } @Override public int hashCode() { return value; } @Override public String toString() { return String.valueOf(value); } }
src/main/hivemall/utils/lang/mutable/MutableInt.java
package hivemall.utils.lang.mutable; import hivemall.utils.lang.Copyable; import java.io.Serializable; public final class MutableInt extends Number implements Copyable<MutableInt>, Comparable<MutableInt>, Serializable { private static final long serialVersionUID = -3289272606407100628L; private int value; public MutableInt() { super(); } public MutableInt(int value) { super(); this.value = value; } public MutableInt(Number value) { super(); this.value = value.intValue(); } public int getValue() { return value; } public void setValue(int value) { this.value = value; } public void setValue(Number value) { this.value = value.intValue(); } @Override public int intValue() { return value; } @Override public long longValue() { return value; } @Override public float floatValue() { return value; } @Override public double doubleValue() { return value; } @Override public void copyTo(MutableInt another) { another.setValue(value); } @Override public void copyFrom(MutableInt another) { this.value = another.value; } @Override public int compareTo(MutableInt other) { return Integer.compare(value, other.value); } @Override public boolean equals(Object obj) { if(obj instanceof MutableInt) { return value == ((MutableInt) obj).intValue(); } return false; } @Override public int hashCode() { return value; } @Override public String toString() { return String.valueOf(value); } }
Avoid using Integer.compare() because it is supported since Java 7
src/main/hivemall/utils/lang/mutable/MutableInt.java
Avoid using Integer.compare() because it is supported since Java 7
<ide><path>rc/main/hivemall/utils/lang/mutable/MutableInt.java <ide> <ide> @Override <ide> public int compareTo(MutableInt other) { <del> return Integer.compare(value, other.value); <add> return compare(value, other.value); <add> } <add> <add> private static int compare(final int x, final int y) { <add> return (x < y) ? -1 : ((x == y) ? 0 : 1); <ide> } <ide> <ide> @Override
Java
mit
b2324057038530b8084deed7f59c1cb4eccf125d
0
chav1961/purelib,chav1961/purelib,chav1961/purelib
package chav1961.purelib.ui.swing.useful; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Set; import javax.swing.JComponent; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableModel; import chav1961.purelib.basic.PureLibSettings; import chav1961.purelib.basic.exceptions.FlowException; import chav1961.purelib.basic.exceptions.LocalizationException; import chav1961.purelib.basic.interfaces.LoggerFacade.Severity; import chav1961.purelib.cdb.CompilerUtils; import chav1961.purelib.concurrent.LightWeightListenerList; import chav1961.purelib.i18n.interfaces.Localizer; import chav1961.purelib.i18n.interfaces.Localizer.LocaleChangeListener; import chav1961.purelib.model.TableContainer; import chav1961.purelib.model.interfaces.ContentMetadataInterface.ContentNodeMetadata; import chav1961.purelib.model.interfaces.NodeMetadataOwner; import chav1961.purelib.sql.interfaces.InstanceManager; import chav1961.purelib.ui.interfaces.FormManager; import chav1961.purelib.ui.interfaces.RecordFormManager.RecordAction; import chav1961.purelib.ui.interfaces.RefreshMode; import chav1961.purelib.ui.swing.SwingUtils; public class JDataBaseTableWithMeta<K,Inst> extends JFreezableTable implements NodeMetadataOwner, LocaleChangeListener { private static final long serialVersionUID = -6707307489832770493L; private static final String CONFIRM_DELETE_TITLE = "JDataBaseTableWithMeta.confirm.delete.title"; private static final String CONFIRM_DELETE_MESSAGE = "JDataBaseTableWithMeta.confirm.delete.message"; private final ContentNodeMetadata meta; private final Localizer localizer; private final InnerTableModel<K,Inst> model; private final boolean enableManipulations; private final LightWeightListenerList<ContentChangedListener<K,Inst>> listeners = new LightWeightListenerList(ContentChangedListener.class); private FormManager<K,Inst> mgr = null; private InstanceManager<K,Inst> instMgr = null; @FunctionalInterface public static interface ContentChangedListener<K,Inst> { public enum ChangeType { INSERTED, DUPLICATED, DELETED } void process(JDataBaseTableWithMeta<K,Inst> table, ChangeType ct, K keyValue, String fieldName); } public JDataBaseTableWithMeta(final ContentNodeMetadata meta, final Localizer localizer, final boolean enableManipulations, final boolean enableEdit) throws NullPointerException, IllegalArgumentException { super(buildTableModel(meta, localizer, enableEdit), buildFreezedColumns(meta)); if (meta == null) { throw new NullPointerException("Metadata can't be null"); } else if (localizer == null) { throw new NullPointerException("Localizer can't be null"); } else { this.meta = meta; this.localizer = localizer; this.model = (InnerTableModel<K,Inst>)getSourceModel(); this.enableManipulations = enableManipulations; SwingUtils.assignActionKey(this, SwingUtils.KS_INSERT, (e)->manipulate(getSelectedRow(), SwingUtils.ACTION_INSERT), SwingUtils.ACTION_INSERT); SwingUtils.assignActionKey(this, SwingUtils.KS_DUPLICATE, (e)->manipulate(getSelectedRow(), SwingUtils.ACTION_DUPLICATE), SwingUtils.ACTION_DUPLICATE); SwingUtils.assignActionKey(this, SwingUtils.KS_DELETE, (e)->manipulate(getSelectedRow(), SwingUtils.ACTION_DELETE), SwingUtils.ACTION_DELETE); setAutoResizeMode(AUTO_RESIZE_OFF); fillLocalizedStrings(); } } @Override public void localeChanged(final Locale oldLocale, final Locale newLocale) throws LocalizationException { fillLocalizedStrings(); } @Override public ContentNodeMetadata getNodeMetadata() { return meta; } public synchronized void assignResultSet(final ResultSet rs) throws NullPointerException, IllegalArgumentException, SQLException { if (rs == null) { throw new NullPointerException("Result set can't be null"); } else if (rs.getFetchDirection() == ResultSet.TYPE_FORWARD_ONLY) { throw new IllegalArgumentException("Result set type is 'TYPE_FORWARD_ONLY'. This type is not supported for this call"); } else { this.mgr = null; this.instMgr = null; model.assignOwner(this, rs, null, null); } } public synchronized void assignResultSetAndManagers(final ResultSet rs, final FormManager<K, Inst> mgr, final InstanceManager<K, Inst> instMgr) throws NullPointerException, IllegalArgumentException, SQLException { if (rs == null) { throw new NullPointerException("Result set can't be null"); } else if (mgr == null) { throw new NullPointerException("Form manager can't be null"); } else if (instMgr == null) { throw new NullPointerException("Instance manager can't be null"); } else if (rs.getFetchDirection() == ResultSet.TYPE_FORWARD_ONLY) { throw new IllegalArgumentException("Result set type is 'TYPE_FORWARD_ONLY'. This type is not supported for this call"); } else { this.mgr = mgr; this.instMgr = instMgr; model.assignOwner(this, rs, mgr, instMgr); } } public synchronized void resetResultSetAndManagers() { mgr = null; try{model.assignOwner(null, null, null, null); } catch (SQLException exc) { SwingUtils.getNearestLogger(this).message(Severity.error, exc.getLocalizedMessage()); } } public void resizeColumns() { resizeColumns(getPreferredSize().width); } public void resizeColumns(final int width) { resizeColumns(width, model); } public void refresh() { model.fireTableDataChanged(); } public void processAction(final String action) { manipulate(editingRow, action); } public K getSelectedKey() throws SQLException { if (getSelectedRow() >= 0) { model.desc.rs.absolute(getSelectedRow() + 1); return instMgr.extractKey(model.desc.rs); } else { return null; } } public void addContentChangedListener(final ContentChangedListener<K,Inst> listener) { if (listener == null) { throw new NullPointerException("Listener to add can't be null"); } else { listeners.addListener(listener); } } public void removeContentChangedListener(final ContentChangedListener<K,Inst> listener) { if (listener == null) { throw new NullPointerException("Listener to remove can't be null"); } else { listeners.removeListener(listener); } } protected K insertRow(final Inst content) throws SQLException, FlowException { if (mgr == null) { throw new IllegalStateException("Manager is not assigned for the control"); } else { final K newKey = instMgr.extractKey(content); if (mgr.onRecord(RecordAction.INSERT, null, null, content, newKey) != RefreshMode.REJECT) { model.desc.rs.moveToInsertRow(); instMgr.storeInstance(model.desc.rs, content, false); model.desc.rs.insertRow(); model.desc.rs.moveToCurrentRow(); model.fireTableDataChanged(); return newKey; } else { return null; } } } protected K duplicateRow(final int row, final Inst sourceRow) throws SQLException, FlowException { if (mgr == null) { throw new IllegalStateException("Manager is not assigned for the control"); } else { final Inst duplicatedRow = instMgr.clone(sourceRow); final K newKey = instMgr.newKey(); instMgr.assignKey(duplicatedRow, newKey); if (mgr.onRecord(RecordAction.DUPLICATE, sourceRow, instMgr.extractKey(sourceRow), duplicatedRow, newKey) != RefreshMode.REJECT) { model.desc.rs.moveToInsertRow(); instMgr.storeInstance(model.desc.rs, duplicatedRow, false); model.desc.rs.insertRow(); model.desc.rs.moveToCurrentRow(); model.fireTableDataChanged(); return newKey; } else { return null; } } } protected K deleteRow(final int row) throws SQLException, FlowException { if (mgr == null) { throw new IllegalStateException("Manager is not assigned for the control"); } else { model.desc.rs.absolute(row); final Inst inst = loadRow(row); if (mgr.onRecord(RecordAction.DELETE, inst, instMgr.extractKey(inst), null, null) != RefreshMode.REJECT) { final K key = instMgr.extractKey(inst); model.desc.rs.deleteRow(); model.fireTableDataChanged(); return key; } else { return null; } } } protected Inst newRow() throws SQLException { return instMgr.newInstance(); } protected Inst loadRow(final int row) throws SQLException { final Inst inst = instMgr.newInstance(); instMgr.loadInstance(model.desc.rs, inst); return inst; } private void manipulate(final int row, final String action) { if (!model.rsIsReadOnly && instMgr != null && enableManipulations) { try{switch (action) { case SwingUtils.ACTION_INSERT : final K keyInserted = insertRow(newRow()); listeners.fireEvent((l)->l.process(this, ContentChangedListener.ChangeType.INSERTED, keyInserted, "")); break; case SwingUtils.ACTION_DUPLICATE : if (model.getRowCount() > 0) { model.desc.rs.absolute(row + 1); final K keyDuplicated = duplicateRow(model.desc.rs.getRow(), loadRow(model.desc.rs.getRow())); listeners.fireEvent((l)->l.process(this, ContentChangedListener.ChangeType.DUPLICATED, keyDuplicated, "")); } break; case SwingUtils.ACTION_DELETE : if (model.getRowCount() > 0) { if (new JLocalizedOptionPane(localizer).confirm(this, CONFIRM_DELETE_MESSAGE, CONFIRM_DELETE_TITLE, JOptionPane.QUESTION_MESSAGE, JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) { final K keyRemoved = deleteRow(row + 1); listeners.fireEvent((l)->l.process(this, ContentChangedListener.ChangeType.DELETED, keyRemoved, "")); } } break; default : throw new UnsupportedOperationException("Action ["+action+"] is not supported yet"); } } catch (SQLException | FlowException e) { SwingUtils.getNearestLogger(this).message(Severity.error, e,e.getLocalizedMessage()); } } } private void resizeColumns(final int width, final InnerTableModel<K, Inst> model) { final int[] sizes = new int[model.getColumnCount()]; int totalSize = 0, index = 0; for (String name : model.getMetadataChildrenNames()) { final ContentNodeMetadata meta = model.getNodeMetadata(name); if (meta.getFormatAssociated() != null && meta.getFormatAssociated().getLength() > 0) { sizes[index] = meta.getFormatAssociated().getLength(); totalSize += sizes[index++]; } else { totalSize += sizes[index++] = 10; } } final float scale = 1.0f * width / totalSize; for (int col = 0, maxCol = getColumnModel().getColumnCount(); col < maxCol; col++) { final int currentWidth = (int) (scale * sizes[col]); getColumnModel().getColumn(col).setPreferredWidth(currentWidth); } } private void fillLocalizedStrings() { } static <K, Inst> TableModel buildTableModel(final ContentNodeMetadata meta, final Localizer localizer, final boolean enableEdit) { if (meta == null) { throw new NullPointerException("Metadata can't be null"); } else if (meta.getType() != TableContainer.class) { throw new IllegalArgumentException("Metadata type ["+meta.getType().getCanonicalName()+"] doesn't declare table container. It's type must be "+TableContainer.class.getCanonicalName()); } else { final List<ContentNodeMetadata> result = new ArrayList<>(); final Set<String> names = new HashSet<>(); for (ContentNodeMetadata item : meta) { if (!names.contains(item.getName())) { if (item.getFormatAssociated() != null && item.getFormatAssociated().isUsedInList()) { result.add(item); names.add(item.getName()); } } } return new InnerTableModel<K, Inst>(meta, result.toArray(new ContentNodeMetadata[result.size()]), localizer, enableEdit); } } static String[] buildFreezedColumns(final ContentNodeMetadata meta) { final List<String> result = new ArrayList<>(); for (ContentNodeMetadata item : meta) { if (item.getFormatAssociated() != null && item.getFormatAssociated().isAnchored()) { result.add(item.getName()); } } return result.toArray(new String[result.size()]); } private static class InnerTableModel<K,Inst> extends DefaultTableModel implements NodeMetadataOwner { private static final long serialVersionUID = 4821572920544412802L; private final ContentNodeMetadata owner; private final ContentNodeMetadata[] metadata; private final Localizer localizer; private volatile ContentDesc<K, Inst> desc = null; private Inst lastRow; private boolean rsIsReadOnly = false; private InnerTableModel(final ContentNodeMetadata owner, final ContentNodeMetadata[] metadata, final Localizer localizer, final boolean enableEdit) { this.owner = owner; this.metadata = metadata; this.localizer = localizer; } @Override public ContentNodeMetadata getNodeMetadata() { return owner; } @Override public boolean hasNodeMetadata(final String childName) { if (childName == null || childName.isEmpty()) { throw new IllegalArgumentException("Child name can't be null or empty"); } else { for (ContentNodeMetadata item : metadata) { if (childName.equals(item.getName())) { return true; } } return false; } } @Override public ContentNodeMetadata getNodeMetadata(final String childName) { if (childName == null || childName.isEmpty()) { throw new IllegalArgumentException("Child name can't be null or empty"); } else { for (ContentNodeMetadata item : metadata) { if (childName.equals(item.getName())) { return item; } } throw new IllegalArgumentException("Child name ["+childName+"] not found in he model"); } } @Override public String[] getMetadataChildrenNames() { final String[] result = new String[metadata.length]; int index = 0; for (ContentNodeMetadata item : metadata) { result[index++] = item.getName(); } return result; } @Override public int getRowCount() { try{if (desc == null || desc.rs == null || desc.rs.isClosed()) { return 0; } else { final int last = desc.rs.getRow(); if (desc.rs.last()) { final int result = desc.rs.getRow(); desc.rs.absolute(last); return result; } else { desc.rs.absolute(last); return 0; } } } catch (SQLException e) { printError(e); return 0; } } @Override public int getColumnCount() { return metadata.length; } @Override public String getColumnName(final int columnIndex) { try{return localizer.getValue(metadata[columnIndex].getLabelId()); } catch (LocalizationException e) { return metadata[columnIndex].getLabelId(); } } @Override public Class<?> getColumnClass(final int columnIndex) { return CompilerUtils.toWrappedClass(metadata[columnIndex].getType()); } @Override public boolean isCellEditable(final int rowIndex, final int columnIndex) { return desc.rs != null && !rsIsReadOnly && (metadata[columnIndex].getFormatAssociated() == null || !metadata[columnIndex].getFormatAssociated().isReadOnly(true)); } @Override public Object getValueAt(final int rowIndex, final int columnIndex) { try{desc.rs.absolute(rowIndex + 1); if (desc.instMgr != null) { desc.instMgr.loadInstance(desc.rs, lastRow); } return desc.instMgr != null ? desc.instMgr.get(lastRow, metadata[columnIndex].getName()) : desc.rs.getObject(metadata[columnIndex].getName()); } catch (SQLException e) { printError(e); return null; } } @Override public void setValueAt(final Object aValue, final int rowIndex, final int columnIndex) { try{desc.rs.absolute(rowIndex + 1); desc.instMgr.loadInstance(desc.rs, lastRow); final String fieldName = metadata[columnIndex].getName(); final Object oldValue = desc.instMgr.get(lastRow, fieldName); desc.instMgr.set(lastRow, fieldName, aValue); if (desc.mgr == null || desc.mgr.onField(lastRow, desc.instMgr.extractKey(lastRow), metadata[columnIndex].getName(), oldValue, true) != RefreshMode.REJECT) { desc.rs.absolute(rowIndex + 1); desc.instMgr.storeInstance(desc.rs, lastRow, true); desc.rs.updateRow(); fireTableRowsUpdated(rowIndex, rowIndex); } else { desc.instMgr.set(lastRow, fieldName, oldValue); } } catch (SQLException | FlowException e) { printError(e); } } public ContentNodeMetadata[] getMetaData() { return metadata; } public void assignOwner(final JComponent owner, final ResultSet rs, final FormManager<K,Inst> mgr, final InstanceManager<K,Inst> instMgr) throws SQLException { this.lastRow = instMgr != null ? instMgr.newInstance() : null; this.rsIsReadOnly = rs != null && rs.getConcurrency() == ResultSet.CONCUR_READ_ONLY; this.desc = new ContentDesc<K, Inst>(rs, mgr, instMgr, owner); fireTableStructureChanged(); fireTableDataChanged(); } private void printError(final Exception exc) { if (desc.owner != null) { SwingUtils.getNearestLogger(desc.owner).message(Severity.error, exc.getLocalizedMessage()); } else { PureLibSettings.CURRENT_LOGGER.message(Severity.error, exc.getLocalizedMessage()); } } static class ContentDesc<K, Inst> { final ResultSet rs; final FormManager<K, Inst> mgr; final InstanceManager<K, Inst> instMgr; final JComponent owner; ContentDesc(final ResultSet rs, final FormManager<K, Inst> mgr, final InstanceManager<K, Inst> instMgr, final JComponent owner) throws SQLException { this.rs = rs; this.mgr = mgr; this.instMgr = instMgr; this.owner = owner; } } } }
src/main/java/chav1961/purelib/ui/swing/useful/JDataBaseTableWithMeta.java
package chav1961.purelib.ui.swing.useful; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Set; import javax.swing.JComponent; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableModel; import chav1961.purelib.basic.PureLibSettings; import chav1961.purelib.basic.exceptions.FlowException; import chav1961.purelib.basic.exceptions.LocalizationException; import chav1961.purelib.basic.interfaces.LoggerFacade.Severity; import chav1961.purelib.cdb.CompilerUtils; import chav1961.purelib.concurrent.LightWeightListenerList; import chav1961.purelib.i18n.interfaces.Localizer; import chav1961.purelib.i18n.interfaces.Localizer.LocaleChangeListener; import chav1961.purelib.model.TableContainer; import chav1961.purelib.model.interfaces.ContentMetadataInterface.ContentNodeMetadata; import chav1961.purelib.model.interfaces.NodeMetadataOwner; import chav1961.purelib.sql.interfaces.InstanceManager; import chav1961.purelib.ui.interfaces.FormManager; import chav1961.purelib.ui.interfaces.RecordFormManager.RecordAction; import chav1961.purelib.ui.interfaces.RefreshMode; import chav1961.purelib.ui.swing.SwingUtils; public class JDataBaseTableWithMeta<K,Inst> extends JFreezableTable implements NodeMetadataOwner, LocaleChangeListener { private static final long serialVersionUID = -6707307489832770493L; private static final String CONFIRM_DELETE_TITLE = "JDataBaseTableWithMeta.confirm.delete.title"; private static final String CONFIRM_DELETE_MESSAGE = "JDataBaseTableWithMeta.confirm.delete.message"; private final ContentNodeMetadata meta; private final Localizer localizer; private final InnerTableModel<K,Inst> model; private final boolean enableManipulations; private final LightWeightListenerList<ContentChangedListener<K,Inst>> listeners = new LightWeightListenerList(ContentChangedListener.class); private FormManager<K,Inst> mgr = null; private InstanceManager<K,Inst> instMgr = null; @FunctionalInterface public static interface ContentChangedListener<K,Inst> { public enum ChangeType { INSERTED, DUPLICATED, DELETED } void process(JDataBaseTableWithMeta<K,Inst> table, ChangeType ct, K keyValue, String fieldName); } public JDataBaseTableWithMeta(final ContentNodeMetadata meta, final Localizer localizer, final boolean enableManipulations, final boolean enableEdit) throws NullPointerException, IllegalArgumentException { super(buildTableModel(meta, localizer, enableEdit), buildFreezedColumns(meta)); if (meta == null) { throw new NullPointerException("Metadata can't be null"); } else if (localizer == null) { throw new NullPointerException("Localizer can't be null"); } else { this.meta = meta; this.localizer = localizer; this.model = (InnerTableModel<K,Inst>)getSourceModel(); this.enableManipulations = enableManipulations; SwingUtils.assignActionKey(this, SwingUtils.KS_INSERT, (e)->manipulate(getSelectedRow(), SwingUtils.ACTION_INSERT), SwingUtils.ACTION_INSERT); SwingUtils.assignActionKey(this, SwingUtils.KS_DUPLICATE, (e)->manipulate(getSelectedRow(), SwingUtils.ACTION_DUPLICATE), SwingUtils.ACTION_DUPLICATE); SwingUtils.assignActionKey(this, SwingUtils.KS_DELETE, (e)->manipulate(getSelectedRow(), SwingUtils.ACTION_DELETE), SwingUtils.ACTION_DELETE); setAutoResizeMode(AUTO_RESIZE_OFF); fillLocalizedStrings(); } } @Override public void localeChanged(final Locale oldLocale, final Locale newLocale) throws LocalizationException { fillLocalizedStrings(); } @Override public ContentNodeMetadata getNodeMetadata() { return meta; } public synchronized void assignResultSet(final ResultSet rs) throws NullPointerException, IllegalArgumentException, SQLException { if (rs == null) { throw new NullPointerException("Result set can't be null"); } else if (rs.getFetchDirection() == ResultSet.TYPE_FORWARD_ONLY) { throw new IllegalArgumentException("Result set type is 'TYPE_FORWARD_ONLY'. This type is not supported for this call"); } else { this.mgr = null; this.instMgr = null; model.assignOwner(this, rs, null, null); } } public synchronized void assignResultSetAndManagers(final ResultSet rs, final FormManager<K, Inst> mgr, final InstanceManager<K, Inst> instMgr) throws NullPointerException, IllegalArgumentException, SQLException { if (rs == null) { throw new NullPointerException("Result set can't be null"); } else if (mgr == null) { throw new NullPointerException("Form manager can't be null"); } else if (instMgr == null) { throw new NullPointerException("Instance manager can't be null"); } else if (rs.getFetchDirection() == ResultSet.TYPE_FORWARD_ONLY) { throw new IllegalArgumentException("Result set type is 'TYPE_FORWARD_ONLY'. This type is not supported for this call"); } else { this.mgr = mgr; this.instMgr = instMgr; model.assignOwner(this, rs, mgr, instMgr); } } public synchronized void resetResultSetAndManagers() { mgr = null; try{model.assignOwner(null, null, null, null); } catch (SQLException exc) { SwingUtils.getNearestLogger(this).message(Severity.error, exc.getLocalizedMessage()); } } public void resizeColumns() { resizeColumns(getPreferredSize().width); } public void resizeColumns(final int width) { resizeColumns(width, model); } public void refresh() { model.fireTableDataChanged(); } public void processAction(final String action) { manipulate(editingRow, action); } public K getSelectedKey() throws SQLException { if (getSelectedRow() >= 0) { model.desc.rs.absolute(getSelectedRow() + 1); return instMgr.extractKey(model.desc.rs); } else { return null; } } public void addContentChangedListener(final ContentChangedListener<K,Inst> listener) { if (listener == null) { throw new NullPointerException("Listener to add can't be null"); } else { listeners.addListener(listener); } } public void removeContentChangedListener(final ContentChangedListener<K,Inst> listener) { if (listener == null) { throw new NullPointerException("Listener to remove can't be null"); } else { listeners.removeListener(listener); } } protected K insertRow(final Inst content) throws SQLException, FlowException { if (mgr == null) { throw new IllegalStateException("Manager is not assigned for the control"); } else { final K newKey = instMgr.extractKey(content); if (mgr.onRecord(RecordAction.INSERT, null, null, content, newKey) != RefreshMode.REJECT) { model.desc.rs.moveToInsertRow(); instMgr.storeInstance(model.desc.rs, content, false); model.desc.rs.insertRow(); model.desc.rs.moveToCurrentRow(); model.fireTableDataChanged(); return newKey; } else { return null; } } } protected K duplicateRow(final int row, final Inst sourceRow) throws SQLException, FlowException { if (mgr == null) { throw new IllegalStateException("Manager is not assigned for the control"); } else { final Inst duplicatedRow = instMgr.clone(sourceRow); final K newKey = instMgr.newKey(); instMgr.assignKey(duplicatedRow, newKey); if (mgr.onRecord(RecordAction.DUPLICATE, sourceRow, instMgr.extractKey(sourceRow), duplicatedRow, newKey) != RefreshMode.REJECT) { model.desc.rs.moveToInsertRow(); instMgr.storeInstance(model.desc.rs, duplicatedRow, false); model.desc.rs.insertRow(); model.desc.rs.moveToCurrentRow(); model.fireTableDataChanged(); return newKey; } else { return null; } } } protected K deleteRow(final int row) throws SQLException, FlowException { if (mgr == null) { throw new IllegalStateException("Manager is not assigned for the control"); } else { model.desc.rs.absolute(row); final Inst inst = loadRow(row); if (mgr.onRecord(RecordAction.DELETE, inst, instMgr.extractKey(inst), null, null) != RefreshMode.REJECT) { final K key = instMgr.extractKey(inst); model.desc.rs.deleteRow(); model.fireTableDataChanged(); return key; } else { return null; } } } protected Inst newRow() throws SQLException { return instMgr.newInstance(); } protected Inst loadRow(final int row) throws SQLException { final Inst inst = instMgr.newInstance(); instMgr.loadInstance(model.desc.rs, inst); return inst; } private void manipulate(final int row, final String action) { if (!model.rsIsReadOnly && instMgr != null && enableManipulations) { try{switch (action) { case SwingUtils.ACTION_INSERT : final K keyInserted = insertRow(newRow()); listeners.fireEvent((l)->l.process(this, ContentChangedListener.ChangeType.INSERTED, keyInserted, "")); break; case SwingUtils.ACTION_DUPLICATE : if (model.getRowCount() > 0) { model.desc.rs.absolute(row + 1); final K keyDuplicated = duplicateRow(model.desc.rs.getRow(), loadRow(model.desc.rs.getRow())); listeners.fireEvent((l)->l.process(this, ContentChangedListener.ChangeType.DUPLICATED, keyDuplicated, "")); } break; case SwingUtils.ACTION_DELETE : if (model.getRowCount() > 0) { if (new JLocalizedOptionPane(localizer).confirm(this, CONFIRM_DELETE_MESSAGE, CONFIRM_DELETE_TITLE, JOptionPane.QUESTION_MESSAGE, JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) { final K keyRemoved = deleteRow(row + 1); listeners.fireEvent((l)->l.process(this, ContentChangedListener.ChangeType.DELETED, keyRemoved, "")); } } break; default : throw new UnsupportedOperationException("Action ["+action+"] is not supported yet"); } } catch (SQLException | FlowException e) { SwingUtils.getNearestLogger(this).message(Severity.error, e,e.getLocalizedMessage()); } } } private void resizeColumns(final int width, final InnerTableModel<K, Inst> model) { final int[] sizes = new int[model.getColumnCount()]; int totalSize = 0, index = 0; for (String name : model.getMetadataChildrenNames()) { final ContentNodeMetadata meta = model.getNodeMetadata(name); if (meta.getFormatAssociated() != null && meta.getFormatAssociated().getLength() > 0) { sizes[index] = meta.getFormatAssociated().getLength(); totalSize += sizes[index++]; } else { totalSize += sizes[index++] = 10; } } final float scale = 1.0f * width / totalSize; for (int col = 0, maxCol = getColumnModel().getColumnCount(); col < maxCol; col++) { final int currentWidth = (int) (scale * sizes[col]); getColumnModel().getColumn(col).setPreferredWidth(currentWidth); } } private void fillLocalizedStrings() { } static <K, Inst> TableModel buildTableModel(final ContentNodeMetadata meta, final Localizer localizer, final boolean enableEdit) { if (meta == null) { throw new NullPointerException("Metadata can't be null"); } else if (meta.getType() != TableContainer.class) { throw new IllegalArgumentException("Metadata type ["+meta.getType().getCanonicalName()+"] doesn't declare table container. It's type must be "+TableContainer.class.getCanonicalName()); } else { final List<ContentNodeMetadata> result = new ArrayList<>(); final Set<String> names = new HashSet<>(); for (ContentNodeMetadata item : meta) { if (!names.contains(item.getName())) { if (item.getFormatAssociated() != null && item.getFormatAssociated().isUsedInList()) { result.add(item); names.add(item.getName()); } } } return new InnerTableModel<K, Inst>(meta, result.toArray(new ContentNodeMetadata[result.size()]), localizer, enableEdit); } } static String[] buildFreezedColumns(final ContentNodeMetadata meta) { final List<String> result = new ArrayList<>(); for (ContentNodeMetadata item : meta) { if (item.getFormatAssociated() != null && item.getFormatAssociated().isAnchored()) { result.add(item.getName()); } } return result.toArray(new String[result.size()]); } private static class InnerTableModel<K,Inst> extends DefaultTableModel implements NodeMetadataOwner { private static final long serialVersionUID = 4821572920544412802L; private final ContentNodeMetadata owner; private final ContentNodeMetadata[] metadata; private final Localizer localizer; private volatile ContentDesc<K, Inst> desc = null; private Inst lastRow; private boolean rsIsReadOnly = false; private InnerTableModel(final ContentNodeMetadata owner, final ContentNodeMetadata[] metadata, final Localizer localizer, final boolean enableEdit) { this.owner = owner; this.metadata = metadata; this.localizer = localizer; } @Override public ContentNodeMetadata getNodeMetadata() { return owner; } @Override public boolean hasNodeMetadata(final String childName) { if (childName == null || childName.isEmpty()) { throw new IllegalArgumentException("Child name can't be null or empty"); } else { for (ContentNodeMetadata item : metadata) { if (childName.equals(item.getName())) { return true; } } return false; } } @Override public ContentNodeMetadata getNodeMetadata(final String childName) { if (childName == null || childName.isEmpty()) { throw new IllegalArgumentException("Child name can't be null or empty"); } else { for (ContentNodeMetadata item : metadata) { if (childName.equals(item.getName())) { return item; } } throw new IllegalArgumentException("Child name ["+childName+"] not found in he model"); } } @Override public String[] getMetadataChildrenNames() { final String[] result = new String[metadata.length]; int index = 0; for (ContentNodeMetadata item : metadata) { result[index++] = item.getName(); } return result; } @Override public int getRowCount() { try{if (desc == null || desc.rs == null || desc.rs.isClosed()) { return 0; } else { final int last = desc.rs.getRow(); if (desc.rs.last()) { final int result = desc.rs.getRow(); desc.rs.absolute(last); return result; } else { desc.rs.absolute(last); return 0; } } } catch (SQLException e) { printError(e); return 0; } } @Override public int getColumnCount() { return metadata.length; } @Override public String getColumnName(final int columnIndex) { try{return localizer.getValue(metadata[columnIndex].getLabelId()); } catch (LocalizationException e) { return metadata[columnIndex].getLabelId(); } } @Override public Class<?> getColumnClass(final int columnIndex) { return CompilerUtils.toWrappedClass(metadata[columnIndex].getType()); } @Override public boolean isCellEditable(final int rowIndex, final int columnIndex) { return desc.rs != null && !rsIsReadOnly && (metadata[columnIndex].getFormatAssociated() == null || !metadata[columnIndex].getFormatAssociated().isReadOnly(true)); } @Override public Object getValueAt(final int rowIndex, final int columnIndex) { try{desc.rs.absolute(rowIndex + 1); if (desc.instMgr != null) { desc.instMgr.loadInstance(desc.rs, lastRow); } return desc.instMgr != null ? desc.instMgr.get(lastRow, metadata[columnIndex].getName()) : desc.rs.getObject(metadata[columnIndex].getName()); } catch (SQLException e) { printError(e); return null; } } @Override public void setValueAt(final Object aValue, final int rowIndex, final int columnIndex) { try{desc.rs.absolute(rowIndex + 1); desc.instMgr.loadInstance(desc.rs, lastRow); final String fieldName = metadata[columnIndex].getName(); final Object oldValue = desc.instMgr.get(lastRow, fieldName); desc.instMgr.set(lastRow, fieldName, aValue); if (desc.mgr == null || desc.mgr.onField(lastRow, desc.instMgr.extractKey(lastRow), metadata[columnIndex].getName(), oldValue, true) != RefreshMode.REJECT) { desc.rs.absolute(rowIndex + 1); desc.instMgr.storeInstance(desc.rs, lastRow, true); desc.rs.updateRow(); fireTableRowsUpdated(rowIndex, rowIndex); } else { desc.instMgr.set(lastRow, fieldName, oldValue); } } catch (SQLException | FlowException e) { printError(e); } } public ContentNodeMetadata[] getMetaData() { return metadata; } public void assignOwner(final JComponent owner, final ResultSet rs, final FormManager<K,Inst> mgr, final InstanceManager<K,Inst> instMgr) throws SQLException { this.lastRow = instMgr != null ? instMgr.newInstance() : null; this.rsIsReadOnly = rs != null && rs.getConcurrency() == ResultSet.CONCUR_READ_ONLY; this.desc = new ContentDesc<K, Inst>(rs, mgr, instMgr, owner); fireTableStructureChanged(); fireTableDataChanged(); } private void printError(final Exception exc) { if (desc.owner != null) { SwingUtils.getNearestLogger(desc.owner).message(Severity.error, exc.getLocalizedMessage()); } else { PureLibSettings.CURRENT_LOGGER.message(Severity.error, exc.getLocalizedMessage()); } } static class ContentDesc<K, Inst> { final ResultSet rs; final FormManager<K, Inst> mgr; final InstanceManager<K, Inst> instMgr; final JComponent owner; ContentDesc(final ResultSet rs, final FormManager<K, Inst> mgr, final InstanceManager<K, Inst> instMgr, final JComponent owner) throws SQLException { this.rs = rs; this.mgr = mgr; this.instMgr = instMgr; this.owner = owner; } } } }
DAily commit
src/main/java/chav1961/purelib/ui/swing/useful/JDataBaseTableWithMeta.java
DAily commit
<ide><path>rc/main/java/chav1961/purelib/ui/swing/useful/JDataBaseTableWithMeta.java <ide> private final ContentNodeMetadata[] metadata; <ide> private final Localizer localizer; <ide> private volatile ContentDesc<K, Inst> desc = null; <del> private Inst lastRow; <add> private Inst lastRow; <ide> private boolean rsIsReadOnly = false; <ide> <ide> private InnerTableModel(final ContentNodeMetadata owner, final ContentNodeMetadata[] metadata, final Localizer localizer, final boolean enableEdit) {
Java
agpl-3.0
c9b975f09ff7b3d5678957befbefd70f278a2e7d
0
automenta/java_dann
/****************************************************************************** * * * Copyright: (c) Syncleus, Inc. * * * * You may redistribute and modify this source code under the terms and * * conditions of the Open Source Community License - Type C version 1.0 * * or any later version as published by Syncleus, Inc. at www.syncleus.com. * * There should be a copy of the license included with this file. If a copy * * of the license is not included you are granted no right to distribute or * * otherwise use this file except through a legal and valid license. You * * should also contact Syncleus, Inc. at the information below if you cannot * * find a license: * * * * Syncleus, Inc. * * 2604 South 12th Street * * Philadelphia, PA 19148 * * * ******************************************************************************/ package com.syncleus.dann.graph; import com.syncleus.dann.math.set.Combinations; import java.util.*; public abstract class AbstractGraph<N, E extends Edge<? extends N>, W extends Walk<? extends N, ? extends E>> implements Graph<N,E,W> { public int getDegree(N node) { List<E> adjacentEdges = this.getEdges(node); int degree = 0; for(E adjacentEdge : adjacentEdges) for(N adjacentNode : adjacentEdge.getNodes()) if(adjacentNode == node) degree++; return degree; } public boolean isConnected() { Set<N> nodes = this.getNodes(); for(N fromNode : nodes) for(N toNode : nodes) if((toNode != fromNode)&&(!this.isConnected(toNode, fromNode))) return false; return true; } public Set<Graph<N,E,W>> getConnectedComponents() { return null; } public boolean isMaximalSubgraph(Graph<? extends N, ? extends E, ? extends W> subgraph) { if( !this.isSubGraph(subgraph)) return false; //find all edges in the parent graph, but not in the subgraph final List<E> exclusiveParentEdges = this.getEdges(); final List<? extends E> subedges = subgraph.getEdges(); exclusiveParentEdges.removeAll(subedges); //check to make sure none of the edges exclusive to the parent graph //connect to any of the nodes in the subgraph. final Set<? extends N> subnodes = subgraph.getNodes(); for(E exclusiveParentEdge : exclusiveParentEdges) for(N exclusiveParentNode : exclusiveParentEdge.getNodes()) if(subnodes.contains(exclusiveParentNode)) return false; //passed all the tests, must be maximal return true; } private SimpleGraph deleteFromGraph(Set<? extends N> nodes, List<? extends E> edges) { //remove the nodes final Set cutNodes = this.getNodes(); cutNodes.removeAll(nodes); //remove the edges final List<Edge> cutEdges = new ArrayList<Edge>(this.getEdges()); for(E edge : edges) cutEdges.remove(edge); //remove any remaining edges which connect to removed nodes //also replace edges that have one removed node but still have //2 or more remaining nodes with a new edge. final List<Edge> removeEdges = new ArrayList(); final List<Edge> addEdges = new ArrayList(); for(Edge cutEdge : cutEdges) { final List<? extends N> cutEdgeNeighbors = cutEdge.getNodes(); cutEdgeNeighbors.removeAll(cutNodes); if( cutEdgeNeighbors.size() != cutEdge.getNodes().size()) removeEdges.add(cutEdge); if( cutEdgeNeighbors.size() > 1) addEdges.add(new SimpleEdge(cutEdgeNeighbors)); } for(Edge removeEdge : removeEdges) cutEdges.remove(removeEdge); cutEdges.addAll(addEdges); //check if a graph fromt he new set of edges and nodes is still //connected return new SimpleGraph(cutNodes, cutEdges); } public boolean isCut(Set<? extends N> nodes, List<? extends E> edges) { return this.deleteFromGraph(nodes, edges).isConnected(); } public boolean isCut(Set<? extends N> nodes, List<? extends E> edges, N begin, N end) { return this.deleteFromGraph(nodes, edges).isConnected(begin, end); } public boolean isCut(Set<? extends N> nodes) { return this.isCut(nodes, new ArrayList<E>()); } public boolean isCut(List<? extends E> edges) { return this.isCut(new HashSet<N>(), edges); } public boolean isCut(N node) { return this.isCut(Collections.singleton(node), new ArrayList<E>()); } public boolean isCut(E edge) { return this.isCut(new HashSet<N>(), Collections.singletonList(edge)); } public boolean isCut(Set<? extends N> nodes, N begin, N end) { return this.isCut(nodes, new ArrayList<E>(), begin, end); } public boolean isCut(List<? extends E> edges, N begin, N end) { return this.isCut(new HashSet<N>(), edges, begin, end); } public boolean isCut(N node, N begin, N end) { return this.isCut(Collections.singleton(node), new ArrayList<E>(), begin, end); } public boolean isCut(E edge, N begin, N end) { return this.isCut(new HashSet<N>(), Collections.singletonList(edge), begin, end); } public int getNodeConnectivity() { final Set<Set<N>> combinations = Combinations.everyCombination(this.getNodes()); final SortedSet<Set<N>> sortedCombinations = new TreeSet<Set<N>>(new SizeComparator()); sortedCombinations.addAll(combinations); for(Set<N> cutNodes : combinations) if(this.isCut(cutNodes)) return cutNodes.size(); return this.getNodes().size(); } public int getEdgeConnectivity() { final Set<List<E>> combinations = Combinations.everyCombination(this.getEdges()); final SortedSet<List<E>> sortedCombinations = new TreeSet<List<E>>(new SizeComparator()); sortedCombinations.addAll(combinations); for(List<E> cutEdges : combinations) if(this.isCut(cutEdges)) return cutEdges.size(); return this.getEdges().size(); } public int getNodeConnectivity(N begin, N end) { final Set<Set<N>> combinations = Combinations.everyCombination(this.getNodes()); final SortedSet<Set<N>> sortedCombinations = new TreeSet<Set<N>>(new SizeComparator()); sortedCombinations.addAll(combinations); for(Set<N> cutNodes : combinations) if(this.isCut(cutNodes, begin, end)) return cutNodes.size(); return this.getNodes().size(); } public int getEdgeConnectivity(N begin, N end) { final Set<List<E>> combinations = Combinations.everyCombination(this.getEdges()); final SortedSet<List<E>> sortedCombinations = new TreeSet<List<E>>(new SizeComparator()); sortedCombinations.addAll(combinations); for(List<E> cutEdges : combinations) if(this.isCut(cutEdges, begin, end)) return cutEdges.size(); return this.getEdges().size(); } public boolean isComplete() { for(N startNode : this.getNodes()) for(N endNode : this.getNodes()) if(!startNode.equals(endNode)) if(!this.getTraversableNeighbors(startNode).contains(endNode)) return false; return true; } public int getOrder() { return this.getNodes().size(); } public int getCycleCount() { return 0; } public boolean isPancyclic() { return false; } public int getGirth() { return 0; } public int getCircumference() { return 0; } public boolean isTraceable() { return false; } public boolean isSpanning(W walk) { return false; } public boolean isSpanning(TreeGraph graph) { return false; } public boolean isTraversable() { return false; } public boolean isEularian(W walk) { return false; } public boolean isTree() { return false; } public boolean isSubGraph(Graph<? extends N, ? extends E, ? extends W> subgraph) { Set<N> nodes = this.getNodes(); Set<? extends N> subnodes = subgraph.getNodes(); for(N subnode : subnodes) if( !nodes.contains(subnode) ) return false; List<E> edges = this.getEdges(); List<? extends E> subedges = subgraph.getEdges(); for(E subedge : subedges) if( !edges.contains(subedge)) return false; return true; } public boolean isKnot(Graph<? extends N, ? extends E, ? extends W> subGraph) { return false; } public int getTotalDegree() { return 0; } public boolean isMultigraph() { return false; } public boolean isIsomorphic(Graph<? extends N, ? extends E, ? extends W> isomorphicGraph) { return false; } public boolean isHomomorphic(Graph<? extends N, ? extends E, ? extends W> homomorphicGraph) { return false; } public boolean isRegular() { return false; } private static class SizeComparator<O> implements Comparator<Collection> { public int compare(Collection first, Collection second) { if(first.size() < second.size()) return -1; else if(first.size() > second.size()) return 1; return 0; } @Override public boolean equals(Object compareWith) { if(compareWith instanceof SizeComparator) return true; return false; } @Override public int hashCode() { return super.hashCode(); } } }
src/com/syncleus/dann/graph/AbstractGraph.java
/****************************************************************************** * * * Copyright: (c) Syncleus, Inc. * * * * You may redistribute and modify this source code under the terms and * * conditions of the Open Source Community License - Type C version 1.0 * * or any later version as published by Syncleus, Inc. at www.syncleus.com. * * There should be a copy of the license included with this file. If a copy * * of the license is not included you are granted no right to distribute or * * otherwise use this file except through a legal and valid license. You * * should also contact Syncleus, Inc. at the information below if you cannot * * find a license: * * * * Syncleus, Inc. * * 2604 South 12th Street * * Philadelphia, PA 19148 * * * ******************************************************************************/ package com.syncleus.dann.graph; import com.syncleus.dann.math.set.Combinations; import java.util.*; public abstract class AbstractGraph<N, E extends Edge<? extends N>, W extends Walk<? extends N, ? extends E>> implements Graph<N,E,W> { public int getDegree(N node) { List<E> adjacentEdges = this.getEdges(node); int degree = 0; for(E adjacentEdge : adjacentEdges) for(N adjacentNode : adjacentEdge.getNodes()) if(adjacentNode == node) degree++; return degree; } public boolean isConnected() { Set<N> nodes = this.getNodes(); for(N fromNode : nodes) for(N toNode : nodes) if((toNode != fromNode)&&(!this.isConnected(toNode, fromNode))) return false; return true; } public Set<Graph<N,E,W>> getConnectedComponents() { return null; } public boolean isMaximalSubgraph(Graph<? extends N, ? extends E, ? extends W> subgraph) { if( !this.isSubGraph(subgraph)) return false; //find all edges in the parent graph, but not in the subgraph final List<E> exclusiveParentEdges = this.getEdges(); final List<? extends E> subedges = subgraph.getEdges(); exclusiveParentEdges.removeAll(subedges); //check to make sure none of the edges exclusive to the parent graph //connect to any of the nodes in the subgraph. final Set<? extends N> subnodes = subgraph.getNodes(); for(E exclusiveParentEdge : exclusiveParentEdges) for(N exclusiveParentNode : exclusiveParentEdge.getNodes()) if(subnodes.contains(exclusiveParentNode)) return false; //passed all the tests, must be maximal return true; } private SimpleGraph deleteFromGraph(Set<? extends N> nodes, List<? extends E> edges) { //remove the nodes final Set cutNodes = this.getNodes(); cutNodes.removeAll(nodes); //remove the edges final List<Edge> cutEdges = new ArrayList<Edge>(this.getEdges()); for(E edge : edges) cutEdges.remove(edge); //remove any remaining edges which connect to removed nodes //also replace edges that have one removed node but still have //2 or more remaining nodes with a new edge. final List<Edge> removeEdges = new ArrayList(); final List<Edge> addEdges = new ArrayList(); for(Edge cutEdge : cutEdges) { final List<? extends N> cutEdgeNeighbors = cutEdge.getNodes(); cutEdgeNeighbors.removeAll(cutNodes); if( cutEdgeNeighbors.size() != cutEdge.getNodes().size()) removeEdges.add(cutEdge); if( cutEdgeNeighbors.size() > 1) addEdges.add(new SimpleEdge(cutEdgeNeighbors)); } for(Edge removeEdge : removeEdges) cutEdges.remove(removeEdge); cutEdges.addAll(addEdges); //check if a graph fromt he new set of edges and nodes is still //connected return new SimpleGraph(cutNodes, cutEdges); } public boolean isCut(Set<? extends N> nodes, List<? extends E> edges) { return this.deleteFromGraph(nodes, edges).isConnected(); } public boolean isCut(Set<? extends N> nodes, List<? extends E> edges, N begin, N end) { return this.deleteFromGraph(nodes, edges).isConnected(begin, end); } public boolean isCut(Set<? extends N> nodes) { return this.isCut(nodes, new ArrayList<E>()); } public boolean isCut(List<? extends E> edges) { return this.isCut(new HashSet<N>(), edges); } public boolean isCut(N node) { return this.isCut(Collections.singleton(node), new ArrayList<E>()); } public boolean isCut(E edge) { return this.isCut(new HashSet<N>(), Collections.singletonList(edge)); } public boolean isCut(Set<? extends N> nodes, N begin, N end) { return this.isCut(nodes, new ArrayList<E>(), begin, end); } public boolean isCut(List<? extends E> edges, N begin, N end) { return this.isCut(new HashSet<N>(), edges, begin, end); } public boolean isCut(N node, N begin, N end) { return this.isCut(Collections.singleton(node), new ArrayList<E>(), begin, end); } public boolean isCut(E edge, N begin, N end) { return this.isCut(new HashSet<N>(), Collections.singletonList(edge), begin, end); } public int getNodeConnectivity() { final Set<Set<N>> combinations = Combinations.everyCombination(this.getNodes()); final SortedSet<Set<N>> sortedCombinations = new TreeSet<Set<N>>(new SizeComparator()); sortedCombinations.addAll(combinations); for(Set<N> cutNodes : combinations) if(this.isCut(cutNodes)) return cutNodes.size(); return this.getNodes().size(); } public int getEdgeConnectivity() { final Set<List<E>> combinations = Combinations.everyCombination(this.getEdges()); final SortedSet<List<E>> sortedCombinations = new TreeSet<List<E>>(new SizeComparator()); sortedCombinations.addAll(combinations); for(List<E> cutEdges : combinations) if(this.isCut(cutEdges)) return cutEdges.size(); return this.getEdges().size(); } public int getNodeConnectivity(N begin, N end) { return 0; } public int getEdgeConnectivity(N begin, N end) { return 0; } public boolean isComplete() { return false; } public int getOrder() { return 0; } public int getCycleCount() { return 0; } public boolean isPancyclic() { return false; } public int getGirth() { return 0; } public int getCircumference() { return 0; } public boolean isTraceable() { return false; } public boolean isSpanning(W walk) { return false; } public boolean isSpanning(TreeGraph graph) { return false; } public boolean isTraversable() { return false; } public boolean isEularian(W walk) { return false; } public boolean isTree() { return false; } public boolean isSubGraph(Graph<? extends N, ? extends E, ? extends W> subgraph) { Set<N> nodes = this.getNodes(); Set<? extends N> subnodes = subgraph.getNodes(); for(N subnode : subnodes) if( !nodes.contains(subnode) ) return false; List<E> edges = this.getEdges(); List<? extends E> subedges = subgraph.getEdges(); for(E subedge : subedges) if( !edges.contains(subedge)) return false; return true; } public boolean isKnot(Graph<? extends N, ? extends E, ? extends W> subGraph) { return false; } public int getTotalDegree() { return 0; } public boolean isMultigraph() { return false; } public boolean isIsomorphic(Graph<? extends N, ? extends E, ? extends W> isomorphicGraph) { return false; } public boolean isHomomorphic(Graph<? extends N, ? extends E, ? extends W> homomorphicGraph) { return false; } public boolean isRegular() { return false; } private static class SizeComparator<O> implements Comparator<Collection> { public int compare(Collection first, Collection second) { if(first.size() < second.size()) return -1; else if(first.size() > second.size()) return 1; return 0; } @Override public boolean equals(Object compareWith) { if(compareWith instanceof SizeComparator) return true; return false; } @Override public int hashCode() { return super.hashCode(); } } }
Expanded some stub methods in the graph package
src/com/syncleus/dann/graph/AbstractGraph.java
Expanded some stub methods in the graph package
<ide><path>rc/com/syncleus/dann/graph/AbstractGraph.java <ide> <ide> public int getNodeConnectivity(N begin, N end) <ide> { <del> return 0; <add> final Set<Set<N>> combinations = Combinations.everyCombination(this.getNodes()); <add> final SortedSet<Set<N>> sortedCombinations = new TreeSet<Set<N>>(new SizeComparator()); <add> sortedCombinations.addAll(combinations); <add> for(Set<N> cutNodes : combinations) <add> if(this.isCut(cutNodes, begin, end)) <add> return cutNodes.size(); <add> return this.getNodes().size(); <ide> } <ide> <ide> public int getEdgeConnectivity(N begin, N end) <ide> { <del> return 0; <add> final Set<List<E>> combinations = Combinations.everyCombination(this.getEdges()); <add> final SortedSet<List<E>> sortedCombinations = new TreeSet<List<E>>(new SizeComparator()); <add> sortedCombinations.addAll(combinations); <add> for(List<E> cutEdges : combinations) <add> if(this.isCut(cutEdges, begin, end)) <add> return cutEdges.size(); <add> return this.getEdges().size(); <ide> } <ide> <ide> public boolean isComplete() <ide> { <del> return false; <add> for(N startNode : this.getNodes()) <add> for(N endNode : this.getNodes()) <add> if(!startNode.equals(endNode)) <add> if(!this.getTraversableNeighbors(startNode).contains(endNode)) <add> return false; <add> return true; <ide> } <ide> <ide> public int getOrder() <ide> { <del> return 0; <add> return this.getNodes().size(); <ide> } <ide> <ide> public int getCycleCount()
Java
apache-2.0
afbac33dc1959a91c20e9f8925fe2122e83e1d8d
0
sasmit4it/JqRepo
package pack; public class Tester { public static void main(String[] args) { System.out.println("runnertyoonmn"); System.out.println("local.."); } }
jQueryProj/src/pack/Tester.java
package pack; public class Tester { public static void main(String[] args) { System.out.println("runnertyoonmn"); } }
six comm
jQueryProj/src/pack/Tester.java
six comm
<ide><path>QueryProj/src/pack/Tester.java <ide> <ide> public static void main(String[] args) { <ide> System.out.println("runnertyoonmn"); <add> System.out.println("local.."); <ide> } <ide> <ide> }
Java
apache-2.0
cdd3165071d8be657c3f0c976b97774063e3e47b
0
TangHao1987/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,ol-loginov/intellij-community,ftomassetti/intellij-community,pwoodworth/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,ibinti/intellij-community,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,holmes/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,jagguli/intellij-community,muntasirsyed/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,caot/intellij-community,nicolargo/intellij-community,caot/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,gnuhub/intellij-community,mglukhikh/intellij-community,consulo/consulo,jagguli/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,FHannes/intellij-community,supersven/intellij-community,da1z/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,slisson/intellij-community,clumsy/intellij-community,alphafoobar/intellij-community,ryano144/intellij-community,caot/intellij-community,akosyakov/intellij-community,izonder/intellij-community,kdwink/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,ryano144/intellij-community,suncycheng/intellij-community,ftomassetti/intellij-community,izonder/intellij-community,petteyg/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,akosyakov/intellij-community,diorcety/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,ryano144/intellij-community,fnouama/intellij-community,samthor/intellij-community,ivan-fedorov/intellij-community,akosyakov/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,retomerz/intellij-community,FHannes/intellij-community,blademainer/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,ftomassetti/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,youdonghai/intellij-community,slisson/intellij-community,adedayo/intellij-community,kool79/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,allotria/intellij-community,xfournet/intellij-community,adedayo/intellij-community,nicolargo/intellij-community,da1z/intellij-community,blademainer/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,fnouama/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,kdwink/intellij-community,fitermay/intellij-community,FHannes/intellij-community,alphafoobar/intellij-community,caot/intellij-community,pwoodworth/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,ryano144/intellij-community,asedunov/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,signed/intellij-community,ibinti/intellij-community,jagguli/intellij-community,consulo/consulo,ernestp/consulo,signed/intellij-community,supersven/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,muntasirsyed/intellij-community,SerCeMan/intellij-community,da1z/intellij-community,muntasirsyed/intellij-community,orekyuu/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,dslomov/intellij-community,vladmm/intellij-community,caot/intellij-community,supersven/intellij-community,ahb0327/intellij-community,holmes/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,allotria/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,clumsy/intellij-community,nicolargo/intellij-community,SerCeMan/intellij-community,supersven/intellij-community,dslomov/intellij-community,pwoodworth/intellij-community,salguarnieri/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,vladmm/intellij-community,ftomassetti/intellij-community,samthor/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,ftomassetti/intellij-community,clumsy/intellij-community,diorcety/intellij-community,amith01994/intellij-community,tmpgit/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,allotria/intellij-community,ahb0327/intellij-community,allotria/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,pwoodworth/intellij-community,tmpgit/intellij-community,asedunov/intellij-community,Lekanich/intellij-community,adedayo/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,slisson/intellij-community,FHannes/intellij-community,asedunov/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,Distrotech/intellij-community,TangHao1987/intellij-community,dslomov/intellij-community,signed/intellij-community,suncycheng/intellij-community,alphafoobar/intellij-community,jagguli/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,orekyuu/intellij-community,fengbaicanhe/intellij-community,FHannes/intellij-community,fitermay/intellij-community,petteyg/intellij-community,MichaelNedzelsky/intellij-community,kdwink/intellij-community,slisson/intellij-community,diorcety/intellij-community,muntasirsyed/intellij-community,izonder/intellij-community,blademainer/intellij-community,FHannes/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,samthor/intellij-community,jagguli/intellij-community,adedayo/intellij-community,suncycheng/intellij-community,dslomov/intellij-community,blademainer/intellij-community,michaelgallacher/intellij-community,TangHao1987/intellij-community,michaelgallacher/intellij-community,blademainer/intellij-community,signed/intellij-community,salguarnieri/intellij-community,samthor/intellij-community,idea4bsd/idea4bsd,alphafoobar/intellij-community,holmes/intellij-community,samthor/intellij-community,signed/intellij-community,adedayo/intellij-community,blademainer/intellij-community,Distrotech/intellij-community,nicolargo/intellij-community,ThiagoGarciaAlves/intellij-community,petteyg/intellij-community,nicolargo/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,da1z/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,ol-loginov/intellij-community,retomerz/intellij-community,semonte/intellij-community,allotria/intellij-community,ernestp/consulo,vvv1559/intellij-community,Distrotech/intellij-community,caot/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,clumsy/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,dslomov/intellij-community,blademainer/intellij-community,ahb0327/intellij-community,suncycheng/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,mglukhikh/intellij-community,caot/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,alphafoobar/intellij-community,kool79/intellij-community,da1z/intellij-community,fnouama/intellij-community,mglukhikh/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,retomerz/intellij-community,vladmm/intellij-community,izonder/intellij-community,blademainer/intellij-community,suncycheng/intellij-community,ernestp/consulo,ivan-fedorov/intellij-community,wreckJ/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,dslomov/intellij-community,amith01994/intellij-community,fengbaicanhe/intellij-community,petteyg/intellij-community,wreckJ/intellij-community,pwoodworth/intellij-community,gnuhub/intellij-community,ThiagoGarciaAlves/intellij-community,SerCeMan/intellij-community,xfournet/intellij-community,allotria/intellij-community,gnuhub/intellij-community,diorcety/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,asedunov/intellij-community,wreckJ/intellij-community,holmes/intellij-community,MichaelNedzelsky/intellij-community,robovm/robovm-studio,michaelgallacher/intellij-community,holmes/intellij-community,ryano144/intellij-community,fitermay/intellij-community,samthor/intellij-community,SerCeMan/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,alphafoobar/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,fengbaicanhe/intellij-community,ivan-fedorov/intellij-community,Distrotech/intellij-community,ivan-fedorov/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,ryano144/intellij-community,kdwink/intellij-community,apixandru/intellij-community,apixandru/intellij-community,amith01994/intellij-community,alphafoobar/intellij-community,asedunov/intellij-community,tmpgit/intellij-community,ol-loginov/intellij-community,signed/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,consulo/consulo,ahb0327/intellij-community,retomerz/intellij-community,diorcety/intellij-community,amith01994/intellij-community,fnouama/intellij-community,hurricup/intellij-community,kool79/intellij-community,amith01994/intellij-community,samthor/intellij-community,Lekanich/intellij-community,blademainer/intellij-community,izonder/intellij-community,nicolargo/intellij-community,signed/intellij-community,supersven/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,fitermay/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,Distrotech/intellij-community,muntasirsyed/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,kool79/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,signed/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,akosyakov/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,caot/intellij-community,MER-GROUP/intellij-community,michaelgallacher/intellij-community,gnuhub/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,jagguli/intellij-community,salguarnieri/intellij-community,ol-loginov/intellij-community,ernestp/consulo,salguarnieri/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,MER-GROUP/intellij-community,jagguli/intellij-community,retomerz/intellij-community,jagguli/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,fnouama/intellij-community,youdonghai/intellij-community,SerCeMan/intellij-community,supersven/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,ol-loginov/intellij-community,clumsy/intellij-community,tmpgit/intellij-community,holmes/intellij-community,dslomov/intellij-community,suncycheng/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,robovm/robovm-studio,apixandru/intellij-community,ibinti/intellij-community,akosyakov/intellij-community,kdwink/intellij-community,MER-GROUP/intellij-community,suncycheng/intellij-community,signed/intellij-community,fitermay/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,tmpgit/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,ryano144/intellij-community,allotria/intellij-community,clumsy/intellij-community,fnouama/intellij-community,da1z/intellij-community,consulo/consulo,MichaelNedzelsky/intellij-community,izonder/intellij-community,jagguli/intellij-community,pwoodworth/intellij-community,clumsy/intellij-community,SerCeMan/intellij-community,adedayo/intellij-community,hurricup/intellij-community,retomerz/intellij-community,caot/intellij-community,signed/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,ahb0327/intellij-community,tmpgit/intellij-community,ivan-fedorov/intellij-community,caot/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,amith01994/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,ftomassetti/intellij-community,supersven/intellij-community,SerCeMan/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,orekyuu/intellij-community,robovm/robovm-studio,fnouama/intellij-community,salguarnieri/intellij-community,consulo/consulo,retomerz/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,asedunov/intellij-community,da1z/intellij-community,apixandru/intellij-community,amith01994/intellij-community,kool79/intellij-community,wreckJ/intellij-community,caot/intellij-community,fengbaicanhe/intellij-community,vladmm/intellij-community,robovm/robovm-studio,orekyuu/intellij-community,diorcety/intellij-community,fitermay/intellij-community,adedayo/intellij-community,fitermay/intellij-community,pwoodworth/intellij-community,semonte/intellij-community,wreckJ/intellij-community,allotria/intellij-community,xfournet/intellij-community,TangHao1987/intellij-community,fengbaicanhe/intellij-community,retomerz/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,kdwink/intellij-community,clumsy/intellij-community,allotria/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,ivan-fedorov/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,tmpgit/intellij-community,xfournet/intellij-community,samthor/intellij-community,adedayo/intellij-community,hurricup/intellij-community,holmes/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,TangHao1987/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,supersven/intellij-community,retomerz/intellij-community,amith01994/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,slisson/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,pwoodworth/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,holmes/intellij-community,FHannes/intellij-community,ibinti/intellij-community,adedayo/intellij-community,Lekanich/intellij-community,holmes/intellij-community,tmpgit/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,akosyakov/intellij-community,supersven/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,robovm/robovm-studio,ivan-fedorov/intellij-community,suncycheng/intellij-community,orekyuu/intellij-community,wreckJ/intellij-community,kool79/intellij-community,youdonghai/intellij-community,diorcety/intellij-community,Lekanich/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,ol-loginov/intellij-community,slisson/intellij-community,orekyuu/intellij-community,fnouama/intellij-community,fnouama/intellij-community,petteyg/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,semonte/intellij-community,vladmm/intellij-community,supersven/intellij-community,asedunov/intellij-community,diorcety/intellij-community,robovm/robovm-studio,Lekanich/intellij-community,apixandru/intellij-community,jagguli/intellij-community,gnuhub/intellij-community,ol-loginov/intellij-community,Lekanich/intellij-community,vladmm/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,FHannes/intellij-community,fengbaicanhe/intellij-community,nicolargo/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,kdwink/intellij-community,samthor/intellij-community,mglukhikh/intellij-community,ryano144/intellij-community,kdwink/intellij-community,petteyg/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,supersven/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,Lekanich/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,vladmm/intellij-community,akosyakov/intellij-community,caot/intellij-community,slisson/intellij-community,fengbaicanhe/intellij-community,ftomassetti/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,izonder/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,allotria/intellij-community,asedunov/intellij-community,ftomassetti/intellij-community,ftomassetti/intellij-community,ivan-fedorov/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,FHannes/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,fnouama/intellij-community,clumsy/intellij-community,ol-loginov/intellij-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,ahb0327/intellij-community,pwoodworth/intellij-community,dslomov/intellij-community,ivan-fedorov/intellij-community,semonte/intellij-community,ol-loginov/intellij-community,holmes/intellij-community,da1z/intellij-community,pwoodworth/intellij-community,tmpgit/intellij-community,salguarnieri/intellij-community,SerCeMan/intellij-community,Distrotech/intellij-community,muntasirsyed/intellij-community,ryano144/intellij-community,kdwink/intellij-community,dslomov/intellij-community,consulo/consulo,MichaelNedzelsky/intellij-community,da1z/intellij-community,fnouama/intellij-community,ibinti/intellij-community,Distrotech/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,xfournet/intellij-community,asedunov/intellij-community,vladmm/intellij-community,dslomov/intellij-community,ryano144/intellij-community,kool79/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,mglukhikh/intellij-community,petteyg/intellij-community,dslomov/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,Distrotech/intellij-community,xfournet/intellij-community,semonte/intellij-community,nicolargo/intellij-community,signed/intellij-community,gnuhub/intellij-community,fengbaicanhe/intellij-community,ibinti/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,orekyuu/intellij-community,holmes/intellij-community,Distrotech/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,diorcety/intellij-community,Lekanich/intellij-community,MichaelNedzelsky/intellij-community,diorcety/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,suncycheng/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,allotria/intellij-community,robovm/robovm-studio,petteyg/intellij-community,retomerz/intellij-community,kool79/intellij-community,samthor/intellij-community,TangHao1987/intellij-community,ernestp/consulo,suncycheng/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,amith01994/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,gnuhub/intellij-community,mglukhikh/intellij-community,amith01994/intellij-community,slisson/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,FHannes/intellij-community,asedunov/intellij-community,kdwink/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,amith01994/intellij-community,nicolargo/intellij-community,ernestp/consulo,MichaelNedzelsky/intellij-community,petteyg/intellij-community,vvv1559/intellij-community,izonder/intellij-community,hurricup/intellij-community,robovm/robovm-studio,xfournet/intellij-community,fengbaicanhe/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,izonder/intellij-community,gnuhub/intellij-community,lucafavatella/intellij-community,petteyg/intellij-community,vvv1559/intellij-community,supersven/intellij-community,ibinti/intellij-community,diorcety/intellij-community,michaelgallacher/intellij-community,fengbaicanhe/intellij-community,kool79/intellij-community
/* * Copyright 2000-2012 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 org.jetbrains.plugins.groovy.refactoring.convertToJava; import com.intellij.openapi.diagnostic.Logger; import com.intellij.psi.PsiModifier; import com.intellij.psi.PsiPrimitiveType; import com.intellij.psi.PsiType; import com.intellij.psi.util.PsiTreeUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.plugins.groovy.codeInspection.noReturnMethod.MissingReturnInspection; import org.jetbrains.plugins.groovy.codeInspection.utils.ControlFlowUtils; import org.jetbrains.plugins.groovy.lang.psi.GroovyFile; import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement; import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory; import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement; import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock; import org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMember; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrReflectedMethod; import org.jetbrains.plugins.groovy.lang.psi.impl.GroovyFileImpl; import java.util.Collection; import static org.jetbrains.plugins.groovy.refactoring.convertToJava.TypeWriter.writeType; import static org.jetbrains.plugins.groovy.refactoring.convertToJava.TypeWriter.writeTypeForNew; /** * @author Maxim.Medvedev */ public class ClosureGenerator { private static final Logger LOG = Logger.getInstance(ClosureGenerator.class); public static final String[] MODIFIERS = new String[]{PsiModifier.PUBLIC}; private final StringBuilder builder; private final ExpressionContext context; public ClosureGenerator(@NotNull StringBuilder builder, @NotNull ExpressionContext context) { this.builder = builder; this.context = context; } public void generate(@NotNull GrClosableBlock closure) { final String owner = getOwner(closure); builder.append("new "); writeTypeForNew(builder, closure.getType(), closure); builder.append('('); builder.append(owner).append(", ").append(owner).append(") {\n"); generateClosureMainMethod(closure); final ClassItemGeneratorImpl generator = new ClassItemGeneratorImpl(context); final GrMethod method = generateClosureMethod(closure); final GrReflectedMethod[] reflectedMethods = method.getReflectedMethods(); if (reflectedMethods.length > 0) { for (GrReflectedMethod reflectedMethod : reflectedMethods) { if (reflectedMethod.getSkippedParameters().length > 0) { generator.writeMethod(builder, reflectedMethod); builder.append('\n'); } } } builder.append('}'); } private void generateClosureMainMethod(@NotNull GrClosableBlock block) { builder.append("public "); final PsiType returnType = block.getReturnType(); writeType(builder, returnType, block); builder.append(" doCall"); final GrParameter[] parameters = block.getAllParameters(); GenerationUtil.writeParameterList(builder, parameters, new GeneratorClassNameProvider(), context); Collection<GrStatement> myExitPoints = ControlFlowUtils.collectReturns(block); boolean shouldInsertReturnNull = !(returnType instanceof PsiPrimitiveType) && MissingReturnInspection.methodMissesSomeReturns(block, MissingReturnInspection.ReturnStatus.shouldNotReturnValue); new CodeBlockGenerator(builder, context.extend(), myExitPoints).generateCodeBlock(block, shouldInsertReturnNull); builder.append('\n'); } @NotNull private GrMethod generateClosureMethod(@NotNull GrClosableBlock block) { final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(context.project); final GrMethod method = factory.createMethodFromText("def doCall(){}", block); method.setReturnType(block.getReturnType()); if (block.hasParametersSection()) { method.getParameterList().replace(block.getParameterList()); } else { final GrParameter[] allParameters = block.getAllParameters(); LOG.assertTrue(allParameters.length == 1); final GrParameter itParameter = allParameters[0]; final GrParameter parameter = factory.createParameter("it", itParameter.getType().getCanonicalText(), "null", block); method.getParameterList().add(parameter); } ((GroovyFileImpl)method.getContainingFile()).setContextNullable(null); return method; } @NonNls @NotNull private static String getOwner(@NotNull GrClosableBlock closure) { final GroovyPsiElement context = PsiTreeUtil.getParentOfType(closure, GrMember.class, GrClosableBlock.class, GroovyFile.class); LOG.assertTrue(context != null); if (context instanceof GrTypeDefinition) { LOG.error("closure must have member parent"); return "this"; } if (context instanceof GrMember && ((GrMember)context).hasModifierProperty(PsiModifier.STATIC)) { return "null"; } return "this"; } }
plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/convertToJava/ClosureGenerator.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 org.jetbrains.plugins.groovy.refactoring.convertToJava; import com.intellij.openapi.diagnostic.Logger; import com.intellij.psi.PsiModifier; import com.intellij.psi.PsiPrimitiveType; import com.intellij.psi.PsiType; import com.intellij.psi.util.PsiTreeUtil; import org.jetbrains.plugins.groovy.codeInspection.noReturnMethod.MissingReturnInspection; import org.jetbrains.plugins.groovy.codeInspection.utils.ControlFlowUtils; import org.jetbrains.plugins.groovy.lang.psi.GroovyFile; import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement; import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory; import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement; import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock; import org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMember; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrReflectedMethod; import org.jetbrains.plugins.groovy.lang.psi.impl.GroovyFileImpl; import java.util.Collection; import static org.jetbrains.plugins.groovy.refactoring.convertToJava.TypeWriter.writeType; import static org.jetbrains.plugins.groovy.refactoring.convertToJava.TypeWriter.writeTypeForNew; /** * @author Maxim.Medvedev */ public class ClosureGenerator { private static final Logger LOG = Logger.getInstance("#org.jetbrains.plugins.groovy.refactoring.convertToJava.ClosureGenerator"); public static final String[] MODIFIERS = new String[]{PsiModifier.PUBLIC}; StringBuilder builder; ExpressionContext context; public ClosureGenerator(StringBuilder builder, ExpressionContext context) { this.builder = builder; this.context = context; } public void generate(GrClosableBlock closure) { final String owner = getOwner(closure); builder.append("new "); writeTypeForNew(builder, closure.getType(), closure); builder.append('('); builder.append(owner).append(", ").append(owner).append(") {\n"); generateClosureMainMethod(closure); final ClassItemGeneratorImpl generator = new ClassItemGeneratorImpl(context); final GrMethod method = generateClosureMethod(closure); final GrReflectedMethod[] reflectedMethods = method.getReflectedMethods(); if (reflectedMethods.length > 0) { for (GrReflectedMethod reflectedMethod : reflectedMethods) { if (reflectedMethod.getSkippedParameters().length > 0) { generator.writeMethod(builder, reflectedMethod); builder.append('\n'); } } } builder.append('}'); } private void generateClosureMainMethod(GrClosableBlock block) { builder.append("public "); final PsiType returnType = block.getReturnType(); writeType(builder, returnType, block); builder.append(" doCall"); final GrParameter[] parameters = block.getAllParameters(); GenerationUtil.writeParameterList(builder, parameters, new GeneratorClassNameProvider(), context); Collection<GrStatement> myExitPoints = ControlFlowUtils.collectReturns(block); boolean shouldInsertReturnNull = !(returnType instanceof PsiPrimitiveType) && MissingReturnInspection.methodMissesSomeReturns(block, MissingReturnInspection.ReturnStatus.shouldNotReturnValue); new CodeBlockGenerator(builder, context.extend(), myExitPoints).generateCodeBlock(block, shouldInsertReturnNull); builder.append('\n'); } private GrMethod generateClosureMethod(GrClosableBlock block) { final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(context.project); final GrMethod method = factory.createMethodFromText("def doCall(){}", block); method.setReturnType(block.getReturnType()); if (block.hasParametersSection()) { method.getParameterList().replace(block.getParameterList()); } else { final GrParameter[] allParameters = block.getAllParameters(); LOG.assertTrue(allParameters.length == 1); final GrParameter itParameter = allParameters[0]; final GrParameter parameter = factory.createParameter("it", itParameter.getType().getCanonicalText(), "null", block); method.getParameterList().add(parameter); } ((GroovyFileImpl)method.getContainingFile()).setContextNullable(null); return method; } private static String getOwner(GrClosableBlock closure) { final GroovyPsiElement context = PsiTreeUtil.getParentOfType(closure, GrMember.class, GrClosableBlock.class, GroovyFile.class); LOG.assertTrue(context != null); if (context instanceof GrTypeDefinition) { LOG.error("closure must have member parent"); return "this"; } if (context instanceof GrMember && ((GrMember)context).hasModifierProperty(PsiModifier.STATIC)) { return "null"; } return "this"; } }
cleanup
plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/convertToJava/ClosureGenerator.java
cleanup
<ide><path>lugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/convertToJava/ClosureGenerator.java <ide> /* <del> * Copyright 2000-2011 JetBrains s.r.o. <add> * Copyright 2000-2012 JetBrains s.r.o. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> import com.intellij.psi.PsiPrimitiveType; <ide> import com.intellij.psi.PsiType; <ide> import com.intellij.psi.util.PsiTreeUtil; <add>import org.jetbrains.annotations.NonNls; <add>import org.jetbrains.annotations.NotNull; <ide> import org.jetbrains.plugins.groovy.codeInspection.noReturnMethod.MissingReturnInspection; <ide> import org.jetbrains.plugins.groovy.codeInspection.utils.ControlFlowUtils; <ide> import org.jetbrains.plugins.groovy.lang.psi.GroovyFile; <ide> * @author Maxim.Medvedev <ide> */ <ide> public class ClosureGenerator { <del> private static final Logger LOG = Logger.getInstance("#org.jetbrains.plugins.groovy.refactoring.convertToJava.ClosureGenerator"); <add> private static final Logger LOG = Logger.getInstance(ClosureGenerator.class); <add> <ide> public static final String[] MODIFIERS = new String[]{PsiModifier.PUBLIC}; <ide> <del> StringBuilder builder; <del> ExpressionContext context; <add> private final StringBuilder builder; <add> private final ExpressionContext context; <ide> <del> public ClosureGenerator(StringBuilder builder, ExpressionContext context) { <add> public ClosureGenerator(@NotNull StringBuilder builder, @NotNull ExpressionContext context) { <ide> this.builder = builder; <ide> this.context = context; <ide> } <ide> <del> public void generate(GrClosableBlock closure) { <add> public void generate(@NotNull GrClosableBlock closure) { <ide> final String owner = getOwner(closure); <ide> builder.append("new "); <ide> writeTypeForNew(builder, closure.getType(), closure); <ide> builder.append('}'); <ide> } <ide> <del> private void generateClosureMainMethod(GrClosableBlock block) { <add> private void generateClosureMainMethod(@NotNull GrClosableBlock block) { <ide> builder.append("public "); <ide> final PsiType returnType = block.getReturnType(); <ide> writeType(builder, returnType, block); <ide> builder.append('\n'); <ide> } <ide> <del> private GrMethod generateClosureMethod(GrClosableBlock block) { <add> @NotNull <add> private GrMethod generateClosureMethod(@NotNull GrClosableBlock block) { <ide> final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(context.project); <ide> final GrMethod method = factory.createMethodFromText("def doCall(){}", block); <ide> <ide> return method; <ide> } <ide> <del> private static String getOwner(GrClosableBlock closure) { <add> @NonNls <add> @NotNull <add> private static String getOwner(@NotNull GrClosableBlock closure) { <ide> final GroovyPsiElement context = PsiTreeUtil.getParentOfType(closure, GrMember.class, GrClosableBlock.class, GroovyFile.class); <ide> LOG.assertTrue(context != null); <ide>
Java
mit
22fc34f9ddc3085ca8e6ee9f1306bf30e4680967
0
adrian-wozniak/yagga,yu55/gog,yu55/yagga,yu55/gog,yu55/yagga,adrian-wozniak/yagga,yu55/gog,adrian-wozniak/yagga,yu55/yagga
package org.yu55.yagga.handler.git; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.io.File; import java.util.List; import org.junit.Test; import org.yu55.yagga.core.annotate.model.AnnotateResponse; import org.yu55.yagga.core.grep.model.GrepResponseLine; import org.yu55.yagga.handler.git.command.common.GitCommandExecutor; import org.yu55.yagga.handler.git.command.common.GitCommandExecutorFactory; import org.yu55.yagga.handler.git.command.common.GitCommandOutput; import org.yu55.yagga.handler.git.command.common.GitCommandOutputLine; /* TODO: these tests are too complex. Something is wrong... */ public class GitRepositoryTest { @Test public void testPull() throws Exception { // given GitCommandExecutor executor = mock(GitCommandExecutor.class); GitCommandExecutorFactory commandExecutorFactory = mock(GitCommandExecutorFactory.class); File file = mock(File.class); GitRepository repository = new GitRepository(file, commandExecutorFactory); when(commandExecutorFactory.factorizePull()).thenReturn(executor); // when repository.pull(); // then verify(executor).execute(file); } @Test public void testAnnotate() throws Exception { // given GitCommandExecutor executor = mock(GitCommandExecutor.class); GitCommandExecutorFactory commandExecutorFactory = mock(GitCommandExecutorFactory.class); File file = mock(File.class); GitRepository repository = new GitRepository(file, commandExecutorFactory); GitCommandOutput gitCommandOutput = new GitCommandOutput(file.getName()); String fileToAnnotate = "build.gradle"; when(commandExecutorFactory.factorizeAnnotate(fileToAnnotate)).thenReturn(executor); when(executor.execute(file)).thenReturn(gitCommandOutput); gitCommandOutput.addOutputLine(new GitCommandOutputLine( "716ec6a6 ( Marcin P 2015-09-17 21:23:13 +0200 1)buildscript {")); // when AnnotateResponse annotateResponse = repository.annotate(fileToAnnotate); // then verify(executor).execute(file); assertThat(annotateResponse.getAnnotations()).contains("Marcin P"); assertThat(annotateResponse.getFileContent()).contains("buildscript"); } @Test public void testGrep() throws Exception { // given GitCommandExecutor executor = mock(GitCommandExecutor.class); GitCommandExecutorFactory commandExecutorFactory = mock(GitCommandExecutorFactory.class); File repositoryDirectory = mock(File.class); when(repositoryDirectory.getName()).thenReturn("repo"); GitRepository repository = new GitRepository(repositoryDirectory, commandExecutorFactory); GitCommandOutput gitCommandOutput = new GitCommandOutput(repositoryDirectory.getName()); String wanted = "buildscript"; when(commandExecutorFactory.factorizeGrep(wanted)).thenReturn(executor); when(executor.execute(repositoryDirectory)).thenReturn(gitCommandOutput); gitCommandOutput.addOutputLine(new GitCommandOutputLine("build.gradle:1:buildscript {")); // when List<GrepResponseLine> grep = repository.grep(wanted); // then verify(executor).execute(repositoryDirectory); assertThat(grep.size()).isEqualTo(1); GrepResponseLine grepResponseLine = grep.get(0); assertThat(grepResponseLine.getFile()).isEqualTo("build.gradle"); assertThat(grepResponseLine.getLineNumber()).isEqualTo(1); assertThat(grepResponseLine.getMatchedTextLine()).isEqualTo("buildscript {"); assertThat(grepResponseLine.getRepository()).isEqualTo("repo"); } }
src/test/java/org/yu55/yagga/handler/git/GitRepositoryTest.java
package org.yu55.yagga.handler.git; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.io.File; import java.util.List; import org.junit.Test; import org.yu55.yagga.core.annotate.model.AnnotateResponse; import org.yu55.yagga.core.grep.model.GrepResponseLine; import org.yu55.yagga.handler.git.command.common.GitCommandExecutor; import org.yu55.yagga.handler.git.command.common.GitCommandExecutorFactory; import org.yu55.yagga.handler.git.command.common.GitCommandOutput; import org.yu55.yagga.handler.git.command.common.GitCommandOutputLine; public class GitRepositoryTest { @Test public void testPull() throws Exception { // given GitCommandExecutor executor = mock(GitCommandExecutor.class); GitCommandExecutorFactory commandExecutorFactory = mock(GitCommandExecutorFactory.class); File file = mock(File.class); GitRepository repository = new GitRepository(file, commandExecutorFactory); when(commandExecutorFactory.factorizePull()).thenReturn(executor); // when repository.pull(); // then verify(executor).execute(file); } @Test public void testAnnotate() throws Exception { // given GitCommandExecutor executor = mock(GitCommandExecutor.class); GitCommandExecutorFactory commandExecutorFactory = mock(GitCommandExecutorFactory.class); File file = mock(File.class); GitRepository repository = new GitRepository(file, commandExecutorFactory); GitCommandOutput gitCommandOutput = new GitCommandOutput(file.getName()); String fileToAnnotate = "build.gradle"; when(commandExecutorFactory.factorizeAnnotate(fileToAnnotate)).thenReturn(executor); when(executor.execute(file)).thenReturn(gitCommandOutput); gitCommandOutput.addOutputLine(new GitCommandOutputLine( "716ec6a6 ( Marcin P 2015-09-17 21:23:13 +0200 1)buildscript {")); // when AnnotateResponse annotateResponse = repository.annotate(fileToAnnotate); // then verify(executor).execute(file); assertThat(annotateResponse.getAnnotations()).contains("Marcin P"); assertThat(annotateResponse.getFileContent()).contains("buildscript"); } @Test public void testGrep() throws Exception { // given GitCommandExecutor executor = mock(GitCommandExecutor.class); GitCommandExecutorFactory commandExecutorFactory = mock(GitCommandExecutorFactory.class); File repositoryDirectory = mock(File.class); GitRepository repository = new GitRepository(repositoryDirectory, commandExecutorFactory); GitCommandOutput gitCommandOutput = new GitCommandOutput(repositoryDirectory.getName()); String wanted = "buildscript"; when(commandExecutorFactory.factorizeGrep(wanted)).thenReturn(executor); when(executor.execute(repositoryDirectory)).thenReturn(gitCommandOutput); when(repositoryDirectory.getName()).thenReturn("repo"); gitCommandOutput.addOutputLine(new GitCommandOutputLine( "build.gradle:1:buildscript {")); // when List<GrepResponseLine> grep = repository.grep(wanted); // then verify(executor).execute(repositoryDirectory); assertThat(grep.size()).isEqualTo(1); GrepResponseLine grepResponseLine =grep.get(0); assertThat(grepResponseLine.getFile()).isEqualTo("build.gradle"); assertThat(grepResponseLine.getLineNumber()).isEqualTo(1); assertThat(grepResponseLine.getMatchedTextLine()).isEqualTo("buildscript {"); assertThat(grepResponseLine.getRepository()).isEqualTo("repo"); } }
Fixed test
src/test/java/org/yu55/yagga/handler/git/GitRepositoryTest.java
Fixed test
<ide><path>rc/test/java/org/yu55/yagga/handler/git/GitRepositoryTest.java <ide> import org.yu55.yagga.handler.git.command.common.GitCommandOutput; <ide> import org.yu55.yagga.handler.git.command.common.GitCommandOutputLine; <ide> <add>/* <add>TODO: these tests are too complex. Something is wrong... <add> */ <ide> public class GitRepositoryTest { <ide> <ide> @Test <ide> GitCommandExecutor executor = mock(GitCommandExecutor.class); <ide> GitCommandExecutorFactory commandExecutorFactory = mock(GitCommandExecutorFactory.class); <ide> File repositoryDirectory = mock(File.class); <add> when(repositoryDirectory.getName()).thenReturn("repo"); <ide> GitRepository repository = new GitRepository(repositoryDirectory, commandExecutorFactory); <ide> GitCommandOutput gitCommandOutput = new GitCommandOutput(repositoryDirectory.getName()); <del> <ide> String wanted = "buildscript"; <ide> when(commandExecutorFactory.factorizeGrep(wanted)).thenReturn(executor); <ide> when(executor.execute(repositoryDirectory)).thenReturn(gitCommandOutput); <del> when(repositoryDirectory.getName()).thenReturn("repo"); <del> gitCommandOutput.addOutputLine(new GitCommandOutputLine( <del> "build.gradle:1:buildscript {")); <add> gitCommandOutput.addOutputLine(new GitCommandOutputLine("build.gradle:1:buildscript {")); <add> <ide> // when <ide> List<GrepResponseLine> grep = repository.grep(wanted); <ide> <ide> // then <ide> verify(executor).execute(repositoryDirectory); <ide> assertThat(grep.size()).isEqualTo(1); <del> GrepResponseLine grepResponseLine =grep.get(0); <add> GrepResponseLine grepResponseLine = grep.get(0); <ide> assertThat(grepResponseLine.getFile()).isEqualTo("build.gradle"); <ide> assertThat(grepResponseLine.getLineNumber()).isEqualTo(1); <ide> assertThat(grepResponseLine.getMatchedTextLine()).isEqualTo("buildscript {");
JavaScript
apache-2.0
cc421a94f02c5b73bf0eb737918763204b8ef1e8
0
smaldini/grails-events-push,smaldini/grails-events-push
/** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Copyright 2012, Stephane Maldini - adapted from vertx.io EventBus.js library to use atmosphere & events-push grails * plugin. * Licensed under the Apache License, Version 2.0 * http://www.apache.org/licenses/LICENSE-2.0 * */ var grails = grails || {}; (function () { if (!grails.Events) { grails.Events = function (root, path, options) { var that = this; var socket = $.atmosphere; that.root = (root && (typeof root == "string")) ? root : (window.location.protocol + '//' + window.location.hostname + ':' + window.location.port); that.path = (path && (typeof path == "string")) ? path : "g-eventsbus"; var hasOptions = (options && (typeof options == "object")); that.globalTopicName = hasOptions && options.globalTopicName && (typeof options.globalTopicName == "string") ? options.globalTopicName : "eventsbus"; that.transport = hasOptions && options.transport && (typeof options.transport == "string") ? options.transport : "websocket"; var state = grails.Events.CONNECTING; that.onopen = null; that.onglobalmessage = null; that.onclose = null; var handlerMap = {}; var handlerQueue = []; that.send = function (topic, message) { checkSpecified("topic", 'string', topic); checkSpecified("message", 'object', message); checkOpen(); var envelope = { topic:topic, body:message }; that.globalTopicSocket.push({data:$.stringifyJSON(envelope)}); }; that.on = function (topic, handler, request) { checkSpecified("topic", 'string', topic); checkSpecified("handler", 'function', handler); var handlers = handlerMap[topic]; if (!handlers || request) { handlers = [handler]; handlerMap[topic] = handlers; if (request) { var topics = ""; for (var _topic in handlerMap) { topics += _topic + ','; } if (topics[topics.length - 1] == ',') { topics = topics.substr(0, topics.length - 1); } request.headers = {'topics':topics}; request.url = that.root + '/' + that.path + '/' + that.globalTopicName; request.transport = request.transport ? request.transport : that.transport; return socket.subscribe(request); } else { socket.unsubscribeUrl(that.root + '/' + that.path + '/' + that.globalTopicName); init(); } } else { handlers[handlers.length] = handler; } }; that.unregisterHandler = function (topic, handler) { checkSpecified("topic", 'string', topic); checkSpecified("handler", 'function', handler); checkOpen(); var handlers = handlerMap[topic]; if (handlers) { var idx = handlers.indexOf(handler); if (idx != -1) handlers.splice(idx, 1); if (handlers.length == 0) { // No more local handlers so we should unregister the connection socket.unsubscribeUrl(that.root + '/' + that.path + '/' + that.globalTopicName); init(); delete handlerMap[topic]; } } }; that.close = function () { checkOpen(); state = grails.Events.CLOSING; socket.unsubscribe(); }; that.readyState = function () { return state; }; function init() { var request = {}; var connecting = function () { state = grails.Events.OPEN; if (that.onopen) { that.onopen(); } }; request.onOpen = connecting; request.onReconnect = connecting; request.onClose = function (e) { state = grails.Events.CLOSED; if (that.onclose) { that.onclose(); } }; request.onMessage = function (response) { if (response.status == 200) { var data; if (response.responseBody.length > 0) { data = $.parseJSON(response.responseBody); var handlers = handlerMap[data.topic ? data.topic : that.globalTopicName]; if (handlers) { // We make a copy since the handler might get unregistered from within the // handler itself, which would screw up our iteration var copy = handlers.slice(0); for (var i = 0; i < copy.length; i++) { copy[i](data.body, data, response); } } } } else if (response.status == 504) { socket.unsubscribeUrl(that.root + '/' + that.path + '/' + that.globalTopicName); init(); } }; that.globalTopicSocket = that.on(that.globalTopicName, function (data, e) { if (that.onglobalmessage) { that.onglobalmessage(data); } }, request); } function checkOpen() { if (state != grails.Events.OPEN) { throw new Error('INVALID_STATE_ERR'); } } function checkSpecified(paramName, paramType, param, optional) { if (!optional && !param) { throw new Error("Parameter " + paramName + " must be specified"); } if (param && typeof param != paramType) { throw new Error("Parameter " + paramName + " must be of type " + paramType); } } init(); }; grails.Events.CONNECTING = 0; grails.Events.OPEN = 1; grails.Events.CLOSING = 2; grails.Events.CLOSED = 3; } })();
web-app/js/grails/grailsEvents.js
/** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Copyright 2012, Stephane Maldini - adapted from vertx.io EventBus.js library to use atmosphere & events-push grails * plugin. * Licensed under the Apache License, Version 2.0 * http://www.apache.org/licenses/LICENSE-2.0 * */ var grails = grails || {}; (function () { if (!grails.Events) { grails.Events = function (root, path, options) { var that = this; var socket = $.atmosphere; that.root = (root && (typeof root == "string")) ? root : (window.location.protocol + '//' + window.location.hostname + ':' + window.location.port); that.path = (path && (typeof path == "string")) ? path : "g-eventsbus"; var hasOptions = (options && (typeof options == "object")); that.globalTopicName = hasOptions && options.globalTopicName && (typeof options.globalTopicName == "string") ? options.globalTopicName : "eventsbus"; that.transport = hasOptions && options.transport && (typeof options.transport == "string") ? options.transport : "websocket"; var state = grails.Events.CONNECTING; that.onopen = null; that.onglobalmessage = null; that.onclose = null; var handlerMap = {}; var handlerQueue = []; that.send = function (topic, message) { checkSpecified("topic", 'string', topic); checkSpecified("message", 'object', message); checkOpen(); var envelope = { topic:topic, body:message }; that.globalTopicSocket.push({data:$.stringifyJSON(envelope)}); }; that.on = function (topic, handler, request) { checkSpecified("topic", 'string', topic); checkSpecified("handler", 'function', handler); var handlers = handlerMap[topic]; if (!handlers || request) { handlers = [handler]; handlerMap[topic] = handlers; if (request) { var topics = ""; for (var _topic in handlerMap) { topics += _topic + ','; } if (topics[topics.length - 1] == ',') { topics = topics.substr(0, topics.length - 1); } request.headers = {'topics':topics}; request.url = that.root + '/' + that.path + '/' + that.globalTopicName; request.transport = request.transport ? request.transport : that.transport; return socket.subscribe(request); } else { socket.unsubscribeUrl(that.root + '/' + that.path + '/' + that.globalTopicName); init(); } } else { handlers[handlers.length] = handler; } }; that.unregisterHandler = function (topic, handler) { checkSpecified("topic", 'string', topic); checkSpecified("handler", 'function', handler); checkOpen(); var handlers = handlerMap[topic]; if (handlers) { var idx = handlers.indexOf(handler); if (idx != -1) handlers.splice(idx, 1); if (handlers.length == 0) { // No more local handlers so we should unregister the connection socket.unsubscribeUrl(that.root + '/' + that.path + '/' + that.globalTopicName); init(); delete handlerMap[topic]; } } }; that.close = function () { checkOpen(); state = grails.Events.CLOSING; socket.unsubscribe(); }; that.readyState = function () { return state; }; function init() { var request = {}; var connecting = function () { state = grails.Events.OPEN; if (that.onopen) { that.onopen(); } }; request.onOpen = connecting; request.onReconnect = connecting; request.onClose = function (e) { state = grails.Events.CLOSED; if (that.onclose) { that.onclose(); } }; request.onMessage = function (response) { if (response.status == 200) { var data; if (response.responseBody.length > 0) { data = $.parseJSON(response.responseBody); var handlers = handlerMap[data.topic ? data.topic : that.globalTopicName]; if (handlers) { // We make a copy since the handler might get unregistered from within the // handler itself, which would screw up our iteration var copy = handlers.slice(0); for (var i = 0; i < copy.length; i++) { copy[i](data.body, data, response); } } } } }; that.globalTopicSocket = that.on(that.globalTopicName, function (data, e) { if (that.onglobalmessage) { that.onglobalmessage(data); } }, request); } function checkOpen() { if (state != grails.Events.OPEN) { throw new Error('INVALID_STATE_ERR'); } } function checkSpecified(paramName, paramType, param, optional) { if (!optional && !param) { throw new Error("Parameter " + paramName + " must be specified"); } if (param && typeof param != paramType) { throw new Error("Parameter " + paramName + " must be of type " + paramType); } } init(); }; grails.Events.CONNECTING = 0; grails.Events.OPEN = 1; grails.Events.CLOSING = 2; grails.Events.CLOSED = 3; } })();
handling 504 timeout
web-app/js/grails/grailsEvents.js
handling 504 timeout
<ide><path>eb-app/js/grails/grailsEvents.js <ide> checkSpecified("handler", 'function', handler); <ide> <ide> var handlers = handlerMap[topic]; <del> if (!handlers || request) { <add> if (!handlers || request) { <ide> <ide> handlers = [handler]; <ide> handlerMap[topic] = handlers; <ide> var request = {}; <ide> <ide> var connecting = function () { <del> state = grails.Events.OPEN; <del> if (that.onopen) { <del> that.onopen(); <del> } <del> }; <add> state = grails.Events.OPEN; <add> if (that.onopen) { <add> that.onopen(); <add> } <add> }; <ide> <ide> request.onOpen = connecting; <ide> request.onReconnect = connecting; <ide> } <ide> } <ide> } <add> } else if (response.status == 504) { <add> socket.unsubscribeUrl(that.root + '/' + that.path + '/' + that.globalTopicName); <add> init(); <ide> } <ide> }; <ide>
Java
apache-2.0
688e936a8e6d490b500f7cf0d84eb9cb9d896968
0
AVnetWS/Hentoid,AVnetWS/Hentoid,AVnetWS/Hentoid
package me.devsaki.hentoid.viewmodels; import android.app.Application; import android.content.Context; import android.net.Uri; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.documentfile.provider.DocumentFile; import androidx.lifecycle.AndroidViewModel; import androidx.lifecycle.LiveData; import androidx.lifecycle.MediatorLiveData; import androidx.lifecycle.MutableLiveData; import com.annimon.stream.IntStream; import com.annimon.stream.Stream; import com.annimon.stream.function.Consumer; import org.greenrobot.eventbus.EventBus; import java.io.File; import java.io.IOException; import java.security.InvalidParameterException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import io.reactivex.Completable; import io.reactivex.Observable; import io.reactivex.ObservableEmitter; import io.reactivex.Single; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.disposables.Disposable; import io.reactivex.disposables.Disposables; import io.reactivex.schedulers.Schedulers; import me.devsaki.hentoid.database.CollectionDAO; import me.devsaki.hentoid.database.ObjectBoxDAO; import me.devsaki.hentoid.database.domains.Content; import me.devsaki.hentoid.database.domains.ImageFile; import me.devsaki.hentoid.events.ProcessEvent; import me.devsaki.hentoid.util.ArchiveHelper; import me.devsaki.hentoid.util.Consts; import me.devsaki.hentoid.util.ContentHelper; import me.devsaki.hentoid.util.FileHelper; import me.devsaki.hentoid.util.Helper; import me.devsaki.hentoid.util.Preferences; import me.devsaki.hentoid.util.ToastUtil; import me.devsaki.hentoid.util.exception.ContentNotRemovedException; import me.devsaki.hentoid.widget.ContentSearchManager; import timber.log.Timber; public class ImageViewerViewModel extends AndroidViewModel { private static final String KEY_IS_SHUFFLED = "is_shuffled"; // Collection DAO private final CollectionDAO collectionDao; private ContentSearchManager searchManager; // Settings private boolean isShuffled = false; // True if images have to be shuffled; false if presented in the book order private boolean showFavourites = false; // True if viewer only shows favourite images; false if shows all pages // Collection data private final MutableLiveData<Content> content = new MutableLiveData<>(); // Current content private List<Long> contentIds = Collections.emptyList(); // Content Ids of the whole collection ordered according to current filter private int currentContentIndex = -1; // Index of current content within the above list private long loadedContentId = -1; // ID of currently loaded book // Pictures data private LiveData<List<ImageFile>> currentImageSource; private final MediatorLiveData<List<ImageFile>> images = new MediatorLiveData<>(); // Currently displayed set of images private final MutableLiveData<Integer> startingIndex = new MutableLiveData<>(); // 0-based index of the current image private final MutableLiveData<Boolean> shuffled = new MutableLiveData<>(); // Shuffle state of the current book private int thumbIndex; // Index of the thumbnail among loaded pages // Write cache for read indicator (no need to update DB and JSON at every page turn) private final Set<Integer> readPageNumbers = new HashSet<>(); // TODO doc private final Map<Integer, String> imageLocations = new HashMap<>(); // Technical private final CompositeDisposable compositeDisposable = new CompositeDisposable(); private Disposable searchDisposable = Disposables.empty(); private Disposable unarchiveDisposable = Disposables.empty(); private Disposable imageLoadDisposable = Disposables.empty(); private Disposable leaveDisposable = Disposables.empty(); private Disposable emptyCacheDisposable = Disposables.empty(); private boolean isArchiveExtracting = false; public ImageViewerViewModel(@NonNull Application application, @NonNull CollectionDAO collectionDAO) { super(application); collectionDao = collectionDAO; } @Override protected void onCleared() { super.onCleared(); collectionDao.cleanup(); searchDisposable.dispose(); compositeDisposable.clear(); } @NonNull public LiveData<Content> getContent() { return content; } @NonNull public LiveData<List<ImageFile>> getImages() { return images; } @NonNull public LiveData<Integer> getStartingIndex() { return startingIndex; } @NonNull public LiveData<Boolean> getShuffled() { return shuffled; } public void onSaveState(Bundle outState) { outState.putBoolean(KEY_IS_SHUFFLED, isShuffled); } public void onRestoreState(@Nullable Bundle savedState) { if (savedState == null) return; isShuffled = savedState.getBoolean(KEY_IS_SHUFFLED, false); } public void loadFromContent(long contentId) { if (contentId > 0) { Content loadedContent = collectionDao.selectContent(contentId); if (loadedContent != null) processContent(loadedContent); } } public void loadFromSearchParams(long contentId, @NonNull Bundle bundle) { searchManager = new ContentSearchManager(collectionDao); searchManager.loadFromBundle(bundle); applySearchParams(contentId); } private void applySearchParams(long contentId) { searchDisposable.dispose(); searchDisposable = searchManager.searchLibraryForId().subscribe( list -> { contentIds = list; loadFromContent(contentId); }, throwable -> { Timber.w(throwable); ToastUtil.toast("Book list loading failed"); } ); } public void setReaderStartingIndex(int index) { startingIndex.setValue(index); } private void setImages(@NonNull Content theContent, @NonNull List<ImageFile> newImages) { Observable<ImageFile> observable; // Don't reload from disk / archive again if the image list hasn't changed // e.g. page favourited // List<ImageFile> currentImages = images.getValue(); if (imageLocations.isEmpty() || newImages.size() != imageLocations.size()) { if (theContent.isArchive()) observable = Observable.create(emitter -> processArchiveImages(theContent, newImages, emitter)); else observable = Observable.create(emitter -> processDiskImages(theContent, newImages, emitter)); AtomicInteger nbProcessed = new AtomicInteger(); imageLoadDisposable = observable .subscribeOn(Schedulers.io()) .observeOn(Schedulers.io()) .doOnComplete( // Called this way to properly run on io thread () -> postLoadProcessing(getApplication().getApplicationContext(), theContent) ) .observeOn(AndroidSchedulers.mainThread()) .subscribe( imageFile -> { nbProcessed.getAndIncrement(); EventBus.getDefault().post(new ProcessEvent(ProcessEvent.EventType.PROGRESS, 0, nbProcessed.get(), 0, newImages.size())); }, t -> { Timber.e(t); EventBus.getDefault().post(new ProcessEvent(ProcessEvent.EventType.COMPLETE, 0, nbProcessed.get(), 0, newImages.size())); }, () -> { EventBus.getDefault().post(new ProcessEvent(ProcessEvent.EventType.COMPLETE, 0, nbProcessed.get(), 0, newImages.size())); for (ImageFile img : newImages) imageLocations.put(img.getOrder(), img.getFileUri()); initViewer(theContent, newImages); imageLoadDisposable.dispose(); } ); } else { // Copy location properties of the new list on the current list for (int i = 0; i < newImages.size(); i++) { ImageFile newImg = newImages.get(i); String location = imageLocations.get(newImg.getOrder()); newImg.setFileUri(location); } initViewer(theContent, newImages); } } private void processDiskImages( @NonNull Content theContent, @NonNull List<ImageFile> newImages, @NonNull final ObservableEmitter<ImageFile> emitter) { if (theContent.isArchive()) throw new IllegalArgumentException("Content must not be an archive"); boolean missingUris = Stream.of(newImages).filter(img -> img.getFileUri().isEmpty()).count() > 0; List<ImageFile> newImageFiles = new ArrayList<>(newImages); // Reattach actual files to the book's pictures if they are empty or have no URI's if (missingUris || newImages.isEmpty()) { List<DocumentFile> pictureFiles = ContentHelper.getPictureFilesFromContent(getApplication(), theContent); if (!pictureFiles.isEmpty()) { if (newImages.isEmpty()) { newImageFiles = ContentHelper.createImageListFromFiles(pictureFiles); theContent.setImageFiles(newImageFiles); collectionDao.insertContent(theContent); } else { // Match files for viewer display; no need to persist that ContentHelper.matchFilesToImageList(pictureFiles, newImageFiles); } } } // Replace initial images with updated images newImages.clear(); newImages.addAll(newImageFiles); emitter.onComplete(); } public void emptyCacheFolder() { emptyCacheDisposable = Completable.fromRunnable(this::doEmptyCacheFolder) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( () -> emptyCacheDisposable.dispose(), Timber::e ); } private void doEmptyCacheFolder() { Helper.assertNonUiThread(); File cachePicFolder = getOrCreatePictureCacheFolder(); if (cachePicFolder != null) { File[] files = cachePicFolder.listFiles(); if (files != null) for (File f : files) if (!f.delete()) Timber.w("Unable to delete file %s", f.getAbsolutePath()); } } private synchronized void processArchiveImages( @NonNull Content theContent, @NonNull List<ImageFile> newImages, @NonNull final ObservableEmitter<ImageFile> emitter) throws IOException { if (!theContent.isArchive()) throw new IllegalArgumentException("Content must be an archive"); if (isArchiveExtracting) return; List<ImageFile> newImageFiles = new ArrayList<>(newImages); List<ImageFile> currentImages = images.getValue(); if ((!newImages.isEmpty() && loadedContentId != newImages.get(0).getContent().getTargetId()) || null == currentImages) { // Load a new book // TODO create a smarter cache that works with a window of a given size File cachePicFolder = getOrCreatePictureCacheFolder(); if (cachePicFolder != null) { // Empty the cache folder where previous cached images might be File[] files = cachePicFolder.listFiles(); if (files != null) for (File f : files) if (!f.delete()) Timber.w("Unable to delete file %s", f.getAbsolutePath()); // Extract the images if they are contained within an archive // Unzip the archive in the app's cache folder DocumentFile archiveFile = FileHelper.getFileFromSingleUriString(getApplication(), theContent.getStorageUri()); // TODO replace that with a proper on-demand loading if (archiveFile != null) { isArchiveExtracting = true; unarchiveDisposable = ArchiveHelper.extractArchiveEntriesRx( getApplication(), archiveFile, Stream.of(newImageFiles).filter(i -> i.getFileUri().startsWith(theContent.getStorageUri())).map(i -> i.getFileUri().replace(theContent.getStorageUri() + File.separator, "")).toList(), cachePicFolder, null) .subscribeOn(Schedulers.io()) .observeOn(Schedulers.computation()) .subscribe( uri -> emitter.onNext(mapUriToImageFile(newImages, uri)), t -> { Timber.e(t); isArchiveExtracting = false; }, () -> { isArchiveExtracting = false; emitter.onComplete(); unarchiveDisposable.dispose(); } ); } } } else { // Refresh current book with new data for (int i = 0; i < newImageFiles.size(); i++) { ImageFile newImg = newImageFiles.get(i); String location = imageLocations.get(newImg.getOrder()); newImg.setFileUri(location); } // Replace initial images with updated images newImages.clear(); newImages.addAll(newImageFiles); emitter.onComplete(); } } // TODO doc private ImageFile mapUriToImageFile(@NonNull final List<ImageFile> imageFiles, @NonNull final Uri uri) { String path = uri.getPath(); if (null == path) return new ImageFile(); // Feed the Uri's of unzipped files back into the corresponding images for viewing for (ImageFile img : imageFiles) { if (FileHelper.getFileNameWithoutExtension(img.getFileUri()).equalsIgnoreCase(ArchiveHelper.extractCacheFileName(path))) { return img.setFileUri(uri.toString()); } } return new ImageFile(); } private void initViewer(@NonNull Content theContent, @NonNull List<ImageFile> imageFiles) { sortAndSetImages(imageFiles, isShuffled); if (theContent.getId() != loadedContentId) { // To be done once per book only int collectionStartingIndex = 0; // Auto-restart at last read position if asked to if (Preferences.isViewerResumeLastLeft()) collectionStartingIndex = theContent.getLastReadPageIndex(); // Correct offset with the thumb index thumbIndex = -1; for (int i = 0; i < imageFiles.size(); i++) if (!imageFiles.get(i).isReadable()) { thumbIndex = i; break; } if (thumbIndex == collectionStartingIndex) collectionStartingIndex += 1; setReaderStartingIndex(collectionStartingIndex - thumbIndex - 1); // Init the read pages write cache readPageNumbers.clear(); Collection<Integer> readPages = Stream.of(imageFiles).filter(ImageFile::isRead).filter(ImageFile::isReadable).map(ImageFile::getOrder).toList(); // Fix pre-v1.13 books where ImageFile.read has no value if (readPages.isEmpty() && theContent.getLastReadPageIndex() > 0 && theContent.getLastReadPageIndex() < imageFiles.size()) { int lastReadPageNumber = imageFiles.get(theContent.getLastReadPageIndex()).getOrder(); readPageNumbers.addAll(IntStream.rangeClosed(1, lastReadPageNumber).boxed().toList()); } else { readPageNumbers.addAll(readPages); } // Mark initial page as read if (collectionStartingIndex < imageFiles.size()) markPageAsRead(imageFiles.get(collectionStartingIndex).getOrder()); } loadedContentId = theContent.getId(); } public void onShuffleClick() { isShuffled = !isShuffled; shuffled.postValue(isShuffled); List<ImageFile> imgs = getImages().getValue(); if (imgs != null) sortAndSetImages(imgs, isShuffled); } private void sortAndSetImages(@NonNull List<ImageFile> imgs, boolean shuffle) { if (shuffle) { Collections.shuffle(imgs); // Don't keep the cover thumb imgs = Stream.of(imgs).filter(ImageFile::isReadable).toList(); } else { // Sort images according to their Order; don't keep the cover thumb imgs = Stream.of(imgs).sortBy(ImageFile::getOrder).filter(ImageFile::isReadable).toList(); } if (showFavourites) imgs = Stream.of(imgs).filter(ImageFile::isFavourite).toList(); for (int i = 0; i < imgs.size(); i++) imgs.get(i).setDisplayOrder(i); images.setValue(imgs); } public void onLeaveBook(int readerIndex) { List<ImageFile> theImages = images.getValue(); Content theContent = collectionDao.selectContent(loadedContentId); if (null == theImages || null == theContent) return; int readThresholdPref = Preferences.getViewerReadThreshold(); int readThresholdPosition; switch (readThresholdPref) { case Preferences.Constant.VIEWER_READ_THRESHOLD_2: readThresholdPosition = 2; break; case Preferences.Constant.VIEWER_READ_THRESHOLD_5: readThresholdPosition = 5; break; case Preferences.Constant.VIEWER_READ_THRESHOLD_ALL: readThresholdPosition = theImages.size(); break; default: readThresholdPosition = 1; } int collectionIndex = readerIndex + thumbIndex + 1; boolean updateReads = (readPageNumbers.size() >= readThresholdPosition || theContent.getReads() > 0); // Reset the memorized page index if it represents the last page int indexToSet = (collectionIndex >= theImages.size()) ? 0 : collectionIndex; leaveDisposable = Completable.fromRunnable(() -> doLeaveBook(theContent.getId(), indexToSet, updateReads)) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( () -> leaveDisposable.dispose(), Timber::e ); } private void doLeaveBook(final long contentId, int indexToSet, boolean updateReads) { Helper.assertNonUiThread(); // Use a brand new DAO for that (the viewmodel's DAO may be in the process of being cleaned up) CollectionDAO dao = new ObjectBoxDAO(getApplication()); try { // Get a fresh version of current content in case it has been updated since the initial load // (that can be the case when viewing a book that is being downloaded) Content savedContent = dao.selectContent(contentId); if (null == savedContent) return; List<ImageFile> theImages = savedContent.getImageFiles(); if (null == theImages) return; // Update image read status with the cached read statuses long previousReadPagesCount = Stream.of(theImages).filter(ImageFile::isRead).filter(ImageFile::isReadable).count(); if (readPageNumbers.size() > previousReadPagesCount) { for (ImageFile img : theImages) if (readPageNumbers.contains(img.getOrder())) img.setRead(true); } if (indexToSet != savedContent.getLastReadPageIndex() || updateReads || readPageNumbers.size() > previousReadPagesCount) ContentHelper.updateContentReadStats(getApplication(), dao, savedContent, theImages, indexToSet, updateReads); } finally { dao.cleanup(); } } public void toggleFilterFavouritePages(Consumer<Boolean> callback) { if (loadedContentId > -1) { showFavourites = !showFavourites; if (searchManager != null) searchManager.setFilterPageFavourites(showFavourites); applySearchParams(loadedContentId); callback.accept(showFavourites); } } public void togglePageFavourite(ImageFile file, Consumer<ImageFile> callback) { compositeDisposable.add( Single.fromCallable(() -> doTogglePageFavourite(getApplication().getApplicationContext(), file.getId())) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( result -> onToggleFavouriteSuccess(result, callback), Timber::e ) ); } private void onToggleFavouriteSuccess(ImageFile result, Consumer<ImageFile> callback) { List<ImageFile> imgs = getImages().getValue(); if (imgs != null) { for (ImageFile img : imgs) if (img.getId() == result.getId()) { img.setFavourite(result.isFavourite()); // Update new state in memory result.setDisplayOrder(img.getDisplayOrder()); // Set the display order of the item to callback.accept(result); // Inform the view } } compositeDisposable.clear(); } /** * Toggles favourite flag in DB and in the content JSON * * @param context Context to be used for this operation * @param imageId ID of the image whose flag to toggle * @return ImageFile with the new state */ private ImageFile doTogglePageFavourite(Context context, long imageId) { Helper.assertNonUiThread(); ImageFile img = collectionDao.selectImageFile(imageId); if (img != null) { img.setFavourite(!img.isFavourite()); // Persist in DB collectionDao.insertImageFile(img); // Persist in JSON Content theContent = img.getContent().getTarget(); if (!theContent.getJsonUri().isEmpty()) ContentHelper.updateContentJson(context, theContent); else ContentHelper.createContentJson(context, theContent); return img; } else throw new InvalidParameterException(String.format("Invalid image ID %s", imageId)); } public void deleteBook(Consumer<Throwable> onError) { Content targetContent = collectionDao.selectContent(loadedContentId); if (null == targetContent) return; // Unplug image source listener (avoid displaying pages as they are being deleted; it messes up with DB transactions) if (currentImageSource != null) images.removeSource(currentImageSource); compositeDisposable.add( Completable.fromAction(() -> doDeleteBook(targetContent)) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( () -> { currentImageSource = null; // Switch to the next book if the list is populated (multi-book) if (!contentIds.isEmpty()) { contentIds.remove(currentContentIndex); if (currentContentIndex >= contentIds.size() && currentContentIndex > 0) currentContentIndex--; if (contentIds.size() > currentContentIndex) loadFromContent(contentIds.get(currentContentIndex)); } else { // Close the viewer if the list is empty (single book) content.postValue(null); } }, e -> { onError.accept(e); // Restore image source listener on error images.addSource(currentImageSource, imgs -> setImages(targetContent, imgs)); } ) ); } private void doDeleteBook(@NonNull Content targetContent) throws ContentNotRemovedException { Helper.assertNonUiThread(); ContentHelper.removeQueuedContent(getApplication(), collectionDao, targetContent); } public void deletePage(int pageIndex, Consumer<Throwable> onError) { List<ImageFile> imageFiles = images.getValue(); if (imageFiles != null && imageFiles.size() > pageIndex) deletePages(Stream.of(imageFiles.get(pageIndex)).toList(), onError); } public void deletePages(List<ImageFile> pages, Consumer<Throwable> onError) { compositeDisposable.add( Completable.fromRunnable(() -> doDeletePages(pages)) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( () -> { // Update is done through LiveData }, e -> { Timber.e(e); onError.accept(e); } ) ); } private void doDeletePages(@NonNull List<ImageFile> pages) { Helper.assertNonUiThread(); ContentHelper.removePages(pages, collectionDao, getApplication()); } public void setCover(ImageFile page) { compositeDisposable.add( Completable.fromRunnable(() -> doSetCover(page)) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( () -> { // Update is done through LiveData }, Timber::e ) ); } private void doSetCover(@NonNull ImageFile page) { Helper.assertNonUiThread(); ContentHelper.setContentCover(page, collectionDao, getApplication()); } public void loadNextContent(int readerIndex) { if (currentContentIndex < contentIds.size() - 1) { currentContentIndex++; if (!contentIds.isEmpty()) { onLeaveBook(readerIndex); loadFromContent(contentIds.get(currentContentIndex)); } } } public void loadPreviousContent(int readerIndex) { if (currentContentIndex > 0) { currentContentIndex--; if (!contentIds.isEmpty()) { onLeaveBook(readerIndex); loadFromContent(contentIds.get(currentContentIndex)); } } } private void processContent(@NonNull Content theContent) { currentContentIndex = contentIds.indexOf(theContent.getId()); if (-1 == currentContentIndex) currentContentIndex = 0; theContent.setFirst(0 == currentContentIndex); theContent.setLast(currentContentIndex >= contentIds.size() - 1); if (contentIds.size() > currentContentIndex && loadedContentId != contentIds.get(currentContentIndex)) imageLocations.clear(); content.postValue(theContent); // Observe the content's images // NB : It has to be dynamic to be updated when viewing a book from the queue screen if (currentImageSource != null) images.removeSource(currentImageSource); currentImageSource = collectionDao.selectDownloadedImagesFromContent(theContent.getId()); images.addSource(currentImageSource, imgs -> setImages(theContent, imgs)); } private void postLoadProcessing(@NonNull Context context, @NonNull Content content) { // Cache images in the Json file cacheJson(context, content); } public void updateContentPreferences(@NonNull final Map<String, String> newPrefs) { compositeDisposable.add( Completable.fromRunnable(() -> doUpdateContentPreferences(getApplication().getApplicationContext(), loadedContentId, newPrefs)) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( () -> { // Update is done through LiveData }, Timber::e ) ); } private void doUpdateContentPreferences(@NonNull final Context context, long contentId, @NonNull final Map<String, String> newPrefs) { Helper.assertNonUiThread(); Content theContent = collectionDao.selectContent(contentId); if (null == theContent) return; theContent.setBookPreferences(newPrefs); // Persist in DB collectionDao.insertContent(theContent); // Repost the updated content content.postValue(theContent); // Persist in JSON if (!theContent.getJsonUri().isEmpty()) ContentHelper.updateContentJson(context, theContent); else ContentHelper.createContentJson(context, theContent); } // Cache JSON URI in the database to speed up favouriting private void cacheJson(@NonNull Context context, @NonNull Content content) { Helper.assertNonUiThread(); if (!content.getJsonUri().isEmpty() || content.isArchive()) return; DocumentFile folder = FileHelper.getFolderFromTreeUriString(context, content.getStorageUri()); if (null == folder) return; DocumentFile foundFile = FileHelper.findFile(getApplication(), folder, Consts.JSON_FILE_NAME_V2); if (null == foundFile) { Timber.e("JSON file not detected in %s", content.getStorageUri()); return; } // Cache the URI of the JSON to the database content.setJsonUri(foundFile.getUri().toString()); collectionDao.insertContent(content); } @Nullable private File getOrCreatePictureCacheFolder() { File cacheDir = getApplication().getCacheDir(); File pictureCacheDir = new File(cacheDir.getAbsolutePath() + File.separator + Consts.PICTURE_CACHE_FOLDER); if (pictureCacheDir.exists()) return pictureCacheDir; else if (pictureCacheDir.mkdir()) return pictureCacheDir; else return null; } public void markPageAsRead(int pageNumber) { readPageNumbers.add(pageNumber); } }
app/src/main/java/me/devsaki/hentoid/viewmodels/ImageViewerViewModel.java
package me.devsaki.hentoid.viewmodels; import android.app.Application; import android.content.Context; import android.net.Uri; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.documentfile.provider.DocumentFile; import androidx.lifecycle.AndroidViewModel; import androidx.lifecycle.LiveData; import androidx.lifecycle.MediatorLiveData; import androidx.lifecycle.MutableLiveData; import com.annimon.stream.IntStream; import com.annimon.stream.Stream; import com.annimon.stream.function.Consumer; import org.greenrobot.eventbus.EventBus; import java.io.File; import java.io.IOException; import java.security.InvalidParameterException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import io.reactivex.Completable; import io.reactivex.Observable; import io.reactivex.ObservableEmitter; import io.reactivex.Single; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.disposables.Disposable; import io.reactivex.disposables.Disposables; import io.reactivex.schedulers.Schedulers; import me.devsaki.hentoid.database.CollectionDAO; import me.devsaki.hentoid.database.ObjectBoxDAO; import me.devsaki.hentoid.database.domains.Content; import me.devsaki.hentoid.database.domains.ImageFile; import me.devsaki.hentoid.events.ProcessEvent; import me.devsaki.hentoid.util.ArchiveHelper; import me.devsaki.hentoid.util.Consts; import me.devsaki.hentoid.util.ContentHelper; import me.devsaki.hentoid.util.FileHelper; import me.devsaki.hentoid.util.Helper; import me.devsaki.hentoid.util.Preferences; import me.devsaki.hentoid.util.ToastUtil; import me.devsaki.hentoid.util.exception.ContentNotRemovedException; import me.devsaki.hentoid.widget.ContentSearchManager; import timber.log.Timber; public class ImageViewerViewModel extends AndroidViewModel { private static final String KEY_IS_SHUFFLED = "is_shuffled"; // Collection DAO private final CollectionDAO collectionDao; private ContentSearchManager searchManager; // Settings private boolean isShuffled = false; // True if images have to be shuffled; false if presented in the book order private boolean showFavourites = false; // True if viewer only shows favourite images; false if shows all pages // Collection data private final MutableLiveData<Content> content = new MutableLiveData<>(); // Current content private List<Long> contentIds = Collections.emptyList(); // Content Ids of the whole collection ordered according to current filter private int currentContentIndex = -1; // Index of current content within the above list private long loadedContentId = -1; // ID of currently loaded book // Pictures data private LiveData<List<ImageFile>> currentImageSource; private final MediatorLiveData<List<ImageFile>> images = new MediatorLiveData<>(); // Currently displayed set of images private final MutableLiveData<Integer> startingIndex = new MutableLiveData<>(); // 0-based index of the current image private final MutableLiveData<Boolean> shuffled = new MutableLiveData<>(); // Shuffle state of the current book private int thumbIndex; // Index of the thumbnail among loaded pages // Write cache for read indicator (no need to update DB and JSON at every page turn) private final Set<Integer> readPageNumbers = new HashSet<>(); // TODO doc private final Map<Integer, String> imageLocations = new HashMap<>(); // Technical private final CompositeDisposable compositeDisposable = new CompositeDisposable(); private Disposable searchDisposable = Disposables.empty(); private Disposable unarchiveDisposable = Disposables.empty(); private Disposable imageLoadDisposable = Disposables.empty(); private Disposable leaveDisposable = Disposables.empty(); private Disposable emptyCacheDisposable = Disposables.empty(); private boolean isArchiveExtracting = false; public ImageViewerViewModel(@NonNull Application application, @NonNull CollectionDAO collectionDAO) { super(application); collectionDao = collectionDAO; } @Override protected void onCleared() { super.onCleared(); collectionDao.cleanup(); searchDisposable.dispose(); compositeDisposable.clear(); } @NonNull public LiveData<Content> getContent() { return content; } @NonNull public LiveData<List<ImageFile>> getImages() { return images; } @NonNull public LiveData<Integer> getStartingIndex() { return startingIndex; } @NonNull public LiveData<Boolean> getShuffled() { return shuffled; } public void onSaveState(Bundle outState) { outState.putBoolean(KEY_IS_SHUFFLED, isShuffled); } public void onRestoreState(@Nullable Bundle savedState) { if (savedState == null) return; isShuffled = savedState.getBoolean(KEY_IS_SHUFFLED, false); } public void loadFromContent(long contentId) { if (contentId > 0) { Content loadedContent = collectionDao.selectContent(contentId); if (loadedContent != null) processContent(loadedContent); } } public void loadFromSearchParams(long contentId, @NonNull Bundle bundle) { searchManager = new ContentSearchManager(collectionDao); searchManager.loadFromBundle(bundle); applySearchParams(contentId); } private void applySearchParams(long contentId) { searchDisposable.dispose(); searchDisposable = searchManager.searchLibraryForId().subscribe( list -> { contentIds = list; loadFromContent(contentId); }, throwable -> { Timber.w(throwable); ToastUtil.toast("Book list loading failed"); } ); } public void setReaderStartingIndex(int index) { startingIndex.setValue(index); } private void setImages(@NonNull Content theContent, @NonNull List<ImageFile> newImages) { Observable<ImageFile> observable; // Don't reload from disk / archive again if the image list hasn't changed // e.g. page favourited // List<ImageFile> currentImages = images.getValue(); if (imageLocations.isEmpty() || newImages.size() != imageLocations.size()) { if (theContent.isArchive()) observable = Observable.create(emitter -> processArchiveImages(theContent, newImages, emitter)); else observable = Observable.create(emitter -> processDiskImages(theContent, newImages, emitter)); AtomicInteger nbProcessed = new AtomicInteger(); imageLoadDisposable = observable .subscribeOn(Schedulers.io()) .observeOn(Schedulers.io()) .doOnComplete( // Called this way to properly run on io thread () -> postLoadProcessing(getApplication().getApplicationContext(), theContent) ) .observeOn(AndroidSchedulers.mainThread()) .subscribe( imageFile -> { nbProcessed.getAndIncrement(); EventBus.getDefault().post(new ProcessEvent(ProcessEvent.EventType.PROGRESS, 0, nbProcessed.get(), 0, newImages.size())); }, t -> { Timber.e(t); EventBus.getDefault().post(new ProcessEvent(ProcessEvent.EventType.COMPLETE, 0, nbProcessed.get(), 0, newImages.size())); }, () -> { EventBus.getDefault().post(new ProcessEvent(ProcessEvent.EventType.COMPLETE, 0, nbProcessed.get(), 0, newImages.size())); for (ImageFile img : newImages) imageLocations.put(img.getOrder(), img.getFileUri()); initViewer(theContent, newImages); imageLoadDisposable.dispose(); } ); } else { // Copy location properties of the new list on the current list for (int i = 0; i < newImages.size(); i++) { ImageFile newImg = newImages.get(i); String location = imageLocations.get(newImg.getOrder()); newImg.setFileUri(location); } initViewer(theContent, newImages); } } private void processDiskImages( @NonNull Content theContent, @NonNull List<ImageFile> newImages, @NonNull final ObservableEmitter<ImageFile> emitter) { if (theContent.isArchive()) throw new IllegalArgumentException("Content must not be an archive"); boolean missingUris = Stream.of(newImages).filter(img -> img.getFileUri().isEmpty()).count() > 0; List<ImageFile> newImageFiles = new ArrayList<>(newImages); // Reattach actual files to the book's pictures if they are empty or have no URI's if (missingUris || newImages.isEmpty()) { List<DocumentFile> pictureFiles = ContentHelper.getPictureFilesFromContent(getApplication(), theContent); if (!pictureFiles.isEmpty()) { if (newImages.isEmpty()) { newImageFiles = ContentHelper.createImageListFromFiles(pictureFiles); theContent.setImageFiles(newImageFiles); collectionDao.insertContent(theContent); } else { // Match files for viewer display; no need to persist that ContentHelper.matchFilesToImageList(pictureFiles, newImageFiles); } } } // Replace initial images with updated images newImages.clear(); newImages.addAll(newImageFiles); emitter.onComplete(); } public void emptyCacheFolder() { emptyCacheDisposable = Completable.fromRunnable(this::doEmptyCacheFolder) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( () -> emptyCacheDisposable.dispose(), Timber::e ); } private void doEmptyCacheFolder() { Helper.assertNonUiThread(); File cachePicFolder = getOrCreatePictureCacheFolder(); if (cachePicFolder != null) { File[] files = cachePicFolder.listFiles(); if (files != null) for (File f : files) if (!f.delete()) Timber.w("Unable to delete file %s", f.getAbsolutePath()); } } private synchronized void processArchiveImages( @NonNull Content theContent, @NonNull List<ImageFile> newImages, @NonNull final ObservableEmitter<ImageFile> emitter) throws IOException { if (!theContent.isArchive()) throw new IllegalArgumentException("Content must be an archive"); if (isArchiveExtracting) return; List<ImageFile> newImageFiles = new ArrayList<>(newImages); List<ImageFile> currentImages = images.getValue(); if ((!newImages.isEmpty() && loadedContentId != newImages.get(0).getContent().getTargetId()) || null == currentImages) { // Load a new book // TODO create a smarter cache that works with a window of a given size File cachePicFolder = getOrCreatePictureCacheFolder(); if (cachePicFolder != null) { // Empty the cache folder where previous cached images might be File[] files = cachePicFolder.listFiles(); if (files != null) for (File f : files) if (!f.delete()) Timber.w("Unable to delete file %s", f.getAbsolutePath()); // Extract the images if they are contained within an archive // Unzip the archive in the app's cache folder DocumentFile archiveFile = FileHelper.getFileFromSingleUriString(getApplication(), theContent.getStorageUri()); // TODO replace that with a proper on-demand loading if (archiveFile != null) { isArchiveExtracting = true; unarchiveDisposable = ArchiveHelper.extractArchiveEntriesRx( getApplication(), archiveFile, Stream.of(newImageFiles).filter(i -> i.getFileUri().startsWith(theContent.getStorageUri())).map(i -> i.getFileUri().replace(theContent.getStorageUri() + File.separator, "")).toList(), cachePicFolder, null) .subscribeOn(Schedulers.io()) .observeOn(Schedulers.computation()) .subscribe( uri -> emitter.onNext(mapUriToImageFile(newImages, uri)), t -> { Timber.e(t); isArchiveExtracting = false; }, () -> { isArchiveExtracting = false; emitter.onComplete(); unarchiveDisposable.dispose(); } ); } } } else { // Refresh current book with new data for (int i = 0; i < newImageFiles.size(); i++) { ImageFile newImg = newImageFiles.get(i); String location = imageLocations.get(newImg.getOrder()); newImg.setFileUri(location); } // Replace initial images with updated images newImages.clear(); newImages.addAll(newImageFiles); emitter.onComplete(); } } // TODO doc private ImageFile mapUriToImageFile(@NonNull final List<ImageFile> imageFiles, @NonNull final Uri uri) { String path = uri.getPath(); if (null == path) return new ImageFile(); // Feed the Uri's of unzipped files back into the corresponding images for viewing for (ImageFile img : imageFiles) { if (FileHelper.getFileNameWithoutExtension(img.getFileUri()).equalsIgnoreCase(ArchiveHelper.extractCacheFileName(path))) { return img.setFileUri(uri.toString()); } } return new ImageFile(); } private void initViewer(@NonNull Content theContent, @NonNull List<ImageFile> imageFiles) { sortAndSetImages(imageFiles, isShuffled); if (theContent.getId() != loadedContentId) { // To be done once per book only int collectionStartingIndex = 0; // Auto-restart at last read position if asked to if (Preferences.isViewerResumeLastLeft()) collectionStartingIndex = theContent.getLastReadPageIndex(); // Correct offset with the thumb index thumbIndex = -1; for (int i = 0; i < imageFiles.size(); i++) if (!imageFiles.get(i).isReadable()) { thumbIndex = i; break; } if (thumbIndex == collectionStartingIndex) collectionStartingIndex += 1; setReaderStartingIndex(collectionStartingIndex - thumbIndex - 1); // Init the read pages write cache readPageNumbers.clear(); Collection<Integer> readPages = Stream.of(imageFiles).filter(ImageFile::isRead).filter(ImageFile::isReadable).map(ImageFile::getOrder).toList(); // Fix pre-v1.13 books where ImageFile.read has no value if (readPages.isEmpty() && theContent.getLastReadPageIndex() > 0 && theContent.getLastReadPageIndex() < imageFiles.size()) { int lastReadPageNumber = imageFiles.get(theContent.getLastReadPageIndex()).getOrder(); readPageNumbers.addAll(IntStream.rangeClosed(1, lastReadPageNumber).boxed().toList()); } else { readPageNumbers.addAll(readPages); } // Mark initial page as read if (collectionStartingIndex < imageFiles.size()) markPageAsRead(imageFiles.get(collectionStartingIndex).getOrder()); } loadedContentId = theContent.getId(); } public void onShuffleClick() { isShuffled = !isShuffled; shuffled.postValue(isShuffled); List<ImageFile> imgs = getImages().getValue(); if (imgs != null) sortAndSetImages(imgs, isShuffled); } private void sortAndSetImages(@NonNull List<ImageFile> imgs, boolean shuffle) { if (shuffle) { Collections.shuffle(imgs); // Don't keep the cover thumb imgs = Stream.of(imgs).filter(ImageFile::isReadable).toList(); } else { // Sort images according to their Order; don't keep the cover thumb imgs = Stream.of(imgs).sortBy(ImageFile::getOrder).filter(ImageFile::isReadable).toList(); } if (showFavourites) imgs = Stream.of(imgs).filter(ImageFile::isFavourite).toList(); for (int i = 0; i < imgs.size(); i++) imgs.get(i).setDisplayOrder(i); images.setValue(imgs); } public void onLeaveBook(int readerIndex) { List<ImageFile> theImages = images.getValue(); Content theContent = collectionDao.selectContent(loadedContentId); if (null == theImages || null == theContent) return; int readThresholdPref = Preferences.getViewerReadThreshold(); int readThresholdPosition; switch (readThresholdPref) { case Preferences.Constant.VIEWER_READ_THRESHOLD_2: readThresholdPosition = 2; break; case Preferences.Constant.VIEWER_READ_THRESHOLD_5: readThresholdPosition = 5; break; case Preferences.Constant.VIEWER_READ_THRESHOLD_ALL: readThresholdPosition = theImages.size(); break; default: readThresholdPosition = 1; } int collectionIndex = readerIndex + thumbIndex + 1; boolean updateReads = (readPageNumbers.size() >= readThresholdPosition || theContent.getReads() > 0); // Reset the memorized page index if it represents the last page int indexToSet = (collectionIndex >= theImages.size()) ? 0 : collectionIndex; leaveDisposable = Completable.fromRunnable(() -> doLeaveBook(theContent.getId(), indexToSet, updateReads)) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( () -> leaveDisposable.dispose(), Timber::e ); } private void doLeaveBook(final long contentId, int indexToSet, boolean updateReads) { Helper.assertNonUiThread(); // Use a brand new DAO for that (the viewmodel's DAO may be in the process of being cleaned up) CollectionDAO dao = new ObjectBoxDAO(getApplication()); try { // Get a fresh version of current content in case it has been updated since the initial load // (that can be the case when viewing a book that is being downloaded) Content savedContent = dao.selectContent(contentId); if (null == savedContent) return; List<ImageFile> theImages = savedContent.getImageFiles(); if (null == theImages) return; // Update image read status with the cached read statuses long previousReadPagesCount = Stream.of(theImages).filter(ImageFile::isRead).filter(ImageFile::isReadable).count(); if (readPageNumbers.size() > previousReadPagesCount) { for (ImageFile img : theImages) if (readPageNumbers.contains(img.getOrder())) img.setRead(true); } if (indexToSet != savedContent.getLastReadPageIndex() || updateReads || readPageNumbers.size() > previousReadPagesCount) ContentHelper.updateContentReadStats(getApplication(), dao, savedContent, theImages, indexToSet, updateReads); } finally { dao.cleanup(); } } public void toggleFilterFavouritePages(Consumer<Boolean> callback) { if (loadedContentId > -1) { showFavourites = !showFavourites; if (searchManager != null) searchManager.setFilterPageFavourites(showFavourites); applySearchParams(loadedContentId); callback.accept(showFavourites); } } public void togglePageFavourite(ImageFile file, Consumer<ImageFile> callback) { compositeDisposable.add( Single.fromCallable(() -> doTogglePageFavourite(getApplication().getApplicationContext(), file.getId())) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( result -> onToggleFavouriteSuccess(result, callback), Timber::e ) ); } private void onToggleFavouriteSuccess(ImageFile result, Consumer<ImageFile> callback) { List<ImageFile> imgs = getImages().getValue(); if (imgs != null) { for (ImageFile img : imgs) if (img.getId() == result.getId()) { img.setFavourite(result.isFavourite()); // Update new state in memory result.setDisplayOrder(img.getDisplayOrder()); // Set the display order of the item to callback.accept(result); // Inform the view } } compositeDisposable.clear(); } /** * Toggles favourite flag in DB and in the content JSON * * @param context Context to be used for this operation * @param imageId ID of the image whose flag to toggle * @return ImageFile with the new state */ private ImageFile doTogglePageFavourite(Context context, long imageId) { Helper.assertNonUiThread(); ImageFile img = collectionDao.selectImageFile(imageId); if (img != null) { img.setFavourite(!img.isFavourite()); // Persist in DB collectionDao.insertImageFile(img); // Persist in JSON Content theContent = img.getContent().getTarget(); if (!theContent.getJsonUri().isEmpty()) ContentHelper.updateContentJson(context, theContent); else ContentHelper.createContentJson(context, theContent); return img; } else throw new InvalidParameterException(String.format("Invalid image ID %s", imageId)); } public void deleteBook(Consumer<Throwable> onError) { Content targetContent = collectionDao.selectContent(loadedContentId); if (null == targetContent) return; // Unplug image source listener (avoid displaying pages as they are being deleted; it messes up with DB transactions) if (currentImageSource != null) images.removeSource(currentImageSource); compositeDisposable.add( Completable.fromAction(() -> doDeleteBook(targetContent)) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( () -> { currentImageSource = null; // Switch to the next book if the list is populated (multi-book) if (!contentIds.isEmpty()) { contentIds.remove(currentContentIndex); if (currentContentIndex >= contentIds.size() && currentContentIndex > 0) currentContentIndex--; if (contentIds.size() > currentContentIndex) loadFromContent(contentIds.get(currentContentIndex)); } else { // Close the viewer if the list is empty (single book) content.postValue(null); } }, e -> { onError.accept(e); // Restore image source listener on error images.addSource(currentImageSource, imgs -> setImages(targetContent, imgs)); } ) ); } private void doDeleteBook(@NonNull Content targetContent) throws ContentNotRemovedException { Helper.assertNonUiThread(); ContentHelper.removeQueuedContent(getApplication(), collectionDao, targetContent); } public void deletePage(int pageIndex, Consumer<Throwable> onError) { List<ImageFile> imageFiles = images.getValue(); if (imageFiles != null && imageFiles.size() > pageIndex) deletePages(Stream.of(imageFiles.get(pageIndex)).toList(), onError); } public void deletePages(List<ImageFile> pages, Consumer<Throwable> onError) { compositeDisposable.add( Completable.fromRunnable(() -> doDeletePages(pages)) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( () -> { // Update is done through LiveData }, e -> { Timber.e(e); onError.accept(e); } ) ); } private void doDeletePages(@NonNull List<ImageFile> pages) { Helper.assertNonUiThread(); ContentHelper.removePages(pages, collectionDao, getApplication()); } public void setCover(ImageFile page) { compositeDisposable.add( Completable.fromRunnable(() -> doSetCover(page)) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( () -> { // Update is done through LiveData }, Timber::e ) ); } private void doSetCover(@NonNull ImageFile page) { Helper.assertNonUiThread(); ContentHelper.setContentCover(page, collectionDao, getApplication()); } public void loadNextContent(int readerIndex) { if (currentContentIndex < contentIds.size() - 1) { currentContentIndex++; if (!contentIds.isEmpty()) { onLeaveBook(readerIndex); loadFromContent(contentIds.get(currentContentIndex)); } } } public void loadPreviousContent(int readerIndex) { if (currentContentIndex > 0) { currentContentIndex--; if (!contentIds.isEmpty()) { onLeaveBook(readerIndex); loadFromContent(contentIds.get(currentContentIndex)); } } } private void processContent(@NonNull Content theContent) { currentContentIndex = contentIds.indexOf(theContent.getId()); if (-1 == currentContentIndex) currentContentIndex = 0; theContent.setFirst(0 == currentContentIndex); theContent.setLast(currentContentIndex >= contentIds.size() - 1); if (contentIds.size() > currentContentIndex && loadedContentId != contentIds.get(currentContentIndex)) imageLocations.clear(); content.postValue(theContent); // Observe the content's images // NB : It has to be dynamic to be updated when viewing a book from the queue screen if (currentImageSource != null) images.removeSource(currentImageSource); currentImageSource = collectionDao.selectDownloadedImagesFromContent(theContent.getId()); images.addSource(currentImageSource, imgs -> setImages(theContent, imgs)); } private void postLoadProcessing(@NonNull Context context, @NonNull Content content) { // Cache images in the Json file cacheJson(context, content); } public void updateContentPreferences(@NonNull final Map<String, String> newPrefs) { Content theContent = collectionDao.selectContent(loadedContentId); if (null == theContent) return; compositeDisposable.add( Completable.fromRunnable(() -> doUpdateContentPreferences(getApplication().getApplicationContext(), theContent, newPrefs)) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( () -> { // Update is done through LiveData }, Timber::e ) ); } private void doUpdateContentPreferences(@NonNull final Context context, @NonNull final Content c, @NonNull final Map<String, String> newPrefs) { Helper.assertNonUiThread(); Content theContent = collectionDao.selectContent(c.getId()); if (null == theContent) return; theContent.setBookPreferences(newPrefs); // Persist in DB collectionDao.insertContent(theContent); // Repost the updated content content.postValue(theContent); // Persist in JSON if (!theContent.getJsonUri().isEmpty()) ContentHelper.updateContentJson(context, theContent); else ContentHelper.createContentJson(context, theContent); } // Cache JSON URI in the database to speed up favouriting private void cacheJson(@NonNull Context context, @NonNull Content content) { Helper.assertNonUiThread(); if (!content.getJsonUri().isEmpty() || content.isArchive()) return; DocumentFile folder = FileHelper.getFolderFromTreeUriString(context, content.getStorageUri()); if (null == folder) return; DocumentFile foundFile = FileHelper.findFile(getApplication(), folder, Consts.JSON_FILE_NAME_V2); if (null == foundFile) { Timber.e("JSON file not detected in %s", content.getStorageUri()); return; } // Cache the URI of the JSON to the database content.setJsonUri(foundFile.getUri().toString()); collectionDao.insertContent(content); } @Nullable private File getOrCreatePictureCacheFolder() { File cacheDir = getApplication().getCacheDir(); File pictureCacheDir = new File(cacheDir.getAbsolutePath() + File.separator + Consts.PICTURE_CACHE_FOLDER); if (pictureCacheDir.exists()) return pictureCacheDir; else if (pictureCacheDir.mkdir()) return pictureCacheDir; else return null; } public void markPageAsRead(int pageNumber) { readPageNumbers.add(pageNumber); } }
Remove duplicate call
app/src/main/java/me/devsaki/hentoid/viewmodels/ImageViewerViewModel.java
Remove duplicate call
<ide><path>pp/src/main/java/me/devsaki/hentoid/viewmodels/ImageViewerViewModel.java <ide> } <ide> <ide> public void updateContentPreferences(@NonNull final Map<String, String> newPrefs) { <del> Content theContent = collectionDao.selectContent(loadedContentId); <del> if (null == theContent) return; <del> <ide> compositeDisposable.add( <del> Completable.fromRunnable(() -> doUpdateContentPreferences(getApplication().getApplicationContext(), theContent, newPrefs)) <add> Completable.fromRunnable(() -> doUpdateContentPreferences(getApplication().getApplicationContext(), loadedContentId, newPrefs)) <ide> .subscribeOn(Schedulers.io()) <ide> .observeOn(AndroidSchedulers.mainThread()) <ide> .subscribe( <ide> ); <ide> } <ide> <del> private void doUpdateContentPreferences(@NonNull final Context context, <del> @NonNull final Content c, @NonNull final Map<String, String> newPrefs) { <add> private void doUpdateContentPreferences(@NonNull final Context context, long contentId, @NonNull final Map<String, String> newPrefs) { <ide> Helper.assertNonUiThread(); <ide> <del> Content theContent = collectionDao.selectContent(c.getId()); <add> Content theContent = collectionDao.selectContent(contentId); <ide> if (null == theContent) return; <ide> <ide> theContent.setBookPreferences(newPrefs);
Java
apache-2.0
14f64794c722522da59ec8b83d6dd17f95f8a54d
0
tejksat/docker-java,gesellix/docker-java,gesellix/docker-java,tourea/docker-java,ollie314/docker-java,ollie314/docker-java,tejksat/docker-java,tourea/docker-java,llamahunter/docker-java,magnayn/docker-java,docker-java/docker-java,magnayn/docker-java,llamahunter/docker-java,docker-java/docker-java
package com.github.dockerjava.core.command; import java.util.HashMap; import java.util.Map; import com.fasterxml.jackson.annotation.JsonProperty; import com.github.dockerjava.api.command.CreateNetworkCmd; import com.github.dockerjava.api.command.CreateNetworkResponse; import com.github.dockerjava.api.command.DockerCmdSyncExec; import com.github.dockerjava.api.model.Network; import com.github.dockerjava.api.model.Network.Ipam; public class CreateNetworkCmdImpl extends AbstrDockerCmd<CreateNetworkCmd, CreateNetworkResponse> implements CreateNetworkCmd { @JsonProperty("Name") private String name; @JsonProperty("Driver") private String driver; @JsonProperty("IPAM") private Network.Ipam ipam; @JsonProperty("Options") private Map<String, String> options = new HashMap<>(); public CreateNetworkCmdImpl(DockerCmdSyncExec<CreateNetworkCmd, CreateNetworkResponse> execution) { super(execution); } @Override public String getName() { return name; } @Override public String getDriver() { return driver; } @Override public Network.Ipam getIpam() { return ipam; } @Override public CreateNetworkCmd withName(String name) { this.name = name; return this; } @Override public CreateNetworkCmd withDriver(String driver) { this.driver = driver; return this; } @Override public CreateNetworkCmd withIpamConfig(Ipam.Config config) { if (this.ipam == null) { this.ipam = new Ipam(); } this.ipam.getConfig().add(config); return this; } @Override public CreateNetworkCmd withOptions(Map<String, String> options) { this.options = options; return this; } }
src/main/java/com/github/dockerjava/core/command/CreateNetworkCmdImpl.java
package com.github.dockerjava.core.command; import java.util.HashMap; import java.util.Map; import com.fasterxml.jackson.annotation.JsonProperty; import com.github.dockerjava.api.command.CreateNetworkCmd; import com.github.dockerjava.api.command.CreateNetworkResponse; import com.github.dockerjava.api.command.DockerCmdSyncExec; import com.github.dockerjava.api.model.Network; import com.github.dockerjava.api.model.Network.Ipam; public class CreateNetworkCmdImpl extends AbstrDockerCmd<CreateNetworkCmd, CreateNetworkResponse> implements CreateNetworkCmd { @JsonProperty("Name") private String name; @JsonProperty("Driver") private String driver; @JsonProperty("IPAM") private Network.Ipam ipam; @JsonProperty("Options") private Map<String, String> options = new HashMap<>(); public CreateNetworkCmdImpl(DockerCmdSyncExec<CreateNetworkCmd, CreateNetworkResponse> execution) { super(execution); } @Override public String getName() { return name; } @Override public String getDriver() { return driver; } @Override public Network.Ipam getIpam() { return ipam; } @Override public CreateNetworkCmd withName(String name) { this.name = name; return this; } @Override public CreateNetworkCmd withDriver(String driver) { this.driver = driver; return this; } @Override public CreateNetworkCmd withIpamConfig(Ipam.Config config) { this.ipam.getConfig().add(config); return this; } @Override public CreateNetworkCmd withOptions(Map<String, String> options) { this.options = options; return this; } }
Fix NPE for withIpamConfig
src/main/java/com/github/dockerjava/core/command/CreateNetworkCmdImpl.java
Fix NPE for withIpamConfig
<ide><path>rc/main/java/com/github/dockerjava/core/command/CreateNetworkCmdImpl.java <ide> <ide> @Override <ide> public CreateNetworkCmd withIpamConfig(Ipam.Config config) { <add> if (this.ipam == null) { <add> this.ipam = new Ipam(); <add> } <ide> this.ipam.getConfig().add(config); <ide> return this; <ide> }
Java
apache-2.0
d1e41361c4d9ab98a9fb8b92ef9ea47eac5d2ad0
0
forcedotcom/aura,forcedotcom/aura,madmax983/aura,forcedotcom/aura,madmax983/aura,madmax983/aura,forcedotcom/aura,madmax983/aura,madmax983/aura,madmax983/aura,forcedotcom/aura
/* * Copyright (C) 2013 salesforce.com, 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 org.auraframework.util.javascript.directive; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.EnumSet; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.StringJoiner; import java.util.concurrent.CountDownLatch; import org.auraframework.util.IOUtil; import org.auraframework.util.javascript.CommonJavascriptGroupImpl; import org.auraframework.util.javascript.JavascriptWriter; import org.auraframework.util.resource.ResourceLoader; import org.auraframework.util.text.Hash; import com.google.common.base.Charsets; import com.google.common.io.Resources; /** * Javascript group that contains directives for parsing instructions or metadata or other fun stuff. It starts from one * file which should include the others. */ public class DirectiveBasedJavascriptGroup extends CommonJavascriptGroupImpl { /** * We spawn multiple threads to go the per-mode generation, and throw this to indicate at least one failure. When * printed, this exception will have a "caused by" stack trace for the first error, but its message will identify * the cause (and failing thread, which hints at the compilation mode) for each error encountered. */ public static class CompositeRuntimeException extends RuntimeException { private static final long serialVersionUID = 7863307967596024441L; public Map<String, Throwable> errors; public CompositeRuntimeException(String message, Map<String, Throwable> errors) { super(message, errors == null || errors.isEmpty() ? null : errors.entrySet().iterator().next().getValue()); this.errors = errors; } /** Prints an overall summary, and the message of each error. */ @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append(getClass().getName()); String message = getMessage(); if (message != null && message.isEmpty()) { message = null; } if (message != null || errors.size() > 0) { builder.append(": "); } if (message != null) { builder.append(message); builder.append("\n"); } if (errors.size() > 0) { builder.append(errors.size()); builder.append(" threads failed with throwables\n"); for (Map.Entry<String, Throwable> ent : errors.entrySet()) { builder.append("["); builder.append(ent.getKey()); builder.append("] "); Throwable thrown = ent.getValue(); builder.append(thrown.getClass().getName()); message = thrown.getMessage(); if (message != null && !message.isEmpty()) { builder.append(": "); builder.append(message); } builder.append("\n"); } } return builder.toString(); } } // Caching for resources private static final String LIB_CACHE_TEMP_DIR = IOUtil.newTempDir("auracache"); // name for threads that compress and write the output public static final String THREAD_NAME = "jsgen."; private static final String COMPAT_SUFFIX = "_compat"; private final List<DirectiveType<?>> directiveTypes; private final Set<JavascriptGeneratorMode> modes; private final File startFile; private CountDownLatch counter; private Map<String, Throwable> errors; private String librariesContent = ""; private String librariesContentMin = ""; private String compatLibrariesContent = ""; private String compatLibrariesContentMin = ""; private String locker = ""; private String lockerMin = ""; private String lockerCompat = ""; private String lockerCompatMin = ""; private String engine = ""; private String engineMin = ""; private String engineCompat= ""; private String engineCompatMin = ""; private String engineProdDebug = ""; private String engineCompatProdDebug = ""; // used during parsing, should be clear for storing in memory private DirectiveParser parser; protected ResourceLoader resourceLoader = null; public DirectiveBasedJavascriptGroup(String name, File root, String start) throws IOException { this(name, root, start, DirectiveTypes.DEFAULT_TYPES, EnumSet.of(JavascriptGeneratorMode.DEVELOPMENT, JavascriptGeneratorMode.PRODUCTION)); errors = null; } public DirectiveBasedJavascriptGroup(String name, File root, String start, List<DirectiveType<?>> directiveTypes, Set<JavascriptGeneratorMode> modes) throws IOException { super(name, root); this.directiveTypes = directiveTypes; this.modes = modes; this.startFile = addFile(start); } public List<DirectiveType<?>> getDirectiveTypes() { return directiveTypes; } public File getStartFile() { return startFile; } public Set<JavascriptGeneratorMode> getJavascriptGeneratorModes() { return modes; } @Override public void parse() throws IOException { parser = new DirectiveParser(this, getStartFile()); parser.parseFile(); } @Override public void generate(File destRoot, boolean doValidation) throws IOException { if (parser == null) { throw new RuntimeException("No parser available to generate with"); } // generating all modes along with engine compatibility counter = new CountDownLatch(modes.size() * 2); errors = new HashMap<>(); fetchIncludedSources(); for (JavascriptGeneratorMode mode : modes) { generateForMode(destRoot, mode); } try { counter.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } if (!errors.isEmpty()) { throw new CompositeRuntimeException("Errors generating javascript for " + getName(), errors); } errors = null; } private void fetchIncludedSources() throws MalformedURLException { List<String> libraries = new ArrayList<>(); libraries.add("aura/resources/moment/moment"); libraries.add("aura/resources/DOMPurify/DOMPurify"); StringJoiner libs = new StringJoiner("\n"); StringJoiner libsMin = new StringJoiner("\n"); libraries.forEach( (path) -> { String source = null; String minSource = null; try { source = getSource(path + ".js"); minSource = getSource(path +".min.js"); } catch (MalformedURLException e) {} if (source != null) { libs.add(source); } if (minSource != null) { libsMin.add(minSource); } }); if (libs.length() != 0) { this.librariesContent = "\nAura.externalLibraries = function() {\n" + libs.toString() + "\n};"; } if (libsMin.length() != 0) { this.librariesContentMin = "\nAura.externalLibraries = function() {\n" + libsMin.toString() + "\n};"; } List<String> compatLibraries = new ArrayList<>(); compatLibraries.add("aura/resources/IntlTimeZonePolyfill/IntlTimeZonePolyfill"); compatLibraries.forEach( (path) -> { String source = null; String minSource = null; try { source = getSource(path + ".js"); minSource = getSource(path +".min.js"); } catch (MalformedURLException e) {} if (source != null) { source = "try {\n" + source + "\n} catch (e) {}\n"; libs.add(source); } if (minSource != null) { minSource = "try {\n" + minSource + "\n} catch (e) {}\n"; libsMin.add(minSource); } }); if (libs.length() != 0) { this.compatLibrariesContent = "\nAura.externalLibraries = function() {\n" + libs.toString() + "\n};"; } if (libsMin.length() != 0) { this.compatLibrariesContentMin = "\nAura.externalLibraries = function() {\n" + libsMin.toString() + "\n};"; } // Locker String lockerSource = null; String lockerMinSource = null; String lockerDisabledSource = null; String lockerDisabledMinSource = null; try { lockerSource = getSource("aura/resources/lockerservice/aura-locker.js"); lockerMinSource = getSource("aura/resources/lockerservice/aura-locker.min.js"); lockerDisabledSource = getSource("aura/resources/lockerservice/aura-locker-disabled.js"); lockerDisabledMinSource = getSource("aura/resources/lockerservice/aura-locker-disabled.min.js"); } catch (MalformedURLException e) {} // We always include locker disabled, and don't include locker in compat mode. if (lockerSource != null && lockerDisabledSource != null) { locker = "try {\n" + lockerSource + "\n} catch (e) {}\n" + "try {\n" + lockerDisabledSource + "\n} catch (e) {}\n"; } if (lockerMinSource != null && lockerDisabledMinSource != null) { lockerMin = "try {\n" + lockerMinSource + "\n} catch (e) {}\n" + "try {\n" + lockerDisabledMinSource + "\n} catch (e) {}\n"; } if (lockerDisabledSource != null) { lockerCompat = "try {\n" + lockerDisabledSource + "\n} catch (e) {}\n"; } if (lockerDisabledMinSource != null) { lockerCompatMin = "try {\n" + lockerDisabledMinSource + "\n} catch (e) {}\n"; } // Engine String engineSource = null; String engineMinSource = null; String engineCompatSource = null; String engineCompatMinSource = null; String engineProdDebugSource = null; String engineCompatProdDebugSource = null; // Wire String wireSource = null; String wireMinSource = null; String wireCompatSource = null; String wireCompatMinSource = null; String wireProdDebugSource = null; String wireCompatProdDebugSource = null; // Compat Helper String compatHelpersSource = null; String compatHelpersMinSource = null; try { engineSource = getSource("lwc/engine/es2017/engine.js"); engineMinSource = getSource("lwc/engine/es2017/engine.min.js"); engineCompatSource = getSource("lwc/engine/es5/engine.js"); engineCompatMinSource = getSource("lwc/engine/es5/engine.min.js"); engineProdDebugSource = getSource("lwc/engine/es2017/engine_debug.js"); engineCompatProdDebugSource = getSource("lwc/engine/es5/engine_debug.js"); wireSource = getSource("lwc/wire-service/es2017/wire.js"); wireMinSource = getSource("lwc/wire-service/es2017/wire.min.js"); wireCompatSource = getSource("lwc/wire-service/es5/wire.js"); wireCompatMinSource = getSource("lwc/wire-service/es5/wire.min.js"); wireProdDebugSource = getSource("lwc/wire-service/es2017/wire_debug.js"); wireCompatProdDebugSource = getSource("lwc/wire-service/es2017/wire_debug.js"); compatHelpersSource = getSource("lwc/proxy-compat/compat.js"); compatHelpersMinSource = getSource("lwc/proxy-compat/compat.min.js"); } catch (MalformedURLException e) {} String iifeBegin = "\"undefined\"===typeof Aura&&(Aura={});(function getModuleGlobals(window){\n"; String iifeEnd = "}).call(Aura, window);\n"; if (engineSource != null && wireSource != null) { this.engine = iifeBegin + engineSource + wireSource + iifeEnd; } if (engineMinSource != null && wireMinSource != null) { this.engineMin = iifeBegin + engineMinSource + wireMinSource + iifeEnd; } if (compatHelpersSource != null && engineCompatSource != null && wireCompatSource != null) { this.engineCompat = compatHelpersSource + "\n" + iifeBegin + engineCompatSource + wireCompatSource + iifeEnd; } if (compatHelpersMinSource != null && engineCompatMinSource != null && wireCompatMinSource != null) { this.engineCompatMin = compatHelpersMinSource + "\n" + iifeBegin + engineCompatMinSource + wireCompatMinSource + iifeEnd; } if (engineProdDebugSource != null && wireProdDebugSource != null) { this.engineProdDebug = iifeBegin + engineProdDebugSource + wireProdDebugSource + iifeEnd; } if (compatHelpersSource != null && engineCompatProdDebugSource != null && wireCompatProdDebugSource != null) { this.engineCompatProdDebug = compatHelpersSource + "\n" + iifeBegin + engineCompatProdDebugSource + wireCompatProdDebugSource + iifeEnd; } } public String getSource(String path) throws MalformedURLException { if (this.resourceLoader == null) { this.resourceLoader = new ResourceLoader(LIB_CACHE_TEMP_DIR, true); } URL lib = this.resourceLoader.getResource(path); String source = null; if (lib != null) { try { source = Resources.toString(lib, Charsets.UTF_8); } catch (IOException ignored) { } } return source; } protected void generateForMode(File destRoot, final JavascriptGeneratorMode mode) throws IOException { final File modeJs = new File(destRoot, getName() + "_" + mode.getSuffix() + ".js"); final File modeCompatJs = new File(destRoot, getName() + "_" + mode.getSuffix() + COMPAT_SUFFIX + ".js"); List<File> filesToWrite = new ArrayList<>(); filesToWrite.add(modeJs); filesToWrite.add(modeCompatJs); final String everything = buildContent(mode); final String threadName = THREAD_NAME + mode; int writtenCount = 0; List<File> writtenFiles = new ArrayList<>(); for (File file : filesToWrite) { if (file.exists()) { if (file.lastModified() < getLastMod() || !mode.allowedInProduction()) { file.delete(); } else { // its up to date already, skip counter.countDown(); writtenFiles.add(file); if (++writtenCount == 2) return; else continue; } } file.getParentFile().mkdirs(); } Runnable writeMode = () -> { try { Writer writer = null; JavascriptWriter jsWriter = mode.getJavascriptWriter(); boolean minified = jsWriter == JavascriptWriter.CLOSURE_AURA_PROD; StringWriter stringWriter = new StringWriter(); jsWriter.compress(everything, stringWriter, modeJs.getName()); String compressed = stringWriter.toString(); // strip out spaces and comments for external libraries JavascriptWriter libsJsWriter = JavascriptWriter.CLOSURE_WHITESPACE_ONLY; for (File output : filesToWrite) { if (writtenFiles.contains(output)) continue; boolean isProdDebug = mode == JavascriptGeneratorMode.PRODUCTIONDEBUG; boolean isCompat = output.getName().contains(COMPAT_SUFFIX); try { writer = new FileWriter(output); if (mode != JavascriptGeneratorMode.DOC) { if (mode.isTestingMode()) { writer.append("typeof process === 'undefined' ? (process = { env: { NODE_ENV: 'test' } }) : process.env ? process.env.NODE_ENV = 'test' : process.env = { NODE_ENV: 'test' } ").append("\n"); } // jsdoc errors when parsing engine.js String eng = minified ? (isCompat ? engineCompatMin : mode == JavascriptGeneratorMode.AUTOTESTING ? engine : engineMin) : (isCompat ? ( isProdDebug ? engineCompatProdDebug : engineCompat) : ( isProdDebug ? engineProdDebug : engine)); writer.append(eng).append("\n"); // jsdoc errors when parsing aura-locker.js String ls = minified ? (isCompat ? lockerCompatMin : lockerMin) : (isCompat ? lockerCompat : locker); writer.append(ls).append("\n"); } writer.append(compressed).append("\n"); // external libraries String libs = minified ? (isCompat ? this.compatLibrariesContentMin : this.librariesContentMin) : (isCompat ? this.compatLibrariesContent : librariesContent); StringWriter libsWriter = new StringWriter(); libsJsWriter.compress(libs, libsWriter, output.getName()); writer.append(libsWriter.toString()).append("\n"); } finally { if (writer != null) { writer.close(); } output.setReadOnly(); counter.countDown(); } } } catch (Throwable t) { // Store any problems, to be thrown in a composite runtime exception from the main thread. // Otherwise, they kill this worker thread but are basically ignored. errors.put(threadName, t); } }; new Thread(writeMode, threadName).start(); } protected String buildContent(JavascriptGeneratorMode mode) { return parser.generate(mode); } @Override public boolean isStale() { if (!isGroupHashKnown()) { return true; } // Otherwise, we're stale IFF we have changed contents. try { Hash currentTextHash = computeGroupHash(getFiles()); return !currentTextHash.equals(getGroupHash()); } catch (IOException e) { // presume we're stale; we'll probably try to regenerate and die from that. return true; } } @Override public void postProcess() { // parser isn't needed at runtime parser = null; } @Override public void regenerate(File destRoot) throws IOException { reset(); // 202: Disable JS validation since we precompile definitions generate(destRoot, false); postProcess(); } @Override public void reset() throws IOException { setContents(null, this.startFile); parse(); getGroupHash(); // Ensure the new bundle knows its hash once the directives are parsed. } }
aura-util/src/main/java/org/auraframework/util/javascript/directive/DirectiveBasedJavascriptGroup.java
/* * Copyright (C) 2013 salesforce.com, 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 org.auraframework.util.javascript.directive; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.EnumSet; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.StringJoiner; import java.util.concurrent.CountDownLatch; import org.auraframework.util.IOUtil; import org.auraframework.util.javascript.CommonJavascriptGroupImpl; import org.auraframework.util.javascript.JavascriptWriter; import org.auraframework.util.resource.ResourceLoader; import org.auraframework.util.text.Hash; import com.google.common.base.Charsets; import com.google.common.io.Resources; /** * Javascript group that contains directives for parsing instructions or metadata or other fun stuff. It starts from one * file which should include the others. */ public class DirectiveBasedJavascriptGroup extends CommonJavascriptGroupImpl { /** * We spawn multiple threads to go the per-mode generation, and throw this to indicate at least one failure. When * printed, this exception will have a "caused by" stack trace for the first error, but its message will identify * the cause (and failing thread, which hints at the compilation mode) for each error encountered. */ public static class CompositeRuntimeException extends RuntimeException { private static final long serialVersionUID = 7863307967596024441L; public Map<String, Throwable> errors; public CompositeRuntimeException(String message, Map<String, Throwable> errors) { super(message, errors == null || errors.isEmpty() ? null : errors.entrySet().iterator().next().getValue()); this.errors = errors; } /** Prints an overall summary, and the message of each error. */ @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append(getClass().getName()); String message = getMessage(); if (message != null && message.isEmpty()) { message = null; } if (message != null || errors.size() > 0) { builder.append(": "); } if (message != null) { builder.append(message); builder.append("\n"); } if (errors.size() > 0) { builder.append(errors.size()); builder.append(" threads failed with throwables\n"); for (Map.Entry<String, Throwable> ent : errors.entrySet()) { builder.append("["); builder.append(ent.getKey()); builder.append("] "); Throwable thrown = ent.getValue(); builder.append(thrown.getClass().getName()); message = thrown.getMessage(); if (message != null && !message.isEmpty()) { builder.append(": "); builder.append(message); } builder.append("\n"); } } return builder.toString(); } } // Caching for resources private static final String LIB_CACHE_TEMP_DIR = IOUtil.newTempDir("auracache"); // name for threads that compress and write the output public static final String THREAD_NAME = "jsgen."; private static final String COMPAT_SUFFIX = "_compat"; private final List<DirectiveType<?>> directiveTypes; private final Set<JavascriptGeneratorMode> modes; private final File startFile; private CountDownLatch counter; private Map<String, Throwable> errors; private String librariesContent = ""; private String librariesContentMin = ""; private String compatLibrariesContent = ""; private String compatLibrariesContentMin = ""; private String locker = ""; private String lockerMin = ""; private String lockerCompat = ""; private String lockerCompatMin = ""; private String engine = ""; private String engineMin = ""; private String engineCompat= ""; private String engineCompatMin = ""; private String engineProdDebug = ""; private String engineCompatProdDebug = ""; // used during parsing, should be clear for storing in memory private DirectiveParser parser; protected ResourceLoader resourceLoader = null; public DirectiveBasedJavascriptGroup(String name, File root, String start) throws IOException { this(name, root, start, DirectiveTypes.DEFAULT_TYPES, EnumSet.of(JavascriptGeneratorMode.DEVELOPMENT, JavascriptGeneratorMode.PRODUCTION)); errors = null; } public DirectiveBasedJavascriptGroup(String name, File root, String start, List<DirectiveType<?>> directiveTypes, Set<JavascriptGeneratorMode> modes) throws IOException { super(name, root); this.directiveTypes = directiveTypes; this.modes = modes; this.startFile = addFile(start); } public List<DirectiveType<?>> getDirectiveTypes() { return directiveTypes; } public File getStartFile() { return startFile; } public Set<JavascriptGeneratorMode> getJavascriptGeneratorModes() { return modes; } @Override public void parse() throws IOException { parser = new DirectiveParser(this, getStartFile()); parser.parseFile(); } @Override public void generate(File destRoot, boolean doValidation) throws IOException { if (parser == null) { throw new RuntimeException("No parser available to generate with"); } // generating all modes along with engine compatibility counter = new CountDownLatch(modes.size() * 2); errors = new HashMap<>(); fetchIncludedSources(); for (JavascriptGeneratorMode mode : modes) { generateForMode(destRoot, mode); } try { counter.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } if (!errors.isEmpty()) { throw new CompositeRuntimeException("Errors generating javascript for " + getName(), errors); } errors = null; } private void fetchIncludedSources() throws MalformedURLException { List<String> libraries = new ArrayList<>(); libraries.add("aura/resources/moment/moment"); libraries.add("aura/resources/DOMPurify/DOMPurify"); StringJoiner libs = new StringJoiner("\n"); StringJoiner libsMin = new StringJoiner("\n"); libraries.forEach( (path) -> { String source = null; String minSource = null; try { source = getSource(path + ".js"); minSource = getSource(path +".min.js"); } catch (MalformedURLException e) {} if (source != null) { libs.add(source); } if (minSource != null) { libsMin.add(minSource); } }); if (libs.length() != 0) { this.librariesContent = "\nAura.externalLibraries = function() {\n" + libs.toString() + "\n};"; } if (libsMin.length() != 0) { this.librariesContentMin = "\nAura.externalLibraries = function() {\n" + libsMin.toString() + "\n};"; } List<String> compatLibraries = new ArrayList<>(); compatLibraries.add("aura/resources/IntlTimeZonePolyfill/IntlTimeZonePolyfill"); compatLibraries.forEach( (path) -> { String source = null; String minSource = null; try { source = getSource(path + ".js"); minSource = getSource(path +".min.js"); } catch (MalformedURLException e) {} if (source != null) { libs.add(source); } if (minSource != null) { libsMin.add(minSource); } }); if (libs.length() != 0) { this.compatLibrariesContent = "\nAura.externalLibraries = function() {\n" + libs.toString() + "\n};"; } if (libsMin.length() != 0) { this.compatLibrariesContentMin = "\nAura.externalLibraries = function() {\n" + libsMin.toString() + "\n};"; } // Locker String lockerSource = null; String lockerMinSource = null; String lockerDisabledSource = null; String lockerDisabledMinSource = null; try { lockerSource = getSource("aura/resources/lockerservice/aura-locker.js"); lockerMinSource = getSource("aura/resources/lockerservice/aura-locker.min.js"); lockerDisabledSource = getSource("aura/resources/lockerservice/aura-locker-disabled.js"); lockerDisabledMinSource = getSource("aura/resources/lockerservice/aura-locker-disabled.min.js"); } catch (MalformedURLException e) {} // We always include locker disabled, and don't include locker in compat mode. if (lockerSource != null && lockerDisabledSource != null) { locker = "try {\n" + lockerSource + "\n} catch (e) {}\n" + "try {\n" + lockerDisabledSource + "\n} catch (e) {}\n"; } if (lockerMinSource != null && lockerDisabledMinSource != null) { lockerMin = "try {\n" + lockerMinSource + "\n} catch (e) {}\n" + "try {\n" + lockerDisabledMinSource + "\n} catch (e) {}\n"; } if (lockerDisabledSource != null) { lockerCompat = "try {\n" + lockerDisabledSource + "\n} catch (e) {}\n"; } if (lockerDisabledMinSource != null) { lockerCompatMin = "try {\n" + lockerDisabledMinSource + "\n} catch (e) {}\n"; } // Engine String engineSource = null; String engineMinSource = null; String engineCompatSource = null; String engineCompatMinSource = null; String engineProdDebugSource = null; String engineCompatProdDebugSource = null; // Wire String wireSource = null; String wireMinSource = null; String wireCompatSource = null; String wireCompatMinSource = null; String wireProdDebugSource = null; String wireCompatProdDebugSource = null; // Compat Helper String compatHelpersSource = null; String compatHelpersMinSource = null; try { engineSource = getSource("lwc/engine/es2017/engine.js"); engineMinSource = getSource("lwc/engine/es2017/engine.min.js"); engineCompatSource = getSource("lwc/engine/es5/engine.js"); engineCompatMinSource = getSource("lwc/engine/es5/engine.min.js"); engineProdDebugSource = getSource("lwc/engine/es2017/engine_debug.js"); engineCompatProdDebugSource = getSource("lwc/engine/es5/engine_debug.js"); wireSource = getSource("lwc/wire-service/es2017/wire.js"); wireMinSource = getSource("lwc/wire-service/es2017/wire.min.js"); wireCompatSource = getSource("lwc/wire-service/es5/wire.js"); wireCompatMinSource = getSource("lwc/wire-service/es5/wire.min.js"); wireProdDebugSource = getSource("lwc/wire-service/es2017/wire_debug.js"); wireCompatProdDebugSource = getSource("lwc/wire-service/es2017/wire_debug.js"); compatHelpersSource = getSource("lwc/proxy-compat/compat.js"); compatHelpersMinSource = getSource("lwc/proxy-compat/compat.min.js"); } catch (MalformedURLException e) {} String iifeBegin = "\"undefined\"===typeof Aura&&(Aura={});(function getModuleGlobals(window){\n"; String iifeEnd = "}).call(Aura, window);\n"; if (engineSource != null && wireSource != null) { this.engine = iifeBegin + engineSource + wireSource + iifeEnd; } if (engineMinSource != null && wireMinSource != null) { this.engineMin = iifeBegin + engineMinSource + wireMinSource + iifeEnd; } if (compatHelpersSource != null && engineCompatSource != null && wireCompatSource != null) { this.engineCompat = compatHelpersSource + "\n" + iifeBegin + engineCompatSource + wireCompatSource + iifeEnd; } if (compatHelpersMinSource != null && engineCompatMinSource != null && wireCompatMinSource != null) { this.engineCompatMin = compatHelpersMinSource + "\n" + iifeBegin + engineCompatMinSource + wireCompatMinSource + iifeEnd; } if (engineProdDebugSource != null && wireProdDebugSource != null) { this.engineProdDebug = iifeBegin + engineProdDebugSource + wireProdDebugSource + iifeEnd; } if (compatHelpersSource != null && engineCompatProdDebugSource != null && wireCompatProdDebugSource != null) { this.engineCompatProdDebug = compatHelpersSource + "\n" + iifeBegin + engineCompatProdDebugSource + wireCompatProdDebugSource + iifeEnd; } } public String getSource(String path) throws MalformedURLException { if (this.resourceLoader == null) { this.resourceLoader = new ResourceLoader(LIB_CACHE_TEMP_DIR, true); } URL lib = this.resourceLoader.getResource(path); String source = null; if (lib != null) { try { source = Resources.toString(lib, Charsets.UTF_8); } catch (IOException ignored) { } } return source; } protected void generateForMode(File destRoot, final JavascriptGeneratorMode mode) throws IOException { final File modeJs = new File(destRoot, getName() + "_" + mode.getSuffix() + ".js"); final File modeCompatJs = new File(destRoot, getName() + "_" + mode.getSuffix() + COMPAT_SUFFIX + ".js"); List<File> filesToWrite = new ArrayList<>(); filesToWrite.add(modeJs); filesToWrite.add(modeCompatJs); final String everything = buildContent(mode); final String threadName = THREAD_NAME + mode; int writtenCount = 0; List<File> writtenFiles = new ArrayList<>(); for (File file : filesToWrite) { if (file.exists()) { if (file.lastModified() < getLastMod() || !mode.allowedInProduction()) { file.delete(); } else { // its up to date already, skip counter.countDown(); writtenFiles.add(file); if (++writtenCount == 2) return; else continue; } } file.getParentFile().mkdirs(); } Runnable writeMode = () -> { try { Writer writer = null; JavascriptWriter jsWriter = mode.getJavascriptWriter(); boolean minified = jsWriter == JavascriptWriter.CLOSURE_AURA_PROD; StringWriter stringWriter = new StringWriter(); jsWriter.compress(everything, stringWriter, modeJs.getName()); String compressed = stringWriter.toString(); // strip out spaces and comments for external libraries JavascriptWriter libsJsWriter = JavascriptWriter.CLOSURE_WHITESPACE_ONLY; for (File output : filesToWrite) { if (writtenFiles.contains(output)) continue; boolean isProdDebug = mode == JavascriptGeneratorMode.PRODUCTIONDEBUG; boolean isCompat = output.getName().contains(COMPAT_SUFFIX); try { writer = new FileWriter(output); if (mode != JavascriptGeneratorMode.DOC) { if (mode.isTestingMode()) { writer.append("typeof process === 'undefined' ? (process = { env: { NODE_ENV: 'test' } }) : process.env ? process.env.NODE_ENV = 'test' : process.env = { NODE_ENV: 'test' } ").append("\n"); } // jsdoc errors when parsing engine.js String eng = minified ? (isCompat ? engineCompatMin : mode == JavascriptGeneratorMode.AUTOTESTING ? engine : engineMin) : (isCompat ? ( isProdDebug ? engineCompatProdDebug : engineCompat) : ( isProdDebug ? engineProdDebug : engine)); writer.append(eng).append("\n"); // jsdoc errors when parsing aura-locker.js String ls = minified ? (isCompat ? lockerCompatMin : lockerMin) : (isCompat ? lockerCompat : locker); writer.append(ls).append("\n"); } writer.append(compressed).append("\n"); // external libraries String libs = minified ? (isCompat ? this.compatLibrariesContentMin : this.librariesContentMin) : (isCompat ? this.compatLibrariesContent : librariesContent); StringWriter libsWriter = new StringWriter(); libsJsWriter.compress(libs, libsWriter, output.getName()); writer.append(libsWriter.toString()).append("\n"); } finally { if (writer != null) { writer.close(); } output.setReadOnly(); counter.countDown(); } } } catch (Throwable t) { // Store any problems, to be thrown in a composite runtime exception from the main thread. // Otherwise, they kill this worker thread but are basically ignored. errors.put(threadName, t); } }; new Thread(writeMode, threadName).start(); } protected String buildContent(JavascriptGeneratorMode mode) { return parser.generate(mode); } @Override public boolean isStale() { if (!isGroupHashKnown()) { return true; } // Otherwise, we're stale IFF we have changed contents. try { Hash currentTextHash = computeGroupHash(getFiles()); return !currentTextHash.equals(getGroupHash()); } catch (IOException e) { // presume we're stale; we'll probably try to regenerate and die from that. return true; } } @Override public void postProcess() { // parser isn't needed at runtime parser = null; } @Override public void regenerate(File destRoot) throws IOException { reset(); // 202: Disable JS validation since we precompile definitions generate(destRoot, false); postProcess(); } @Override public void reset() throws IOException { setContents(null, this.startFile); parse(); getGroupHash(); // Ensure the new bundle knows its hash once the directives are parsed. } }
try catch Intl polyfill for ie9 support (#2929)
aura-util/src/main/java/org/auraframework/util/javascript/directive/DirectiveBasedJavascriptGroup.java
try catch Intl polyfill for ie9 support (#2929)
<ide><path>ura-util/src/main/java/org/auraframework/util/javascript/directive/DirectiveBasedJavascriptGroup.java <ide> minSource = getSource(path +".min.js"); <ide> } catch (MalformedURLException e) {} <ide> if (source != null) { <add> source = "try {\n" + source + "\n} catch (e) {}\n"; <ide> libs.add(source); <ide> } <ide> if (minSource != null) { <add> minSource = "try {\n" + minSource + "\n} catch (e) {}\n"; <ide> libsMin.add(minSource); <ide> } <ide> });
Java
apache-2.0
334441363019e7dddbda058078417a6060beed4e
0
hortonworks/cloudbreak,hortonworks/cloudbreak,hortonworks/cloudbreak,hortonworks/cloudbreak,hortonworks/cloudbreak,hortonworks/cloudbreak
package com.sequenceiq.environment.network.service; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.List; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import com.sequenceiq.cloudbreak.cloud.CloudConnector; import com.sequenceiq.cloudbreak.cloud.NetworkConnector; import com.sequenceiq.cloudbreak.cloud.init.CloudPlatformConnectors; import com.sequenceiq.cloudbreak.cloud.model.CloudSubnet; import com.sequenceiq.cloudbreak.cloud.model.SubnetSelectionParameters; import com.sequenceiq.cloudbreak.cloud.model.SubnetSelectionResult; import com.sequenceiq.cloudbreak.common.mappable.CloudPlatform; import com.sequenceiq.common.api.type.Tunnel; import com.sequenceiq.environment.network.dto.NetworkDto; @ExtendWith(MockitoExtension.class) class SubnetIdProviderTest { private static final String SUBNET_ID_1 = "subnetId1"; private static final String SUBNET_ID_2 = "subnetId2"; private static final String SUBNET_ID_3 = "subnetId3"; @Mock private CloudPlatformConnectors cloudPlatformConnectors; @InjectMocks private SubnetIdProvider underTest; @Test void testProvideThenNetworkSelectorCalled() { NetworkDto networkDto = NetworkDto.builder() .withSubnetMetas(Map.of("AZ-a", new CloudSubnet())) .build(); NetworkConnector networkConnector = setupConnectorWithSelectionResult(List.of(new CloudSubnet())); Tunnel tunnel = Tunnel.DIRECT; underTest.provide(networkDto, tunnel, CloudPlatform.AWS); ArgumentCaptor<SubnetSelectionParameters> subnetSelectionParametersCaptor = ArgumentCaptor.forClass(SubnetSelectionParameters.class); verify(networkConnector).selectSubnets(any(), subnetSelectionParametersCaptor.capture()); assertFalse(subnetSelectionParametersCaptor.getValue().isForDatabase()); assertFalse(subnetSelectionParametersCaptor.getValue().isHa()); assertEquals(tunnel, subnetSelectionParametersCaptor.getValue().getTunnel()); } @Test void testProvideShouldReturnNullWhenNetworkNull() { String actual = underTest.provide(null, Tunnel.DIRECT, CloudPlatform.AWS); Assertions.assertNull(actual); } @Test void testProvideShouldReturnNullWhenNoSubnetMetas() { NetworkDto networkDto = NetworkDto.builder() .withSubnetMetas(Map.of()) .build(); String actual = underTest.provide(networkDto, Tunnel.DIRECT, CloudPlatform.AWS); Assertions.assertNull(actual); } @Test void testProvideShouldReturnAnySubnetWhenResultHasError() { setupConnectorWithSelectionError("error message"); NetworkDto networkDto = NetworkDto.builder() .withSubnetMetas(Map.of( "AZ-a", new CloudSubnet("id-1", "name-1"), "AZ-b", new CloudSubnet("id-2", "name-2") )) .build(); String actual = underTest.provide(networkDto, Tunnel.DIRECT, CloudPlatform.AWS); Assertions.assertNotNull(actual); } @Test void testProvideShouldReturnAnySubnetWhenResultIsEmptyAndNoError() { setupConnectorWithSelectionResult(List.of()); NetworkDto networkDto = NetworkDto.builder() .withSubnetMetas(Map.of( "AZ-a", new CloudSubnet("id-1", "name-1"), "AZ-b", new CloudSubnet("id-2", "name-2") )) .build(); String actual = underTest.provide(networkDto, Tunnel.DIRECT, CloudPlatform.AWS); Assertions.assertNotNull(actual); } @Test void testProvideShouldReturnAnySubnetWhenResultIsNotEmptyAndNoErrorButAtLeastTwoSubnetComesBackAsResult() { List<CloudSubnet> subnets = List.of( new CloudSubnet("id-1", "name-1"), new CloudSubnet("id-2", "name-2") ); setupConnectorWithSelectionResult(subnets); NetworkDto networkDto = NetworkDto.builder() .withSubnetMetas(Map.of( "AZ-a", new CloudSubnet("id-1", "name-1"), "AZ-b", new CloudSubnet("id-2", "name-2") )) .build(); String actual = underTest.provide(networkDto, Tunnel.DIRECT, CloudPlatform.AWS); Assertions.assertNotNull(actual); } private NetworkConnector setupConnectorWithSelectionResult(List<CloudSubnet> selectedSubnets) { return setupConnector(null, selectedSubnets); } private NetworkConnector setupConnectorWithSelectionError(String errorMessage) { return setupConnector(errorMessage, null); } private NetworkConnector setupConnector(String errorMessage, List<CloudSubnet> selectedSubnets) { CloudConnector cloudConnector = mock(CloudConnector.class); NetworkConnector networkConnector = mock(NetworkConnector.class); SubnetSelectionResult subnetSelectionResult = StringUtils.isEmpty(errorMessage) ? new SubnetSelectionResult(selectedSubnets) : new SubnetSelectionResult(errorMessage); when(networkConnector.selectSubnets(any(), any())) .thenReturn(subnetSelectionResult); when(cloudConnector.networkConnector()).thenReturn(networkConnector); when(cloudPlatformConnectors.get(any())).thenReturn(cloudConnector); return networkConnector; } }
environment/src/test/java/com/sequenceiq/environment/network/service/SubnetIdProviderTest.java
package com.sequenceiq.environment.network.service; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.List; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import com.sequenceiq.cloudbreak.cloud.CloudConnector; import com.sequenceiq.cloudbreak.cloud.NetworkConnector; import com.sequenceiq.cloudbreak.cloud.init.CloudPlatformConnectors; import com.sequenceiq.cloudbreak.cloud.model.CloudSubnet; import com.sequenceiq.cloudbreak.cloud.model.SubnetSelectionParameters; import com.sequenceiq.cloudbreak.cloud.model.SubnetSelectionResult; import com.sequenceiq.cloudbreak.common.mappable.CloudPlatform; import com.sequenceiq.common.api.type.Tunnel; import com.sequenceiq.environment.network.dto.NetworkDto; @ExtendWith(MockitoExtension.class) class SubnetIdProviderTest { private static final String SUBNET_ID_1 = "subnetId1"; private static final String SUBNET_ID_2 = "subnetId2"; private static final String SUBNET_ID_3 = "subnetId3"; @Mock private CloudPlatformConnectors cloudPlatformConnectors; @InjectMocks private SubnetIdProvider underTest; @Test void testProvideThenNetworkSelectorCalled() { NetworkDto networkDto = NetworkDto.builder() .withSubnetMetas(Map.of("AZ-a", new CloudSubnet())) .build(); NetworkConnector networkConnector = setupConnectorWithSelectionResult(List.of(new CloudSubnet())); Tunnel tunnel = Tunnel.DIRECT; underTest.provide(networkDto, tunnel, CloudPlatform.AWS); ArgumentCaptor<SubnetSelectionParameters> subnetSelectionParametersCaptor = ArgumentCaptor.forClass(SubnetSelectionParameters.class); verify(networkConnector).selectSubnets(any(), subnetSelectionParametersCaptor.capture()); assertFalse(subnetSelectionParametersCaptor.getValue().isForDatabase()); assertFalse(subnetSelectionParametersCaptor.getValue().isHa()); assertEquals(tunnel, subnetSelectionParametersCaptor.getValue().getTunnel()); } @Test void testProvideShouldReturnNullWhenNetworkNull() { String actual = underTest.provide(null, Tunnel.DIRECT, CloudPlatform.AWS); Assertions.assertNull(actual); } @Test void testProvideShouldReturnNullWhenNoSubnetMetas() { NetworkDto networkDto = NetworkDto.builder() .withSubnetMetas(Map.of()) .build(); String actual = underTest.provide(networkDto, Tunnel.DIRECT, CloudPlatform.AWS); Assertions.assertNull(actual); } @Test void testProvideShouldReturnAnySubnetWhenResultHasError() { setupConnectorWithSelectionError("error message"); NetworkDto networkDto = NetworkDto.builder() .withSubnetMetas(Map.of( "AZ-a", new CloudSubnet("id-1", "name-1"), "AZ-b", new CloudSubnet("id-2", "name-2") )) .build(); String actual = underTest.provide(networkDto, Tunnel.DIRECT, CloudPlatform.AWS); Assertions.assertNotNull(actual); } @Test void testProvideShouldReturnAnySubnetWhenResultIsEmptyAndNoError() { setupConnectorWithSelectionResult(List.of()); NetworkDto networkDto = NetworkDto.builder() .withSubnetMetas(Map.of( "AZ-a", new CloudSubnet("id-1", "name-1"), "AZ-b", new CloudSubnet("id-2", "name-2") )) .build(); String actual = underTest.provide(networkDto, Tunnel.DIRECT, CloudPlatform.AWS); Assertions.assertNotNull(actual); } @Test void testProvideShouldReturnAnySubnetWhenResultIsEmptyAndNoError1() { List<CloudSubnet> subnets = List.of( new CloudSubnet("id-1", "name-1"), new CloudSubnet("id-2", "name-2") ); setupConnectorWithSelectionResult(subnets); NetworkDto networkDto = NetworkDto.builder() .withSubnetMetas(Map.of( "AZ-a", new CloudSubnet("id-1", "name-1"), "AZ-b", new CloudSubnet("id-2", "name-2") )) .build(); String actual = underTest.provide(networkDto, Tunnel.DIRECT, CloudPlatform.AWS); Assertions.assertNotNull(actual); } private NetworkConnector setupConnectorWithSelectionResult(List<CloudSubnet> selectedSubnets) { return setupConnector(null, selectedSubnets); } private NetworkConnector setupConnectorWithSelectionError(String errorMessage) { return setupConnector(errorMessage, null); } private NetworkConnector setupConnector(String errorMessage, List<CloudSubnet> selectedSubnets) { CloudConnector cloudConnector = mock(CloudConnector.class); NetworkConnector networkConnector = mock(NetworkConnector.class); SubnetSelectionResult subnetSelectionResult = StringUtils.isEmpty(errorMessage) ? new SubnetSelectionResult(selectedSubnets) : new SubnetSelectionResult(errorMessage); when(networkConnector.selectSubnets(any(), any())) .thenReturn(subnetSelectionResult); when(cloudConnector.networkConnector()).thenReturn(networkConnector); when(cloudPlatformConnectors.get(any())).thenReturn(cloudConnector); return networkConnector; } }
CB-3864 renamed unit test
environment/src/test/java/com/sequenceiq/environment/network/service/SubnetIdProviderTest.java
CB-3864 renamed unit test
<ide><path>nvironment/src/test/java/com/sequenceiq/environment/network/service/SubnetIdProviderTest.java <ide> } <ide> <ide> @Test <del> void testProvideShouldReturnAnySubnetWhenResultIsEmptyAndNoError1() { <add> void testProvideShouldReturnAnySubnetWhenResultIsNotEmptyAndNoErrorButAtLeastTwoSubnetComesBackAsResult() { <ide> List<CloudSubnet> subnets = List.of( <ide> new CloudSubnet("id-1", "name-1"), <ide> new CloudSubnet("id-2", "name-2")
Java
apache-2.0
9ae4c8e92533a7e6a4face66ac47236f0d378962
0
mglukhikh/intellij-community,apixandru/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,ibinti/intellij-community,FHannes/intellij-community,asedunov/intellij-community,xfournet/intellij-community,apixandru/intellij-community,ibinti/intellij-community,apixandru/intellij-community,ibinti/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,ibinti/intellij-community,semonte/intellij-community,xfournet/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,semonte/intellij-community,asedunov/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,xfournet/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,allotria/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,allotria/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,apixandru/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,asedunov/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,ibinti/intellij-community,xfournet/intellij-community,allotria/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,semonte/intellij-community,apixandru/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,allotria/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,signed/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,da1z/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,signed/intellij-community,signed/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,youdonghai/intellij-community,allotria/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,ibinti/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,apixandru/intellij-community,asedunov/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,suncycheng/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,ibinti/intellij-community,semonte/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,ibinti/intellij-community,xfournet/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,semonte/intellij-community,signed/intellij-community,ibinti/intellij-community,fitermay/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,allotria/intellij-community,allotria/intellij-community,semonte/intellij-community,da1z/intellij-community,fitermay/intellij-community,fitermay/intellij-community,da1z/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,signed/intellij-community,fitermay/intellij-community,allotria/intellij-community,semonte/intellij-community,xfournet/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,signed/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,asedunov/intellij-community,semonte/intellij-community,signed/intellij-community,allotria/intellij-community
/* * Copyright 2000-2016 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.ide.ui; import com.intellij.ide.WelcomeWizardUtil; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.components.PersistentStateComponent; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.components.State; import com.intellij.openapi.components.Storage; import com.intellij.openapi.util.IconLoader; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.SimpleModificationTracker; import com.intellij.openapi.util.SystemInfo; import com.intellij.util.ComponentTreeEventDispatcher; import com.intellij.util.EventDispatcher; import com.intellij.util.PlatformUtils; import com.intellij.util.SystemProperties; import com.intellij.util.ui.UIUtil; import com.intellij.util.xmlb.Accessor; import com.intellij.util.xmlb.SerializationFilter; import com.intellij.util.xmlb.XmlSerializerUtil; import com.intellij.util.xmlb.annotations.Property; import com.intellij.util.xmlb.annotations.Transient; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import sun.swing.SwingUtilities2; import javax.swing.*; import java.awt.*; import static com.intellij.util.ui.UIUtil.isValidFont; @State( name = "UISettings", storages = @Storage("ui.lnf.xml") ) public class UISettings extends SimpleModificationTracker implements PersistentStateComponent<UISettings> { /** Not tabbed pane. */ public static final int TABS_NONE = 0; private static UISettings ourSettings; @Nullable public static UISettings getInstance() { return ourSettings = ServiceManager.getService(UISettings.class); } /** * Use this method if you are not sure whether the application is initialized. * @return persisted UISettings instance or default values. */ @NotNull public static UISettings getShadowInstance() { Application application = ApplicationManager.getApplication(); UISettings settings = application == null ? null : getInstance(); return settings == null ? new UISettings() : settings; } @Property(filter = FontFilter.class) public String FONT_FACE; @Property(filter = FontFilter.class) public int FONT_SIZE; public int RECENT_FILES_LIMIT = 50; public int CONSOLE_COMMAND_HISTORY_LIMIT = 300; public boolean OVERRIDE_CONSOLE_CYCLE_BUFFER_SIZE = false; public int CONSOLE_CYCLE_BUFFER_SIZE_KB = 1024; public int EDITOR_TAB_LIMIT = 10; public boolean REUSE_NOT_MODIFIED_TABS = false; public boolean ANIMATE_WINDOWS = true; @Deprecated //todo remove in IDEA 16 public int ANIMATION_SPEED = 4000; // Pixels per second public int ANIMATION_DURATION = 300; // Milliseconds public boolean SHOW_TOOL_WINDOW_NUMBERS = true; public boolean HIDE_TOOL_STRIPES = true; public boolean WIDESCREEN_SUPPORT = false; public boolean LEFT_HORIZONTAL_SPLIT = false; public boolean RIGHT_HORIZONTAL_SPLIT = false; public boolean SHOW_EDITOR_TOOLTIP = true; public boolean SHOW_MEMORY_INDICATOR = false; public boolean ALLOW_MERGE_BUTTONS = true; public boolean SHOW_MAIN_TOOLBAR = false; public boolean SHOW_STATUS_BAR = true; public boolean SHOW_NAVIGATION_BAR = true; public boolean ALWAYS_SHOW_WINDOW_BUTTONS = false; public boolean CYCLE_SCROLLING = true; public boolean SCROLL_TAB_LAYOUT_IN_EDITOR = true; public boolean HIDE_TABS_IF_NEED = true; public boolean SHOW_CLOSE_BUTTON = true; public int EDITOR_TAB_PLACEMENT = 1; public boolean HIDE_KNOWN_EXTENSION_IN_TABS = false; public boolean SHOW_ICONS_IN_QUICK_NAVIGATION = true; public boolean CLOSE_NON_MODIFIED_FILES_FIRST = false; public boolean ACTIVATE_MRU_EDITOR_ON_CLOSE = false; public boolean ACTIVATE_RIGHT_EDITOR_ON_CLOSE = false; public AntialiasingType IDE_AA_TYPE = AntialiasingType.SUBPIXEL; public AntialiasingType EDITOR_AA_TYPE = AntialiasingType.SUBPIXEL; public ColorBlindness COLOR_BLINDNESS; public boolean USE_LCD_RENDERING_IN_EDITOR = true; public boolean MOVE_MOUSE_ON_DEFAULT_BUTTON = false; public boolean ENABLE_ALPHA_MODE = false; public int ALPHA_MODE_DELAY = 1500; public float ALPHA_MODE_RATIO = 0.5f; public int MAX_CLIPBOARD_CONTENTS = 5; public boolean OVERRIDE_NONIDEA_LAF_FONTS = false; public boolean SHOW_ICONS_IN_MENUS = true; public boolean DISABLE_MNEMONICS = SystemInfo.isMac; // IDEADEV-33409, should be disabled by default on MacOS public boolean DISABLE_MNEMONICS_IN_CONTROLS = false; public boolean USE_SMALL_LABELS_ON_TABS = SystemInfo.isMac; public boolean SORT_LOOKUP_ELEMENTS_LEXICOGRAPHICALLY = false; public int MAX_LOOKUP_WIDTH2 = 500; public int MAX_LOOKUP_LIST_HEIGHT = 11; public boolean HIDE_NAVIGATION_ON_FOCUS_LOSS = true; public boolean DND_WITH_PRESSED_ALT_ONLY = false; public boolean FILE_COLORS_IN_PROJECT_VIEW = false; public boolean DEFAULT_AUTOSCROLL_TO_SOURCE = false; @Transient public boolean PRESENTATION_MODE = false; public int PRESENTATION_MODE_FONT_SIZE = 24; public boolean MARK_MODIFIED_TABS_WITH_ASTERISK = false; public boolean SHOW_TABS_TOOLTIPS = true; public boolean SHOW_DIRECTORY_FOR_NON_UNIQUE_FILENAMES = true; public boolean NAVIGATE_TO_PREVIEW = false; public boolean SORT_BOOKMARKS = false; public boolean MERGE_EQUAL_STACKTRACES = true; private final EventDispatcher<UISettingsListener> myDispatcher = EventDispatcher.create(UISettingsListener.class); private final ComponentTreeEventDispatcher<UISettingsListener> myTreeDispatcher = ComponentTreeEventDispatcher.create(UISettingsListener.class); public UISettings() { tweakPlatformDefaults(); setSystemFontFaceAndSize(); Boolean scrollToSource = WelcomeWizardUtil.getAutoScrollToSource(); if (scrollToSource != null) { DEFAULT_AUTOSCROLL_TO_SOURCE = scrollToSource; } } private void tweakPlatformDefaults() { // TODO[anton] consider making all IDEs use the same settings if (PlatformUtils.isAppCode()) { SCROLL_TAB_LAYOUT_IN_EDITOR = true; ACTIVATE_RIGHT_EDITOR_ON_CLOSE = true; SHOW_ICONS_IN_MENUS = false; } } public void addUISettingsListener(@NotNull final UISettingsListener listener, @NotNull Disposable parentDisposable) { myDispatcher.addListener(listener, parentDisposable); } /** * Notifies all registered listeners that UI settings has been changed. */ public void fireUISettingsChanged() { incModificationCount(); myDispatcher.getMulticaster().uiSettingsChanged(this); if (ourSettings == this) { // if this is the main UISettings instance push event to bus and to all current components myTreeDispatcher.getMulticaster().uiSettingsChanged(this); ApplicationManager.getApplication().getMessageBus().syncPublisher(UISettingsListener.TOPIC).uiSettingsChanged(this); } IconLoader.setFilter(MatrixFilter.get(COLOR_BLINDNESS)); } /** * @deprecated use {@link UISettings#addUISettingsListener(UISettingsListener, Disposable disposable)} instead. */ public void removeUISettingsListener(UISettingsListener listener) { myDispatcher.removeListener(listener); } private void setSystemFontFaceAndSize() { if (FONT_FACE == null || FONT_SIZE <= 0) { final Pair<String, Integer> fontData = getSystemFontFaceAndSize(); FONT_FACE = fontData.first; FONT_SIZE = fontData.second; } } private static Pair<String, Integer> getSystemFontFaceAndSize() { final Pair<String,Integer> fontData = UIUtil.getSystemFontData(); if (fontData != null) { return fontData; } return Pair.create("Dialog", 12); } public static class FontFilter implements SerializationFilter { @Override public boolean accepts(@NotNull Accessor accessor, @NotNull Object bean) { UISettings settings = (UISettings)bean; return !hasDefaultFontSetting(settings); } } private static boolean hasDefaultFontSetting(final UISettings settings) { final Pair<String, Integer> fontData = getSystemFontFaceAndSize(); return fontData.first.equals(settings.FONT_FACE) && fontData.second.equals(settings.FONT_SIZE); } @Override public UISettings getState() { return this; } @Override public void loadState(UISettings object) { XmlSerializerUtil.copyBean(object, this); // Check tab placement in editor if (EDITOR_TAB_PLACEMENT != TABS_NONE && EDITOR_TAB_PLACEMENT != SwingConstants.TOP && EDITOR_TAB_PLACEMENT != SwingConstants.LEFT && EDITOR_TAB_PLACEMENT != SwingConstants.BOTTOM && EDITOR_TAB_PLACEMENT != SwingConstants.RIGHT) { EDITOR_TAB_PLACEMENT = SwingConstants.TOP; } // Check that alpha delay and ratio are valid if (ALPHA_MODE_DELAY < 0) { ALPHA_MODE_DELAY = 1500; } if (ALPHA_MODE_RATIO < 0.0f || ALPHA_MODE_RATIO > 1.0f) { ALPHA_MODE_RATIO = 0.5f; } setSystemFontFaceAndSize(); // 1. Sometimes system font cannot display standard ASCII symbols. If so we have // find any other suitable font withing "preferred" fonts first. boolean fontIsValid = isValidFont(new Font(FONT_FACE, Font.PLAIN, FONT_SIZE)); if (!fontIsValid) { @NonNls final String[] preferredFonts = {"dialog", "Arial", "Tahoma"}; for (String preferredFont : preferredFonts) { if (isValidFont(new Font(preferredFont, Font.PLAIN, FONT_SIZE))) { FONT_FACE = preferredFont; fontIsValid = true; break; } } // 2. If all preferred fonts are not valid in current environment // we have to find first valid font (if any) if (!fontIsValid) { String[] fontNames = UIUtil.getValidFontNames(false); if (fontNames.length > 0) { FONT_FACE = fontNames[0]; } } } if (MAX_CLIPBOARD_CONTENTS <= 0) { MAX_CLIPBOARD_CONTENTS = 5; } fireUISettingsChanged(); } public static final boolean FORCE_USE_FRACTIONAL_METRICS = SystemProperties.getBooleanProperty("idea.force.use.fractional.metrics", false); public static void setupFractionalMetrics(final Graphics2D g2d) { if (FORCE_USE_FRACTIONAL_METRICS) { g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); } } /** * This method must not be used for set up antialiasing for editor components. To make sure antialiasing settings are taken into account * when preferred size of component is calculated, {@link #setupComponentAntialiasing(JComponent)} method should be called from * <code>updateUI()</code> or <code>setUI()</code> method of component. */ public static void setupAntialiasing(final Graphics g) { Graphics2D g2d = (Graphics2D)g; g2d.setRenderingHint(RenderingHints.KEY_TEXT_LCD_CONTRAST, UIUtil.getLcdContrastValue()); Application application = ApplicationManager.getApplication(); if (application == null) { // We cannot use services while Application has not been loaded yet // So let's apply the default hints. UIUtil.applyRenderingHints(g); return; } UISettings uiSettings = getInstance(); if (uiSettings != null) { g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, AntialiasingType.getKeyForCurrentScope(false)); } else { g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); } setupFractionalMetrics(g2d); } /** * @see #setupComponentAntialiasing(JComponent) */ public static void setupComponentAntialiasing(JComponent component) { component.putClientProperty(SwingUtilities2.AA_TEXT_PROPERTY_KEY, AntialiasingType.getAAHintForSwingComponent()); } }
platform/editor-ui-api/src/com/intellij/ide/ui/UISettings.java
/* * Copyright 2000-2016 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.ide.ui; import com.intellij.ide.WelcomeWizardUtil; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.components.PersistentStateComponent; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.components.State; import com.intellij.openapi.components.Storage; import com.intellij.openapi.util.IconLoader; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.SimpleModificationTracker; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.registry.Registry; import com.intellij.util.ComponentTreeEventDispatcher; import com.intellij.util.EventDispatcher; import com.intellij.util.PlatformUtils; import com.intellij.util.SystemProperties; import com.intellij.util.ui.UIUtil; import com.intellij.util.xmlb.Accessor; import com.intellij.util.xmlb.SerializationFilter; import com.intellij.util.xmlb.XmlSerializerUtil; import com.intellij.util.xmlb.annotations.Property; import com.intellij.util.xmlb.annotations.Transient; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import sun.swing.SwingUtilities2; import javax.swing.*; import java.awt.*; import static com.intellij.util.ui.UIUtil.isValidFont; @State( name = "UISettings", storages = @Storage("ui.lnf.xml") ) public class UISettings extends SimpleModificationTracker implements PersistentStateComponent<UISettings> { /** Not tabbed pane. */ public static final int TABS_NONE = 0; private static UISettings ourSettings; @Nullable public static UISettings getInstance() { return ourSettings = ServiceManager.getService(UISettings.class); } /** * Use this method if you are not sure whether the application is initialized. * @return persisted UISettings instance or default values. */ @NotNull public static UISettings getShadowInstance() { Application application = ApplicationManager.getApplication(); UISettings settings = application == null ? null : getInstance(); return settings == null ? new UISettings() : settings; } @Property(filter = FontFilter.class) public String FONT_FACE; @Property(filter = FontFilter.class) public int FONT_SIZE; public int RECENT_FILES_LIMIT = 50; public int CONSOLE_COMMAND_HISTORY_LIMIT = 300; public boolean OVERRIDE_CONSOLE_CYCLE_BUFFER_SIZE = false; public int CONSOLE_CYCLE_BUFFER_SIZE_KB = 1024; public int EDITOR_TAB_LIMIT = 10; public boolean REUSE_NOT_MODIFIED_TABS = false; public boolean ANIMATE_WINDOWS = true; @Deprecated //todo remove in IDEA 16 public int ANIMATION_SPEED = 4000; // Pixels per second public int ANIMATION_DURATION = 300; // Milliseconds public boolean SHOW_TOOL_WINDOW_NUMBERS = true; public boolean HIDE_TOOL_STRIPES = true; public boolean WIDESCREEN_SUPPORT = false; public boolean LEFT_HORIZONTAL_SPLIT = false; public boolean RIGHT_HORIZONTAL_SPLIT = false; public boolean SHOW_EDITOR_TOOLTIP = true; public boolean SHOW_MEMORY_INDICATOR = false; public boolean ALLOW_MERGE_BUTTONS = true; public boolean SHOW_MAIN_TOOLBAR = false; public boolean SHOW_STATUS_BAR = true; public boolean SHOW_NAVIGATION_BAR = true; public boolean ALWAYS_SHOW_WINDOW_BUTTONS = false; public boolean CYCLE_SCROLLING = true; public boolean SCROLL_TAB_LAYOUT_IN_EDITOR = true; public boolean HIDE_TABS_IF_NEED = true; public boolean SHOW_CLOSE_BUTTON = true; public int EDITOR_TAB_PLACEMENT = 1; public boolean HIDE_KNOWN_EXTENSION_IN_TABS = false; public boolean SHOW_ICONS_IN_QUICK_NAVIGATION = true; public boolean CLOSE_NON_MODIFIED_FILES_FIRST = false; public boolean ACTIVATE_MRU_EDITOR_ON_CLOSE = false; public boolean ACTIVATE_RIGHT_EDITOR_ON_CLOSE = false; public AntialiasingType IDE_AA_TYPE = AntialiasingType.SUBPIXEL; public AntialiasingType EDITOR_AA_TYPE = AntialiasingType.SUBPIXEL; public ColorBlindness COLOR_BLINDNESS; public boolean USE_LCD_RENDERING_IN_EDITOR = true; public boolean MOVE_MOUSE_ON_DEFAULT_BUTTON = false; public boolean ENABLE_ALPHA_MODE = false; public int ALPHA_MODE_DELAY = 1500; public float ALPHA_MODE_RATIO = 0.5f; public int MAX_CLIPBOARD_CONTENTS = 5; public boolean OVERRIDE_NONIDEA_LAF_FONTS = false; public boolean SHOW_ICONS_IN_MENUS = true; public boolean DISABLE_MNEMONICS = SystemInfo.isMac; // IDEADEV-33409, should be disabled by default on MacOS public boolean DISABLE_MNEMONICS_IN_CONTROLS = false; public boolean USE_SMALL_LABELS_ON_TABS = SystemInfo.isMac; public boolean SORT_LOOKUP_ELEMENTS_LEXICOGRAPHICALLY = false; public int MAX_LOOKUP_WIDTH2 = 500; public int MAX_LOOKUP_LIST_HEIGHT = 11; public boolean HIDE_NAVIGATION_ON_FOCUS_LOSS = true; public boolean DND_WITH_PRESSED_ALT_ONLY = false; public boolean FILE_COLORS_IN_PROJECT_VIEW = false; public boolean DEFAULT_AUTOSCROLL_TO_SOURCE = false; @Transient public boolean PRESENTATION_MODE = false; public int PRESENTATION_MODE_FONT_SIZE = 24; public boolean MARK_MODIFIED_TABS_WITH_ASTERISK = false; public boolean SHOW_TABS_TOOLTIPS = true; public boolean SHOW_DIRECTORY_FOR_NON_UNIQUE_FILENAMES = true; public boolean NAVIGATE_TO_PREVIEW = false; public boolean SORT_BOOKMARKS = false; public boolean MERGE_EQUAL_STACKTRACES = true; private final EventDispatcher<UISettingsListener> myDispatcher = EventDispatcher.create(UISettingsListener.class); private final ComponentTreeEventDispatcher<UISettingsListener> myTreeDispatcher = ComponentTreeEventDispatcher.create(UISettingsListener.class); public UISettings() { tweakPlatformDefaults(); setSystemFontFaceAndSize(); Boolean scrollToSource = WelcomeWizardUtil.getAutoScrollToSource(); if (scrollToSource != null) { DEFAULT_AUTOSCROLL_TO_SOURCE = scrollToSource; } } private void tweakPlatformDefaults() { // TODO[anton] consider making all IDEs use the same settings if (PlatformUtils.isAppCode()) { SCROLL_TAB_LAYOUT_IN_EDITOR = true; ACTIVATE_RIGHT_EDITOR_ON_CLOSE = true; SHOW_ICONS_IN_MENUS = false; } } /** * @deprecated use {@link UISettings#addUISettingsListener(UISettingsListener, Disposable disposable)} instead. */ public void addUISettingsListener(UISettingsListener listener) { myDispatcher.addListener(listener); } public void addUISettingsListener(@NotNull final UISettingsListener listener, @NotNull Disposable parentDisposable) { myDispatcher.addListener(listener, parentDisposable); } /** * Notifies all registered listeners that UI settings has been changed. */ public void fireUISettingsChanged() { incModificationCount(); myDispatcher.getMulticaster().uiSettingsChanged(this); if (ourSettings == this) { // if this is the main UISettings instance push event to bus and to all current components myTreeDispatcher.getMulticaster().uiSettingsChanged(this); ApplicationManager.getApplication().getMessageBus().syncPublisher(UISettingsListener.TOPIC).uiSettingsChanged(this); } IconLoader.setFilter(MatrixFilter.get(COLOR_BLINDNESS)); } /** * @deprecated use {@link UISettings#addUISettingsListener(UISettingsListener, Disposable disposable)} instead. */ public void removeUISettingsListener(UISettingsListener listener) { myDispatcher.removeListener(listener); } private void setSystemFontFaceAndSize() { if (FONT_FACE == null || FONT_SIZE <= 0) { final Pair<String, Integer> fontData = getSystemFontFaceAndSize(); FONT_FACE = fontData.first; FONT_SIZE = fontData.second; } } private static Pair<String, Integer> getSystemFontFaceAndSize() { final Pair<String,Integer> fontData = UIUtil.getSystemFontData(); if (fontData != null) { return fontData; } return Pair.create("Dialog", 12); } public static class FontFilter implements SerializationFilter { @Override public boolean accepts(@NotNull Accessor accessor, @NotNull Object bean) { UISettings settings = (UISettings)bean; return !hasDefaultFontSetting(settings); } } private static boolean hasDefaultFontSetting(final UISettings settings) { final Pair<String, Integer> fontData = getSystemFontFaceAndSize(); return fontData.first.equals(settings.FONT_FACE) && fontData.second.equals(settings.FONT_SIZE); } @Override public UISettings getState() { return this; } @Override public void loadState(UISettings object) { XmlSerializerUtil.copyBean(object, this); // Check tab placement in editor if (EDITOR_TAB_PLACEMENT != TABS_NONE && EDITOR_TAB_PLACEMENT != SwingConstants.TOP && EDITOR_TAB_PLACEMENT != SwingConstants.LEFT && EDITOR_TAB_PLACEMENT != SwingConstants.BOTTOM && EDITOR_TAB_PLACEMENT != SwingConstants.RIGHT) { EDITOR_TAB_PLACEMENT = SwingConstants.TOP; } // Check that alpha delay and ratio are valid if (ALPHA_MODE_DELAY < 0) { ALPHA_MODE_DELAY = 1500; } if (ALPHA_MODE_RATIO < 0.0f || ALPHA_MODE_RATIO > 1.0f) { ALPHA_MODE_RATIO = 0.5f; } setSystemFontFaceAndSize(); // 1. Sometimes system font cannot display standard ASCII symbols. If so we have // find any other suitable font withing "preferred" fonts first. boolean fontIsValid = isValidFont(new Font(FONT_FACE, Font.PLAIN, FONT_SIZE)); if (!fontIsValid) { @NonNls final String[] preferredFonts = {"dialog", "Arial", "Tahoma"}; for (String preferredFont : preferredFonts) { if (isValidFont(new Font(preferredFont, Font.PLAIN, FONT_SIZE))) { FONT_FACE = preferredFont; fontIsValid = true; break; } } // 2. If all preferred fonts are not valid in current environment // we have to find first valid font (if any) if (!fontIsValid) { String[] fontNames = UIUtil.getValidFontNames(false); if (fontNames.length > 0) { FONT_FACE = fontNames[0]; } } } if (MAX_CLIPBOARD_CONTENTS <= 0) { MAX_CLIPBOARD_CONTENTS = 5; } fireUISettingsChanged(); } public static final boolean FORCE_USE_FRACTIONAL_METRICS = SystemProperties.getBooleanProperty("idea.force.use.fractional.metrics", false); public static void setupFractionalMetrics(final Graphics2D g2d) { if (FORCE_USE_FRACTIONAL_METRICS) { g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); } } /** * This method must not be used for set up antialiasing for editor components. To make sure antialiasing settings are taken into account * when preferred size of component is calculated, {@link #setupComponentAntialiasing(JComponent)} method should be called from * <code>updateUI()</code> or <code>setUI()</code> method of component. */ public static void setupAntialiasing(final Graphics g) { Graphics2D g2d = (Graphics2D)g; g2d.setRenderingHint(RenderingHints.KEY_TEXT_LCD_CONTRAST, UIUtil.getLcdContrastValue()); Application application = ApplicationManager.getApplication(); if (application == null) { // We cannot use services while Application has not been loaded yet // So let's apply the default hints. UIUtil.applyRenderingHints(g); return; } UISettings uiSettings = getInstance(); if (uiSettings != null) { g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, AntialiasingType.getKeyForCurrentScope(false)); } else { g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); } setupFractionalMetrics(g2d); } /** * @see #setupComponentAntialiasing(JComponent) */ public static void setupComponentAntialiasing(JComponent component) { component.putClientProperty(SwingUtilities2.AA_TEXT_PROPERTY_KEY, AntialiasingType.getAAHintForSwingComponent()); } }
remove unused addUISettingsListener
platform/editor-ui-api/src/com/intellij/ide/ui/UISettings.java
remove unused addUISettingsListener
<ide><path>latform/editor-ui-api/src/com/intellij/ide/ui/UISettings.java <ide> import com.intellij.openapi.util.Pair; <ide> import com.intellij.openapi.util.SimpleModificationTracker; <ide> import com.intellij.openapi.util.SystemInfo; <del>import com.intellij.openapi.util.registry.Registry; <ide> import com.intellij.util.ComponentTreeEventDispatcher; <ide> import com.intellij.util.EventDispatcher; <ide> import com.intellij.util.PlatformUtils; <ide> } <ide> } <ide> <del> /** <del> * @deprecated use {@link UISettings#addUISettingsListener(UISettingsListener, Disposable disposable)} instead. <del> */ <del> public void addUISettingsListener(UISettingsListener listener) { <del> myDispatcher.addListener(listener); <del> } <del> <ide> public void addUISettingsListener(@NotNull final UISettingsListener listener, @NotNull Disposable parentDisposable) { <ide> myDispatcher.addListener(listener, parentDisposable); <ide> }
Java
apache-2.0
de1ae6f6e3912cf544fada530fd3509704df63b9
0
google/ground-android,google/ground-android,google/ground-android
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gnd.ui.editobservation; import static androidx.lifecycle.LiveDataReactiveStreams.fromPublisher; import static java8.util.stream.StreamSupport.stream; import android.content.res.Resources; import android.graphics.Bitmap; import android.net.Uri; import android.util.Log; import android.view.View; import androidx.databinding.ObservableArrayMap; import androidx.databinding.ObservableMap; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; import com.google.android.gnd.GndApplication; import com.google.android.gnd.R; import com.google.android.gnd.model.form.Element; import com.google.android.gnd.model.form.Element.Type; import com.google.android.gnd.model.form.Field; import com.google.android.gnd.model.form.Form; import com.google.android.gnd.model.observation.Observation; import com.google.android.gnd.model.observation.ObservationMutation; import com.google.android.gnd.model.observation.Response; import com.google.android.gnd.model.observation.ResponseDelta; import com.google.android.gnd.model.observation.ResponseMap; import com.google.android.gnd.model.observation.TextResponse; import com.google.android.gnd.persistence.remote.FirestoreStorageManager; import com.google.android.gnd.repository.ObservationRepository; import com.google.android.gnd.rx.Event; import com.google.android.gnd.rx.Nil; import com.google.android.gnd.system.AuthenticationManager; import com.google.android.gnd.system.CameraManager; import com.google.android.gnd.system.StorageManager; import com.google.android.gnd.ui.common.AbstractViewModel; import com.google.android.gnd.ui.util.FileUtil; import com.google.common.collect.ImmutableList; import io.reactivex.Completable; import io.reactivex.Maybe; import io.reactivex.Observable; import io.reactivex.Single; import io.reactivex.processors.BehaviorProcessor; import io.reactivex.processors.PublishProcessor; import java.io.File; import java.io.FileNotFoundException; import java.util.Date; import java8.util.Optional; import java8.util.StringJoiner; import javax.annotation.Nullable; import javax.inject.Inject; // TODO: Save draft to local db on each change. public class EditObservationViewModel extends AbstractViewModel { private static final String TAG = EditObservationViewModel.class.getSimpleName(); // TODO: Move out of id and into fragment args. private static final String ADD_OBSERVATION_ID_PLACEHOLDER = "NEW"; // Injected inputs. private final ObservationRepository observationRepository; private final AuthenticationManager authManager; private final Resources resources; private final StorageManager storageManager; private final CameraManager cameraManager; private final FirestoreStorageManager firestoreStorageManager; private final FileUtil fileUtil; // Input events. /** Arguments passed in from view on initialize(). */ private final BehaviorProcessor<EditObservationFragmentArgs> viewArgs = BehaviorProcessor.create(); /** "Save" button clicks. */ private final PublishProcessor<Nil> saveClicks = PublishProcessor.create(); // View state streams. /** Form definition, loaded when view is initialized. */ private final LiveData<Form> form; /** Toolbar title, based on whether user is adding new or editing existing observation. */ private final MutableLiveData<String> toolbarTitle = new MutableLiveData<>(); /** Original form responses, loaded when view is initialized. */ private final ObservableMap<String, Response> responses = new ObservableArrayMap<>(); /** Form validation errors, updated when existing for loaded and when responses change. */ private final ObservableMap<String, String> validationErrors = new ObservableArrayMap<>(); /** Visibility of process widget shown while loading. */ private final MutableLiveData<Integer> loadingSpinnerVisibility = new MutableLiveData<>(View.GONE); /** Visibility of "Save" button hidden while loading. */ private final MutableLiveData<Integer> saveButtonVisibility = new MutableLiveData<>(View.GONE); /** Visibility of saving progress dialog, show saving. */ private final MutableLiveData<Integer> savingProgressVisibility = new MutableLiveData<>(View.GONE); /** Outcome of user clicking "Save". */ private final LiveData<Event<SaveResult>> saveResults; private EditObservationFragmentArgs args; public Maybe<Uri> getFirestoreDownloadUrl(String path) { return firestoreStorageManager.getDownloadUrl(path); } /** Possible outcomes of user clicking "Save". */ enum SaveResult { HAS_VALIDATION_ERRORS, NO_CHANGES_TO_SAVE, SAVED } // Internal state. /** Observation state loaded when view is initialized. */ @Nullable private Observation originalObservation; /** True if the observation is being added, false if editing an existing one. */ private boolean isNew; @Inject EditObservationViewModel( GndApplication application, ObservationRepository observationRepository, AuthenticationManager authenticationManager, StorageManager storageManager, CameraManager cameraManager, FirestoreStorageManager firestoreStorageManager, FileUtil fileUtil) { this.resources = application.getResources(); this.observationRepository = observationRepository; this.authManager = authenticationManager; this.storageManager = storageManager; this.cameraManager = cameraManager; this.firestoreStorageManager = firestoreStorageManager; this.fileUtil = fileUtil; this.form = fromPublisher(viewArgs.switchMapSingle(this::onInitialize)); this.saveResults = fromPublisher(saveClicks.switchMapSingle(__ -> onSave())); } public LiveData<Form> getForm() { return form; } public LiveData<Integer> getLoadingSpinnerVisibility() { return loadingSpinnerVisibility; } public LiveData<Integer> getSaveButtonVisibility() { return saveButtonVisibility; } public LiveData<Integer> getSavingProgressVisibility() { return savingProgressVisibility; } public LiveData<String> getToolbarTitle() { return toolbarTitle; } public LiveData<Event<SaveResult>> getSaveResults() { return saveResults; } public void initialize(EditObservationFragmentArgs args) { this.args = args; viewArgs.onNext(args); } public ObservableMap<String, Response> getResponses() { return responses; } public Optional<Response> getResponse(String fieldId) { return Optional.ofNullable(responses.get(fieldId)); } public ObservableMap<String, String> getValidationErrors() { return validationErrors; } public void onTextChanged(Field field, String text) { Log.v(TAG, "onTextChanged: " + field.getId()); onResponseChanged(field, TextResponse.fromString(text)); } public void onResponseChanged(Field field, Optional<Response> newResponse) { Log.v( TAG, "onResponseChanged: " + field.getId() + " = '" + Response.toString(newResponse) + "'"); newResponse.ifPresentOrElse( r -> responses.put(field.getId(), r), () -> responses.remove(field.getId())); updateError(field, newResponse); } public void onFocusChange(Field field, boolean hasFocus) { if (!hasFocus) { updateError(field); } } void showPhotoSelector(String fieldId) { /* * Didn't subscribe this with Fragment's lifecycle because we need to retain the disposable * after the fragment is destroyed (for activity result) */ // TODO: launch intent through fragment and handle activity result callbacks async disposeOnClear( storageManager.launchPhotoPicker().andThen(handlePhotoPickerResult(fieldId)).subscribe()); } private Completable handlePhotoPickerResult(String fieldId) { return storageManager .photoPickerResult() .compose(bitmap -> saveBitmapAndUpdateResponse(bitmap, fieldId)) .ignoreElements(); } void showPhotoCapture(String fieldId) { /* * Didn't subscribe this with Fragment's lifecycle because we need to retain the disposable * after the fragment is destroyed (for activity result) */ // TODO: launch intent through fragment and handle activity result callbacks async disposeOnClear( cameraManager.launchPhotoCapture().andThen(handlePhotoCaptureResult(fieldId)).subscribe()); } private Completable handlePhotoCaptureResult(String fieldId) { return cameraManager .capturePhotoResult() .compose(bitmap -> saveBitmapAndUpdateResponse(bitmap, fieldId)) .ignoreElements(); } private Observable<String> saveBitmapAndUpdateResponse( Observable<Bitmap> source, String fieldId) { return source .map(bitmap -> fileUtil.saveBitmap(bitmap, fieldId + ".jpg")) .map( file -> { // If offline, Firebase will automatically upload the image when the network // connectivity is re-established. // TODO: Implement offline photo sync using Android Workers and local db String destinationPath = getRemoteImagePath(file.getName()); return firestoreStorageManager.uploadMediaFromFile(file, destinationPath); }) .doOnNext( url -> { // update observable response map onTextChanged(form.getValue().getField(fieldId).get(), url); }); } /** * Returns the path of the file saved in the sdcard used for uploading to the provided destination * path. */ File getLocalFileFromDestinationPath(String destinationPath) throws FileNotFoundException { String[] splits = destinationPath.split("/"); return fileUtil.getFile(splits[splits.length - 1]); } /** * Generates destination path for saving the image to Firestore Storage. * * <p>/uploaded_media/{project_id}/{form_id}/{feature_id}/{filename.jpg} */ private String getRemoteImagePath(String filename) { return new StringJoiner(File.separator) .add(args.getProjectId()) .add(args.getFormId()) .add(args.getFeatureId()) .add(filename) .toString(); } public void onSaveClick() { saveClicks.onNext(Nil.NIL); } private Single<Form> onInitialize(EditObservationFragmentArgs viewArgs) { saveButtonVisibility.setValue(View.GONE); loadingSpinnerVisibility.setValue(View.VISIBLE); isNew = isAddObservationRequest(viewArgs); Single<Observation> obs; if (isNew) { toolbarTitle.setValue(resources.getString(R.string.add_observation_toolbar_title)); obs = createObservation(viewArgs); } else { toolbarTitle.setValue(resources.getString(R.string.edit_observation_toolbar_title)); obs = loadObservation(viewArgs); } return obs.doOnSuccess(this::onObservationLoaded).map(Observation::getForm); } private void onObservationLoaded(Observation observation) { this.originalObservation = observation; refreshResponseMap(observation); if (isNew) { validationErrors.clear(); } else { refreshValidationErrors(); } saveButtonVisibility.postValue(View.VISIBLE); loadingSpinnerVisibility.postValue(View.GONE); } private static boolean isAddObservationRequest(EditObservationFragmentArgs args) { return args.getObservationId().equals(ADD_OBSERVATION_ID_PLACEHOLDER); } private Single<Observation> createObservation(EditObservationFragmentArgs args) { return observationRepository .createObservation( args.getProjectId(), args.getFeatureId(), args.getFormId(), authManager.getCurrentUser()) .onErrorResumeNext(this::onError); } private Single<Observation> loadObservation(EditObservationFragmentArgs args) { return observationRepository .getObservation(args.getProjectId(), args.getFeatureId(), args.getObservationId()) .onErrorResumeNext(this::onError); } private Single<Event<SaveResult>> onSave() { if (originalObservation == null) { Log.e(TAG, "Save attempted before observation loaded"); return Single.just(Event.create(SaveResult.NO_CHANGES_TO_SAVE)); } refreshValidationErrors(); if (hasValidationErrors()) { return Single.just(Event.create(SaveResult.HAS_VALIDATION_ERRORS)); } if (!hasUnsavedChanges()) { return Single.just(Event.create(SaveResult.NO_CHANGES_TO_SAVE)); } return save(); } private <T> Single<T> onError(Throwable throwable) { // TODO: Refactor and stream to UI. Log.e(TAG, "Error", throwable); return Single.never(); } private Single<Event<SaveResult>> save() { savingProgressVisibility.setValue(View.VISIBLE); ObservationMutation observationMutation = ObservationMutation.builder() .setType(isNew ? ObservationMutation.Type.CREATE : ObservationMutation.Type.UPDATE) .setProjectId(originalObservation.getProject().getId()) .setFeatureId(originalObservation.getFeature().getId()) .setLayerId(originalObservation.getFeature().getLayer().getId()) .setObservationId(originalObservation.getId()) .setFormId(originalObservation.getForm().getId()) .setResponseDeltas(getResponseDeltas()) .setClientTimestamp(new Date()) .setUserId(authManager.getCurrentUser().getId()) .build(); return observationRepository .applyAndEnqueue(observationMutation) .doOnComplete(() -> savingProgressVisibility.postValue(View.GONE)) .toSingleDefault(Event.create(SaveResult.SAVED)); } private void refreshResponseMap(Observation obs) { Log.v(TAG, "Rebuilding response map"); responses.clear(); ResponseMap responses = obs.getResponses(); for (String fieldId : responses.fieldIds()) { obs.getForm() .getField(fieldId) .ifPresent(field -> onResponseChanged(field, responses.getResponse(fieldId))); } } private ImmutableList<ResponseDelta> getResponseDeltas() { if (originalObservation == null) { Log.e(TAG, "Response diff attempted before observation loaded"); return ImmutableList.of(); } ImmutableList.Builder<ResponseDelta> deltas = ImmutableList.builder(); ResponseMap originalResponses = originalObservation.getResponses(); Log.v(TAG, "Responses:\n Before: " + originalResponses + " \nAfter: " + responses); for (Element e : originalObservation.getForm().getElements()) { if (e.getType() != Type.FIELD) { continue; } String fieldId = e.getField().getId(); Optional<Response> originalResponse = originalResponses.getResponse(fieldId); Optional<Response> currentResponse = getResponse(fieldId).filter(r -> !r.isEmpty()); if (currentResponse.equals(originalResponse)) { continue; } deltas.add( ResponseDelta.builder().setFieldId(fieldId).setNewResponse(currentResponse).build()); } ImmutableList<ResponseDelta> result = deltas.build(); Log.v(TAG, "Deltas: " + result); return result; } private void refreshValidationErrors() { validationErrors.clear(); stream(originalObservation.getForm().getElements()) .filter(e -> e.getType().equals(Type.FIELD)) .map(Element::getField) .forEach(this::updateError); } private void updateError(Field field) { updateError(field, getResponse(field.getId())); } private void updateError(Field field, Optional<Response> response) { String key = field.getId(); if (field.isRequired() && !response.filter(r -> !r.isEmpty()).isPresent()) { Log.d(TAG, "Missing: " + key); validationErrors.put(field.getId(), resources.getString(R.string.required_field)); } else { Log.d(TAG, "Valid: " + key); validationErrors.remove(field.getId()); } } public boolean hasUnsavedChanges() { return !getResponseDeltas().isEmpty(); } private boolean hasValidationErrors() { return !validationErrors.isEmpty(); } }
gnd/src/main/java/com/google/android/gnd/ui/editobservation/EditObservationViewModel.java
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gnd.ui.editobservation; import static androidx.lifecycle.LiveDataReactiveStreams.fromPublisher; import static java8.util.stream.StreamSupport.stream; import android.content.res.Resources; import android.graphics.Bitmap; import android.net.Uri; import android.util.Log; import android.view.View; import androidx.databinding.ObservableArrayMap; import androidx.databinding.ObservableMap; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; import com.google.android.gnd.GndApplication; import com.google.android.gnd.R; import com.google.android.gnd.model.form.Element; import com.google.android.gnd.model.form.Element.Type; import com.google.android.gnd.model.form.Field; import com.google.android.gnd.model.form.Form; import com.google.android.gnd.model.observation.Observation; import com.google.android.gnd.model.observation.ObservationMutation; import com.google.android.gnd.model.observation.Response; import com.google.android.gnd.model.observation.ResponseDelta; import com.google.android.gnd.model.observation.ResponseMap; import com.google.android.gnd.model.observation.TextResponse; import com.google.android.gnd.persistence.remote.FirestoreStorageManager; import com.google.android.gnd.repository.ObservationRepository; import com.google.android.gnd.rx.Event; import com.google.android.gnd.rx.Nil; import com.google.android.gnd.system.AuthenticationManager; import com.google.android.gnd.system.CameraManager; import com.google.android.gnd.system.StorageManager; import com.google.android.gnd.ui.common.AbstractViewModel; import com.google.android.gnd.ui.util.FileUtil; import com.google.common.collect.ImmutableList; import io.reactivex.Completable; import io.reactivex.Maybe; import io.reactivex.Observable; import io.reactivex.Single; import io.reactivex.processors.BehaviorProcessor; import io.reactivex.processors.PublishProcessor; import java.io.File; import java.io.FileNotFoundException; import java.util.Date; import java8.util.Optional; import java8.util.StringJoiner; import javax.annotation.Nullable; import javax.inject.Inject; // TODO: Save draft to local db on each change. public class EditObservationViewModel extends AbstractViewModel { private static final String TAG = EditObservationViewModel.class.getSimpleName(); // TODO: Move out of id and into fragment args. private static final String ADD_OBSERVATION_ID_PLACEHOLDER = "NEW"; // Injected inputs. private final ObservationRepository observationRepository; private final AuthenticationManager authManager; private final Resources resources; private final StorageManager storageManager; private final CameraManager cameraManager; private final FirestoreStorageManager firestoreStorageManager; private final FileUtil fileUtil; // Input events. /** Arguments passed in from view on initialize(). */ private final BehaviorProcessor<EditObservationFragmentArgs> viewArgs = BehaviorProcessor.create(); /** "Save" button clicks. */ private final PublishProcessor<Nil> saveClicks = PublishProcessor.create(); // View state streams. /** Form definition, loaded when view is initialized. */ private final LiveData<Form> form; /** Toolbar title, based on whether user is adding new or editing existing observation. */ private final MutableLiveData<String> toolbarTitle = new MutableLiveData<>(); /** Original form responses, loaded when view is initialized. */ private final ObservableMap<String, Response> responses = new ObservableArrayMap<>(); /** Form validation errors, updated when existing for loaded and when responses change. */ private final ObservableMap<String, String> validationErrors = new ObservableArrayMap<>(); /** Visibility of process widget shown while loading. */ private final MutableLiveData<Integer> loadingSpinnerVisibility = new MutableLiveData<>(View.GONE); /** Visibility of "Save" button hidden while loading. */ private final MutableLiveData<Integer> saveButtonVisibility = new MutableLiveData<>(View.GONE); /** Visibility of saving progress dialog, show saving. */ private final MutableLiveData<Integer> savingProgressVisibility = new MutableLiveData<>(View.GONE); /** Outcome of user clicking "Save". */ private final LiveData<Event<SaveResult>> saveResults; private EditObservationFragmentArgs args; public Maybe<Uri> getFirestoreDownloadUrl(String path) { return firestoreStorageManager.getDownloadUrl(path); } /** Possible outcomes of user clicking "Save". */ enum SaveResult { HAS_VALIDATION_ERRORS, NO_CHANGES_TO_SAVE, SAVED } // Internal state. /** Observation state loaded when view is initialized. */ @Nullable private Observation originalObservation; /** True if the observation is being added, false if editing an existing one. */ private boolean isNew; @Inject EditObservationViewModel( GndApplication application, ObservationRepository observationRepository, AuthenticationManager authenticationManager, StorageManager storageManager, CameraManager cameraManager, FirestoreStorageManager firestoreStorageManager, FileUtil fileUtil) { this.resources = application.getResources(); this.observationRepository = observationRepository; this.authManager = authenticationManager; this.storageManager = storageManager; this.cameraManager = cameraManager; this.firestoreStorageManager = firestoreStorageManager; this.fileUtil = fileUtil; this.form = fromPublisher(viewArgs.switchMapSingle(this::onInitialize)); this.saveResults = fromPublisher(saveClicks.switchMapSingle(__ -> onSave())); } public LiveData<Form> getForm() { return form; } public LiveData<Integer> getLoadingSpinnerVisibility() { return loadingSpinnerVisibility; } public LiveData<Integer> getSaveButtonVisibility() { return saveButtonVisibility; } public LiveData<Integer> getSavingProgressVisibility() { return savingProgressVisibility; } public LiveData<String> getToolbarTitle() { return toolbarTitle; } public LiveData<Event<SaveResult>> getSaveResults() { return saveResults; } public void initialize(EditObservationFragmentArgs args) { this.args = args; viewArgs.onNext(args); } public ObservableMap<String, Response> getResponses() { return responses; } public Optional<Response> getResponse(String fieldId) { return Optional.ofNullable(responses.get(fieldId)); } public ObservableMap<String, String> getValidationErrors() { return validationErrors; } public void onTextChanged(Field field, String text) { Log.v(TAG, "onTextChanged: " + field.getId()); onResponseChanged(field, TextResponse.fromString(text)); } public void onResponseChanged(Field field, Optional<Response> newResponse) { Log.v( TAG, "onResponseChanged: " + field.getId() + " = '" + Response.toString(newResponse) + "'"); newResponse.ifPresentOrElse( r -> responses.put(field.getId(), r), () -> responses.remove(field.getId())); updateError(field, newResponse); } public void onFocusChange(Field field, boolean hasFocus) { if (!hasFocus) { updateError(field); } } void showPhotoSelector(String fieldId) { /* * Didn't subscribe this with Fragment's lifecycle because we need to retain the disposable * after the fragment is destroyed (for activity result) */ // TODO: launch intent through fragment and handle activity result callbacks async disposeOnClear( storageManager.launchPhotoPicker().andThen(handlePhotoPickerResult(fieldId)).subscribe()); } private Completable handlePhotoPickerResult(String fieldId) { return storageManager .photoPickerResult() .compose(bitmap -> saveBitmapAndUpdateResponse(bitmap, fieldId)) .ignoreElements(); } void showPhotoCapture(String fieldId) { /* * Didn't subscribe this with Fragment's lifecycle because we need to retain the disposable * after the fragment is destroyed (for activity result) */ // TODO: launch intent through fragment and handle activity result callbacks async disposeOnClear( cameraManager.launchPhotoCapture().andThen(handlePhotoCaptureResult(fieldId)).subscribe()); } private Completable handlePhotoCaptureResult(String fieldId) { return cameraManager .capturePhotoResult() .compose(bitmap -> saveBitmapAndUpdateResponse(bitmap, fieldId)) .ignoreElements(); } private Observable<String> saveBitmapAndUpdateResponse( Observable<Bitmap> source, String fieldId) { return source .map(bitmap -> fileUtil.saveBitmap(bitmap, fieldId + ".jpg")) .map( file -> { // If offline, Firebase will automatically upload the image when the network // connectivity is re-established. // TODO: Implement offline photo sync using Android Workers and local db String destinationPath = getRemoteImagePath(file.getName()); return firestoreStorageManager.uploadMediaFromFile(file, destinationPath); }) .doOnNext( url -> { // update observable response map onTextChanged(form.getValue().getField(fieldId).get(), url); }); } /** * Returns the path of the file saved in the sdcard used for uploading to the provided destination * path. */ File getLocalFileFromDestinationPath(String destinationPath) throws FileNotFoundException { String[] splits = destinationPath.split(File.separator); return fileUtil.getFile(splits[splits.length - 1]); } /** * Generates destination path for saving the image to Firestore Storage. * * <p>/uploaded_media/<project_id>/<form_id>/<feature_id>/filename.jpg */ private String getRemoteImagePath(String filename) { return new StringJoiner(File.separator) .add(args.getProjectId()) .add(args.getFormId()) .add(args.getFeatureId()) .add(filename) .toString(); } public void onSaveClick() { saveClicks.onNext(Nil.NIL); } private Single<Form> onInitialize(EditObservationFragmentArgs viewArgs) { saveButtonVisibility.setValue(View.GONE); loadingSpinnerVisibility.setValue(View.VISIBLE); isNew = isAddObservationRequest(viewArgs); Single<Observation> obs; if (isNew) { toolbarTitle.setValue(resources.getString(R.string.add_observation_toolbar_title)); obs = createObservation(viewArgs); } else { toolbarTitle.setValue(resources.getString(R.string.edit_observation_toolbar_title)); obs = loadObservation(viewArgs); } return obs.doOnSuccess(this::onObservationLoaded).map(Observation::getForm); } private void onObservationLoaded(Observation observation) { this.originalObservation = observation; refreshResponseMap(observation); if (isNew) { validationErrors.clear(); } else { refreshValidationErrors(); } saveButtonVisibility.postValue(View.VISIBLE); loadingSpinnerVisibility.postValue(View.GONE); } private static boolean isAddObservationRequest(EditObservationFragmentArgs args) { return args.getObservationId().equals(ADD_OBSERVATION_ID_PLACEHOLDER); } private Single<Observation> createObservation(EditObservationFragmentArgs args) { return observationRepository .createObservation( args.getProjectId(), args.getFeatureId(), args.getFormId(), authManager.getCurrentUser()) .onErrorResumeNext(this::onError); } private Single<Observation> loadObservation(EditObservationFragmentArgs args) { return observationRepository .getObservation(args.getProjectId(), args.getFeatureId(), args.getObservationId()) .onErrorResumeNext(this::onError); } private Single<Event<SaveResult>> onSave() { if (originalObservation == null) { Log.e(TAG, "Save attempted before observation loaded"); return Single.just(Event.create(SaveResult.NO_CHANGES_TO_SAVE)); } refreshValidationErrors(); if (hasValidationErrors()) { return Single.just(Event.create(SaveResult.HAS_VALIDATION_ERRORS)); } if (!hasUnsavedChanges()) { return Single.just(Event.create(SaveResult.NO_CHANGES_TO_SAVE)); } return save(); } private <T> Single<T> onError(Throwable throwable) { // TODO: Refactor and stream to UI. Log.e(TAG, "Error", throwable); return Single.never(); } private Single<Event<SaveResult>> save() { savingProgressVisibility.setValue(View.VISIBLE); ObservationMutation observationMutation = ObservationMutation.builder() .setType(isNew ? ObservationMutation.Type.CREATE : ObservationMutation.Type.UPDATE) .setProjectId(originalObservation.getProject().getId()) .setFeatureId(originalObservation.getFeature().getId()) .setLayerId(originalObservation.getFeature().getLayer().getId()) .setObservationId(originalObservation.getId()) .setFormId(originalObservation.getForm().getId()) .setResponseDeltas(getResponseDeltas()) .setClientTimestamp(new Date()) .setUserId(authManager.getCurrentUser().getId()) .build(); return observationRepository .applyAndEnqueue(observationMutation) .doOnComplete(() -> savingProgressVisibility.postValue(View.GONE)) .toSingleDefault(Event.create(SaveResult.SAVED)); } private void refreshResponseMap(Observation obs) { Log.v(TAG, "Rebuilding response map"); responses.clear(); ResponseMap responses = obs.getResponses(); for (String fieldId : responses.fieldIds()) { obs.getForm() .getField(fieldId) .ifPresent(field -> onResponseChanged(field, responses.getResponse(fieldId))); } } private ImmutableList<ResponseDelta> getResponseDeltas() { if (originalObservation == null) { Log.e(TAG, "Response diff attempted before observation loaded"); return ImmutableList.of(); } ImmutableList.Builder<ResponseDelta> deltas = ImmutableList.builder(); ResponseMap originalResponses = originalObservation.getResponses(); Log.v(TAG, "Responses:\n Before: " + originalResponses + " \nAfter: " + responses); for (Element e : originalObservation.getForm().getElements()) { if (e.getType() != Type.FIELD) { continue; } String fieldId = e.getField().getId(); Optional<Response> originalResponse = originalResponses.getResponse(fieldId); Optional<Response> currentResponse = getResponse(fieldId).filter(r -> !r.isEmpty()); if (currentResponse.equals(originalResponse)) { continue; } deltas.add( ResponseDelta.builder().setFieldId(fieldId).setNewResponse(currentResponse).build()); } ImmutableList<ResponseDelta> result = deltas.build(); Log.v(TAG, "Deltas: " + result); return result; } private void refreshValidationErrors() { validationErrors.clear(); stream(originalObservation.getForm().getElements()) .filter(e -> e.getType().equals(Type.FIELD)) .map(Element::getField) .forEach(this::updateError); } private void updateError(Field field) { updateError(field, getResponse(field.getId())); } private void updateError(Field field, Optional<Response> response) { String key = field.getId(); if (field.isRequired() && !response.filter(r -> !r.isEmpty()).isPresent()) { Log.d(TAG, "Missing: " + key); validationErrors.put(field.getId(), resources.getString(R.string.required_field)); } else { Log.d(TAG, "Valid: " + key); validationErrors.remove(field.getId()); } } public boolean hasUnsavedChanges() { return !getResponseDeltas().isEmpty(); } private boolean hasValidationErrors() { return !validationErrors.isEmpty(); } }
Spotbugs: File.separator can't be used in regex pmd: fix comment
gnd/src/main/java/com/google/android/gnd/ui/editobservation/EditObservationViewModel.java
Spotbugs: File.separator can't be used in regex pmd: fix comment
<ide><path>nd/src/main/java/com/google/android/gnd/ui/editobservation/EditObservationViewModel.java <ide> * path. <ide> */ <ide> File getLocalFileFromDestinationPath(String destinationPath) throws FileNotFoundException { <del> String[] splits = destinationPath.split(File.separator); <add> String[] splits = destinationPath.split("/"); <ide> return fileUtil.getFile(splits[splits.length - 1]); <ide> } <ide> <ide> /** <ide> * Generates destination path for saving the image to Firestore Storage. <ide> * <del> * <p>/uploaded_media/<project_id>/<form_id>/<feature_id>/filename.jpg <add> * <p>/uploaded_media/{project_id}/{form_id}/{feature_id}/{filename.jpg} <ide> */ <ide> private String getRemoteImagePath(String filename) { <ide> return new StringJoiner(File.separator)
Java
artistic-2.0
be098ed8e32fd281c93d560b1c1bd4cf86d14c01
0
jdownloader-mirror/appwork-utils
/** * Copyright (c) 2009 - 2010 AppWork UG(haftungsbeschränkt) <[email protected]> * * This file is part of org.appwork.utils.swing.dialog * * This software is licensed under the Artistic License 2.0, * see the LICENSE file or http://www.opensource.org/licenses/artistic-license-2.0.php * for details */ package org.appwork.utils.swing.dialog; import javax.swing.Icon; import javax.swing.JComponent; import javax.swing.JScrollPane; import javax.swing.JTextPane; import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkListener; import org.appwork.swing.MigPanel; import org.appwork.uio.ConfirmDialogInterface; import org.appwork.uio.UIOManager; import org.appwork.utils.BinaryLogic; import org.appwork.utils.logging.Log; import org.appwork.utils.os.CrossSystem; public class ConfirmDialog extends AbstractDialog<Integer> implements ConfirmDialogInterface { private String message; public void setMessage(final String message) { this.message = message; } private JTextPane textField; public ConfirmDialog(final int flag, final String title, final String message, final Icon icon, final String okOption, final String cancelOption) { super(flag, title, icon, okOption, cancelOption); Log.L.fine("Dialog [" + okOption + "][" + cancelOption + "]\r\nflag: " + Integer.toBinaryString(flag) + "\r\ntitle: " + title + "\r\nmsg: \r\n" + message); this.message = message; } /** * @param i * @param name * @param gui_settings_extensions_show_now */ public ConfirmDialog(final int flag, final String title, final String message) { this(flag, title, message, null, null, null); } public String getMessage() { return message; } public ConfirmDialogInterface show() { return UIOManager.I().show(ConfirmDialogInterface.class, this); } @Override protected Integer createReturnValue() { // TODO Auto-generated method stub return getReturnmask(); } protected boolean isResizable() { // TODO Auto-generated method stub return true; } @Override public JComponent layoutDialogContent() { final MigPanel p = new MigPanel("ins 0", "[]", "[]"); addMessageComponent(p); return p; } protected void addMessageComponent(final MigPanel p) { textField = new JTextPane() { private static final long serialVersionUID = 1L; @Override public boolean getScrollableTracksViewportWidth() { return !BinaryLogic.containsAll(ConfirmDialog.this.flagMask, Dialog.STYLE_LARGE); } }; if (BinaryLogic.containsAll(flagMask, Dialog.STYLE_HTML)) { textField.setContentType("text/html"); textField.addHyperlinkListener(new HyperlinkListener() { public void hyperlinkUpdate(final HyperlinkEvent e) { if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { CrossSystem.openURL(e.getURL()); } } }); } else { textField.setContentType("text/plain"); // this.textField.setMaximumSize(new Dimension(450, 600)); } textField.setText(message); textField.setEditable(false); textField.setBackground(null); textField.setOpaque(false); textField.setFocusable(false); textField.putClientProperty("Synthetica.opaque", Boolean.FALSE); textField.setCaretPosition(0); if (BinaryLogic.containsAll(flagMask, Dialog.STYLE_LARGE)) { p.add(new JScrollPane(textField), "pushx,growx"); } else { p.add(textField); } } @Override public String toString() { if (BinaryLogic.containsAll(flagMask, Dialog.LOGIC_DONOTSHOW_BASED_ON_TITLE_ONLY)) { return ("dialog-" + getTitle()).replaceAll("\\W", "_"); } else { return ("dialog-" + getTitle() + "_" + message).replaceAll("\\W", "_"); } } }
src/org/appwork/utils/swing/dialog/ConfirmDialog.java
/** * Copyright (c) 2009 - 2010 AppWork UG(haftungsbeschränkt) <[email protected]> * * This file is part of org.appwork.utils.swing.dialog * * This software is licensed under the Artistic License 2.0, * see the LICENSE file or http://www.opensource.org/licenses/artistic-license-2.0.php * for details */ package org.appwork.utils.swing.dialog; import javax.swing.Icon; import javax.swing.JComponent; import javax.swing.JScrollPane; import javax.swing.JTextPane; import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkListener; import org.appwork.swing.MigPanel; import org.appwork.uio.ConfirmDialogInterface; import org.appwork.uio.UIOManager; import org.appwork.utils.BinaryLogic; import org.appwork.utils.logging.Log; import org.appwork.utils.os.CrossSystem; public class ConfirmDialog extends AbstractDialog<Integer> implements ConfirmDialogInterface { private String message; public void setMessage(final String message) { this.message = message; } private JTextPane textField; public ConfirmDialog(final int flag, final String title, final String message, final Icon icon, final String okOption, final String cancelOption) { super(flag, title, icon, okOption, cancelOption); Log.L.fine("Dialog [" + okOption + "][" + cancelOption + "]\r\nflag: " + Integer.toBinaryString(flag) + "\r\ntitle: " + title + "\r\nmsg: \r\n" + message); this.message = message; } /** * @param i * @param name * @param gui_settings_extensions_show_now */ public ConfirmDialog(final int flag, final String title, final String message) { this(flag, title, message, null, null, null); } public String getMessage() { return message; } public ConfirmDialogInterface show() { return UIOManager.I().show(ConfirmDialogInterface.class, this); } @Override protected Integer createReturnValue() { // TODO Auto-generated method stub return getReturnmask(); } protected boolean isResizable() { // TODO Auto-generated method stub return true; } @Override public JComponent layoutDialogContent() { final MigPanel p = new MigPanel("ins 0", "[]", "[]"); addMessageComponent(p); return p; } protected void addMessageComponent(final MigPanel p) { textField = new JTextPane() { private static final long serialVersionUID = 1L; @Override public boolean getScrollableTracksViewportWidth() { return !BinaryLogic.containsAll(ConfirmDialog.this.flagMask, Dialog.STYLE_LARGE); } }; if (BinaryLogic.containsAll(flagMask, Dialog.STYLE_HTML)) { textField.setContentType("text/html"); textField.addHyperlinkListener(new HyperlinkListener() { public void hyperlinkUpdate(final HyperlinkEvent e) { if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { CrossSystem.openURL(e.getURL()); } } }); } else { textField.setContentType("text/plain"); // this.textField.setMaximumSize(new Dimension(450, 600)); } textField.setText(message); textField.setEditable(false); textField.setBackground(null); textField.setOpaque(false); textField.setFocusable(false); textField.putClientProperty("Synthetica.opaque", Boolean.FALSE); textField.setCaretPosition(0); if (BinaryLogic.containsAll(flagMask, Dialog.STYLE_LARGE)) { p.add(new JScrollPane(textField), "pushx,growx"); } else { p.add(textField); } } @Override public String toString() { if (BinaryLogic.containsAll(flagMask, Dialog.LOGIC_DONOTSHOW_BASED_ON_TITLE_ONLY)) { return ("dialog-" + getTitle()).replaceAll("\\W", "_"); } else { return ("dialog-" + getTitle() + "_" + message).replaceAll("\\W", "_"); } } }
API work. new DownloadV2 API and OSR Activation
src/org/appwork/utils/swing/dialog/ConfirmDialog.java
API work. new DownloadV2 API and OSR Activation
<ide><path>rc/org/appwork/utils/swing/dialog/ConfirmDialog.java <ide> @Override <ide> protected Integer createReturnValue() { <ide> // TODO Auto-generated method stub <add> <ide> return getReturnmask(); <ide> } <ide>
Java
apache-2.0
35c4302967a3e77ec37673ff59e128467a9ff795
0
gilsouza/webdriverextensions,gilsouza/webdriverextensions,webdriverextensions/webdriverextensions,webdriverextensions/webdriverextensions
package org.andidev.webdriverextension; import java.util.List; import org.apache.commons.lang3.math.NumberUtils; import org.openqa.selenium.Keys; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.Select; import org.openqa.selenium.support.ui.WebDriverWait; public class WebDriverBot { public static double delayTime = 0.0; // public static boolean debugMode = false; Implement later public static void check(WebElement webElement) { delay(); if (!isChecked(webElement)) { webElement.click(); // DEBUG TEXT: Checked <input type="checkbox" name=""> } else { // DEBUG TEXT: Checkbox already checked! Skipped checking <input type="checkbox" name=""> } } public static void clear(WebElement webElement) { webElement.clear(); delay(); // DEBUG TEXT: Cleared text "textcleared" in <input name=""> } public static void clearAndType(String str, WebElement webElement) { if (str == null) { return; } clear(webElement); type(str, webElement); } public static void click(WebElement webElement) { delay(); webElement.click(); // DEBUG TEXT: Clicked <tagname ...> } public static boolean isChecked(WebElement webElement) { delay(); return webElement.isSelected(); } public static boolean isDisplayed(WebElement webElement) { delay(); boolean isDisplayed; try { isDisplayed = webElement.isDisplayed(); } catch (NoSuchElementException e) { isDisplayed = false; } return isDisplayed; } public static boolean isLoaded(WebPage page) { delay(); boolean isLoaded = true; try { page.isLoaded(); } catch (AssertionError e) { isLoaded = false; } return isLoaded; } public static boolean isText(String expected, WebElement webElement) { delay(); return webElement.getText().equals(expected); } public static boolean isTextContaining(String expected, WebElement webElement) { delay(); return webElement.getText().contains(expected); } public static boolean isTextEndingWith(String expected, WebElement webElement) { delay(); return webElement.getText().endsWith(expected); } public static boolean isTextStartingWith(String expected, WebElement webElement) { delay(); return webElement.getText().startsWith(expected); } public static void open(WebPage page) { delay(); page.get(); } public static void pressKeys(WebElement webElement, CharSequence... keysToSend) { delay(); webElement.sendKeys(keysToSend); // DEBUG TEXT: Pressed keys "keysToSend" in <input name=""> } public static void pressEnter(WebElement webElement) { delay(); webElement.sendKeys(Keys.ENTER); // DEBUG TEXT: Pressed enter key in <input name=""> } public static void type(String str, WebElement webElement) { if (str == null) { return; } delay(); webElement.sendKeys(str); // DEBUG TEXT: Typed "str" in <input name=""> } public static String read(WebElement webElement) { delay(); return webElement.getText(); } public static Double readAsNumber(WebElement webElement) { delay(); String string = read(webElement); if (NumberUtils.isNumber(string)) { return NumberUtils.toDouble(string); } else { return null; } } public static void select(String optionText, WebElement webElement) { delay(); new Select(webElement).selectByVisibleText(optionText); // DEBUG TEXT: Selected "optionText" from <select name=""> } public static void uncheck(WebElement webElement) { delay(); if (isChecked(webElement)) { webElement.click(); // DEBUG TEXT: Un-checked <input type="checkbox" name=""> } else { // DEBUG TEXT: Checkbox already un-checked! Skipped un-checking <input type="checkbox" name=""> } } private static void debug(String str) { System.out.println(str); } public static void debugNumberOfElements(List<WebElement> webElements) { System.out.println("Number of " + webElements.get(0).getTagName() + "-tags: " + webElements.size()); } public static void debugText(WebElement webElement) { System.out.println("Text in " + webElement.getTagName() + "-tag: " + webElement.getText()); } public static void debugText(List<WebElement> webElements) { for (WebElement webElement : webElements) { debugText(webElement); } } public static void waitForHtmlToDisplay(WebElement webElement, WebDriver driver) { delay(); WebDriverWait wait = new WebDriverWait(driver, 30); wait.until(ExpectedConditions.visibilityOf(webElement)); } public static void delay(double seconds) { if (seconds > 0) { try { Thread.sleep((long) (seconds * 1000)); } catch (InterruptedException ex) { // Swallow exception ex.printStackTrace(); } } } public static void delay() { delay(delayTime); } }
webdriver-extension-core/src/main/java/org/andidev/webdriverextension/WebDriverBot.java
package org.andidev.webdriverextension; import java.util.List; import mx4j.tools.remote.http.WebContainer; import org.apache.commons.lang3.math.NumberUtils; import org.openqa.selenium.Keys; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.Select; import org.openqa.selenium.support.ui.WebDriverWait; public class WebDriverBot { public static double delayTime = 0.0; // public static boolean debugMode = false; Implement later public static void click(WebElement webElement) { delay(); webElement.click(); // DEBUG TEXT: Clicked <tagname ...> } public static void type(String str, WebElement webElement) { if (str == null) { return; } delay(); webElement.sendKeys(str); // DEBUG TEXT: Typed "str" in <input name=""> } public static void pressKeys(WebElement webElement, CharSequence... keysToSend) { delay(); webElement.sendKeys(keysToSend); // DEBUG TEXT: Pressed keys "keysToSend" in <input name=""> } public static void pressEnter(WebElement webElement) { delay(); webElement.sendKeys(Keys.ENTER); // DEBUG TEXT: Pressed enter key in <input name=""> } public static void clear(WebElement webElement) { webElement.clear(); delay(); // DEBUG TEXT: Cleared text "textcleared" in <input name=""> } public static void clearAndType(String str, WebElement webElement) { if (str == null) { return; } clear(webElement); type(str, webElement); } public static boolean isChecked(WebElement webElement) { delay(); return webElement.isSelected(); } public static boolean isText(String expected, WebElement webElement) { delay(); return webElement.getText().equals(expected); } public static boolean isTextContaining(String expected, WebElement webElement) { delay(); return webElement.getText().contains(expected); } public static boolean isTextStartingWith(String expected, WebElement webElement) { delay(); return webElement.getText().startsWith(expected); } public static boolean isTextEndingWith(String expected, WebElement webElement) { delay(); return webElement.getText().endsWith(expected); } public static boolean isDisplayed(WebElement webElement) { delay(); boolean isDisplayed; try { isDisplayed = webElement.isDisplayed(); } catch (NoSuchElementException e) { isDisplayed = false; } return isDisplayed; } public static boolean isLoaded(WebPage page) { delay(); boolean isLoaded = true; try { page.isLoaded(); } catch (AssertionError e) { isLoaded = false; } return isLoaded; } public static void check(WebElement webElement) { delay(); if (!isChecked(webElement)) { webElement.click(); // DEBUG TEXT: Checked <input type="checkbox" name=""> } else { // DEBUG TEXT: Checkbox already checked! Skipped checking <input type="checkbox" name=""> } } public static void uncheck(WebElement webElement) { delay(); if (isChecked(webElement)) { webElement.click(); // DEBUG TEXT: Un-checked <input type="checkbox" name=""> } else { // DEBUG TEXT: Checkbox already un-checked! Skipped un-checking <input type="checkbox" name=""> } } public static String read(WebElement webElement) { delay(); return webElement.getText(); } public static Double readAsNumber(WebElement webElement) { delay(); String string = read(webElement); if(NumberUtils.isNumber(string)) { return NumberUtils.toDouble(string); } else { return null; } } public static void select(String optionText, WebElement webElement) { delay(); new Select(webElement).selectByVisibleText(optionText); // DEBUG TEXT: Selected "optionText" from <select name=""> } public static void open(WebPage page) { delay(); page.get(); } public static void debugNumberOfElements(List<WebElement> webElements) { delay(); System.out.println("Number of " + webElements.get(0).getTagName() + "-tags: " + webElements.size()); } public static void debugText(WebElement webElement) { delay(); System.out.println("Text in " + webElement.getTagName() + "-tag: " + webElement.getText()); } public static void debugText(List<WebElement> webElements) { delay(); for (WebElement webElement : webElements) { debugText(webElement); } } public static void waitForVisibilityOfElement(WebElement webElement, WebDriver driver) { delay(); WebDriverWait wait = new WebDriverWait(driver, 30); wait.until(ExpectedConditions.visibilityOf(webElement)); } public static void delay(double seconds) { if (seconds > 0) { try { Thread.sleep((long) (seconds * 1000)); } catch (InterruptedException ex) { // Swallow exception ex.printStackTrace(); } } } public static void delay() { delay(delayTime); } private static void debug(String str) { System.out.println(str); } }
Intriduced alphabetical orderding and minor changes
webdriver-extension-core/src/main/java/org/andidev/webdriverextension/WebDriverBot.java
Intriduced alphabetical orderding and minor changes
<ide><path>ebdriver-extension-core/src/main/java/org/andidev/webdriverextension/WebDriverBot.java <ide> package org.andidev.webdriverextension; <ide> <ide> import java.util.List; <del>import mx4j.tools.remote.http.WebContainer; <ide> import org.apache.commons.lang3.math.NumberUtils; <ide> import org.openqa.selenium.Keys; <ide> import org.openqa.selenium.NoSuchElementException; <ide> public static double delayTime = 0.0; <ide> // public static boolean debugMode = false; Implement later <ide> <del> public static void click(WebElement webElement) { <add> public static void check(WebElement webElement) { <ide> delay(); <del> webElement.click(); <del> // DEBUG TEXT: Clicked <tagname ...> <del> } <del> <del> public static void type(String str, WebElement webElement) { <del> if (str == null) { <del> return; <add> if (!isChecked(webElement)) { <add> webElement.click(); <add> // DEBUG TEXT: Checked <input type="checkbox" name=""> <add> } else { <add> // DEBUG TEXT: Checkbox already checked! Skipped checking <input type="checkbox" name=""> <ide> } <del> delay(); <del> webElement.sendKeys(str); <del> // DEBUG TEXT: Typed "str" in <input name=""> <del> } <del> <del> public static void pressKeys(WebElement webElement, CharSequence... keysToSend) { <del> delay(); <del> webElement.sendKeys(keysToSend); <del> // DEBUG TEXT: Pressed keys "keysToSend" in <input name=""> <del> } <del> <del> public static void pressEnter(WebElement webElement) { <del> delay(); <del> webElement.sendKeys(Keys.ENTER); <del> // DEBUG TEXT: Pressed enter key in <input name=""> <ide> } <ide> <ide> public static void clear(WebElement webElement) { <ide> type(str, webElement); <ide> } <ide> <add> public static void click(WebElement webElement) { <add> delay(); <add> webElement.click(); <add> // DEBUG TEXT: Clicked <tagname ...> <add> } <add> <ide> public static boolean isChecked(WebElement webElement) { <ide> delay(); <ide> return webElement.isSelected(); <del> } <del> <del> public static boolean isText(String expected, WebElement webElement) { <del> delay(); <del> return webElement.getText().equals(expected); <del> } <del> <del> public static boolean isTextContaining(String expected, WebElement webElement) { <del> delay(); <del> return webElement.getText().contains(expected); <del> } <del> <del> public static boolean isTextStartingWith(String expected, WebElement webElement) { <del> delay(); <del> return webElement.getText().startsWith(expected); <del> } <del> <del> public static boolean isTextEndingWith(String expected, WebElement webElement) { <del> delay(); <del> return webElement.getText().endsWith(expected); <ide> } <ide> <ide> public static boolean isDisplayed(WebElement webElement) { <ide> return isLoaded; <ide> } <ide> <del> public static void check(WebElement webElement) { <add> public static boolean isText(String expected, WebElement webElement) { <ide> delay(); <del> if (!isChecked(webElement)) { <del> webElement.click(); <del> // DEBUG TEXT: Checked <input type="checkbox" name=""> <add> return webElement.getText().equals(expected); <add> } <add> <add> public static boolean isTextContaining(String expected, WebElement webElement) { <add> delay(); <add> return webElement.getText().contains(expected); <add> } <add> <add> public static boolean isTextEndingWith(String expected, WebElement webElement) { <add> delay(); <add> return webElement.getText().endsWith(expected); <add> } <add> <add> public static boolean isTextStartingWith(String expected, WebElement webElement) { <add> delay(); <add> return webElement.getText().startsWith(expected); <add> } <add> <add> public static void open(WebPage page) { <add> delay(); <add> page.get(); <add> } <add> <add> public static void pressKeys(WebElement webElement, CharSequence... keysToSend) { <add> delay(); <add> webElement.sendKeys(keysToSend); <add> // DEBUG TEXT: Pressed keys "keysToSend" in <input name=""> <add> } <add> <add> public static void pressEnter(WebElement webElement) { <add> delay(); <add> webElement.sendKeys(Keys.ENTER); <add> // DEBUG TEXT: Pressed enter key in <input name=""> <add> } <add> <add> public static void type(String str, WebElement webElement) { <add> if (str == null) { <add> return; <add> } <add> delay(); <add> webElement.sendKeys(str); <add> // DEBUG TEXT: Typed "str" in <input name=""> <add> } <add> <add> public static String read(WebElement webElement) { <add> delay(); <add> return webElement.getText(); <add> } <add> <add> public static Double readAsNumber(WebElement webElement) { <add> delay(); <add> String string = read(webElement); <add> if (NumberUtils.isNumber(string)) { <add> return NumberUtils.toDouble(string); <ide> } else { <del> // DEBUG TEXT: Checkbox already checked! Skipped checking <input type="checkbox" name=""> <add> return null; <ide> } <add> } <add> <add> public static void select(String optionText, WebElement webElement) { <add> delay(); <add> new Select(webElement).selectByVisibleText(optionText); <add> // DEBUG TEXT: Selected "optionText" from <select name=""> <ide> } <ide> <ide> public static void uncheck(WebElement webElement) { <ide> } <ide> } <ide> <del> public static String read(WebElement webElement) { <del> delay(); <del> return webElement.getText(); <add> private static void debug(String str) { <add> System.out.println(str); <ide> } <ide> <del> public static Double readAsNumber(WebElement webElement) { <del> delay(); <del> String string = read(webElement); <del> if(NumberUtils.isNumber(string)) { <del> return NumberUtils.toDouble(string); <del> } else { <del> return null; <del> } <del> } <del> <del> public static void select(String optionText, WebElement webElement) { <del> delay(); <del> new Select(webElement).selectByVisibleText(optionText); <del> // DEBUG TEXT: Selected "optionText" from <select name=""> <del> } <del> <del> public static void open(WebPage page) { <del> delay(); <del> page.get(); <del> } <del> <del> <ide> public static void debugNumberOfElements(List<WebElement> webElements) { <del> delay(); <ide> System.out.println("Number of " + webElements.get(0).getTagName() + "-tags: " + webElements.size()); <ide> } <ide> <ide> public static void debugText(WebElement webElement) { <del> delay(); <ide> System.out.println("Text in " + webElement.getTagName() + "-tag: " + webElement.getText()); <ide> } <ide> <ide> public static void debugText(List<WebElement> webElements) { <del> delay(); <ide> for (WebElement webElement : webElements) { <ide> debugText(webElement); <ide> } <ide> } <ide> <del> public static void waitForVisibilityOfElement(WebElement webElement, WebDriver driver) { <add> public static void waitForHtmlToDisplay(WebElement webElement, WebDriver driver) { <ide> delay(); <ide> WebDriverWait wait = new WebDriverWait(driver, 30); <ide> wait.until(ExpectedConditions.visibilityOf(webElement)); <ide> public static void delay() { <ide> delay(delayTime); <ide> } <del> <del> private static void debug(String str) { <del> System.out.println(str); <del> } <ide> }
Java
bsd-3-clause
c3497b588dd1c469a76ccb9ccdc210a83cb2cf7a
0
svn2github/semanticvectors,svn2github/semanticvectors,svn2github/semanticvectors,svn2github/semanticvectors
/** Copyright (c) 2007, University of Pittsburgh 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 University of Pittsburgh 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 pitt.search.semanticvectors; import java.io.File; import java.io.IOException; import java.lang.IllegalArgumentException; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.Enumeration; import java.util.List; import java.util.logging.Logger; import org.apache.lucene.document.Document; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexReader; import org.apache.lucene.search.BooleanQuery; import org.apache.lucene.search.Explanation; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.TermQuery; import org.apache.lucene.search.TopDocs; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import pitt.search.semanticvectors.LuceneUtils; import pitt.search.semanticvectors.VectorStore; import pitt.search.semanticvectors.vectors.BinaryVectorUtils; import pitt.search.semanticvectors.vectors.IncompatibleVectorsException; import pitt.search.semanticvectors.vectors.Vector; import pitt.search.semanticvectors.vectors.VectorFactory; import pitt.search.semanticvectors.vectors.VectorType; import pitt.search.semanticvectors.vectors.VectorUtils; import pitt.search.semanticvectors.vectors.ZeroVectorException; /** * Class for searching vector stores using different scoring functions. * Each VectorSearcher implements a particular scoring function which is * normally query dependent, so each query needs its own VectorSearcher. */ abstract public class VectorSearcher { private static final Logger logger = Logger.getLogger(VectorSearcher.class.getCanonicalName()); private FlagConfig flagConfig; private VectorStore searchVecStore; private LuceneUtils luceneUtils; /** * Expand search space for dual-predicate searches */ public static VectorStore expandSearchSpace(VectorStore searchVecStore, FlagConfig flagConfig) { VectorStoreRAM nusearchspace = new VectorStoreRAM(flagConfig); Enumeration<ObjectVector> allVectors = searchVecStore.getAllVectors(); ArrayList<ObjectVector> storeVectors = new ArrayList<ObjectVector>(); while (allVectors.hasMoreElements()) { ObjectVector nextObjectVector = allVectors.nextElement(); nusearchspace.putVector(nextObjectVector.getObject(), nextObjectVector.getVector()); storeVectors.add(nextObjectVector); } for (int x=0; x < storeVectors.size()-1; x++) { for (int y=x; y < storeVectors.size(); y++) { Vector vec1 = storeVectors.get(x).getVector().copy(); Vector vec2 = storeVectors.get(y).getVector().copy(); String obj1 = storeVectors.get(x).getObject().toString(); String obj2 = storeVectors.get(y).getObject().toString(); if (obj1.equals(obj2)) continue; vec1.release(vec2); nusearchspace.putVector(obj2+":"+obj1, vec1); if (flagConfig.vectortype().equals(VectorType.COMPLEX)) { vec2.release(storeVectors.get(x).getVector().copy()); nusearchspace.putVector(obj1+":"+obj2, vec2); } } } System.err.println("Expanding search space from "+storeVectors.size()+" to "+nusearchspace.getNumVectors()); return nusearchspace; } /** * This needs to be filled in for each subclass. It takes an individual * vector and assigns it a relevance score for this VectorSearcher. */ public abstract double getScore(Vector testVector); /** * Performs basic initialization; subclasses should normally call super() to use this. * @param queryVecStore Vector store to use for query generation. * @param searchVecStore The vector store to search. * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) * @param flagConfig Flag configuration (cannot be null). */ public VectorSearcher(VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, FlagConfig flagConfig) { this.flagConfig = flagConfig; this.searchVecStore = searchVecStore; this.luceneUtils = luceneUtils; if (flagConfig.expandsearchspace()) { this.searchVecStore = expandSearchSpace(searchVecStore, flagConfig); } } /** * This nearest neighbor search is implemented in the abstract * VectorSearcher class itself: this enables all subclasses to reuse * the search whatever scoring method they implement. Since query * expressions are built into the VectorSearcher, * getNearestNeighbors no longer takes a query vector as an * argument. * @param numResults the number of results / length of the result list. */ public LinkedList<SearchResult> getNearestNeighbors(int numResults) { final double unsetScore = -Math.PI; final int bufferSize = 1000; final int indexSize = numResults + bufferSize; LinkedList<SearchResult> results = new LinkedList<SearchResult>(); List<SearchResult> tmpResults = new ArrayList<SearchResult>(indexSize); double score = -1; double threshold = flagConfig.searchresultsminscore(); if (flagConfig.stdev()) threshold = 0; //Counters for statistics to calculate standard deviation double sum=0, sumsquared=0; int count=0; int pos = 0; for(int i=0; i < indexSize; i++) { tmpResults.add(new SearchResult(unsetScore, null)); } Enumeration<ObjectVector> vecEnum = searchVecStore.getAllVectors(); while (vecEnum.hasMoreElements()) { // Test this element. ObjectVector testElement = vecEnum.nextElement(); score = getScore(testElement.getVector()); // This is a way of using the Lucene Index to get term and // document frequency information to reweight all results. It // seems to be good at moving excessively common terms further // down the results. Note that using this means that scores // returned are no longer just cosine similarities. if (this.luceneUtils != null && flagConfig.usetermweightsinsearch()) { score = score * luceneUtils.getGlobalTermWeightFromString((String) testElement.getObject()); } if (flagConfig.stdev()) { count++; sum += score; sumsquared += Math.pow(score, 2); } if (score > threshold) { // set existing object in buffer space tmpResults.get(numResults+pos++).set(score, testElement); } if(pos == bufferSize) { pos = 0; Collections.sort(tmpResults); threshold = tmpResults.get(indexSize - 1).getScore(); } } Collections.sort(tmpResults); for(int i = 0; i < numResults; i++) { SearchResult sr = tmpResults.get(i); if(sr.getScore() == unsetScore) { break; } results.add(sr); } if (flagConfig.stdev()) results = transformToStats(results, count, sum, sumsquared); return results; } /** * This search is implemented in the abstract * VectorSearcher class itself: this enables all subclasses to reuse * the search whatever scoring method they implement. Since query * expressions are built into the VectorSearcher, * getAllAboveThreshold does not takes a query vector as an * argument. * * This will retrieve all the results above the threshold score passed * as a parameter. It is more computationally convenient than getNearestNeighbor * when large numbers of results are anticipated * * @param threshold minimum score required to get into results list. */ public LinkedList<SearchResult> getAllAboveThreshold(float threshold) { LinkedList<SearchResult> results = new LinkedList<SearchResult>(); double score; Enumeration<ObjectVector> vecEnum = null; vecEnum = searchVecStore.getAllVectors(); while (vecEnum.hasMoreElements()) { // Test this element. ObjectVector testElement = vecEnum.nextElement(); if (testElement == null) score = Float.MIN_VALUE; else { Vector testVector = testElement.getVector(); score = getScore(testVector); } if (score > threshold || threshold == Float.MIN_VALUE) { results.add(new SearchResult(score, testElement));} } Collections.sort(results); return results; } /** * Class that searches based on cosine similarity with given queryvector. */ static public class VectorSearcherPlain extends VectorSearcher { Vector queryVector; /** * Plain constructor that just fills in the query vector and vector store to be searched. */ public VectorSearcherPlain(VectorStore searchVecStore, Vector queryVector, FlagConfig flagConfig) { super(searchVecStore, searchVecStore, null, flagConfig); this.queryVector = queryVector; } @Override public double getScore(Vector testVector) { return queryVector.measureOverlap(testVector); } } /** * Class for searching a vector store using cosine similarity. * Takes a sum of positive query terms and optionally negates some terms. */ static public class VectorSearcherCosine extends VectorSearcher { Vector queryVector; /** * @param queryVecStore Vector store to use for query generation. * @param searchVecStore The vector store to search. * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) * @param queryTerms Terms that will be parsed into a query * expression. If the string "NOT" appears, terms after this will be negated. */ public VectorSearcherCosine( VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, FlagConfig flagConfig, String[] queryTerms) throws ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils, flagConfig); this.queryVector = CompoundVectorBuilder.getQueryVector( queryVecStore, luceneUtils, flagConfig, queryTerms); if (this.queryVector.isZeroVector()) { throw new ZeroVectorException("Query vector is zero ... no results."); } } /** * @param queryVecStore Vector store to use for query generation. * @param searchVecStore The vector store to search. * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) * @param queryVector Vector representing query * expression. If the string "NOT" appears, terms after this will be negated. */ public VectorSearcherCosine( VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, FlagConfig flagConfig, Vector queryVector) throws ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils, flagConfig); this.queryVector = queryVector; Vector testVector = searchVecStore.getAllVectors().nextElement().getVector(); IncompatibleVectorsException.checkVectorsCompatible(queryVector, testVector); if (this.queryVector.isZeroVector()) { throw new ZeroVectorException("Query vector is zero ... no results."); } } @Override public double getScore(Vector testVector) { return this.queryVector.measureOverlap(testVector); } } /** * Class for searching a vector store using the bound product of a series two vectors. */ static public class VectorSearcherBoundProduct extends VectorSearcher { Vector queryVector; public VectorSearcherBoundProduct(VectorStore queryVecStore, VectorStore boundVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, FlagConfig flagConfig, String term1, String term2) throws ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils, flagConfig); this.queryVector = CompoundVectorBuilder.getQueryVectorFromString(queryVecStore, null, flagConfig, term1); queryVector.release(CompoundVectorBuilder.getBoundProductQueryVectorFromString( flagConfig, boundVecStore, term2)); if (this.queryVector.isZeroVector()) { throw new ZeroVectorException("Query vector is zero ... no results."); } } public VectorSearcherBoundProduct(VectorStore elementalVecStore, VectorStore semanticVecStore, VectorStore predicateVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, FlagConfig flagConfig, String term1) throws ZeroVectorException { super(semanticVecStore, searchVecStore, luceneUtils, flagConfig); this.queryVector = CompoundVectorBuilder.getBoundProductQueryVectorFromString( flagConfig, elementalVecStore, semanticVecStore, predicateVecStore, luceneUtils, term1); if (this.queryVector.isZeroVector()) { throw new ZeroVectorException("Query vector is zero ... no results."); } } public VectorSearcherBoundProduct(VectorStore queryVecStore, VectorStore boundVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, FlagConfig flagConfig, ArrayList<Vector> incomingVectors) throws ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils, flagConfig); Vector theSuperposition = VectorFactory.createZeroVector( flagConfig.vectortype(), flagConfig.dimension()); for (int q = 0; q < incomingVectors.size(); q++) theSuperposition.superpose(incomingVectors.get(q), 1, null); theSuperposition.normalize(); this.queryVector = theSuperposition; if (this.queryVector.isZeroVector()) { throw new ZeroVectorException("Query vector is zero ... no results."); } } /** * @param queryVecStore Vector store to use for query generation. * @param searchVecStore The vector store to search. * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) * @param queryVector Vector representing query * expression. If the string "NOT" appears, terms after this will be negated. */ public VectorSearcherBoundProduct(VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, FlagConfig flagConfig, Vector queryVector) throws ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils, flagConfig); this.queryVector = queryVector; Vector testVector = searchVecStore.getAllVectors().nextElement().getVector(); IncompatibleVectorsException.checkVectorsCompatible(queryVector, testVector); if (this.queryVector.isZeroVector()) { throw new ZeroVectorException("Query vector is zero ... no results."); } } @Override public double getScore(Vector testVector) { return this.queryVector.measureOverlap(testVector); } } /** * Class for searching a vector store using the bound product of a series two vectors. */ public static class VectorSearcherBoundProductSubSpace extends VectorSearcher { private ArrayList<Vector> disjunctSpace; public VectorSearcherBoundProductSubSpace(VectorStore queryVecStore, VectorStore boundVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, FlagConfig flagConfig, String term1, String term2) throws ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils, flagConfig); disjunctSpace = new ArrayList<Vector>(); Vector queryVector = queryVecStore.getVector(term1).copy(); if (queryVector.isZeroVector()) { throw new ZeroVectorException("Query vector is zero ... no results."); } this.disjunctSpace = CompoundVectorBuilder.getBoundProductQuerySubSpaceFromString( flagConfig, boundVecStore, queryVector, term2); } public VectorSearcherBoundProductSubSpace(VectorStore elementalVecStore, VectorStore semanticVecStore, VectorStore predicateVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, FlagConfig flagConfig, String term1) throws ZeroVectorException { super(semanticVecStore, searchVecStore, luceneUtils, flagConfig); disjunctSpace = new ArrayList<Vector>(); this.disjunctSpace = CompoundVectorBuilder.getBoundProductQuerySubspaceFromString( flagConfig, elementalVecStore, semanticVecStore, predicateVecStore, term1); } public VectorSearcherBoundProductSubSpace(VectorStore queryVecStore, VectorStore boundVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, FlagConfig flagConfig, ArrayList<Vector> incomingDisjunctSpace) throws ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils, flagConfig); this.disjunctSpace = incomingDisjunctSpace; } @Override public double getScore(Vector testVector) { return VectorUtils.compareWithProjection(testVector, disjunctSpace); } } /** * Class for searching a vector store using the bound product of a series two vectors. */ public static class VectorSearcherBoundMinimum extends VectorSearcher { private ArrayList<Vector> disjunctSpace; public VectorSearcherBoundMinimum(VectorStore queryVecStore, VectorStore boundVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, FlagConfig flagConfig, String term1, String term2) throws ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils, flagConfig); disjunctSpace = new ArrayList<Vector>(); Vector queryVector = queryVecStore.getVector(term1).copy(); if (queryVector.isZeroVector()) { throw new ZeroVectorException("Query vector is zero ... no results."); } this.disjunctSpace = CompoundVectorBuilder.getBoundProductQuerySubSpaceFromString( flagConfig, boundVecStore, queryVector, term2); } public VectorSearcherBoundMinimum(VectorStore elementalVecStore, VectorStore semanticVecStore, VectorStore predicateVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, FlagConfig flagConfig, String term1) throws ZeroVectorException { super(semanticVecStore, searchVecStore, luceneUtils, flagConfig); disjunctSpace = new ArrayList<Vector>(); this.disjunctSpace = CompoundVectorBuilder.getBoundProductQuerySubspaceFromString( flagConfig, elementalVecStore, semanticVecStore, predicateVecStore, term1); } public VectorSearcherBoundMinimum(VectorStore queryVecStore, VectorStore boundVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, FlagConfig flagConfig, ArrayList<Vector> incomingDisjunctSpace) throws ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils, flagConfig); this.disjunctSpace = incomingDisjunctSpace; } @Override public double getScore(Vector testVector) { double score = Double.MAX_VALUE; for (int q=0; q < disjunctSpace.size(); q ++) score = Math.min(score, testVector.measureOverlap(disjunctSpace.get(q))); return score; } } /** * Class for searching a vector store using quantum disjunction similarity. */ static public class VectorSearcherSubspaceSim extends VectorSearcher { private ArrayList<Vector> disjunctSpace; private VectorType vectorType; /** * @param queryVecStore Vector store to use for query generation. * @param searchVecStore The vector store to search. * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) * @param queryTerms Terms that will be parsed and used to generate a query subspace. */ public VectorSearcherSubspaceSim(VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, FlagConfig flagConfig, String[] queryTerms) throws ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils, flagConfig); this.disjunctSpace = new ArrayList<Vector>(); for (int i = 0; i < queryTerms.length; ++i) { System.out.println("\t" + queryTerms[i]); // There may be compound disjuncts, e.g., "A NOT B" as a single argument. String[] tmpTerms = queryTerms[i].split("\\s"); Vector tmpVector = CompoundVectorBuilder.getQueryVector( queryVecStore, luceneUtils, flagConfig, tmpTerms); if (tmpVector != null) { this.disjunctSpace.add(tmpVector); } } if (this.disjunctSpace.size() == 0) { throw new ZeroVectorException("No nonzero input vectors ... no results."); } if (!vectorType.equals(VectorType.BINARY)) VectorUtils.orthogonalizeVectors(this.disjunctSpace); else BinaryVectorUtils.orthogonalizeVectors(this.disjunctSpace); } /** * Scoring works by taking scalar product with disjunctSpace * (which must by now be represented using an orthogonal basis). * @param testVector Vector being tested. */ @Override public double getScore(Vector testVector) { if (!vectorType.equals(VectorType.BINARY)) return VectorUtils.compareWithProjection(testVector, disjunctSpace); else return BinaryVectorUtils.compareWithProjection(testVector, disjunctSpace); } } /** * Class for searching a vector store using minimum distance similarity. */ static public class VectorSearcherMaxSim extends VectorSearcher { private ArrayList<Vector> disjunctVectors; /** * @param queryVecStore Vector store to use for query generation. * @param searchVecStore The vector store to search. * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) * @param queryTerms Terms that will be parsed and used to generate a query subspace. */ public VectorSearcherMaxSim(VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, FlagConfig flagConfig, String[] queryTerms) throws ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils, flagConfig); this.disjunctVectors = new ArrayList<Vector>(); for (int i = 0; i < queryTerms.length; ++i) { // There may be compound disjuncts, e.g., "A NOT B" as a single argument. String[] tmpTerms = queryTerms[i].split("\\s"); Vector tmpVector = CompoundVectorBuilder.getQueryVector( queryVecStore, luceneUtils, flagConfig, tmpTerms); if (tmpVector != null) { this.disjunctVectors.add(tmpVector); } } if (this.disjunctVectors.size() == 0) { throw new ZeroVectorException("No nonzero input vectors ... no results."); } } /** * @param queryVecStore Vector store to use for query generation. * @param searchVecStore The vector store to search. * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) * @param queryTerms Terms that will be parsed and used to generate a query subspace. */ public VectorSearcherMaxSim(VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, FlagConfig flagConfig, Vector[] queryTerms) throws ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils, flagConfig); this.disjunctVectors = new ArrayList<Vector>(); for (int i = 0; i < queryTerms.length; ++i) { // There may be compound disjuncts, e.g., "A NOT B" as a single argument. Vector tmpVector = queryTerms[i]; if (tmpVector != null) { this.disjunctVectors.add(tmpVector); } } if (this.disjunctVectors.size() == 0) { throw new ZeroVectorException("No nonzero input vectors ... no results."); } } /** * Scoring works by taking scalar product with disjunctSpace * (which must by now be represented using an orthogonal basis). * @param testVector Vector being tested. */ @Override public double getScore(Vector testVector) { double score = -1; double max_score = -1; for (int i = 0; i < disjunctVectors.size(); ++i) { score = this.disjunctVectors.get(i).measureOverlap(testVector); if (score > max_score) { max_score = score; } } return max_score; } } /** * Class for searching a vector store using minimum distance similarity * (i.e. the minimum across the vector cues, which may * be of use for finding middle terms). */ static public class VectorSearcherMinSim extends VectorSearcher { private ArrayList<Vector> disjunctVectors; /** * @param queryVecStore Vector store to use for query generation. * @param searchVecStore The vector store to search. * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) * @param queryTerms Terms that will be parsed and used to generate a query subspace. */ public VectorSearcherMinSim(VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, FlagConfig flagConfig, String[] queryTerms) throws ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils, flagConfig); this.disjunctVectors = new ArrayList<Vector>(); for (int i = 0; i < queryTerms.length; ++i) { // There may be compound disjuncts, e.g., "A NOT B" as a single argument. String[] tmpTerms = queryTerms[i].split("\\s"); Vector tmpVector = CompoundVectorBuilder.getQueryVector( queryVecStore, luceneUtils, flagConfig, tmpTerms); if (tmpVector != null) { this.disjunctVectors.add(tmpVector); } } if (this.disjunctVectors.size() == 0) { throw new ZeroVectorException("No nonzero input vectors ... no results."); } } /** * @param queryVecStore Vector store to use for query generation. * @param searchVecStore The vector store to search. * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) * @param queryTerms Terms that will be parsed and used to generate a query subspace. */ public VectorSearcherMinSim(VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, FlagConfig flagConfig, Vector[] queryTerms) throws ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils, flagConfig); this.disjunctVectors = new ArrayList<Vector>(); for (int i = 0; i < queryTerms.length; ++i) { // There may be compound disjuncts, e.g., "A NOT B" as a single argument. Vector tmpVector = queryTerms[i]; if (tmpVector != null) { this.disjunctVectors.add(tmpVector); } } if (this.disjunctVectors.size() == 0) { throw new ZeroVectorException("No nonzero input vectors ... no results."); } } /** * Scoring works by taking scalar product with disjunctSpace * (which must by now be represented using an orthogonal basis). * @param testVector Vector being tested. */ @Override public double getScore(Vector testVector) { double score = -1; double min_score = Double.MAX_VALUE; for (int i = 0; i < disjunctVectors.size(); ++i) { score = this.disjunctVectors.get(i).measureOverlap(testVector); if (score < min_score) { min_score = score; } } return min_score; } } /** * Class for searching a permuted vector store using cosine similarity. * Uses implementation of rotation for permutation proposed by Sahlgren et al 2008 * Should find the term that appears frequently in the position p relative to the * index term (i.e. sat +1 would find a term occurring frequently immediately after "sat" */ public static class VectorSearcherPerm extends VectorSearcher { Vector theAvg; /** * @param queryVecStore Vector store to use for query generation. * @param searchVecStore The vector store to search. * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) * @param queryTerms Terms that will be parsed into a query * expression. If the string "?" appears, terms best fitting into this position will be returned */ public VectorSearcherPerm(VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, FlagConfig flagConfig, String[] queryTerms) throws IllegalArgumentException, ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils, flagConfig); try { theAvg = pitt.search.semanticvectors.CompoundVectorBuilder. getPermutedQueryVector(queryVecStore, luceneUtils, flagConfig, queryTerms); } catch (IllegalArgumentException e) { logger.info("Couldn't create permutation VectorSearcher ..."); throw e; } if (theAvg.isZeroVector()) { throw new ZeroVectorException("Permutation query vector is zero ... no results."); } } @Override public double getScore(Vector testVector) { return theAvg.measureOverlap(testVector); } } /** * Test searcher for finding a is to b as c is to ? * * Doesn't do well yet! * * @author dwiddows */ static public class AnalogySearcher extends VectorSearcher { Vector queryVector; public AnalogySearcher( VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, FlagConfig flagConfig, String[] queryTriple) { super(queryVecStore, searchVecStore, luceneUtils, flagConfig); Vector term0 = CompoundVectorBuilder.getQueryVectorFromString(queryVecStore, luceneUtils, flagConfig, queryTriple[0]); Vector term1 = CompoundVectorBuilder.getQueryVectorFromString(queryVecStore, luceneUtils, flagConfig, queryTriple[1]); Vector term2 = CompoundVectorBuilder.getQueryVectorFromString(queryVecStore, luceneUtils, flagConfig, queryTriple[2]); Vector relationVec = term0.copy(); relationVec.bind(term1); this.queryVector = term2.copy(); this.queryVector.release(relationVec); } @Override public double getScore(Vector testVector) { return queryVector.measureOverlap(testVector); } } /** * Class for searching a permuted vector store using cosine similarity. * Uses implementation of rotation for permutation proposed by Sahlgren et al 2008 * Should find the term that appears frequently in the position p relative to the * index term (i.e. sat +1 would find a term occurring frequently immediately after "sat" * This is a variant that takes into account different results obtained when using either * permuted or random index vectors as the cue terms, by taking the mean of the results * obtained with each of these options. */ static public class BalancedVectorSearcherPerm extends VectorSearcher { Vector oneDirection; Vector otherDirection; VectorStore searchVecStore, queryVecStore; // These "special" fields are here to enable non-static construction of these // static inherited classes. It suggests that the inheritance pattern for VectorSearcher // needs to be reconsidered. LuceneUtils specialLuceneUtils; FlagConfig specialFlagConfig; String[] queryTerms; /** * @param queryVecStore Vector store to use for query generation (this is also reversed). * @param searchVecStore The vector store to search (this is also reversed). * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) * @param queryTerms Terms that will be parsed into a query * expression. If the string "?" appears, terms best fitting into this position will be returned */ public BalancedVectorSearcherPerm( VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, FlagConfig flagConfig, String[] queryTerms) throws IllegalArgumentException, ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils, flagConfig); specialFlagConfig = flagConfig; specialLuceneUtils = luceneUtils; try { oneDirection = pitt.search.semanticvectors.CompoundVectorBuilder. getPermutedQueryVector(queryVecStore, luceneUtils, flagConfig, queryTerms); otherDirection = pitt.search.semanticvectors.CompoundVectorBuilder. getPermutedQueryVector(searchVecStore, luceneUtils, flagConfig, queryTerms); } catch (IllegalArgumentException e) { logger.info("Couldn't create balanced permutation VectorSearcher ..."); throw e; } if (oneDirection.isZeroVector()) { throw new ZeroVectorException("Permutation query vector is zero ... no results."); } } /** * This overrides the nearest neighbor class implemented in the abstract * {@code VectorSearcher} class. * * WARNING: This implementation fails to respect flags used by the * {@code VectorSearcher.getNearestNeighbors} method. * * @param numResults the number of results / length of the result list. */ @Override public LinkedList<SearchResult> getNearestNeighbors(int numResults) { LinkedList<SearchResult> results = new LinkedList<SearchResult>(); double score, score1, score2 = -1; double threshold = specialFlagConfig.searchresultsminscore(); if (specialFlagConfig.stdev()) threshold = 0; // Counters for statistics to calculate standard deviation double sum=0, sumsquared=0; int count=0; Enumeration<ObjectVector> vecEnum = searchVecStore.getAllVectors(); Enumeration<ObjectVector> vecEnum2 = queryVecStore.getAllVectors(); while (vecEnum.hasMoreElements()) { // Test this element. ObjectVector testElement = vecEnum.nextElement(); ObjectVector testElement2 = vecEnum2.nextElement(); score1 = getScore(testElement.getVector()); score2 = getScore2(testElement2.getVector()); score = Math.max(score1,score2); // This is a way of using the Lucene Index to get term and // document frequency information to reweight all results. It // seems to be good at moving excessively common terms further // down the results. Note that using this means that scores // returned are no longer just cosine similarities. if ((specialLuceneUtils != null) && specialFlagConfig.usetermweightsinsearch()) { score = score * specialLuceneUtils.getGlobalTermWeightFromString((String) testElement.getObject()); } if (specialFlagConfig.stdev()) { System.out.println("STDEV"); count++; sum += score; sumsquared += Math.pow(score, 2); } if (score > threshold) { boolean added = false; for (int i = 0; i < results.size(); ++i) { // Add to list if this is right place. if (score > results.get(i).getScore() && added == false) { results.add(i, new SearchResult(score, testElement)); added = true; } } // Prune list if there are already numResults. if (results.size() > numResults) { results.removeLast(); threshold = results.getLast().getScore(); } else { if (added == false) { results.add(new SearchResult(score, testElement)); } } } } if (specialFlagConfig.stdev()) results = transformToStats(results, count, sum, sumsquared); return results; } @Override public double getScore(Vector testVector) { testVector.normalize(); return oneDirection.measureOverlap(testVector); } public double getScore2(Vector testVector) { testVector.normalize(); return (otherDirection.measureOverlap(testVector)); } } /** * Class for implementing Lucene search directly (no semantic vectors required) */ static public class VectorSearcherLucene extends VectorSearcher { // These "special" fields are here to enable non-static construction of these // static inherited classes. It suggests that the inheritance pattern for VectorSearcher // needs to be reconsidered. LuceneUtils specialLuceneUtils; FlagConfig specialFlagConfig; String[] queryTerms; IndexSearcher iSearcher; VectorStoreRAM acceptableTerms; /** * Lucene search, no semantic vectors required * @param luceneUtils LuceneUtils object to use for query weighting. (May not be null.) * @param queryTerms Terms that will be parsed into a query expression */ public VectorSearcherLucene(LuceneUtils luceneUtils, FlagConfig flagConfig, String[] queryTerms) throws IllegalArgumentException, ZeroVectorException { super(null, null, luceneUtils, flagConfig); this.specialLuceneUtils = luceneUtils; this.specialFlagConfig = flagConfig; Directory dir; try { dir = FSDirectory.open(new File(flagConfig.luceneindexpath())); this.iSearcher = new IndexSearcher(DirectoryReader.open(dir)); if (!flagConfig.elementalvectorfile().equals("elementalvectors")) {this.acceptableTerms = new VectorStoreRAM(flagConfig); acceptableTerms.initFromFile(flagConfig.elementalvectorfile()); } } catch (IOException e) { logger.info("Lucene index initialization failed: "+e.getMessage()); } this.queryTerms = queryTerms; } /** * This overrides the nearest neighbor class implemented in the abstract * {@code VectorSearcher} class. * * WARNING: This implementation fails to respect flags used by the * {@code VectorSearcher.getNearestNeighbors} method. * * @param numResults the number of results / length of the result list. */ @Override public LinkedList<SearchResult> getNearestNeighbors(int numResults) { LinkedList<SearchResult> results = new LinkedList<SearchResult>(); BooleanQuery mtq = new BooleanQuery(); for (int q=0; q < queryTerms.length; q++) { //add OR clause to boolean query String term = queryTerms[q]; if (acceptableTerms != null && !acceptableTerms.containsVector(term)) continue; for (String field:this.specialFlagConfig.contentsfields()) mtq.add(new TermQuery(new org.apache.lucene.index.Term( field, term)), org.apache.lucene.search.BooleanClause.Occur.SHOULD); } TopDocs docs; try { docs = iSearcher.search(mtq, specialFlagConfig.numsearchresults()); ScoreDoc[] hits2 = docs.scoreDocs; for (int i = 0; i < hits2.length; i++) { int docId = hits2[i].doc; if (specialFlagConfig.hybridvectors()) if (i < specialFlagConfig.numsearchresults()) { Explanation explain = iSearcher.explain(mtq, docId); System.out.println(explain); } Document d = iSearcher.doc(docId); float dscore = hits2[i].score; results.add(new SearchResult(dscore, new ObjectVector(d.get(specialFlagConfig.docidfield()), null))); } } catch (IOException e) { // TODO Auto-generated catch block logger.info("Lucene search failed: "+e.getMessage()); } return results; } @Override public double getScore(Vector testVector) { // TODO Auto-generated method stub return 0; } } /** * calculates approximation of standard deviation (using a somewhat imprecise single-pass algorithm) * and recasts top scores as number of standard deviations from the mean (for a single search) * * @return list of results with scores as number of standard deviations from mean */ public LinkedList<SearchResult> transformToStats( LinkedList<SearchResult> rawResults,int count, double sum, double sumsq) { LinkedList<SearchResult> transformedResults = new LinkedList<SearchResult>(); double variancesquared = sumsq - (Math.pow(sum,2)/count); double stdev = Math.sqrt(variancesquared/(count)); double mean = sum/count; Iterator<SearchResult> iterator = rawResults.iterator(); while (iterator.hasNext()) { SearchResult temp = iterator.next(); double score = temp.getScore(); score = new Double((score-mean)/stdev).floatValue(); if (score > flagConfig.searchresultsminscore()) transformedResults.add(new SearchResult(score, temp.getObjectVector())); } return transformedResults; } }
src/main/java/pitt/search/semanticvectors/VectorSearcher.java
/** Copyright (c) 2007, University of Pittsburgh 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 University of Pittsburgh 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 pitt.search.semanticvectors; import java.io.File; import java.io.IOException; import java.lang.IllegalArgumentException; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.Enumeration; import java.util.List; import java.util.logging.Logger; import org.apache.lucene.document.Document; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexReader; import org.apache.lucene.search.BooleanQuery; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.TermQuery; import org.apache.lucene.search.TopDocs; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import pitt.search.semanticvectors.LuceneUtils; import pitt.search.semanticvectors.VectorStore; import pitt.search.semanticvectors.vectors.BinaryVectorUtils; import pitt.search.semanticvectors.vectors.IncompatibleVectorsException; import pitt.search.semanticvectors.vectors.Vector; import pitt.search.semanticvectors.vectors.VectorFactory; import pitt.search.semanticvectors.vectors.VectorType; import pitt.search.semanticvectors.vectors.VectorUtils; import pitt.search.semanticvectors.vectors.ZeroVectorException; /** * Class for searching vector stores using different scoring functions. * Each VectorSearcher implements a particular scoring function which is * normally query dependent, so each query needs its own VectorSearcher. */ abstract public class VectorSearcher { private static final Logger logger = Logger.getLogger(VectorSearcher.class.getCanonicalName()); private FlagConfig flagConfig; private VectorStore searchVecStore; private LuceneUtils luceneUtils; /** * Expand search space for dual-predicate searches */ public static VectorStore expandSearchSpace(VectorStore searchVecStore, FlagConfig flagConfig) { VectorStoreRAM nusearchspace = new VectorStoreRAM(flagConfig); Enumeration<ObjectVector> allVectors = searchVecStore.getAllVectors(); ArrayList<ObjectVector> storeVectors = new ArrayList<ObjectVector>(); while (allVectors.hasMoreElements()) { ObjectVector nextObjectVector = allVectors.nextElement(); nusearchspace.putVector(nextObjectVector.getObject(), nextObjectVector.getVector()); storeVectors.add(nextObjectVector); } for (int x=0; x < storeVectors.size()-1; x++) { for (int y=x; y < storeVectors.size(); y++) { Vector vec1 = storeVectors.get(x).getVector().copy(); Vector vec2 = storeVectors.get(y).getVector().copy(); String obj1 = storeVectors.get(x).getObject().toString(); String obj2 = storeVectors.get(y).getObject().toString(); if (obj1.equals(obj2)) continue; vec1.release(vec2); nusearchspace.putVector(obj2+":"+obj1, vec1); if (flagConfig.vectortype().equals(VectorType.COMPLEX)) { vec2.release(storeVectors.get(x).getVector().copy()); nusearchspace.putVector(obj1+":"+obj2, vec2); } } } System.err.println("Expanding search space from "+storeVectors.size()+" to "+nusearchspace.getNumVectors()); return nusearchspace; } /** * This needs to be filled in for each subclass. It takes an individual * vector and assigns it a relevance score for this VectorSearcher. */ public abstract double getScore(Vector testVector); /** * Performs basic initialization; subclasses should normally call super() to use this. * @param queryVecStore Vector store to use for query generation. * @param searchVecStore The vector store to search. * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) * @param flagConfig Flag configuration (cannot be null). */ public VectorSearcher(VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, FlagConfig flagConfig) { this.flagConfig = flagConfig; this.searchVecStore = searchVecStore; this.luceneUtils = luceneUtils; if (flagConfig.expandsearchspace()) { this.searchVecStore = expandSearchSpace(searchVecStore, flagConfig); } } /** * This nearest neighbor search is implemented in the abstract * VectorSearcher class itself: this enables all subclasses to reuse * the search whatever scoring method they implement. Since query * expressions are built into the VectorSearcher, * getNearestNeighbors no longer takes a query vector as an * argument. * @param numResults the number of results / length of the result list. */ public LinkedList<SearchResult> getNearestNeighbors(int numResults) { final double unsetScore = -Math.PI; final int bufferSize = 1000; final int indexSize = numResults + bufferSize; LinkedList<SearchResult> results = new LinkedList<SearchResult>(); List<SearchResult> tmpResults = new ArrayList<SearchResult>(indexSize); double score = -1; double threshold = flagConfig.searchresultsminscore(); if (flagConfig.stdev()) threshold = 0; //Counters for statistics to calculate standard deviation double sum=0, sumsquared=0; int count=0; int pos = 0; for(int i=0; i < indexSize; i++) { tmpResults.add(new SearchResult(unsetScore, null)); } Enumeration<ObjectVector> vecEnum = searchVecStore.getAllVectors(); while (vecEnum.hasMoreElements()) { // Test this element. ObjectVector testElement = vecEnum.nextElement(); score = getScore(testElement.getVector()); // This is a way of using the Lucene Index to get term and // document frequency information to reweight all results. It // seems to be good at moving excessively common terms further // down the results. Note that using this means that scores // returned are no longer just cosine similarities. if (this.luceneUtils != null && flagConfig.usetermweightsinsearch()) { score = score * luceneUtils.getGlobalTermWeightFromString((String) testElement.getObject()); } if (flagConfig.stdev()) { count++; sum += score; sumsquared += Math.pow(score, 2); } if (score > threshold) { // set existing object in buffer space tmpResults.get(numResults+pos++).set(score, testElement); } if(pos == bufferSize) { pos = 0; Collections.sort(tmpResults); threshold = tmpResults.get(indexSize - 1).getScore(); } } Collections.sort(tmpResults); for(int i = 0; i < numResults; i++) { SearchResult sr = tmpResults.get(i); if(sr.getScore() == unsetScore) { break; } results.add(sr); } if (flagConfig.stdev()) results = transformToStats(results, count, sum, sumsquared); return results; } /** * This search is implemented in the abstract * VectorSearcher class itself: this enables all subclasses to reuse * the search whatever scoring method they implement. Since query * expressions are built into the VectorSearcher, * getAllAboveThreshold does not takes a query vector as an * argument. * * This will retrieve all the results above the threshold score passed * as a parameter. It is more computationally convenient than getNearestNeighbor * when large numbers of results are anticipated * * @param threshold minimum score required to get into results list. */ public LinkedList<SearchResult> getAllAboveThreshold(float threshold) { LinkedList<SearchResult> results = new LinkedList<SearchResult>(); double score; Enumeration<ObjectVector> vecEnum = null; vecEnum = searchVecStore.getAllVectors(); while (vecEnum.hasMoreElements()) { // Test this element. ObjectVector testElement = vecEnum.nextElement(); if (testElement == null) score = Float.MIN_VALUE; else { Vector testVector = testElement.getVector(); score = getScore(testVector); } if (score > threshold || threshold == Float.MIN_VALUE) { results.add(new SearchResult(score, testElement));} } Collections.sort(results); return results; } /** * Class that searches based on cosine similarity with given queryvector. */ static public class VectorSearcherPlain extends VectorSearcher { Vector queryVector; /** * Plain constructor that just fills in the query vector and vector store to be searched. */ public VectorSearcherPlain(VectorStore searchVecStore, Vector queryVector, FlagConfig flagConfig) { super(searchVecStore, searchVecStore, null, flagConfig); this.queryVector = queryVector; } @Override public double getScore(Vector testVector) { return queryVector.measureOverlap(testVector); } } /** * Class for searching a vector store using cosine similarity. * Takes a sum of positive query terms and optionally negates some terms. */ static public class VectorSearcherCosine extends VectorSearcher { Vector queryVector; /** * @param queryVecStore Vector store to use for query generation. * @param searchVecStore The vector store to search. * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) * @param queryTerms Terms that will be parsed into a query * expression. If the string "NOT" appears, terms after this will be negated. */ public VectorSearcherCosine( VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, FlagConfig flagConfig, String[] queryTerms) throws ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils, flagConfig); this.queryVector = CompoundVectorBuilder.getQueryVector( queryVecStore, luceneUtils, flagConfig, queryTerms); if (this.queryVector.isZeroVector()) { throw new ZeroVectorException("Query vector is zero ... no results."); } } /** * @param queryVecStore Vector store to use for query generation. * @param searchVecStore The vector store to search. * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) * @param queryVector Vector representing query * expression. If the string "NOT" appears, terms after this will be negated. */ public VectorSearcherCosine( VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, FlagConfig flagConfig, Vector queryVector) throws ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils, flagConfig); this.queryVector = queryVector; Vector testVector = searchVecStore.getAllVectors().nextElement().getVector(); IncompatibleVectorsException.checkVectorsCompatible(queryVector, testVector); if (this.queryVector.isZeroVector()) { throw new ZeroVectorException("Query vector is zero ... no results."); } } @Override public double getScore(Vector testVector) { return this.queryVector.measureOverlap(testVector); } } /** * Class for searching a vector store using the bound product of a series two vectors. */ static public class VectorSearcherBoundProduct extends VectorSearcher { Vector queryVector; public VectorSearcherBoundProduct(VectorStore queryVecStore, VectorStore boundVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, FlagConfig flagConfig, String term1, String term2) throws ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils, flagConfig); this.queryVector = CompoundVectorBuilder.getQueryVectorFromString(queryVecStore, null, flagConfig, term1); queryVector.release(CompoundVectorBuilder.getBoundProductQueryVectorFromString( flagConfig, boundVecStore, term2)); if (this.queryVector.isZeroVector()) { throw new ZeroVectorException("Query vector is zero ... no results."); } } public VectorSearcherBoundProduct(VectorStore elementalVecStore, VectorStore semanticVecStore, VectorStore predicateVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, FlagConfig flagConfig, String term1) throws ZeroVectorException { super(semanticVecStore, searchVecStore, luceneUtils, flagConfig); this.queryVector = CompoundVectorBuilder.getBoundProductQueryVectorFromString( flagConfig, elementalVecStore, semanticVecStore, predicateVecStore, term1); if (this.queryVector.isZeroVector()) { throw new ZeroVectorException("Query vector is zero ... no results."); } } public VectorSearcherBoundProduct(VectorStore queryVecStore, VectorStore boundVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, FlagConfig flagConfig, ArrayList<Vector> incomingVectors) throws ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils, flagConfig); Vector theSuperposition = VectorFactory.createZeroVector( flagConfig.vectortype(), flagConfig.dimension()); for (int q = 0; q < incomingVectors.size(); q++) theSuperposition.superpose(incomingVectors.get(q), 1, null); theSuperposition.normalize(); this.queryVector = theSuperposition; if (this.queryVector.isZeroVector()) { throw new ZeroVectorException("Query vector is zero ... no results."); } } /** * @param queryVecStore Vector store to use for query generation. * @param searchVecStore The vector store to search. * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) * @param queryVector Vector representing query * expression. If the string "NOT" appears, terms after this will be negated. */ public VectorSearcherBoundProduct(VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, FlagConfig flagConfig, Vector queryVector) throws ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils, flagConfig); this.queryVector = queryVector; Vector testVector = searchVecStore.getAllVectors().nextElement().getVector(); IncompatibleVectorsException.checkVectorsCompatible(queryVector, testVector); if (this.queryVector.isZeroVector()) { throw new ZeroVectorException("Query vector is zero ... no results."); } } @Override public double getScore(Vector testVector) { return this.queryVector.measureOverlap(testVector); } } /** * Class for searching a vector store using the bound product of a series two vectors. */ public static class VectorSearcherBoundProductSubSpace extends VectorSearcher { private ArrayList<Vector> disjunctSpace; public VectorSearcherBoundProductSubSpace(VectorStore queryVecStore, VectorStore boundVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, FlagConfig flagConfig, String term1, String term2) throws ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils, flagConfig); disjunctSpace = new ArrayList<Vector>(); Vector queryVector = queryVecStore.getVector(term1).copy(); if (queryVector.isZeroVector()) { throw new ZeroVectorException("Query vector is zero ... no results."); } this.disjunctSpace = CompoundVectorBuilder.getBoundProductQuerySubSpaceFromString( flagConfig, boundVecStore, queryVector, term2); } public VectorSearcherBoundProductSubSpace(VectorStore elementalVecStore, VectorStore semanticVecStore, VectorStore predicateVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, FlagConfig flagConfig, String term1) throws ZeroVectorException { super(semanticVecStore, searchVecStore, luceneUtils, flagConfig); disjunctSpace = new ArrayList<Vector>(); this.disjunctSpace = CompoundVectorBuilder.getBoundProductQuerySubspaceFromString( flagConfig, elementalVecStore, semanticVecStore, predicateVecStore, term1); } public VectorSearcherBoundProductSubSpace(VectorStore queryVecStore, VectorStore boundVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, FlagConfig flagConfig, ArrayList<Vector> incomingDisjunctSpace) throws ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils, flagConfig); this.disjunctSpace = incomingDisjunctSpace; } @Override public double getScore(Vector testVector) { return VectorUtils.compareWithProjection(testVector, disjunctSpace); } } /** * Class for searching a vector store using the bound product of a series two vectors. */ public static class VectorSearcherBoundMinimum extends VectorSearcher { private ArrayList<Vector> disjunctSpace; public VectorSearcherBoundMinimum(VectorStore queryVecStore, VectorStore boundVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, FlagConfig flagConfig, String term1, String term2) throws ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils, flagConfig); disjunctSpace = new ArrayList<Vector>(); Vector queryVector = queryVecStore.getVector(term1).copy(); if (queryVector.isZeroVector()) { throw new ZeroVectorException("Query vector is zero ... no results."); } this.disjunctSpace = CompoundVectorBuilder.getBoundProductQuerySubSpaceFromString( flagConfig, boundVecStore, queryVector, term2); } public VectorSearcherBoundMinimum(VectorStore elementalVecStore, VectorStore semanticVecStore, VectorStore predicateVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, FlagConfig flagConfig, String term1) throws ZeroVectorException { super(semanticVecStore, searchVecStore, luceneUtils, flagConfig); disjunctSpace = new ArrayList<Vector>(); this.disjunctSpace = CompoundVectorBuilder.getBoundProductQuerySubspaceFromString( flagConfig, elementalVecStore, semanticVecStore, predicateVecStore, term1); } public VectorSearcherBoundMinimum(VectorStore queryVecStore, VectorStore boundVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, FlagConfig flagConfig, ArrayList<Vector> incomingDisjunctSpace) throws ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils, flagConfig); this.disjunctSpace = incomingDisjunctSpace; } @Override public double getScore(Vector testVector) { double score = Double.MAX_VALUE; for (int q=0; q < disjunctSpace.size(); q ++) score = Math.min(score, testVector.measureOverlap(disjunctSpace.get(q))); return score; } } /** * Class for searching a vector store using quantum disjunction similarity. */ static public class VectorSearcherSubspaceSim extends VectorSearcher { private ArrayList<Vector> disjunctSpace; private VectorType vectorType; /** * @param queryVecStore Vector store to use for query generation. * @param searchVecStore The vector store to search. * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) * @param queryTerms Terms that will be parsed and used to generate a query subspace. */ public VectorSearcherSubspaceSim(VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, FlagConfig flagConfig, String[] queryTerms) throws ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils, flagConfig); this.disjunctSpace = new ArrayList<Vector>(); for (int i = 0; i < queryTerms.length; ++i) { System.out.println("\t" + queryTerms[i]); // There may be compound disjuncts, e.g., "A NOT B" as a single argument. String[] tmpTerms = queryTerms[i].split("\\s"); Vector tmpVector = CompoundVectorBuilder.getQueryVector( queryVecStore, luceneUtils, flagConfig, tmpTerms); if (tmpVector != null) { this.disjunctSpace.add(tmpVector); } } if (this.disjunctSpace.size() == 0) { throw new ZeroVectorException("No nonzero input vectors ... no results."); } if (!vectorType.equals(VectorType.BINARY)) VectorUtils.orthogonalizeVectors(this.disjunctSpace); else BinaryVectorUtils.orthogonalizeVectors(this.disjunctSpace); } /** * Scoring works by taking scalar product with disjunctSpace * (which must by now be represented using an orthogonal basis). * @param testVector Vector being tested. */ @Override public double getScore(Vector testVector) { if (!vectorType.equals(VectorType.BINARY)) return VectorUtils.compareWithProjection(testVector, disjunctSpace); else return BinaryVectorUtils.compareWithProjection(testVector, disjunctSpace); } } /** * Class for searching a vector store using minimum distance similarity. */ static public class VectorSearcherMaxSim extends VectorSearcher { private ArrayList<Vector> disjunctVectors; /** * @param queryVecStore Vector store to use for query generation. * @param searchVecStore The vector store to search. * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) * @param queryTerms Terms that will be parsed and used to generate a query subspace. */ public VectorSearcherMaxSim(VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, FlagConfig flagConfig, String[] queryTerms) throws ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils, flagConfig); this.disjunctVectors = new ArrayList<Vector>(); for (int i = 0; i < queryTerms.length; ++i) { // There may be compound disjuncts, e.g., "A NOT B" as a single argument. String[] tmpTerms = queryTerms[i].split("\\s"); Vector tmpVector = CompoundVectorBuilder.getQueryVector( queryVecStore, luceneUtils, flagConfig, tmpTerms); if (tmpVector != null) { this.disjunctVectors.add(tmpVector); } } if (this.disjunctVectors.size() == 0) { throw new ZeroVectorException("No nonzero input vectors ... no results."); } } /** * @param queryVecStore Vector store to use for query generation. * @param searchVecStore The vector store to search. * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) * @param queryTerms Terms that will be parsed and used to generate a query subspace. */ public VectorSearcherMaxSim(VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, FlagConfig flagConfig, Vector[] queryTerms) throws ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils, flagConfig); this.disjunctVectors = new ArrayList<Vector>(); for (int i = 0; i < queryTerms.length; ++i) { // There may be compound disjuncts, e.g., "A NOT B" as a single argument. Vector tmpVector = queryTerms[i]; if (tmpVector != null) { this.disjunctVectors.add(tmpVector); } } if (this.disjunctVectors.size() == 0) { throw new ZeroVectorException("No nonzero input vectors ... no results."); } } /** * Scoring works by taking scalar product with disjunctSpace * (which must by now be represented using an orthogonal basis). * @param testVector Vector being tested. */ @Override public double getScore(Vector testVector) { double score = -1; double max_score = -1; for (int i = 0; i < disjunctVectors.size(); ++i) { score = this.disjunctVectors.get(i).measureOverlap(testVector); if (score > max_score) { max_score = score; } } return max_score; } } /** * Class for searching a vector store using minimum distance similarity * (i.e. the minimum across the vector cues, which may * be of use for finding middle terms). */ static public class VectorSearcherMinSim extends VectorSearcher { private ArrayList<Vector> disjunctVectors; /** * @param queryVecStore Vector store to use for query generation. * @param searchVecStore The vector store to search. * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) * @param queryTerms Terms that will be parsed and used to generate a query subspace. */ public VectorSearcherMinSim(VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, FlagConfig flagConfig, String[] queryTerms) throws ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils, flagConfig); this.disjunctVectors = new ArrayList<Vector>(); for (int i = 0; i < queryTerms.length; ++i) { // There may be compound disjuncts, e.g., "A NOT B" as a single argument. String[] tmpTerms = queryTerms[i].split("\\s"); Vector tmpVector = CompoundVectorBuilder.getQueryVector( queryVecStore, luceneUtils, flagConfig, tmpTerms); if (tmpVector != null) { this.disjunctVectors.add(tmpVector); } } if (this.disjunctVectors.size() == 0) { throw new ZeroVectorException("No nonzero input vectors ... no results."); } } /** * @param queryVecStore Vector store to use for query generation. * @param searchVecStore The vector store to search. * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) * @param queryTerms Terms that will be parsed and used to generate a query subspace. */ public VectorSearcherMinSim(VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, FlagConfig flagConfig, Vector[] queryTerms) throws ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils, flagConfig); this.disjunctVectors = new ArrayList<Vector>(); for (int i = 0; i < queryTerms.length; ++i) { // There may be compound disjuncts, e.g., "A NOT B" as a single argument. Vector tmpVector = queryTerms[i]; if (tmpVector != null) { this.disjunctVectors.add(tmpVector); } } if (this.disjunctVectors.size() == 0) { throw new ZeroVectorException("No nonzero input vectors ... no results."); } } /** * Scoring works by taking scalar product with disjunctSpace * (which must by now be represented using an orthogonal basis). * @param testVector Vector being tested. */ @Override public double getScore(Vector testVector) { double score = -1; double min_score = Double.MAX_VALUE; for (int i = 0; i < disjunctVectors.size(); ++i) { score = this.disjunctVectors.get(i).measureOverlap(testVector); if (score < min_score) { min_score = score; } } return min_score; } } /** * Class for searching a permuted vector store using cosine similarity. * Uses implementation of rotation for permutation proposed by Sahlgren et al 2008 * Should find the term that appears frequently in the position p relative to the * index term (i.e. sat +1 would find a term occurring frequently immediately after "sat" */ public static class VectorSearcherPerm extends VectorSearcher { Vector theAvg; /** * @param queryVecStore Vector store to use for query generation. * @param searchVecStore The vector store to search. * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) * @param queryTerms Terms that will be parsed into a query * expression. If the string "?" appears, terms best fitting into this position will be returned */ public VectorSearcherPerm(VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, FlagConfig flagConfig, String[] queryTerms) throws IllegalArgumentException, ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils, flagConfig); try { theAvg = pitt.search.semanticvectors.CompoundVectorBuilder. getPermutedQueryVector(queryVecStore, luceneUtils, flagConfig, queryTerms); } catch (IllegalArgumentException e) { logger.info("Couldn't create permutation VectorSearcher ..."); throw e; } if (theAvg.isZeroVector()) { throw new ZeroVectorException("Permutation query vector is zero ... no results."); } } @Override public double getScore(Vector testVector) { return theAvg.measureOverlap(testVector); } } /** * Test searcher for finding a is to b as c is to ? * * Doesn't do well yet! * * @author dwiddows */ static public class AnalogySearcher extends VectorSearcher { Vector queryVector; public AnalogySearcher( VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, FlagConfig flagConfig, String[] queryTriple) { super(queryVecStore, searchVecStore, luceneUtils, flagConfig); Vector term0 = CompoundVectorBuilder.getQueryVectorFromString(queryVecStore, luceneUtils, flagConfig, queryTriple[0]); Vector term1 = CompoundVectorBuilder.getQueryVectorFromString(queryVecStore, luceneUtils, flagConfig, queryTriple[1]); Vector term2 = CompoundVectorBuilder.getQueryVectorFromString(queryVecStore, luceneUtils, flagConfig, queryTriple[2]); Vector relationVec = term0.copy(); relationVec.bind(term1); this.queryVector = term2.copy(); this.queryVector.release(relationVec); } @Override public double getScore(Vector testVector) { return queryVector.measureOverlap(testVector); } } /** * Class for searching a permuted vector store using cosine similarity. * Uses implementation of rotation for permutation proposed by Sahlgren et al 2008 * Should find the term that appears frequently in the position p relative to the * index term (i.e. sat +1 would find a term occurring frequently immediately after "sat" * This is a variant that takes into account different results obtained when using either * permuted or random index vectors as the cue terms, by taking the mean of the results * obtained with each of these options. */ static public class BalancedVectorSearcherPerm extends VectorSearcher { Vector oneDirection; Vector otherDirection; VectorStore searchVecStore, queryVecStore; // These "special" fields are here to enable non-static construction of these // static inherited classes. It suggests that the inheritance pattern for VectorSearcher // needs to be reconsidered. LuceneUtils specialLuceneUtils; FlagConfig specialFlagConfig; String[] queryTerms; /** * @param queryVecStore Vector store to use for query generation (this is also reversed). * @param searchVecStore The vector store to search (this is also reversed). * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) * @param queryTerms Terms that will be parsed into a query * expression. If the string "?" appears, terms best fitting into this position will be returned */ public BalancedVectorSearcherPerm( VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, FlagConfig flagConfig, String[] queryTerms) throws IllegalArgumentException, ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils, flagConfig); specialFlagConfig = flagConfig; specialLuceneUtils = luceneUtils; try { oneDirection = pitt.search.semanticvectors.CompoundVectorBuilder. getPermutedQueryVector(queryVecStore, luceneUtils, flagConfig, queryTerms); otherDirection = pitt.search.semanticvectors.CompoundVectorBuilder. getPermutedQueryVector(searchVecStore, luceneUtils, flagConfig, queryTerms); } catch (IllegalArgumentException e) { logger.info("Couldn't create balanced permutation VectorSearcher ..."); throw e; } if (oneDirection.isZeroVector()) { throw new ZeroVectorException("Permutation query vector is zero ... no results."); } } /** * This overrides the nearest neighbor class implemented in the abstract * {@code VectorSearcher} class. * * WARNING: This implementation fails to respect flags used by the * {@code VectorSearcher.getNearestNeighbors} method. * * @param numResults the number of results / length of the result list. */ @Override public LinkedList<SearchResult> getNearestNeighbors(int numResults) { LinkedList<SearchResult> results = new LinkedList<SearchResult>(); double score, score1, score2 = -1; double threshold = specialFlagConfig.searchresultsminscore(); if (specialFlagConfig.stdev()) threshold = 0; // Counters for statistics to calculate standard deviation double sum=0, sumsquared=0; int count=0; Enumeration<ObjectVector> vecEnum = searchVecStore.getAllVectors(); Enumeration<ObjectVector> vecEnum2 = queryVecStore.getAllVectors(); while (vecEnum.hasMoreElements()) { // Test this element. ObjectVector testElement = vecEnum.nextElement(); ObjectVector testElement2 = vecEnum2.nextElement(); score1 = getScore(testElement.getVector()); score2 = getScore2(testElement2.getVector()); score = Math.max(score1,score2); // This is a way of using the Lucene Index to get term and // document frequency information to reweight all results. It // seems to be good at moving excessively common terms further // down the results. Note that using this means that scores // returned are no longer just cosine similarities. if ((specialLuceneUtils != null) && specialFlagConfig.usetermweightsinsearch()) { score = score * specialLuceneUtils.getGlobalTermWeightFromString((String) testElement.getObject()); } if (specialFlagConfig.stdev()) { System.out.println("STDEV"); count++; sum += score; sumsquared += Math.pow(score, 2); } if (score > threshold) { boolean added = false; for (int i = 0; i < results.size(); ++i) { // Add to list if this is right place. if (score > results.get(i).getScore() && added == false) { results.add(i, new SearchResult(score, testElement)); added = true; } } // Prune list if there are already numResults. if (results.size() > numResults) { results.removeLast(); threshold = results.getLast().getScore(); } else { if (added == false) { results.add(new SearchResult(score, testElement)); } } } } if (specialFlagConfig.stdev()) results = transformToStats(results, count, sum, sumsquared); return results; } @Override public double getScore(Vector testVector) { testVector.normalize(); return oneDirection.measureOverlap(testVector); } public double getScore2(Vector testVector) { testVector.normalize(); return (otherDirection.measureOverlap(testVector)); } } /** * Class for implementing Lucene search directly (no semantic vectors required) */ static public class VectorSearcherLucene extends VectorSearcher { // These "special" fields are here to enable non-static construction of these // static inherited classes. It suggests that the inheritance pattern for VectorSearcher // needs to be reconsidered. LuceneUtils specialLuceneUtils; FlagConfig specialFlagConfig; String[] queryTerms; IndexSearcher iSearcher; /** * Lucene search, no semantic vectors required * @param luceneUtils LuceneUtils object to use for query weighting. (May not be null.) * @param queryTerms Terms that will be parsed into a query expression */ public VectorSearcherLucene(LuceneUtils luceneUtils, FlagConfig flagConfig, String[] queryTerms) throws IllegalArgumentException, ZeroVectorException { super(null, null, luceneUtils, flagConfig); this.specialLuceneUtils = luceneUtils; this.specialFlagConfig = flagConfig; Directory dir; try { dir = FSDirectory.open(new File(flagConfig.luceneindexpath())); this.iSearcher = new IndexSearcher(DirectoryReader.open(dir)); } catch (IOException e) { logger.info("Lucene index initialization failed: "+e.getMessage()); } this.queryTerms = queryTerms; } /** * This overrides the nearest neighbor class implemented in the abstract * {@code VectorSearcher} class. * * WARNING: This implementation fails to respect flags used by the * {@code VectorSearcher.getNearestNeighbors} method. * * @param numResults the number of results / length of the result list. */ @Override public LinkedList<SearchResult> getNearestNeighbors(int numResults) { LinkedList<SearchResult> results = new LinkedList<SearchResult>(); BooleanQuery mtq = new BooleanQuery(); for (int q=0; q < queryTerms.length; q++) { //add OR clause to boolean query String term = queryTerms[q]; for (String field:this.specialFlagConfig.contentsfields()) mtq.add(new TermQuery(new org.apache.lucene.index.Term( field, term)), org.apache.lucene.search.BooleanClause.Occur.SHOULD); } TopDocs docs; try { docs = iSearcher.search(mtq, specialFlagConfig.numsearchresults()); ScoreDoc[] hits2 = docs.scoreDocs; for (int i = 0; i < hits2.length; i++) { int docId = hits2[i].doc; // if (i < 10) { // Explanation explain = iSearcher.explain(mtq, docId); // System.out.println(explain); // } Document d = iSearcher.doc(docId); float dscore = hits2[i].score; results.add(new SearchResult(dscore, new ObjectVector(d.get(specialFlagConfig.docidfield()), null))); } } catch (IOException e) { // TODO Auto-generated catch block logger.info("Lucene search failed: "+e.getMessage()); } return results; } @Override public double getScore(Vector testVector) { // TODO Auto-generated method stub return 0; } } /** * calculates approximation of standard deviation (using a somewhat imprecise single-pass algorithm) * and recasts top scores as number of standard deviations from the mean (for a single search) * * @return list of results with scores as number of standard deviations from mean */ public LinkedList<SearchResult> transformToStats( LinkedList<SearchResult> rawResults,int count, double sum, double sumsq) { LinkedList<SearchResult> transformedResults = new LinkedList<SearchResult>(); double variancesquared = sumsq - (Math.pow(sum,2)/count); double stdev = Math.sqrt(variancesquared/(count)); double mean = sum/count; Iterator<SearchResult> iterator = rawResults.iterator(); while (iterator.hasNext()) { SearchResult temp = iterator.next(); double score = temp.getScore(); score = new Double((score-mean)/stdev).floatValue(); if (score > flagConfig.searchresultsminscore()) transformedResults.add(new SearchResult(score, temp.getObjectVector())); } return transformedResults; } }
Added weighting for PSI searches git-svn-id: 08ea2b8556b98ff0c759f891b20f299445ddff2f@1125 483481f0-a63c-0410-a8a8-396719eec1a4
src/main/java/pitt/search/semanticvectors/VectorSearcher.java
Added weighting for PSI searches
<ide><path>rc/main/java/pitt/search/semanticvectors/VectorSearcher.java <ide> import org.apache.lucene.index.DirectoryReader; <ide> import org.apache.lucene.index.IndexReader; <ide> import org.apache.lucene.search.BooleanQuery; <add>import org.apache.lucene.search.Explanation; <ide> import org.apache.lucene.search.IndexSearcher; <ide> import org.apache.lucene.search.ScoreDoc; <ide> import org.apache.lucene.search.TermQuery; <ide> super(semanticVecStore, searchVecStore, luceneUtils, flagConfig); <ide> <ide> this.queryVector = CompoundVectorBuilder.getBoundProductQueryVectorFromString( <del> flagConfig, elementalVecStore, semanticVecStore, predicateVecStore, term1); <add> flagConfig, elementalVecStore, semanticVecStore, predicateVecStore, luceneUtils, term1); <ide> <ide> if (this.queryVector.isZeroVector()) { <ide> throw new ZeroVectorException("Query vector is zero ... no results."); <ide> FlagConfig specialFlagConfig; <ide> String[] queryTerms; <ide> IndexSearcher iSearcher; <add> VectorStoreRAM acceptableTerms; <ide> <ide> /** <ide> * Lucene search, no semantic vectors required <ide> try { <ide> dir = FSDirectory.open(new File(flagConfig.luceneindexpath())); <ide> this.iSearcher = new IndexSearcher(DirectoryReader.open(dir)); <del> <add> <add> if (!flagConfig.elementalvectorfile().equals("elementalvectors")) <add> {this.acceptableTerms = new VectorStoreRAM(flagConfig); <add> acceptableTerms.initFromFile(flagConfig.elementalvectorfile()); <add> } <ide> } catch (IOException e) { <ide> logger.info("Lucene index initialization failed: "+e.getMessage()); <ide> } <ide> <ide> for (int q=0; q < queryTerms.length; q++) <ide> { <add> <ide> //add OR clause to boolean query <ide> String term = queryTerms[q]; <add> <add> if (acceptableTerms != null && !acceptableTerms.containsVector(term)) <add> continue; <add> <ide> for (String field:this.specialFlagConfig.contentsfields()) <ide> mtq.add(new TermQuery(new org.apache.lucene.index.Term( <ide> field, term)), org.apache.lucene.search.BooleanClause.Occur.SHOULD); <ide> for (int i = 0; i < hits2.length; i++) { <ide> int docId = hits2[i].doc; <ide> <del> // if (i < 10) { <del> // Explanation explain = iSearcher.explain(mtq, docId); <del> // System.out.println(explain); <del> // } <add> if (specialFlagConfig.hybridvectors()) <add> if (i < specialFlagConfig.numsearchresults()) { <add> Explanation explain = iSearcher.explain(mtq, docId); <add> System.out.println(explain); <add> } <ide> Document d = iSearcher.doc(docId); <ide> float dscore = hits2[i].score; <ide> results.add(new SearchResult(dscore, new ObjectVector(d.get(specialFlagConfig.docidfield()), null)));
Java
epl-1.0
a09569647be0f31fc35aaba8e0ad50ebfee69d46
0
cocosli/mondrian,dkincade/mondrian,mdamour1976/mondrian,wetet2/mondrian,mdamour1976/mondrian,ivanpogodin/mondrian,truvenganong/mondrian,cesarmarinhorj/mondrian,bmorrise/mondrian,bmorrise/mondrian,AvinashPD/mondrian,nextelBIS/mondrian,pedrofvteixeira/mondrian,truvenganong/mondrian,pedrofvteixeira/mondrian,lgrill-pentaho/mondrian,rfellows/mondrian,openedbox/mondrian,syncron/mondrian,stiberger/mondrian,openedbox/mondrian,cesarmarinhorj/mondrian,ivanpogodin/mondrian,preisanalytics/mondrian,lgrill-pentaho/mondrian,syncron/mondrian,Seiferxx/mondrian,lgrill-pentaho/mondrian,AvinashPD/mondrian,pentaho/mondrian,mustangore/mondrian,preisanalytics/mondrian,nextelBIS/mondrian,wetet2/mondrian,cocosli/mondrian,syncron/mondrian,julianhyde/mondrian,cesarmarinhorj/mondrian,dkincade/mondrian,bmorrise/mondrian,wetet2/mondrian,truvenganong/mondrian,mustangore/mondrian,rfellows/mondrian,citycloud-bigdata/mondrian,OSBI/mondrian,pentaho/mondrian,sayanh/mondrian,mustangore/mondrian,Seiferxx/mondrian,preisanalytics/mondrian,citycloud-bigdata/mondrian,citycloud-bigdata/mondrian,stiberger/mondrian,AvinashPD/mondrian,nextelBIS/mondrian,pedrofvteixeira/mondrian,sayanh/mondrian,sayanh/mondrian,Seiferxx/mondrian,OSBI/mondrian,dkincade/mondrian,OSBI/mondrian,julianhyde/mondrian,cocosli/mondrian,mdamour1976/mondrian,ivanpogodin/mondrian,stiberger/mondrian,pentaho/mondrian,openedbox/mondrian
src/main/mondrian/calc/MemberList.java
/* // $Id$ // This software is subject to the terms of the Eclipse Public License v1.0 // Agreement, available at the following URL: // http://www.eclipse.org/legal/epl-v10.html. // Copyright (C) 2010-2011 Julian Hyde // All Rights Reserved. // You must accept the terms of that agreement to use this software. */ package mondrian.calc; import mondrian.olap.Member; import java.util.List; /** * List of members. * * <h2>Design notes</h2> * * <ul> * * <li>Remove {@link mondrian.calc.impl.AbstractListCalc#evaluateList(mondrian.olap.Evaluator)}? * * <li>Change {@link TupleCalc#evaluateTuple(mondrian.olap.Evaluator)} * and {@link mondrian.olap.Evaluator.NamedSetEvaluator#currentTuple()} * to List&lt;Member&gt;</li> * * <li>Search for potential uses of {@link TupleList#get(int, int)} * * <li>Worth creating {@link TupleList}.addAll(TupleIterator)? * * </ul> * * <p>Done</p> * <ul> * <li>obsolete AbstractTupleListCalc (merge into AbstractListCalc) * <li>obsolete AbstractMemberListCalc * <li>obsolete AbstractTupleIterCalc (merge into AbstractIterCalc) * <li>obsolete AbstractMembeIterCalc * <li>obsolete TupleIterCalc (merge into IterCalc) * <li>obsolete MemberIterCalc * <li>rename IterableTupleListCalc to IterableListCalc * <li>obsolete IterableMemberListCalc * * </ul> */ public interface MemberList extends List<Member> { } // End MemberList.java
MONDRIAN: Oops, never intended to check this in. [git-p4: depot-paths = "//open/mondrian/": change = 14040]
src/main/mondrian/calc/MemberList.java
MONDRIAN: Oops, never intended to check this in.
<ide><path>rc/main/mondrian/calc/MemberList.java <del>/* <del>// $Id$ <del>// This software is subject to the terms of the Eclipse Public License v1.0 <del>// Agreement, available at the following URL: <del>// http://www.eclipse.org/legal/epl-v10.html. <del>// Copyright (C) 2010-2011 Julian Hyde <del>// All Rights Reserved. <del>// You must accept the terms of that agreement to use this software. <del>*/ <del>package mondrian.calc; <del> <del>import mondrian.olap.Member; <del> <del>import java.util.List; <del> <del>/** <del> * List of members. <del> * <del> * <h2>Design notes</h2> <del> * <del> * <ul> <del> * <del> * <li>Remove {@link mondrian.calc.impl.AbstractListCalc#evaluateList(mondrian.olap.Evaluator)}? <del> * <del> * <li>Change {@link TupleCalc#evaluateTuple(mondrian.olap.Evaluator)} <del> * and {@link mondrian.olap.Evaluator.NamedSetEvaluator#currentTuple()} <del> * to List&lt;Member&gt;</li> <del> * <del> * <li>Search for potential uses of {@link TupleList#get(int, int)} <del> * <del> * <li>Worth creating {@link TupleList}.addAll(TupleIterator)? <del> * <del> * </ul> <del> * <del> * <p>Done</p> <del> * <ul> <del> * <li>obsolete AbstractTupleListCalc (merge into AbstractListCalc) <del> * <li>obsolete AbstractMemberListCalc <del> * <li>obsolete AbstractTupleIterCalc (merge into AbstractIterCalc) <del> * <li>obsolete AbstractMembeIterCalc <del> * <li>obsolete TupleIterCalc (merge into IterCalc) <del> * <li>obsolete MemberIterCalc <del> * <li>rename IterableTupleListCalc to IterableListCalc <del> * <li>obsolete IterableMemberListCalc <del> * <del> * </ul> <del> */ <del>public interface MemberList extends List<Member> { <del>} <del> <del>// End MemberList.java
Java
mit
error: pathspec 'src/org/joml/geom/Rayf.java' did not match any file(s) known to git
d3fb0a5c8e3bc595b8f3354c8de925fc832389c2
1
Longor1996/JOML-GEOM
package org.joml.geom; import org.joml.Matrix4f; import org.joml.Vector3f; import org.joml.Vector4f; public class Rayf { public float originX; public float originY; public float originZ; public float directionX; public float directionY; public float directionZ; /** Creates a new {@link Rayf} located at (0,0,0) pointing at (0,0,1)/positive Z. **/ public Rayf() { originX = 0; originY = 0; originZ = 0; directionX = 0; directionY = 0; directionZ = 1; } /** Creates a new {@link Rayf} located at (0,0,0) pointing in the given direction. **/ public Rayf(float dirX, float dirY, float dirZ) { originX = 0; originY = 0; originZ = 0; directionX = dirX; directionY = dirY; directionZ = dirZ; } /** Creates a new {@link Rayf} located at a given pointing in the given direction. **/ public Rayf(float dirX, float dirY, float dirZ, float orgX, float orgY, float orgZ) { originX = orgX; originY = orgY; originZ = orgZ; directionX = dirX; directionY = dirY; directionZ = dirZ; } /** Creates a new {@link Rayf} located at (0,0,0) pointing in the given direction. **/ public Rayf(Vector3f direction) { originX = 0; originY = 0; originZ = 0; directionX = direction.x; directionY = direction.y; directionZ = direction.z; } /** Creates a new {@link Rayf} located at a given pointing in the given direction. **/ public Rayf(Vector3f direction, Vector3f origin) { originX = origin.x; originY = origin.y; originZ = origin.z; directionX = direction.x; directionY = direction.y; directionZ = direction.z; } public Vector3f getDirection(Vector3f store) { return store.set(directionX, directionY, directionZ); } public Vector3f getOrigin(Vector3f store) { return store.set(originX, originY, originZ); } public Vector3f trace(float t, Vector3f store) { return store.set(originX+directionX*t, originY+directionY*t, originZ+directionZ*t); } public Vector3f traceReverse(float t, Vector3f store) { return store.set(originX-directionX*t, originY-directionY*t, originZ-directionZ*t); } public Rayf move(float x, float y, float z) { originX += x; originY += y; originZ += z; return this; } public Rayf move(Vector3f load) { originX += load.x; originY += load.y; originZ += load.z; return this; } public Rayf transform(Matrix4f load, Vector4f store, boolean normalizeDirection) { // Transform Origin { store.set(originX, originY, originZ, 1f); load.transform(store); originX = store.x; originY = store.y; originZ = store.z; } // Transform Direction { store.set(directionX, directionY, directionZ, 1f); load.transform(store); if(normalizeDirection) { store.normalize(); } directionX = store.x; directionY = store.y; directionZ = store.z; } return this; } }
src/org/joml/geom/Rayf.java
Added Ray class.
src/org/joml/geom/Rayf.java
Added Ray class.
<ide><path>rc/org/joml/geom/Rayf.java <add>package org.joml.geom; <add> <add>import org.joml.Matrix4f; <add>import org.joml.Vector3f; <add>import org.joml.Vector4f; <add> <add>public class Rayf { <add> public float originX; <add> public float originY; <add> public float originZ; <add> public float directionX; <add> public float directionY; <add> public float directionZ; <add> <add> /** Creates a new {@link Rayf} located at (0,0,0) pointing at (0,0,1)/positive Z. **/ <add> public Rayf() { <add> originX = 0; <add> originY = 0; <add> originZ = 0; <add> directionX = 0; <add> directionY = 0; <add> directionZ = 1; <add> } <add> <add> /** Creates a new {@link Rayf} located at (0,0,0) pointing in the given direction. **/ <add> public Rayf(float dirX, float dirY, float dirZ) { <add> originX = 0; <add> originY = 0; <add> originZ = 0; <add> directionX = dirX; <add> directionY = dirY; <add> directionZ = dirZ; <add> } <add> <add> /** Creates a new {@link Rayf} located at a given pointing in the given direction. **/ <add> public Rayf(float dirX, float dirY, float dirZ, float orgX, float orgY, float orgZ) { <add> originX = orgX; <add> originY = orgY; <add> originZ = orgZ; <add> directionX = dirX; <add> directionY = dirY; <add> directionZ = dirZ; <add> } <add> <add> /** Creates a new {@link Rayf} located at (0,0,0) pointing in the given direction. **/ <add> public Rayf(Vector3f direction) { <add> originX = 0; <add> originY = 0; <add> originZ = 0; <add> directionX = direction.x; <add> directionY = direction.y; <add> directionZ = direction.z; <add> } <add> <add> /** Creates a new {@link Rayf} located at a given pointing in the given direction. **/ <add> public Rayf(Vector3f direction, Vector3f origin) { <add> originX = origin.x; <add> originY = origin.y; <add> originZ = origin.z; <add> directionX = direction.x; <add> directionY = direction.y; <add> directionZ = direction.z; <add> } <add> <add> public Vector3f getDirection(Vector3f store) { <add> return store.set(directionX, directionY, directionZ); <add> } <add> <add> public Vector3f getOrigin(Vector3f store) { <add> return store.set(originX, originY, originZ); <add> } <add> <add> public Vector3f trace(float t, Vector3f store) { <add> return store.set(originX+directionX*t, originY+directionY*t, originZ+directionZ*t); <add> } <add> <add> public Vector3f traceReverse(float t, Vector3f store) { <add> return store.set(originX-directionX*t, originY-directionY*t, originZ-directionZ*t); <add> } <add> <add> public Rayf move(float x, float y, float z) { <add> originX += x; <add> originY += y; <add> originZ += z; <add> return this; <add> } <add> <add> public Rayf move(Vector3f load) { <add> originX += load.x; <add> originY += load.y; <add> originZ += load.z; <add> return this; <add> } <add> <add> public Rayf transform(Matrix4f load, Vector4f store, boolean normalizeDirection) { <add> // Transform Origin <add> { <add> store.set(originX, originY, originZ, 1f); <add> load.transform(store); <add> originX = store.x; <add> originY = store.y; <add> originZ = store.z; <add> } <add> <add> // Transform Direction <add> { <add> store.set(directionX, directionY, directionZ, 1f); <add> load.transform(store); <add> <add> if(normalizeDirection) { <add> store.normalize(); <add> } <add> <add> directionX = store.x; <add> directionY = store.y; <add> directionZ = store.z; <add> } <add> <add> return this; <add> } <add> <add>}
Java
epl-1.0
error: pathspec 'jpa/eclipselink.jpars.test/src/org/eclipse/persistence/jpars/test/model/multitenant/Account.java' did not match any file(s) known to git
dc4d31189e9d517e141ad4c399fb6196ce09c870
1
bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs,bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs,bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs
package org.eclipse.persistence.jpars.test.model.multitenant; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Version; import org.eclipse.persistence.annotations.Multitenant; import org.eclipse.persistence.annotations.TenantDiscriminatorColumn; @Entity @Table(name="JPARS_ACCOUNT") @Multitenant @TenantDiscriminatorColumn(name="TENANT_ID", contextProperty="tenant.id", primaryKey=true) public class Account { @Id @GeneratedValue private int id; private String accoutNumber; @Version private int version; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getAccoutNumber() { return accoutNumber; } public void setAccoutNumber(String accoutNumber) { this.accoutNumber = accoutNumber; } public int getVersion() { return version; } public void setVersion(int version) { this.version = version; } }
jpa/eclipselink.jpars.test/src/org/eclipse/persistence/jpars/test/model/multitenant/Account.java
Add Account Object Former-commit-id: 31acc92990c2a72ba9abbecb25b62e289897b3b2
jpa/eclipselink.jpars.test/src/org/eclipse/persistence/jpars/test/model/multitenant/Account.java
Add Account Object
<ide><path>pa/eclipselink.jpars.test/src/org/eclipse/persistence/jpars/test/model/multitenant/Account.java <add>package org.eclipse.persistence.jpars.test.model.multitenant; <add> <add>import javax.persistence.Entity; <add>import javax.persistence.GeneratedValue; <add>import javax.persistence.Id; <add>import javax.persistence.Table; <add>import javax.persistence.Version; <add> <add>import org.eclipse.persistence.annotations.Multitenant; <add>import org.eclipse.persistence.annotations.TenantDiscriminatorColumn; <add> <add>@Entity <add>@Table(name="JPARS_ACCOUNT") <add>@Multitenant <add>@TenantDiscriminatorColumn(name="TENANT_ID", contextProperty="tenant.id", primaryKey=true) <add>public class Account { <add> <add> @Id <add> @GeneratedValue <add> private int id; <add> private String accoutNumber; <add> @Version <add> private int version; <add> <add> public int getId() { <add> return id; <add> } <add> public void setId(int id) { <add> this.id = id; <add> } <add> public String getAccoutNumber() { <add> return accoutNumber; <add> } <add> public void setAccoutNumber(String accoutNumber) { <add> this.accoutNumber = accoutNumber; <add> } <add> public int getVersion() { <add> return version; <add> } <add> public void setVersion(int version) { <add> this.version = version; <add> } <add>}
Java
apache-2.0
e4566584c2d3c18ca8a9e1f6b4555976a64fff19
0
wyona/yanel,wyona/yanel,wyona/yanel,wyona/yanel,wyona/yanel,wyona/yanel
/* * See the NOTICE.txt file distributed with * this work for additional information regarding copyright ownership. * Wyona 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.wyona.yanel.servlet; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.net.URL; import java.util.Calendar; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.xml.transform.Source; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.sax.SAXResult; import javax.xml.transform.sax.SAXTransformerFactory; import javax.xml.transform.sax.TransformerHandler; import javax.xml.transform.stream.StreamSource; import org.wyona.commons.xml.XMLHelper; import org.wyona.neutron.XMLExceptionV1; import org.wyona.yanel.core.Environment; import org.wyona.yanel.core.Path; import org.wyona.yanel.core.Resource; import org.wyona.yanel.core.ResourceConfiguration; import org.wyona.yanel.core.ResourceNotFoundException; import org.wyona.yanel.core.ResourceTypeIdentifier; import org.wyona.yanel.core.ResourceTypeRegistry; import org.wyona.yanel.core.StateOfView; import org.wyona.yanel.core.ToolbarState; import org.wyona.yanel.core.Yanel; import org.wyona.yanel.core.api.attributes.AnnotatableV1; import org.wyona.yanel.core.api.attributes.IntrospectableV1; import org.wyona.yanel.core.api.attributes.DeletableV1; import org.wyona.yanel.core.api.attributes.ModifiableV1; import org.wyona.yanel.core.api.attributes.ModifiableV2; import org.wyona.yanel.core.api.attributes.TranslatableV1; import org.wyona.yanel.core.api.attributes.VersionableV1; import org.wyona.yanel.core.api.attributes.VersionableV2; import org.wyona.yanel.core.api.attributes.VersionableV3; import org.wyona.yanel.core.api.attributes.ViewableV1; import org.wyona.yanel.core.api.attributes.ViewableV2; import org.wyona.yanel.core.api.attributes.WorkflowableV1; import org.wyona.yanel.core.api.security.WebAuthenticator; import org.wyona.yanel.core.attributes.versionable.RevisionInformation; import org.wyona.yanel.core.attributes.viewable.View; import org.wyona.yanel.core.attributes.viewable.ViewDescriptor; import org.wyona.yanel.core.attributes.tracking.TrackingInformationV1; import org.wyona.yanel.core.navigation.Node; import org.wyona.yanel.core.navigation.Sitetree; import org.wyona.yanel.core.serialization.SerializerFactory; import org.wyona.yanel.core.source.SourceResolver; import org.wyona.yanel.core.source.YanelStreamSource; import org.wyona.yanel.core.transformation.I18nTransformer2; import org.wyona.yanel.core.util.ConfigurationUtil; import org.wyona.yanel.core.util.DateUtil; import org.wyona.yanel.core.util.HttpServletRequestHelper; import org.wyona.yanel.core.workflow.Transition; import org.wyona.yanel.core.workflow.Workflow; import org.wyona.yanel.core.workflow.WorkflowException; import org.wyona.yanel.core.workflow.WorkflowHelper; import org.wyona.yanel.core.map.Map; import org.wyona.yanel.core.map.Realm; import org.wyona.yanel.core.map.ReverseProxyConfig; import org.wyona.yanel.core.util.ResourceAttributeHelper; import org.wyona.yanel.impl.resources.BasicGenericExceptionHandlerResource; import org.wyona.yanel.servlet.IdentityMap; import org.wyona.yanel.servlet.communication.HttpRequest; import org.wyona.yanel.servlet.communication.HttpResponse; import org.wyona.yanel.servlet.security.impl.AutoLogin; import org.wyona.security.core.api.Identity; import org.wyona.security.core.api.Usecase; import org.wyona.security.core.api.User; import org.wyona.security.core.api.UserManager; import org.apache.log4j.Logger; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.ThreadContext; import org.apache.xalan.transformer.TransformerIdentityImpl; import org.apache.xml.resolver.tools.CatalogResolver; import org.apache.xml.serializer.Serializer; import org.apache.avalon.framework.configuration.Configuration; import org.apache.avalon.framework.configuration.DefaultConfiguration; import org.apache.avalon.framework.configuration.DefaultConfigurationBuilder; import org.apache.avalon.framework.configuration.DefaultConfigurationSerializer; import org.apache.avalon.framework.configuration.MutableConfiguration; import org.apache.commons.io.FilenameUtils; //import org.apache.commons.io.IOUtils; import org.apache.commons.io.output.ByteArrayOutputStream; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.quartz.JobDetail; import org.quartz.Scheduler; import org.quartz.SimpleTrigger; import org.quartz.Trigger; import org.quartz.impl.StdSchedulerFactory; /** * Main entry point of Yanel webapp (see method 'service') */ public class YanelServlet extends HttpServlet { private static org.apache.logging.log4j.Logger log = LogManager.getLogger(YanelServlet.class); private static Logger logAccess = Logger.getLogger(AccessLog.CATEGORY); private static Logger logDoNotTrack = Logger.getLogger("DoNotTrack"); // INFO: For debugging only! private static Logger log404 = Logger.getLogger("404"); private Map map; private Yanel yanelInstance; private Sitetree sitetree; private long MEMORY_GROWTH_THRESHOLD = 300; private String defaultXsltInfoAndException; private String xsltLoginScreenDefault; private boolean displayMostRecentVersion = true; public static final String MOBILE_KEY = "yanel.mobile"; public static final String IDENTITY_MAP_KEY = "identity-map"; private static final String TOOLBAR_USECASE = "toolbar"; //TODO is this the same as YanelAuthoringUI.TOOLBAR_KEY? public static final String NAMESPACE = "http://www.wyona.org/yanel/1.0"; private static final String METHOD_PROPFIND = "PROPFIND"; private static final String METHOD_OPTIONS = "OPTIONS"; private static final String METHOD_GET = "GET"; private static final String METHOD_POST = "POST"; private static final String METHOD_PUT = "PUT"; private static final String METHOD_DELETE = "DELETE"; private static final String HTTP_REFERRER = "Referer"; // ah, misspellings, how I hate thee (http://en.wikipedia.org/wiki/Referer)! private String sslPort = null; private String toolbarMasterSwitch = "off"; private String reservedPrefix; private String servletContextRealPath; private int cacheExpires = 0; private YanelHTMLUI yanelUI; private boolean logAccessEnabled = false; private boolean detectMobilePerRequest = false; public static final String DEFAULT_ENCODING = "UTF-8"; public static final String YANEL_ACCESS_POLICY_USECASE = "yanel.policy"; public static final String YANEL_USECASE = "yanel.usecase"; public static final String YANEL_RESOURCE = "yanel.resource"; public static final String YANEL_RESOURCE_USECASE = YANEL_RESOURCE + ".usecase"; public static final String YANEL_RESOURCE_REVISION = YANEL_RESOURCE + ".revision"; public static final String YANEL_RESOURCE_WORKFLOW_TRANSITION = YANEL_RESOURCE + ".workflow.transition"; public static final String YANEL_RESOURCE_WORKFLOW_TRANSITION_OUTPUT = YANEL_RESOURCE_WORKFLOW_TRANSITION + ".output"; public static final String VIEW_ID_PARAM_NAME = "yanel.resource.viewid"; public static final String RESOURCE_META_ID_PARAM_NAME = "yanel.resource.meta"; public static final String RELEASE_LOCK = "release-lock"; private static final String CONTENT_TYPE_XHTML = "xhtml"; public static final String YANEL_LAST_ACCESS_ATTR = "_yanel-last-access"; private Scheduler scheduler; private String[] mobileDevices; private static String ACCESS_LOG_TAG_SEPARATOR; private static final String REVISIONS_TAG_NAME = "revisions"; private static final String NO_REVISIONS_TAG_NAME = "no-revisions-yet"; private static final String EXCEPTION_TAG_NAME = "exception"; private static final String CAS_LOGOUT_REQUEST_PARAM_NAME = "logoutRequest"; /** * @see javax.servlet.GenericServlet#init(ServletConfig) */ @Override public void init(ServletConfig config) throws ServletException { servletContextRealPath = config.getServletContext().getRealPath("/"); if (config.getInitParameter("memory.growth.threshold") != null) { MEMORY_GROWTH_THRESHOLD = new Long(config.getInitParameter("memory.growth.threshold")).longValue(); } defaultXsltInfoAndException = config.getInitParameter("exception-and-info-screen-xslt"); xsltLoginScreenDefault = config.getInitParameter("login-screen-xslt"); displayMostRecentVersion = new Boolean(config.getInitParameter("workflow.not-live.most-recent-version")).booleanValue(); try { yanelInstance = Yanel.getInstance(); yanelInstance.init(); // TODO: Tell Yanel about alternative directory to look for configuration files, e.g. (File) getServletContext().getAttribute("javax.servlet.context.tempdir") map = yanelInstance.getMapImpl("map"); sitetree = yanelInstance.getSitetreeImpl("repo-navigation"); sslPort = config.getInitParameter("ssl-port"); toolbarMasterSwitch = config.getInitParameter("toolbar-master-switch"); reservedPrefix = yanelInstance.getReservedPrefix(); String expires = config.getInitParameter("static-content-cache-expires"); if (expires != null) { this.cacheExpires = Integer.parseInt(expires); } yanelUI = new YanelHTMLUI(map, reservedPrefix); // TODO: Make this value configurable also per realm or per individual user! logAccessEnabled = new Boolean(config.getInitParameter("log-access")).booleanValue(); String TAG_SEP_PARAM_NAME = "access-log-tag-separator"; if (config.getInitParameter(TAG_SEP_PARAM_NAME) != null) { if (config.getInitParameter(TAG_SEP_PARAM_NAME).equals("SPACE")) { // Note that the leading and trailing space around the parameter value is trimmed, hence we denote the space sign by SPACE. ACCESS_LOG_TAG_SEPARATOR = " "; } else { ACCESS_LOG_TAG_SEPARATOR = config.getInitParameter(TAG_SEP_PARAM_NAME); } } else { ACCESS_LOG_TAG_SEPARATOR = ","; log.warn("No access log tag separator parameter '" + TAG_SEP_PARAM_NAME + "' configured, hence use default: " + ACCESS_LOG_TAG_SEPARATOR); } // TODO: Make this value configurable also per realm or per individual user! if (config.getInitParameter("detect-mobile-per-request") != null) { detectMobilePerRequest = new Boolean(config.getInitParameter("detect-mobile-per-request")).booleanValue(); } if (config.getInitParameter("mobile-devices") != null) { mobileDevices = org.springframework.util.StringUtils.tokenizeToStringArray(config.getInitParameter("mobile-devices"), ",", true, true); } else { mobileDevices = new String[]{"iPhone", "Android"}; log.error("No mobile devices configured! Please make sure to update your web.xml configuration file accordingly. Fallback to hard-coded list: " + mobileDevices); } if (yanelInstance.isSchedulerEnabled()) { try { log.debug("Startup scheduler ..."); scheduler = StdSchedulerFactory.getDefaultScheduler(); Realm[] realms = yanelInstance.getRealmConfiguration().getRealms(); for (int i = 0; i < realms.length; i++) { if (realms[i] instanceof org.wyona.yanel.core.map.RealmWithConfigurationExceptionImpl) { String eMessage = ((org.wyona.yanel.core.map.RealmWithConfigurationExceptionImpl) realms[i]).getConfigurationException().getMessage(); log.error("Realm '" + realms[i].getID() + "' has thrown a configuration exception: " + eMessage); } else { String schedulerJobsPath = "/scheduler-jobs.xml"; if (realms[i].getRepository().existsNode(schedulerJobsPath)) { log.debug("Scheduler jobs config found for realm: " + realms[i].getRepository().getID()); try { // Get and filter scheduler config InputStream istream = realms[i].getRepository().getNode(schedulerJobsPath).getInputStream(); log.debug("Filter scheduler configuration of realm '" + realms[i].getID() + "' by target environment '" + yanelInstance.getTargetEnvironment() + "'..."); istream = ConfigurationUtil.filterEnvironment(istream, yanelInstance.getTargetEnvironment()); Document filteredConfiguration = XMLHelper.readDocument(istream); // INFO: Debug filtered scheduler configuration if (log.isDebugEnabled()) { org.wyona.yarep.core.Node filteredConfigDebugNode = null; if (realms[i].getRepository().existsNode(schedulerJobsPath + ".DEBUG")) { filteredConfigDebugNode = realms[i].getRepository().getNode(schedulerJobsPath + ".DEBUG"); } else { filteredConfigDebugNode = org.wyona.yarep.util.YarepUtil.addNodes(realms[i].getRepository(), schedulerJobsPath + ".DEBUG", org.wyona.yarep.core.NodeType.RESOURCE); } XMLHelper.writeDocument(filteredConfiguration, filteredConfigDebugNode.getOutputStream()); } // INFO: Run scheduler util org.wyona.yanel.impl.scheduler.QuartzSchedulerUtil.schedule(scheduler, filteredConfiguration, realms[i]); } catch(Exception e) { log.error(e, e); // INFO: Log error, but otherwise ignore and keep going ... } } } } /* TODO: Make global scheduler jobs configurable String groupName = "yanel"; JobDetail jobDetail = new JobDetail("heartbeatJob", groupName, org.wyona.yanel.servlet.HeartbeatJob.class); Date startDate = new Date(); Date endDate = null; Trigger trigger = new SimpleTrigger("heartbeatTrigger", groupName, startDate, endDate, SimpleTrigger.REPEAT_INDEFINITELY, 60L * 1000L); scheduler.scheduleJob(jobDetail, trigger); */ scheduler.start(); } catch(Exception e) { log.error(e, e); // INFO: Let's be fault tolerant in case the scheduler should not start } } else { log.info("The scheduler is currently disabled."); } } catch (Exception e) { log.error(e.getMessage(), e); throw new ServletException(e.getMessage(), e); } } /** * @see javax.servlet.http.HttpServlet#service(HttpServletRequest, HttpServletResponse) */ @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // NOTE: Do not add code outside the try-catch block, because otherwise exceptions won't be logged try { Runtime rt = Runtime.getRuntime(); long usedMBefore = getUsedMemory(rt); //log.debug("Memory usage before request processed: " + usedMBefore); ThreadContext.put("id", getFishTag(request)); //String httpAcceptMediaTypes = request.getHeader("Accept"); //String httpAcceptLanguage = request.getHeader("Accept-Language"); if (isCASLogoutRequest(request)) { log.warn("DEBUG: CAS logout request received: " + request.getServletPath()); if (doCASLogout(request, response)) { return; } else { log.error("Logout based on CAS request failed!"); } return; } String yanelUsecase = request.getParameter(YANEL_USECASE); if (yanelUsecase != null && yanelUsecase.equals("logout")) { try { log.debug("Disable auto login..."); // TODO: The cookie is not always deleted! AutoLogin.disableAutoLogin(request, response, getRealm(request).getRepository()); } catch (Exception e) { log.error("Exception while disabling auto login: " + e.getMessage(), e); } // INFO: Logout from Yanel if (doLogout(request, response)) { return; } else { log.error("Logout failed!"); } } else if(yanelUsecase != null && yanelUsecase.equals("create")) { // TODO: Why does that not go through access control? // INFO: Create a new resource if(doCreate(request, response) != null) return; } // Check authorization and if authorization failed, then try to authenticate if (doAccessControl(request, response) != null) { // INFO: Either redirect (after successful authentication) or access denied (and response will contain the login screen) return; } else { if (log.isDebugEnabled()) log.debug("Access granted: " + request.getServletPath()); } // Check for requests re policies String policyRequestPara = request.getParameter(YANEL_ACCESS_POLICY_USECASE); if (policyRequestPara != null) { doAccessPolicyRequest(request, response, 1); return; } else if (yanelUsecase != null && yanelUsecase.equals("policy.read")) { doAccessPolicyRequest(request, response, 2); return; } // Check for requests for global data Resource resource = getResource(request, response); String path = resource.getPath(); if (path.indexOf("/" + reservedPrefix + "/") == 0) { getGlobalData(request, response); return; } String value = request.getParameter(YANEL_RESOURCE_USECASE); // Delete node if (value != null && value.equals("delete")) { handleDeleteUsecase(request, response); return; } // INFO: Check if user agent is mobile device doMobile(request); // Delegate ... String method = request.getMethod(); if (method.equals(METHOD_PROPFIND)) { doPropfind(request, response); } else if (method.equals(METHOD_GET)) { doGet(request, response); } else if (method.equals(METHOD_POST)) { doPost(request, response); } else if (method.equals(METHOD_PUT)) { doPut(request, response); } else if (method.equals(METHOD_DELETE)) { doDelete(request, response); } else if (method.equals(METHOD_OPTIONS)) { doOptions(request, response); } else { log.error("No such method implemented: " + method); response.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED); } long usedMAfter = getUsedMemory(rt); //log.debug("Memory usage after request processed: " + usedMAfter); if ((usedMAfter - usedMBefore) > MEMORY_GROWTH_THRESHOLD) { log.warn("Memory usage increased by '" + MEMORY_GROWTH_THRESHOLD + "' while request '" + getRequestURLQS(request, null, false) + "' was processed!"); } } catch (ServletException e) { log.error(e, e); throw new ServletException(e.getMessage(), e); } catch (IOException e) { log.error(e, e); throw new IOException(e.getMessage()); } finally { ThreadContext.clear(); } // NOTE: This was our last chance to log an exception, hence do not add code outside the try-catch block } /** * Get currently used memory */ private long getUsedMemory(Runtime rt) { return (rt.totalMemory() - rt.freeMemory()) / 1024 / 1024; } /** * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest, HttpServletResponse) */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // INFO: Init session in case it does not exist yet HttpSession session = request.getSession(true); // INFO: Enable or disable toolbar yanelUI.switchToolbar(request); // INFO: Handle workflow transitions String transition = request.getParameter(YANEL_RESOURCE_WORKFLOW_TRANSITION); if (transition != null) { executeWorkflowTransition(request, response, request.getParameter(YANEL_RESOURCE_REVISION), transition); return; } // INFO: Init resource Resource resource = getResource(request, response); // INFO: Check for requests refered by WebDAV String yanelWebDAV = request.getParameter("yanel.webdav"); if(yanelWebDAV != null && yanelWebDAV.equals("propfind1")) { log.info("WebDAV client (" + request.getHeader("User-Agent") + ") requests to \"edit\" a resource: " + resource.getRealm() + ", " + resource.getPath()); //return; } // INFO: Handle first specific Yanel usecase requests and then at the very end all other requests String value = request.getParameter(YANEL_RESOURCE_USECASE); try { if (value != null && value.equals(RELEASE_LOCK)) { log.warn("Try to release lock ..."); if (ResourceAttributeHelper.hasAttributeImplemented(resource, "Versionable", "2")) { VersionableV2 versionable = (VersionableV2)resource; String checkoutUserID = versionable.getCheckoutUserID(); Identity identity = getEnvironment(request, response).getIdentity(); String userID = identity.getUsername(); Usecase usecase = new Usecase(RELEASE_LOCK); String path = resource.getPath(); if (checkoutUserID.equals(userID) || resource.getRealm().getPolicyManager().authorize(path, identity, usecase)) { try { versionable.cancelCheckout(); log.debug("Lock has been released."); response.setStatus(HttpServletResponse.SC_OK); response.setContentType("text/html" + "; charset=" + "UTF-8"); String backToRealm = org.wyona.yanel.core.util.PathUtil.backToRealm(resource.getPath()); StringBuilder sb = new StringBuilder("<html xmlns=\"http://www.w3.org/1999/xhtml\"><body>Lock has been released! back to <a href=\""+backToRealm + resource.getPath() +"\">page</a>.</body></html>"); PrintWriter w = response.getWriter(); w.print(sb); return; } catch (Exception e) { throw new ServletException("Releasing the lock of <" + resource.getPath() + "> failed because of: " + e.getMessage(), e); } } else { String eMessage = "Releasing the lock of '" + resource.getPath() + "' failed because"; if (checkoutUserID.equals(userID)) { eMessage = " user '" + userID + "' has no right to release her/his own lock!"; } else { eMessage = " checkout user '" + checkoutUserID + "' and session user '" + userID + "' are not the same and session user '" + userID + "' has no right to release the lock of the checkout user '" + checkoutUserID + "'!"; } log.warn(eMessage); throw new ServletException(eMessage); } } else { throw new ServletException("Resource '" + resource.getPath() + "' is not VersionableV2!"); } } else if (value != null && value.equals("roll-back")) { log.debug("Roll back ..."); org.wyona.yanel.core.util.VersioningUtil.rollBack(resource, request.getParameter(YANEL_RESOURCE_REVISION), getIdentityFromRequest(request, map.getRealm(request.getServletPath())).getUsername()); // TODO: Send confirmation screen getContent(request, response); return; } else { //log.debug("Handle all other GET requests..."); getContent(request, response); return; } } catch (Exception e) { throw new ServletException(e.getMessage(), e); } } /** * Returns the mime-type according to the given file extension. * Default is application/octet-stream. * @param extension * @return */ private static String guessMimeType(String extension) { String ext = extension.toLowerCase(); if (ext.equals("html") || ext.equals("htm")) return "text/html"; if (ext.equals("css")) return "text/css"; if (ext.equals("txt")) return "text/plain"; if (ext.equals("js")) return "application/x-javascript"; if (ext.equals("jpg") || ext.equals("jpg")) return "image/jpeg"; if (ext.equals("gif")) return "image/gif"; if (ext.equals("pdf")) return "application/pdf"; if (ext.equals("zip")) return "application/zip"; if (ext.equals("htc")) return "text/x-component"; if (ext.equals("svg")) return "image/svg+xml"; // TODO: add more mime types // TODO: and move to MimeTypeUtil return "application/octet-stream"; // default } /** * Generate response from view of resource * @param request TODO * @param response TODO */ private void getContent(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // INFO: Generate "yanel" document in order to collect information in case something should go wrong or some meta information should be requested org.w3c.dom.Document doc = null; try { doc = getDocument(NAMESPACE, "yanel"); } catch (Exception e) { throw new ServletException(e.getMessage(), e); } Element rootElement = doc.getDocumentElement(); rootElement.setAttribute("servlet-context-real-path", servletContextRealPath); Element requestElement = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, "request")); requestElement.setAttributeNS(NAMESPACE, "uri", request.getRequestURI()); requestElement.setAttributeNS(NAMESPACE, "servlet-path", request.getServletPath()); HttpSession session = request.getSession(true); Element sessionElement = (Element) rootElement.appendChild(doc.createElement("session")); sessionElement.setAttribute("id", session.getId()); Enumeration<?> attrNames = session.getAttributeNames(); if (!attrNames.hasMoreElements()) { Element sessionNoAttributesElement = (Element) sessionElement.appendChild(doc.createElement("no-attributes")); } while (attrNames.hasMoreElements()) { String name = (String)attrNames.nextElement(); String value = session.getAttribute(name).toString(); Element sessionAttributeElement = (Element) sessionElement.appendChild(doc.createElement("attribute")); sessionAttributeElement.setAttribute("name", name); sessionAttributeElement.appendChild(doc.createTextNode(value)); } String usecase = request.getParameter(YANEL_RESOURCE_USECASE); Resource res = null; TrackingInformationV1 trackInfo = null; long lastModified = -1; long size = -1; // START first try View view = null; try { Environment environment = getEnvironment(request, response); res = getResource(request, response); if (res != null) { if (isTrackable(res)) { //log.debug("Do track: " + res.getPath()); trackInfo = new TrackingInformationV1(); ((org.wyona.yanel.core.api.attributes.TrackableV1) res).doTrack(trackInfo); //} else { // log.debug("Resource '" + res.getPath() + "' is not trackable."); } // START introspection generation if (usecase != null && usecase.equals("introspection")) { sendIntrospectionAsResponse(res, doc, rootElement, request, response); return; } // END introspection generation Element resourceElement = getResourceMetaData(res, doc, rootElement); Element viewElement = (Element) resourceElement.appendChild(doc.createElement("view")); if (ResourceAttributeHelper.hasAttributeImplemented(res, "Viewable", "1")) { if (log.isDebugEnabled()) log.debug("Resource is viewable V1"); viewElement.setAttributeNS(NAMESPACE, "version", "1"); appendViewDescriptors(doc, viewElement, ((ViewableV1) res).getViewDescriptors()); String viewId = getViewID(request); try { view = ((ViewableV1) res).getView(request, viewId); } catch (org.wyona.yarep.core.NoSuchNodeException e) { String message = e.getMessage(); log.error(message, e); do404(request, response, doc, message); return; } catch (Exception e) { String message = e.getMessage(); log.error(message, e); Element exceptionElement = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, EXCEPTION_TAG_NAME)); exceptionElement.appendChild(doc.createTextNode(message)); exceptionElement.setAttributeNS(NAMESPACE, "status", "500"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); setYanelOutput(request, response, doc); return; } } else if (ResourceAttributeHelper.hasAttributeImplemented(res, "Viewable", "2")) { if (log.isDebugEnabled()) log.debug("Resource '" + res.getPath() + "' is viewable V2"); viewElement.setAttributeNS(NAMESPACE, "version", "2"); appendViewDescriptors(doc, viewElement, ((ViewableV2) res).getViewDescriptors()); if (!((ViewableV2) res).exists()) { log.warn("ViewableV2 resource '" + res.getPath() + "' does not seem to exist, whereas this resource might not implement exists() properly. Yanel does not generate a 404 response for backwards compatibility reasons, because there are various ViewableV2 resources which do not implement exists() properly. As a workaround one might want to use the exists() method within the getView(String) method and throw a ResourceNotFoundException instead."); //do404(request, response, doc, res.getPath()); //return; } try { size = ((ViewableV2) res).getSize(); Element sizeElement = (Element) resourceElement.appendChild(doc.createElement("size")); sizeElement.appendChild(doc.createTextNode(String.valueOf(size))); } catch(ResourceNotFoundException e) { log.error(e, e); // INFO: Let's be fault tolerant such that a 404 can be handled more gracefully further down } String viewId = getViewID(request); try { String revisionName = request.getParameter(YANEL_RESOURCE_REVISION); // NOTE: Check also if usecase is not roll-back, because roll-back is also using the yanel.resource.revision if (revisionName != null && !isRollBack(request)) { if (ResourceAttributeHelper.hasAttributeImplemented(res, "Versionable", "2")) { view = ((VersionableV2) res).getView(viewId, revisionName); } else { log.warn("Resource '" + res.getPath() + "' has not VersionableV2 implemented, hence we cannot generate view for revision: " + revisionName); view = ((ViewableV2) res).getView(viewId); } } else if (environment.getStateOfView().equals(StateOfView.LIVE) && ResourceAttributeHelper.hasAttributeImplemented(res, "Workflowable", "1") && WorkflowHelper.getWorkflow(res) != null) { // TODO: Instead using the WorkflowHelper the Workflowable interface should have a method to check if the resource actually has a workflow assigned, see http://lists.wyona.org/pipermail/yanel-development/2009-June/003709.html // TODO: Check if resource actually exists (see the exist problem above), because even it doesn't exist, the workflowable interfaces can return something although it doesn't really make sense. For example if a resource type is workflowable, but it has no workflow associated with it, then WorkflowHelper.isLive will nevertheless return true, whereas WorkflowHelper.getLiveView will throw an exception! if (!((ViewableV2) res).exists()) { log.warn("No such ViewableV2 resource: " + res.getPath()); log.warn("TODO: It seems like many ViewableV2 resources are not implementing exists() properly!"); do404(request, response, doc, res.getPath()); return; } WorkflowableV1 workflowable = (WorkflowableV1)res; if (workflowable.isLive()) { view = workflowable.getLiveView(viewId); } else { String message = "The viewable (V2) resource '" + res.getPath() + "' is WorkflowableV1, but has not been published yet."; log.warn(message); // TODO: Make this configurable per resource (or rather workflowable interface) or per realm?! if (displayMostRecentVersion) { // INFO: Because of backwards compatibility the default should display the most recent version log.warn("Instead a live/published version, the most recent version will be displayed!"); view = ((ViewableV2) res).getView(viewId); } else { log.warn("Instead a live/published version, a 404 will be displayed!"); // TODO: Instead a 404 one might want to show a different kind of screen do404(request, response, doc, message); return; } } } else { view = ((ViewableV2) res).getView(viewId); } } catch (org.wyona.yarep.core.NoSuchNodeException e) { String message = e.getMessage(); log.warn(message, e); do404(request, response, doc, message); return; } catch (ResourceNotFoundException e) { String message = e.getMessage(); log.warn(message, e); do404(request, response, doc, message); return; } catch(Exception e) { log.error(e, e); handleException(request, response, e); return; } } else { // NO Viewable interface implemented! String message = res.getClass().getName() + " is not viewable! (" + res.getPath() + ", " + res.getRealm() + ")"; log.error(message); Element noViewElement = (Element) resourceElement.appendChild(doc.createElement("not-viewable")); noViewElement.appendChild(doc.createTextNode(res.getClass().getName() + " is not viewable!")); Element exceptionElement = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, EXCEPTION_TAG_NAME)); exceptionElement.appendChild(doc.createTextNode(message)); exceptionElement.setAttributeNS(NAMESPACE, "status", "501"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_NOT_IMPLEMENTED); setYanelOutput(request, response, doc); return; } if (ResourceAttributeHelper.hasAttributeImplemented(res, "Modifiable", "2")) { lastModified = ((ModifiableV2) res).getLastModified(); Element lastModifiedElement = (Element) resourceElement.appendChild(doc.createElement("last-modified")); lastModifiedElement.appendChild(doc.createTextNode(new Date(lastModified).toString())); } else { Element noLastModifiedElement = (Element) resourceElement.appendChild(doc.createElement("no-last-modified")); } // INFO: Get the revisions, but only in the meta usecase (because of performance reasons) if (request.getParameter(RESOURCE_META_ID_PARAM_NAME) != null) { appendRevisionsAndWorkflow(doc, resourceElement, res, request); } if (ResourceAttributeHelper.hasAttributeImplemented(res, "Translatable", "1")) { TranslatableV1 translatable = ((TranslatableV1) res); Element translationsElement = (Element) resourceElement.appendChild(doc.createElement("translations")); String[] languages = translatable.getLanguages(); for (int i=0; i<languages.length; i++) { Element translationElement = (Element) translationsElement.appendChild(doc.createElement("translation")); translationElement.setAttribute("language", languages[i]); String path = translatable.getTranslation(languages[i]).getPath(); translationElement.setAttribute("path", path); } } if (usecase != null && usecase.equals("checkout")) { if(log.isDebugEnabled()) log.debug("Checkout data ..."); if (ResourceAttributeHelper.hasAttributeImplemented(res, "Versionable", "2")) { // NOTE: The code below will throw an exception if the document is checked out already by another user. String userID = environment.getIdentity().getUsername(); VersionableV2 versionable = (VersionableV2)res; if (versionable.isCheckedOut()) { String checkoutUserID = versionable.getCheckoutUserID(); if (checkoutUserID.equals(userID)) { log.warn("Resource " + res.getPath() + " is already checked out by this user: " + checkoutUserID); } else { if (isClientSupportingNeutron(request)) { String eMessage = "Resource '" + res.getPath() + "' is already checked out by another user: " + checkoutUserID; response.setContentType("application/xml"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); // TODO: Checkout date and break-lock (optional) response.getWriter().print(XMLExceptionV1.getCheckoutException(eMessage, res.getPath(), checkoutUserID, null)); return; } else { throw new Exception("Resource '" + res.getPath() + "' is already checked out by another user: " + checkoutUserID); } } } else { versionable.checkout(userID); } } else { log.warn("Acquire lock has not been implemented yet ...!"); // acquireLock(); } } } else { Element resourceIsNullElement = (Element) rootElement.appendChild(doc.createElement("resource-is-null")); } } catch (org.wyona.yarep.core.NoSuchNodeException e) { String message = e.getMessage(); log.warn(message, e); do404(request, response, doc, message); return; } catch (org.wyona.yanel.core.ResourceNotFoundException e) { String message = e.getMessage(); log.warn(message, e); do404(request, response, doc, message); return; } catch (Exception e) { log.error(e, e); handleException(request, response, e); return; } // END first try String meta = request.getParameter(RESOURCE_META_ID_PARAM_NAME); if (meta != null) { if (meta.length() > 0) { if (meta.equals("annotations")) { log.debug("Remove everything from the page meta document except the annotations"); cleanMetaDoc(doc); appendAnnotations(doc, res); appendTrackingInformation(doc, trackInfo); } else { log.warn("TODO: Stripping everything from page meta document but, '" + meta + "' not supported!"); } } else { log.debug("Show all meta"); appendAnnotations(doc, res); appendTrackingInformation(doc, trackInfo); } response.setStatus(javax.servlet.http.HttpServletResponse.SC_OK); setYanelOutput(request, response, doc); return; } if (view != null) { if (generateResponse(view, res, request, response, -1, doc, size, lastModified, trackInfo) != null) { //log.debug("Response has been generated successfully :-)"); return; } else { log.warn("No response has been generated!"); } } else { String message = "View is null!"; Element exceptionElement = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, EXCEPTION_TAG_NAME)); exceptionElement.appendChild(doc.createTextNode(message)); } response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); setYanelOutput(request, response, doc); return; } /** * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest, HttpServletResponse) */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String transition = request.getParameter(YANEL_RESOURCE_WORKFLOW_TRANSITION); if (transition != null) { executeWorkflowTransition(request, response, request.getParameter(YANEL_RESOURCE_REVISION), transition); return; } String value = request.getParameter(YANEL_RESOURCE_USECASE); if (value != null && value.equals("save")) { log.debug("Save data ..."); save(request, response, false); return; } else if (value != null && value.equals("checkin")) { log.debug("Checkin data ..."); save(request, response, true); log.warn("Release lock has not been implemented yet ..."); // releaseLock(); return; } else { log.info("No parameter " + YANEL_RESOURCE_USECASE + "!"); String contentType = request.getContentType(); // TODO: Check for type (see section 9.2 of APP spec (e.g. draft 16) if (contentType != null && contentType.indexOf("application/atom+xml") >= 0) { InputStream in = intercept(request.getInputStream()); // Create new Atom entry try { String atomEntryUniversalName = "<{http://www.wyona.org/yanel/resource/1.0}atom-entry/>"; Realm realm = yanelInstance.getMap().getRealm(request.getServletPath()); String newEntryPath = yanelInstance.getMap().getPath(realm, request.getServletPath() + "/" + new Date().getTime() + ".xml"); log.debug("Realm and Path of new Atom entry: " + realm + " " + newEntryPath); Resource atomEntryResource = yanelInstance.getResourceManager().getResource(getEnvironment(request, response), realm, newEntryPath, new ResourceTypeRegistry().getResourceTypeDefinition(atomEntryUniversalName), new ResourceTypeIdentifier(atomEntryUniversalName, null)); ((ModifiableV2)atomEntryResource).write(in); byte buffer[] = new byte[8192]; int bytesRead; InputStream resourceIn = ((ModifiableV2)atomEntryResource).getInputStream(); OutputStream responseOut = response.getOutputStream(); while ((bytesRead = resourceIn.read(buffer)) != -1) { responseOut.write(buffer, 0, bytesRead); } resourceIn.close(); //responseOut.close(); // TODO: Fix Location ... response.setHeader("Location", "http://ulysses.wyona.org" + newEntryPath); response.setStatus(javax.servlet.http.HttpServletResponse.SC_CREATED); return; } catch (Exception e) { throw new ServletException(e.getMessage(), e); } } // Enable or disable toolbar yanelUI.switchToolbar(request); getContent(request, response); } } /** * Perform the given transition on the indicated revision. * @param request TODO * @param response TODO * @param revision TODO * @param transitionID Workflow transition ID * @throws ServletException * @throws IOException */ private void executeWorkflowTransition(HttpServletRequest request, HttpServletResponse response, String revision, String transitionID) throws ServletException, IOException { Resource resource = getResource(request, response); if (ResourceAttributeHelper.hasAttributeImplemented(resource, "Workflowable", "1")) { WorkflowableV1 workflowable = (WorkflowableV1)resource; try { String outputFormat = request.getParameter(YANEL_RESOURCE_WORKFLOW_TRANSITION_OUTPUT); StringBuilder sb = null; workflowable.doTransition(transitionID, revision); response.setStatus(javax.servlet.http.HttpServletResponse.SC_OK); if (outputFormat != null && CONTENT_TYPE_XHTML.equals(outputFormat.toLowerCase())) { Workflow workflow = WorkflowHelper.getWorkflow(resource); Transition transition = workflow.getTransition(transitionID); String description = transitionID; try { description = transition.getDescription(getLanguage(request, "en")); } catch(Exception e) { log.error(e, e); } response.setContentType("text/html; charset=" + DEFAULT_ENCODING); sb = new StringBuilder("<html xmlns=\"http://www.w3.org/1999/xhtml\"><head><meta http-equiv=\"refresh\" content=\"3;URL='" + request.getHeader(HTTP_REFERRER) + "'\"></head><body><div style=\"text-align: center; font-family: sans-serif;\"><p>&#160;<br/>&#160;<br/>The workflow transition <strong style=\"background-color: #dff0d8;\">&#160;" + description + "&#160;</strong> has been performed.</p><p>Return to <a href=\"" + request.getHeader(HTTP_REFERRER) + "\">the page</a>.</p></div></body></html>"); } else { log.warn("DEBUG: No output format query string parameter '" + YANEL_RESOURCE_WORKFLOW_TRANSITION_OUTPUT + "' has been specified."); response.setContentType("application/xml; charset=" + DEFAULT_ENCODING); sb = new StringBuilder("<?xml version=\"1.0\"?>"); sb.append(workflowable.getWorkflowIntrospection()); } PrintWriter w = response.getWriter(); w.print(sb); } catch (WorkflowException e) { log.error(e, e); response.setContentType("application/xml; charset=" + DEFAULT_ENCODING); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); PrintWriter w = response.getWriter(); w.print(getWorkflowException(e.getMessage())); return; } } else { log.warn("Resource not workflowable: " + resource.getPath()); } } /** * HTTP PUT implementation. */ @Override protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO: Reuse code doPost resp. share code with doPut String value = request.getParameter(YANEL_RESOURCE_USECASE); if (value != null && value.equals("save")) { log.debug("Save data ..."); save(request, response, false); return; } else if (value != null && value.equals("checkin")) { log.debug("Checkin data ..."); save(request, response, true); log.warn("Release lock has not been implemented yet ...!"); // releaseLock(); return; } else { log.debug("No parameter " + YANEL_RESOURCE_USECASE + "!"); String contentType = request.getContentType(); if (contentType != null && contentType.indexOf("application/atom+xml") >= 0) { InputStream in = intercept(request.getInputStream()); // Overwrite existing atom entry try { String atomEntryUniversalName = "<{http://www.wyona.org/yanel/resource/1.0}atom-entry/>"; Realm realm = yanelInstance.getMap().getRealm(request.getServletPath()); String entryPath = yanelInstance.getMap().getPath(realm, request.getServletPath()); log.debug("Realm and Path of new Atom entry: " + realm + " " + entryPath); Resource atomEntryResource = yanelInstance.getResourceManager().getResource(getEnvironment(request, response), realm, entryPath, new ResourceTypeRegistry().getResourceTypeDefinition(atomEntryUniversalName), new ResourceTypeIdentifier(atomEntryUniversalName, null)); // TODO: There seems to be a problem ... ((ModifiableV2)atomEntryResource).write(in); // NOTE: This method does not update updated date /* OutputStream out = ((ModifiableV2)atomEntry).getOutputStream(entryPath); byte buffer[] = new byte[8192]; int bytesRead; while ((bytesRead = in.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); } */ log.info("Atom entry has been saved: " + entryPath); response.setStatus(javax.servlet.http.HttpServletResponse.SC_OK); return; } catch (Exception e) { throw new ServletException(e.getMessage(), e); } } else { Resource resource = getResource(request, response); log.debug("Client (" + request.getHeader("User-Agent") + ") requests to save a resource: " + resource.getRealm() + ", " + resource.getPath()); // TODO: Check whether resource exists! save(request, response, false); return; } } } /** * @see javax.servlet.http.HttpServlet#doDelete(HttpServletRequest, HttpServletResponse); */ @Override protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO: generateResponseFromResourceView(request, response, javax.servlet.http.HttpServletResponse.SC_OK, res); try { Resource res = getResource(request, response); if (ResourceAttributeHelper.hasAttributeImplemented(res, "Modifiable", "2")) { if (((ModifiableV2) res).delete()) { // TODO: Also delete resource config! What about access policies?! log.debug("Resource '" + res + "' has been deleted via ModifiableV2 interface."); setResourceDeletedResponse(res, response); return; } else { log.warn("Deletable (or rather ModifiableV2) resource '" + res + "' could not be deleted!"); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } } else if (ResourceAttributeHelper.hasAttributeImplemented(res, "Deletable", "1")) { // TODO: Finish implementation, set resource input ((DeletableV1) res).delete(null); log.debug("Resource '" + res + "' has been deleted via DeletableV1 interface."); setResourceDeletedResponse(res, response); return; } else { log.error("Resource '" + res + "' has neither interface ModifiableV2 nor DeletableV1 implemented." ); response.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED); return; // QUESTION: According to the spec http://docs.oracle.com/javaee/1.4/api/javax/servlet/http/HttpServlet.html#doDelete%28javax.servlet.http.HttpServletRequest,%20javax.servlet.http.HttpServletResponse%29 one should rather throw a ServletException, right? } } catch (Exception e) { throw new ServletException("Could not delete resource with URL <" + request.getRequestURL() + ">: " + e.getMessage(), e); } } /** * */ private void setResourceDeletedResponse(Resource res, HttpServletResponse response) throws Exception { response.setStatus(HttpServletResponse.SC_OK); response.setContentType("text/html" + "; charset=" + "UTF-8"); String backToRealm = org.wyona.yanel.core.util.PathUtil.backToRealm(res.getPath()); StringBuilder sb = new StringBuilder("<html xmlns=\"http://www.w3.org/1999/xhtml\"><body>Page has been deleted! <a href=\"" + backToRealm + res.getPath().substring(1) +"\">Check</a> or return to <a href=\"" + backToRealm + "\">Homepage</a>.</body></html>"); PrintWriter w = response.getWriter(); w.print(sb); } /** * Resolve resource for a specific request */ private Resource getResource(HttpServletRequest request, HttpServletResponse response) throws ServletException { try { Realm realm = map.getRealm(request.getServletPath()); String path = map.getPath(realm, request.getServletPath()); HttpRequest httpRequest = (HttpRequest)request; HttpResponse httpResponse = new HttpResponse(response); Resource res = yanelInstance.getResourceManager().getResource(getEnvironment(httpRequest, httpResponse), realm, path); return res; } catch (Exception e) { log.error(e, e); throw new ServletException("Could not get resource for request <" + request.getServletPath() + ">: " + e.getMessage(), e); } } /** * Get environment containing identity , client request, etc. */ private Environment getEnvironment(HttpServletRequest request, HttpServletResponse response) throws ServletException { Identity identity; try { Realm realm = map.getRealm(request.getServletPath()); identity = getIdentityFromRequest(request, realm); String stateOfView = StateOfView.AUTHORING; if (yanelUI.isToolbarEnabled(request)) { // TODO: Is this the only criteria? stateOfView = StateOfView.AUTHORING; } else { stateOfView = StateOfView.LIVE; } //log.debug("State of view: " + stateOfView); Environment environment = new Environment(request, response, identity, stateOfView, null); if (yanelUI.isToolbarEnabled(request)) { // INFO: Please note that isToolbarEnabled() also checks whether toolbar is suppressed... environment.setToolbarState(ToolbarState.ON); } else if (yanelUI.isToolbarSuppressed(request)) { environment.setToolbarState(ToolbarState.SUPPRESSED); } else { environment.setToolbarState(ToolbarState.OFF); } return environment; } catch (Exception e) { throw new ServletException(e.getMessage(), e); } } /** * Save data * @param request TODO * @param response TODO * @param doCheckin TODO */ private void save(HttpServletRequest request, HttpServletResponse response, boolean doCheckin) throws ServletException, IOException { log.debug("Save data ..."); Resource resource = getResource(request, response); /* NOTE: Commented because the current default repo implementation does not support versioning yet. if (ResourceAttributeHelper.hasAttributeImplemented(resource, "Versionable", "2")) { try { // check the resource state: Identity identity = getIdentity(request); String userID = identity.getUser().getID(); VersionableV2 versionable = (VersionableV2)resource; if (versionable.isCheckedOut()) { String checkoutUserID = versionable.getCheckoutUserID(); if (!checkoutUserID.equals(userID)) { throw new Exception("Resource is checked out by another user: " + checkoutUserID); } } else { throw new Exception("Resource is not checked out."); } } catch (Exception e) { throw new ServletException(e.getMessage(), e); } } */ InputStream in = request.getInputStream(); // TODO: Should be delegated to resource type, e.g. <{http://...}xml/>! // Check on well-formedness ... String contentType = request.getContentType(); log.debug("Content-Type: " + contentType); if (contentType != null && (contentType.indexOf("application/xml") >= 0 || contentType.indexOf("application/xhtml+xml") >= 0)) { try { in = XMLHelper.isWellFormed(in); } catch(Exception e) { log.error(e, e); response.setContentType("application/xml; charset=" + DEFAULT_ENCODING); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); PrintWriter w = response.getWriter(); w.print(XMLExceptionV1.getDefaultException(XMLExceptionV1.DATA_NOT_WELL_FORMED, e.getMessage())); return; } } else { log.info("No well-formedness check required for content type: " + contentType); } // IMPORTANT TODO: Use ModifiableV2.write(InputStream in) such that resource can modify data during saving resp. check if getOutputStream is equals null and then use write .... OutputStream out = null; Resource res = getResource(request, response); if (ResourceAttributeHelper.hasAttributeImplemented(res, "Modifiable", "1")) { out = ((ModifiableV1) res).getOutputStream(new Path(request.getServletPath())); write(in, out, request, response); } else if (ResourceAttributeHelper.hasAttributeImplemented(res, "Modifiable", "2")) { try { out = ((ModifiableV2) res).getOutputStream(); if (out != null) { write(in, out, request, response); } else { log.warn("INFO: ModifiableV2.getOutputStream() returned null, hence fallback to ModifiableV2.write(InputStream)"); ((ModifiableV2) res).write(in); generateResponseFromResourceView(request, response, javax.servlet.http.HttpServletResponse.SC_OK, res); } } catch (Exception e) { throw new ServletException(e.getMessage(), e); } } else { String message = res.getClass().getName() + " is not modifiable (neither V1 nor V2)!"; log.warn(message); // TODO: Differentiate between Neutron based and other clients ... (Use method isClientSupportingNeutron()) response.setContentType("application/xml; charset=" + DEFAULT_ENCODING); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); PrintWriter w = response.getWriter(); // TODO: This is not really a 'checkin' problem, but rather a general 'save-data' problem, but the Neutron spec does not support such a type: http://neutron.wyona.org/draft-neutron-protocol-v0.html#rfc.section.8 w.print(XMLExceptionV1.getDefaultException(XMLExceptionV1.CHECKIN, message)); } if (doCheckin) { if (ResourceAttributeHelper.hasAttributeImplemented(resource, "Versionable", "2")) { VersionableV2 versionable = (VersionableV2)resource; try { versionable.checkin("updated"); } catch (Exception e) { throw new ServletException("Could not check in resource <" + resource.getPath() + ">: " + e.getMessage(), e); } } } } /** * Check authorization and if not authorized then authenticate. Return null if authorization granted, otherwise return 401 and appropriate response such that client can provide credentials for authentication * * @return Null if access is granted and an authentication response if access is denied */ private HttpServletResponse doAccessControl(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // INFO: Get identity, realm, path Identity identity; Realm realm; String pathWithoutQS; try { realm = map.getRealm(request.getServletPath()); /* TBD: Check whether BASIC might be used and if so, then maybe handle things differently (also see https://github.com/wyona/yanel/issues/41) String authorizationHeader = request.getHeader("Authorization"); if (authorizationHeader != null) { if (authorizationHeader.toUpperCase().startsWith("BASIC")) { */ identity = getIdentityFromRequest(request, realm); //log.warn("DEBUG: Identity retrieved from request (for realm '" + realm.getID() + "'): " + identity); pathWithoutQS = map.getPath(realm, request.getServletPath()); } catch (Exception e) { throw new ServletException(e.getMessage(), e); } // INFO: Try Auto-Login if (identity == null || (identity != null && identity.isWorld())) { //log.debug("Not logged in yet, hence try auto login..."); try { if (AutoLogin.tryAutoLogin(request, response, realm)) { log.debug("Auto login successful, hence set identity inside session..."); String username = AutoLogin.getUsername(request); if (username != null) { User user = realm.getIdentityManager().getUserManager().getUser(username); setIdentity(new Identity(user, user.getEmail()), request.getSession(), realm); } else { log.error("Auto login successful, but no username available!"); } } else { //log.debug("No auto login."); } } catch(Exception e) { log.error(e, e); } } // INFO: Check Authorization boolean authorized = false; Usecase usecase = getUsecase(request); try { if (log.isDebugEnabled()) log.debug("Check authorization: realm: " + realm + ", path: " + pathWithoutQS + ", identity: " + identity + ", Usecase: " + usecase.getName()); authorized = realm.getPolicyManager().authorize(pathWithoutQS, request.getQueryString(), identity, usecase); if (log.isDebugEnabled()) log.debug("Check authorization result: " + authorized); } catch (Exception e) { throw new ServletException(e.getMessage(), e); } if (authorized) { if (identity != null && identity.getUsername() != null) { if (identity.getUsername() != null) { if(log.isDebugEnabled()) log.debug("Access for user '" + identity.getUsername() + "' granted: " + getRequestURLQS(request, null, false)); //response.setHeader("Cache-control", "no-cache"); // INFO: Do not allow browsers to cache content for users which are signed in, but we currently do not use this because of performance reasons. One can set the resource property 'yanel:no-cache' on specific pages though in order to prevent caching of protected pages. Related to this see how a timestamp is appened during logout (see doLogout()) } else { if(log.isDebugEnabled()) log.debug("Access for anonymous user (aka WORLD) granted: " + getRequestURLQS(request, null, false)); } } else { if(log.isDebugEnabled()) log.debug("Access for anonymous user (aka WORLD) granted: " + getRequestURLQS(request, null, false)); } return null; // INFO: Return null in order to indicate that access is granted } else { log.warn("Access denied: " + getRequestURLQS(request, null, false) + " (Path of request: " + pathWithoutQS + "; Identity: " + identity + "; Usecase: " + usecase + ")"); // TODO: Implement HTTP BASIC/DIGEST response (see above) // INFO: If request is not via SSL and SSL is configured, then redirect to SSL connection. if(!request.isSecure()) { if(sslPort != null) { log.info("Redirect to SSL (Port: " + sslPort + ") ..."); try { URL url = new URL(getRequestURLQS(request, null, false).toString()); url = new URL("https", url.getHost(), new Integer(sslPort).intValue(), url.getFile()); if (realm.isProxySet()) { if (realm.getProxySSLPort() >= 0) { log.debug("Use configured port: " + realm.getProxySSLPort()); url = new URL(url.getProtocol(), url.getHost(), new Integer(realm.getProxySSLPort()).intValue(), url.getFile()); } else { log.debug("Use default port: " + url.getDefaultPort()); // NOTE: getDefaultPort depends on the Protocol (e.g. https is 443) url = new URL(url.getProtocol(), url.getHost(), url.getDefaultPort(), url.getFile()); } } log.info("Redirect to SSL: " + url); response.setHeader("Location", url.toString()); // TODO: "Yulup Editor" has a bug re TEMPORARY_REDIRECT //response.setStatus(javax.servlet.http.HttpServletResponse.SC_TEMPORARY_REDIRECT); response.setStatus(javax.servlet.http.HttpServletResponse.SC_MOVED_PERMANENTLY); return response; } catch (Exception e) { log.error(e.getMessage(), e); } } else { log.warn("SSL does not seem to be configured!"); } } else { log.info("This connection is already via SSL."); } if (doAuthenticate(request, response) != null) { log.info("Access denied and not authenticated correctly yet, hence return response of web authenticator..."); /* NOTE: Such a response can have different reasons: - Either no credentials provided yet and web authenticator is generating a response to fetch credentials - Or authentication failed and web authenticator is resending response to fetch again credentials"); - Or authentication was successful and web authenticator sends a redirect */ // TODO: Check "would be mime type", etc.: if (logAccessIsApplicable(view.getMimeType())) { if(logAccessEnabled) { // INFO: Although authorization has been denied and user first needs to authenticate, let's log the request anyway if (usecase != null && usecase.getName().equals("introspection")) { log.debug("Ignore introspection request: " + getRequestURLQS(request, null, false)); } else { log.info("Access denied and authentication not completed yet, hence let's log request '" + getRequestURLQS(request, null, false) + "'"); doLogAccess(request, response, HttpServletResponse.SC_UNAUTHORIZED, null, null); } } //log.debug("Returned status code: " + response.getStatus()); // INFO: Only supported by servlet api 3.0 and higher return response; } else { try { //log.debug("Authentication was successful for user: " + getIdentity(request, map).getUsername()); } catch (Exception e) { log.error(e.getMessage(), e); } URL url = new URL(getRequestURLQS(request, null, false).toString()); if (sslPort != null) { url = new URL("https", url.getHost(), new Integer(sslPort).intValue(), url.getFile()); } // INFO: Hash fragment is set by login screen, e.g. src/resources/login/htdocs/login-screen.xsl String hashFragment = request.getParameter("yanel.login.hash.fragment"); if (hashFragment != null && hashFragment.length() > 0) { log.debug("Hash fragment: " + hashFragment); url = new URL(url.getProtocol(), url.getHost(), url.getPort(), url.getFile() + "#" + hashFragment); } log.warn("DEBUG: Redirect to original request: " + url); //response.sendRedirect(url.toString()); // 302 // TODO: "Yulup Editor" has a bug re TEMPORARY_REDIRECT (or is the problem that the load balancer is rewritting 302 reponses?!) response.setHeader("Location", url.toString()); response.setStatus(javax.servlet.http.HttpServletResponse.SC_MOVED_PERMANENTLY); // 301 //response.setStatus(javax.servlet.http.HttpServletResponse.SC_TEMPORARY_REDIRECT); // 302 return response; } } } /** * Patch request with proxy settings re realm configuration * @param request Request which Yanel received * @param addQS Additonal query string * @param xml Flag whether returned URL should be XML compatible, e.g. re ampersands * @return URL which was received by reverse proxy, e.g. http://www.yanel.org/en/download/index.html instead http://127.0.0.1:8080/yanel/yanel-website/en/download/index.html */ private String getRequestURLQS(HttpServletRequest request, String addQS, boolean xml) { try { return Utils.getRequestURLQS(map.getRealm(request.getServletPath()), request, addQS, xml); } catch(Exception e) { log.error(e.getMessage(), e); return null; } } /** * WebDAV PROPFIND implementation. * * Also see https://svn.apache.org/repos/asf/tomcat/container/branches/tc5.0.x/catalina/src/share/org/apache/catalina/servlets/WebdavServlet.java * Also maybe interesting http://sourceforge.net/projects/openharmonise */ private void doPropfind(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Resource resource = getResource(request, response); //Node node = resource.getRealm().getSitetree().getNode(resource.getPath()); Node node = sitetree.getNode(resource.getRealm(),resource.getPath()); String depth = request.getHeader("Depth"); StringBuffer sb = new StringBuffer("<?xml version=\"1.0\"?>"); sb.append("<multistatus xmlns=\"DAV:\">"); if (depth.equals("0")) { if (node.isCollection()) { sb.append(" <response>"); sb.append(" <href>"+request.getRequestURI()+"</href>"); sb.append(" <propstat>"); sb.append(" <prop>"); sb.append(" <resourcetype><collection/></resourcetype>"); sb.append(" <getcontenttype>httpd/unix-directory</getcontenttype>"); sb.append(" </prop>"); sb.append(" <status>HTTP/1.1 200 OK</status>"); sb.append(" </propstat>"); sb.append(" </response>"); } else if (node.isResource()) { sb.append(" <response>"); sb.append(" <href>"+request.getRequestURI()+"</href>"); sb.append(" <propstat>"); sb.append(" <prop>"); sb.append(" <resourcetype/>"); // TODO: Set mime type of node! sb.append(" <getcontenttype>application/octet-stream</getcontenttype>"); // TODO: Set content length and last modified! sb.append(" <getcontentlength>0</getcontentlength>"); sb.append(" <getlastmodified>1969.02.16</getlastmodified>"); // See http://www.webdav.org/specs/rfc2518.html#PROPERTY_source, http://wiki.zope.org/HiperDom/RoundtripEditingDiscussion sb.append(" <source>\n"); sb.append(" <link>\n"); sb.append(" <src>" + request.getRequestURI() + "</src>\n"); sb.append(" <dst>" + request.getRequestURI() + "?yanel.resource.modifiable.source</dst>\n"); sb.append(" </link>\n"); sb.append(" </source>\n"); sb.append(" </prop>"); sb.append(" <status>HTTP/1.1 200 OK</status>"); sb.append(" </propstat>"); sb.append(" </response>"); } else { log.error("Neither collection nor resource!"); } } else if (depth.equals("1")) { // TODO: Shouldn't one check with isCollection() first?! Node[] children = node.getChildren(); if (children != null) { for (int i = 0; i < children.length; i++) { if (children[i].isCollection()) { sb.append(" <response>\n"); sb.append(" <href>" + request.getRequestURI() + "/" + children[i].getName() + "/</href>\n"); sb.append(" <propstat>\n"); sb.append(" <prop>\n"); sb.append(" <displayname>" + children[i].getName() + "</displayname>\n"); sb.append(" <resourcetype><collection/></resourcetype>\n"); sb.append(" <getcontenttype>httpd/unix-directory</getcontenttype>\n"); sb.append(" </prop>\n"); sb.append(" <status>HTTP/1.1 200 OK</status>\n"); sb.append(" </propstat>\n"); sb.append(" </response>\n"); } else if(children[i].isResource()) { sb.append(" <response>\n"); sb.append(" <href>" + request.getRequestURI() + "/" + children[i].getName() + "?yanel.webdav=propfind1</href>\n"); sb.append(" <propstat>\n"); sb.append(" <prop>\n"); sb.append(" <displayname>" + children[i].getName() + "</displayname>\n"); sb.append(" <resourcetype/>\n"); // TODO: Set mime type of node! sb.append(" <getcontenttype>application/octet-stream</getcontenttype>\n"); // TODO: Set content length and last modified! sb.append(" <getcontentlength>0</getcontentlength>"); sb.append(" <getlastmodified>1969.02.16</getlastmodified>"); // See http://www.webdav.org/specs/rfc2518.html#PROPERTY_source, http://wiki.zope.org/HiperDom/RoundtripEditingDiscussion sb.append(" <source>\n"); sb.append(" <link>\n"); sb.append(" <src>" + request.getRequestURI() + "/" + children[i].getName() + "</src>\n"); sb.append(" <dst>" + request.getRequestURI() + "/" + children[i].getName() + "?yanel.resource.modifiable.source</dst>\n"); sb.append(" </link>\n"); sb.append(" </source>\n"); sb.append(" </prop>\n"); sb.append(" <status>HTTP/1.1 200 OK</status>\n"); sb.append(" </propstat>\n"); sb.append(" </response>\n"); } else { log.error("Neither collection nor resource: " + children[i].getPath()); } } } else { log.warn("No children!"); } } else if (depth.equals("infinity")) { log.warn("TODO: List children and their children and their children ..."); } else { log.error("No such depth: " + depth); } sb.append("</multistatus>"); //response.setStatus(javax.servlet.http.HttpServletResponse.SC_MULTI_STATUS); response.setStatus(207, "Multi-Status"); PrintWriter w = response.getWriter(); w.print(sb); } /** * HTTP OPTIONS implementation. */ @Override protected void doOptions(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setHeader("DAV", "1"); // TODO: Is there anything else to do?! } /** * Authentication * @return null when authentication successful or has already been authenticated, otherwise return response generated by web authenticator */ private HttpServletResponse doAuthenticate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { // TODO/TBD: In the case of HTTP-BASIC/DIGEST one needs to check authentication with every request // TODO: enhance API with flag, e.g. session-based="true/false" // WARNING: One needs to separate doAuthenticate from the login screen generation! //if (getIdentity(request) != null) return null; WebAuthenticator wa = map.getRealm(request.getServletPath()).getWebAuthenticator(); return wa.doAuthenticate(request, response, map, reservedPrefix, xsltLoginScreenDefault, servletContextRealPath, sslPort); } catch (Exception e) { log.error(e.getMessage(), e); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return response; } } /** * Escapes all reserved xml characters (&amp; &lt; &gt; &apos; &quot;) in a string. * @param s input string * @return string with escaped characters */ public static String encodeXML(String s) { s = s.replaceAll("&", "&amp;"); s = s.replaceAll("<", "&lt;"); s = s.replaceAll(">", "&gt;"); s = s.replaceAll("'", "&apos;"); s = s.replaceAll("\"", "&quot;"); return s; } /** * Do CAS logout * @param request Request containing CAS ticket information, e.g. <samlp:LogoutRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" ID="LR-35-Cb0GJEEVItSWd5U2J4SEuzhvJ5uOORPhvG6" Version="2.0" IssueInstant="2014-05-12T10:12:10Z"><saml:NameID xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">@NOT_USED@</saml:NameID><samlp:SessionIndex>ST-37-rAzNSduFbOh7hJyzuNjW-cas01.example.org</samlp:SessionIndex></samlp:LogoutRequest> * @param response TODO * @return true when logout was successful and false otherwise */ private boolean doCASLogout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String body = request.getParameter(CAS_LOGOUT_REQUEST_PARAM_NAME); log.debug("Logout request content: " + body); try { Document doc = XMLHelper.readDocument(new java.io.ByteArrayInputStream(body.getBytes()), false); String id = doc.getDocumentElement().getAttribute("ID"); log.warn("DEBUG: CAS ID: " + id); Element[] sessionIndexEls = XMLHelper.getChildElements(doc.getDocumentElement(), "SessionIndex", "urn:oasis:names:tc:SAML:2.0:protocol"); if (sessionIndexEls != null && sessionIndexEls.length == 1) { String sessionIndex = sessionIndexEls[0].getFirstChild().getNodeValue(); log.warn("DEBUG: CAS SessionIndex: " + sessionIndex); HttpSession[] activeSessions = org.wyona.yanel.servlet.SessionCounter.getActiveSessions(); for (int i = 0; i < activeSessions.length; i++) { //log.debug("Yanel session ID: " + activeSessions[i].getId()); CASTicketsMap casTicketsMap = (CASTicketsMap) activeSessions[i].getAttribute(org.wyona.yanel.servlet.security.impl.CASWebAuthenticatorImpl.CAS_TICKETS_SESSION_NAME); if (casTicketsMap != null && casTicketsMap.containsValue(sessionIndex)) { log.warn("DEBUG: Session '" + activeSessions[i].getId() + "' contains CAS ticket which matches with SessionIndex: " + sessionIndex); removeIdentitiesAndCASTickets(activeSessions[i], casTicketsMap.getRealmId(sessionIndex)); // TODO: Notify other cluster nodes! return true; } else { //log.debug("Session '" + activeSessions[i].getId() + "' has either no CAS tickets or does not does match with SessionIndex."); } } log.warn("SessionIndex '" + sessionIndex + "' did no match any session."); return false; } else { log.error("No CAS SessionIndex element!"); return false; } } catch(Exception e) { log.error(e, e); return false; } } /** * Remove identities and CAS tickets from session * @param session Session containing identities and CAS tickets * @param realmId Realm ID associated with CAS ticket */ private void removeIdentitiesAndCASTickets(HttpSession session, String realmId) { IdentityMap identityMap = (IdentityMap)session.getAttribute(IDENTITY_MAP_KEY); if (identityMap != null) { log.warn("DEBUG: Remove identity associated with realm '" + realmId + "' from session '" + session.getId() + "' ..."); identityMap.remove(realmId); } else { log.warn("No identity map!"); } CASTicketsMap casTicketsMap = (CASTicketsMap)session.getAttribute(org.wyona.yanel.servlet.security.impl.CASWebAuthenticatorImpl.CAS_TICKETS_SESSION_NAME); if (casTicketsMap != null) { log.warn("DEBUG: Remove CAS ticket associated with realm '" + realmId + "' from session '" + session.getId() + "' ..."); casTicketsMap.remove(realmId); } else { log.warn("No CAS tickets map!"); } String casProxyTicket = (String)session.getAttribute(org.wyona.yanel.servlet.security.impl.CASWebAuthenticatorImpl.CAS_PROXY_TICKET_SESSION_NAME); if (casProxyTicket != null) { log.warn("DEBUG: Remove CAS proxy ticket associated with realm '" + realmId + "' from session '" + session.getId() + "' ..."); session.removeAttribute(org.wyona.yanel.servlet.security.impl.CASWebAuthenticatorImpl.CAS_PROXY_TICKET_SESSION_NAME); } else { log.warn("No CAS proxy ticket map!"); } } /** * Do logout * @param request TODO * @param response TODO * @return true if logout was successful (and set a "Redirect response" for a regular logout and a "Neutron response" if auth scheme is Neutron) */ private boolean doLogout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { if (yanelUI.isToolbarEnabled(request)) { // TODO: Check if WORLD has access to the toolbar //if (getRealm().getPolicyManager().authorize(path, new Identity(), new Usecase(TOOLBAR_USECASE))) { yanelUI.disableToolbar(request); //} } WebAuthenticator wa = map.getRealm(request.getServletPath()).getWebAuthenticator(); boolean successfulLogout = wa.doLogout(request, response, map); //int status = response.getStatus(); // INFO: This only works with servlet spec 3.0 (also see http://tomcat.apache.org/whichversion.html) int status = 301; TrackingInformationV1 trackInfo = null; Resource res = null; doLogAccess(request, response, status, res, trackInfo); if (successfulLogout) { // TODO: Add logout to org.wyona.security.core.UserHistory } return successfulLogout; } catch (Exception e) { log.error(e, e); throw new ServletException(e.getMessage(), e); } } /** * Do create a new resource */ private HttpServletResponse doCreate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.error("Not implemented yet!"); return null; } /** * Patches the mimetype of the Content-Type response field because * Microsoft Internet Explorer does not understand application/xhtml+xml * See http://en.wikipedia.org/wiki/Criticisms_of_Internet_Explorer#XHTML * @param mimeType Preferred mime type * @param request Browser request containing Accept information * @return mime type which should be used */ static public String patchMimeType(String mimeType, HttpServletRequest request) throws ServletException, IOException { if (mimeType != null) { String httpAcceptMediaTypes = request.getHeader("Accept"); if (mimeType.equals("application/xhtml+xml") && httpAcceptMediaTypes != null && httpAcceptMediaTypes.indexOf("application/xhtml+xml") < 0) { log.info("Patch contentType with text/html because client (" + request.getHeader("User-Agent") + ") does not seem to understand application/xhtml+xml"); return "text/html"; } else if (mimeType.equals("text/html")) { log.info("Mime type was already set to text/html for request: " + request.getServletPath()); } } else { log.warn("No mime type returned for request: " + request.getServletPath()); } return mimeType; } /** * Intercept InputStream and log content ... */ private InputStream intercept(InputStream in) throws IOException { java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(); byte[] buf = new byte[8192]; int bytesR; while ((bytesR = in.read(buf)) != -1) { baos.write(buf, 0, bytesR); } // Buffer within memory (TODO: Maybe replace with File-buffering ...) // http://www-128.ibm.com/developerworks/java/library/j-io1/ byte[] memBuffer = baos.toByteArray(); log.debug("InputStream: " + baos); return new java.io.ByteArrayInputStream(memBuffer); } /** * Generate a "Yanel" response (page information, 404, internal server error, ...) */ private void setYanelOutput(HttpServletRequest request, HttpServletResponse response, Document doc) throws ServletException { Resource resource = getResource(request, response); String path = resource.getPath(); String backToRealm = org.wyona.yanel.core.util.PathUtil.backToRealm(path); try { String yanelFormat = request.getParameter("yanel.resource.meta.format"); if(yanelFormat != null) { if (yanelFormat.equals("xml")) { response.setContentType("application/xml; charset=" + DEFAULT_ENCODING); XMLHelper.writeDocument(doc, response.getOutputStream()); } else if (yanelFormat.equals("json")) { log.error("TODO: JSON format not implemented yet!"); } else { log.error("No such format '" + yanelFormat + "' supported!"); } } else { String mimeType = patchMimeType("application/xhtml+xml", request); // TODO: doLogAccess response.setContentType(mimeType + "; charset=" + DEFAULT_ENCODING); // create identity transformer which serves as a dom-to-sax transformer TransformerIdentityImpl transformer = new TransformerIdentityImpl(); // INFO: Create xslt transformer: SAXTransformerFactory saxTransformerFactory = (SAXTransformerFactory)SAXTransformerFactory.newInstance(); TransformerHandler xsltTransformer = saxTransformerFactory.newTransformerHandler(new StreamSource(getXsltInfoAndException(resource))); xsltTransformer.getTransformer().setParameter("yanel.back2realm", backToRealm); xsltTransformer.getTransformer().setParameter("yanel.reservedPrefix", reservedPrefix); // create i18n transformer: I18nTransformer2 i18nTransformer = new I18nTransformer2("global", getLanguage(request, yanelInstance.getMap().getRealm(request.getServletPath()).getDefaultLanguage()), yanelInstance.getMap().getRealm(request.getServletPath()).getDefaultLanguage()); CatalogResolver catalogResolver = new CatalogResolver(); i18nTransformer.setEntityResolver(new CatalogResolver()); // create serializer: Serializer serializer = SerializerFactory.getSerializer(SerializerFactory.XHTML_STRICT); // chain everything together (create a pipeline): xsltTransformer.setResult(new SAXResult(i18nTransformer)); i18nTransformer.setResult(new SAXResult(serializer.asContentHandler())); serializer.setOutputStream(response.getOutputStream()); // execute pipeline: transformer.transform(new DOMSource(doc), new SAXResult(xsltTransformer)); } } catch (Exception e) { throw new ServletException(e.getMessage(), e); } } /** * Get XSLT file to render meta information and exception screen */ private File getXsltInfoAndException(Resource resource) { File realmDir = new File(resource.getRealm().getConfigFile().getParent()); File customXslt = org.wyona.commons.io.FileUtil.file(realmDir.getAbsolutePath(), "src" + File.separator + "webapp" + File.separator + defaultXsltInfoAndException); if (customXslt.isFile()) { return customXslt; } else { return org.wyona.commons.io.FileUtil.file(servletContextRealPath, defaultXsltInfoAndException); } } /** * Get language with the following priorization: 1) yanel.meta.language query string parameter, 2) Accept-Language header, 3) Fallback language * @param fallbackLanguage Fallback when neither query string parameter nor Accept-Language header exists */ public static String getLanguage(HttpServletRequest request, String fallbackLanguage) throws Exception { // TODO: Shouldn't this be replaced by Resource.getRequestedLanguage() or Resource.getContentLanguage() ?! String language = request.getParameter("yanel.meta.language"); if (language == null) { language = request.getHeader("Accept-Language"); if (language != null) { int commaIndex = language.indexOf(","); if (commaIndex > 0) { language = language.substring(0, commaIndex); } int dashIndex = language.indexOf("-"); if (dashIndex > 0) { language = language.substring(0, dashIndex); } } } if(language != null && language.length() > 0) { return language; } return fallbackLanguage; } /** * Write to output stream of modifiable resource */ private void write(InputStream in, OutputStream out, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (out != null) { log.debug("Content-Type: " + request.getContentType()); // TODO: Compare mime-type from response with mime-type of resource //if (contentType.equals("text/xml")) { ... } byte[] buffer = new byte[8192]; int bytesRead; while ((bytesRead = in.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); } out.flush(); out.close(); StringBuffer sb = new StringBuffer(); sb.append("<?xml version=\"1.0\"?>"); sb.append("<html>"); sb.append("<body>"); sb.append("<p>Data has been saved ...</p>"); sb.append("</body>"); sb.append("</html>"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_OK); response.setContentType("application/xhtml+xml; charset=" + DEFAULT_ENCODING); PrintWriter w = response.getWriter(); w.print(sb); log.info("Data has been saved ..."); return; } else { log.error("OutputStream is null!"); StringBuffer sb = new StringBuffer(); sb.append("<?xml version=\"1.0\"?>"); sb.append("<html>"); sb.append("<body>"); sb.append("<p>Exception: OutputStream is null!</p>"); sb.append("</body>"); sb.append("</html>"); PrintWriter w = response.getWriter(); w.print(sb); response.setContentType("application/xhtml+xml; charset=" + DEFAULT_ENCODING); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } } /** * @deprecated Use {@link #getIdentity(HttpSession, String)} instead * Get the identity from the HTTP session (associated with the given request) for a specific realm * @param session HTTP session of client * @param realm Realm * @return Identity if one exist, or otherwise null */ public static Identity getIdentity(HttpSession session, Realm realm) throws Exception { return getIdentity(session, realm.getID()); } /** * Get the identity from the HTTP session (associated with the given request) for a specific realm * @param session HTTP session of client * @param realmID Realm ID * @return Identity if one exist, or otherwise null */ public static Identity getIdentity(HttpSession session, String realmID) throws Exception { //log.debug("Get identity from session for realm '" + realmID + "'."); if (session != null) { IdentityMap identityMap = (IdentityMap)session.getAttribute(IDENTITY_MAP_KEY); if (identityMap != null) { Identity identity = (Identity)identityMap.get(realmID); if (identity != null && !identity.isWorld()) { return identity; } else { log.debug("No identity yet for realm '" + realmID + "'."); if (identity != null && identity.isWorld()) { log.debug("Identity is set to world."); } else { log.debug("No identity set at all."); } } } else { log.debug("No identity map yet."); } } else { log.debug("No session yet."); } return null; } /** * Attach the identity to the HTTP session for a specific realm (associated with the given request) * @param session HTTP session of client * @param realm Realm */ public static void setIdentity(Identity identity, HttpSession session, Realm realm) throws Exception { if (session != null) { IdentityMap identityMap = (IdentityMap)session.getAttribute(IDENTITY_MAP_KEY); if (identityMap == null) { identityMap = new IdentityMap(); session.setAttribute(IDENTITY_MAP_KEY, identityMap); } //log.debug("Firstname: " + identity.getFirstname()); identityMap.put(realm.getID(), identity); // INFO: Please note that the constructor Identity(User, String) is resolving group IDs (including parent group IDs) and hence these are "attached" to the session in order to improve performance during authorization checks } else { log.warn("Session is null!"); } } /** * Get the identity from the given request/session (for a specific realm) or via the 'Authorization' HTTP header in the case of BASIC or DIGEST * @param request Client/Servlet request * @param realm Realm * @return Identity if one exist, or otherwise an empty identity (which is considered to be WORLD) */ private Identity getIdentityFromRequest(HttpServletRequest request, Realm realm) throws Exception { // INFO: Please note that the identity normally gets set inside a WebAuthenticator implementation //log.debug("Get identity for request '" + request.getServletPath() + "'."); Identity identity = getIdentity(request.getSession(false), realm.getID()); if (identity != null) { // INFO: Please note that the WORLD identity (or rather an empty identity) is not added to the session (please see further down) //log.debug("Identity from session: " + identity); return identity; } if (yanelInstance.isPreAuthenticationEnabled()) { String preAuthReqHeaderName = yanelInstance.getPreAuthenticationRequestHeaderName(); if (preAuthReqHeaderName != null && request.getHeader(preAuthReqHeaderName) != null) { String preAuthUserName = request.getHeader(preAuthReqHeaderName); log.warn("DEBUG: Pre authenticated user: " + preAuthUserName); String trueID = realm.getIdentityManager().getUserManager().getTrueId(preAuthUserName); User user = realm.getIdentityManager().getUserManager().getUser(trueID); if (user != null) { log.debug("User '" + user.getID() + "' considered pre-authenticated."); identity = new Identity(user, preAuthUserName); setIdentity(identity, request.getSession(true), realm); return identity; } else { log.warn("No such pre-authenticated user '" + preAuthUserName + "', hence set identity to WORLD!"); identity = new Identity(); setIdentity(identity, request.getSession(true), realm); return identity; } } else { log.warn("Pre-authentication enabled, but no request header name set!"); } } /* TODO: Make configurable! if (true) { log.warn("DEBUG: Do not check for BASIC authentication, but set identity to WORLD."); return new Identity(); } */ // HTTP BASIC Authentication (For clients such as for instance Thunderbird Lightning, OpenOffice or cadaver) // IMPORT NOTE: BASIC Authentication needs to be checked on every request, because clients often do not support session handling String authorizationHeader = request.getHeader("Authorization"); if (log.isDebugEnabled()) log.debug("No identity attached to session, hence check request authorization header: " + authorizationHeader); if (authorizationHeader != null) { if (authorizationHeader.toUpperCase().startsWith("BASIC")) { // Get encoded user and password, comes after "BASIC " String userpassEncoded = authorizationHeader.substring(6); // INFO: Decode it, using base 64 decoder // DEPRECATED //sun.misc.BASE64Decoder dec = new sun.misc.BASE64Decoder(); //String userpassDecoded = new String(dec.decodeBuffer(userpassEncoded)); java.util.Base64.Decoder decoder = java.util.Base64.getMimeDecoder(); String userpassDecoded = new String(decoder.decode(userpassEncoded)); log.debug("Username and Password decoded: " + userpassDecoded); String[] up = userpassDecoded.split(":"); String username = up[0]; String password = up[1]; log.debug("Get identity from BASIC authorization header and try to authenticate user '" + username + "' for request '" + request.getServletPath() + "'"); try { String trueID = realm.getIdentityManager().getUserManager().getTrueId(username); User user = realm.getIdentityManager().getUserManager().getUser(trueID); if (user != null && user.authenticate(password)) { log.debug("User '" + user.getID() + "' successfully authenticated via BASIC authentication."); identity = new Identity(user, username); setIdentity(identity, request.getSession(true), realm); return identity; } else { log.warn("HTTP BASIC Authentication failed for " + username + " (True ID: '" + trueID + "') and request '" + request.getServletPath() + "', hence set identity to WORLD!"); identity = new Identity(); setIdentity(identity, request.getSession(true), realm); return identity; /* INFO: Do not return unauthorized response, but rather just return 'WORLD' as identity... response.setHeader("WWW-Authenticate", "BASIC realm=\"" + realm.getName() + "\""); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); PrintWriter writer = response.getWriter(); writer.print("BASIC Authentication Failed!"); return response; */ } } catch (Exception e) { throw new ServletException(e.getMessage(), e); } } else if (authorizationHeader.toUpperCase().startsWith("DIGEST")) { log.error("DIGEST is not implemented (Request: " + request.getServletPath() + "), hence set identity to WORLD!"); return new Identity(); /* authorized = false; response.sendError(HttpServletResponse.SC_UNAUTHORIZED); response.setHeader("WWW-Authenticate", "DIGEST realm=\"" + realm.getName() + "\""); PrintWriter writer = response.getWriter(); writer.print("DIGEST is not implemented!"); */ } else { log.warn("No such authorization type implemented: " + authorizationHeader); return new Identity(); } } else { if (log.isDebugEnabled()) log.debug("Neither identity inside session yet nor authorization header based identity for request '" + request.getServletPath() + "', hence set identity to WORLD..."); // TBD: Should we add WORLD identity for performance reasons to the session? return new Identity(); } } /** * Create a DOM Document */ static public Document getDocument(String namespace, String localname) throws Exception { return XMLHelper.createDocument(namespace, localname); } private Realm getRealm(HttpServletRequest request) throws Exception { Realm realm = yanelInstance.getMap().getRealm(request.getServletPath()); return realm; } /** * Generate response using a resource configuration * @param response Response which is being generated/completed * @param statusCode HTTP response status code (because one is not able to get status code from response) * @param rc Resource configuration * @return true if generation of response was successful or return false otherwise */ private boolean generateResponseFromRTview(HttpServletRequest request, HttpServletResponse response, int statusCode, ResourceConfiguration rc, String path) throws ServletException { try { Resource resource = yanelInstance.getResourceManager().getResource(getEnvironment(request, response), getRealm(request), path, rc); return generateResponseFromResourceView(request, response, statusCode, resource); } catch (Exception e) { throw new ServletException(e); } } /** * Generate response using a resource configuration * @param statusCode HTTP response status code (because one is not able to get status code from response) * @param resource Resource * @return true if generation of response was successful or return false otherwise */ private boolean generateResponseFromResourceView(HttpServletRequest request, HttpServletResponse response, int statusCode, Resource resource) throws Exception { String viewId = getViewID(request); View view = ((ViewableV2) resource).getView(viewId); if (view != null) { TrackingInformationV1 trackInfo = null; if (generateResponse(view, resource, request, response, statusCode, getDocument(NAMESPACE, "yanel"), -1, -1, trackInfo) != null) { return true; } } log.warn("No response has been generated: " + resource.getPath()); return false; } /** * Get global data located below reserved prefix */ private void getGlobalData(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Resource resource = getResource(request, response); String path = resource.getPath(); java.util.Map<String, String> properties = new HashMap<String, String>(); final String pathPrefix = "/" + reservedPrefix + "/"; final String ABOUT_PAGE_PATH = pathPrefix + "about.html"; // About Yanel final String ABOUT_REALM_PAGE_PATH = pathPrefix + "about-realm.html"; // About realm final String RESOURCE_TYPES_PATH_PREFIX = pathPrefix + "resource-types/"; //XXX REFACTORME: in the cases where we simply use a resource-type's view // we should implement org.wyona.yanel.core.api.ResourceTypeMatcherV1 ( cf. http://lists.wyona.org/pipermail/yanel-development/2009-June/003749.html ) Realm realm; Environment environment = getEnvironment(request, response); ResourceConfiguration rc; YanelGlobalResourceTypeMatcher RTmatcher = new YanelGlobalResourceTypeMatcher(pathPrefix, servletContextRealPath); try { realm = getRealm(request); rc = RTmatcher.getResourceConfiguration(environment, realm, path); } catch (Exception e) { throw new ServletException(e.getMessage(), e); } if (rc != null) { if (generateResponseFromRTview(request, response, -1, rc, path)) { return; } response.setStatus(javax.servlet.http.HttpServletResponse.SC_NOT_FOUND); return; } else if (path.equals(ABOUT_PAGE_PATH)) { //XXX REFACTORME: we should define an "about" resource-type instead! response.setStatus(javax.servlet.http.HttpServletResponse.SC_OK); response.setHeader("Content-Type", "text/html"); PrintWriter w = response.getWriter(); w.print(About.toHTML(yanelInstance.getVersion(), yanelInstance.getRevision(), yanelInstance.getTargetEnvironment())); return; } else if (path.equals(ABOUT_REALM_PAGE_PATH)) { //XXX REFACTORME: we should define an "about-realm" resource-type instead! response.setStatus(javax.servlet.http.HttpServletResponse.SC_OK); response.setHeader("Content-Type", "text/html"); PrintWriter w = response.getWriter(); w.print(AboutRealm.toHTML(realm)); return; } else if (path.startsWith(RESOURCE_TYPES_PATH_PREFIX)) { final String[] namespaceURI_and_rest = path.substring(RESOURCE_TYPES_PATH_PREFIX.length()).split("::", 2); final String namespaceURI = namespaceURI_and_rest[0]; final String[] name_and_rest = namespaceURI_and_rest[1].split("/", 2); final String name = name_and_rest[0]; // INFO: Decode URL, e.g. /yanel/resource-types/^http:^2f^2fwww.wyona.org^2fyanel^2fresource^2f1.0::user-admin/dummy.css final String decoded_namespaceURI = HttpServletRequestHelper.decodeURIinURLpath('^', namespaceURI); log.debug("decoded_namespaceURI: " + decoded_namespaceURI); if (log.isDebugEnabled()) log.debug("decoded_namespaceURI: "+decoded_namespaceURI); // The request (see resource.getPath()) seems to replace 'http://' or 'http%3a%2f%2f' by 'http:/', so let's change this back final String namespace = ! decoded_namespaceURI.equals(namespaceURI) ? decoded_namespaceURI : namespaceURI.replaceAll("http:/", "http://"); rc = new ResourceConfiguration(name, namespace, properties); try { Resource resourceOfPrefix = yanelInstance.getResourceManager().getResource(environment, realm, path, rc); String htdocsPath; if (name_and_rest[1].startsWith(reservedPrefix + "/")) { htdocsPath = "rtyanelhtdocs:" + name_and_rest[1].substring(reservedPrefix.length()).replace('/', File.separatorChar); } else { htdocsPath = "rthtdocs:" + File.separatorChar + name_and_rest[1].replace('/', File.separatorChar); } SourceResolver resolver = new SourceResolver(resourceOfPrefix); Source source = resolver.resolve(htdocsPath, null); long sourceLastModified = -1; // INFO: Compare If-Modified-Since with lastModified and return 304 without content resp. check on ETag if (source instanceof YanelStreamSource) { sourceLastModified = ((YanelStreamSource) source).getLastModified(); long ifModifiedSince = request.getDateHeader("If-Modified-Since"); if (log.isDebugEnabled()) log.debug("sourceLastModified <= ifModifiedSince: " + sourceLastModified + " <= " + ifModifiedSince); if (ifModifiedSince != -1) { if (sourceLastModified <= ifModifiedSince) { response.setStatus(javax.servlet.http.HttpServletResponse.SC_NOT_MODIFIED); return; } } } InputStream htdocIn = ((StreamSource) source).getInputStream(); if (htdocIn != null) { log.debug("Resource-Type specific data: " + htdocsPath); // TODO: Set more HTTP headers (size, etc.) String mimeType = guessMimeType(FilenameUtils.getExtension(FilenameUtils.getName(htdocsPath))); if(sourceLastModified >= 0) response.setDateHeader("Last-Modified", sourceLastModified); response.setHeader("Content-Type", mimeType); // INFO: Tell the client for how long it should cache the data which will be sent by the response if (cacheExpires != 0) { setExpiresHeader(response, cacheExpires); } byte buffer[] = new byte[8192]; int bytesRead; OutputStream out = response.getOutputStream(); while ((bytesRead = htdocIn.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); } htdocIn.close(); return; } else { log.error("No such file or directory: " + htdocsPath); response.setStatus(javax.servlet.http.HttpServletResponse.SC_NOT_FOUND); return; } } catch (Exception e) { throw new ServletException(e.getMessage(), e); } } else { File globalFile = org.wyona.commons.io.FileUtil.file(servletContextRealPath, "htdocs" + File.separator + path.substring(pathPrefix.length())); if (globalFile.exists()) { //log.debug("Get global file: " + globalFile); // INFO: Compare If-Modified-Since with lastModified and return 304 without content resp. check on ETag long ifModifiedSince = request.getDateHeader("If-Modified-Since"); if (ifModifiedSince != -1) { //log.debug("Last modified '" + globalFile.lastModified() + "' versus If-Modified-Since '" + ifModifiedSince + "'."); if (globalFile.lastModified() <= ifModifiedSince) { response.setStatus(javax.servlet.http.HttpServletResponse.SC_NOT_MODIFIED); return; } } // TODO: Set more HTTP headers (size, etc.) String mimeType = guessMimeType(FilenameUtils.getExtension(globalFile.getName())); response.setHeader("Content-Type", mimeType); response.setDateHeader("Last-Modified", globalFile.lastModified()); // INFO: Tell the client for how long it should cache the data which will be sent by the response if (cacheExpires != 0) { //log.debug("Client should consider the content of '" + globalFile + "' as stale in '" + cacheExpires + "' hours from now on ..."); setExpiresHeader(response, cacheExpires); } else { //log.debug("No cache expires set."); } byte buffer[] = new byte[8192]; int bytesRead; InputStream in = new java.io.FileInputStream(globalFile); OutputStream out = response.getOutputStream(); while ((bytesRead = in.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); } in.close(); return; } else { log.error("No such file or directory: " + globalFile); response.setStatus(javax.servlet.http.HttpServletResponse.SC_NOT_FOUND); return; } } } /** * Set expire date within HTTP header (see https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.21) * @param hours Number of hours from now on, after which the response is considered stale */ private void setExpiresHeader(HttpServletResponse response, int hours) { Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.HOUR_OF_DAY, hours); String expires = DateUtil.formatRFC822GMT(calendar.getTime()); response.setHeader("Expires", expires); } /** * Generate response from a resource view, whereas it will be checked first if the resource already wrote the response (if so, then just return) * * @param view View of resource * @param res Resource which handles the request in order to generate a response * @param request TODO * @param response TODO * @param statusCode HTTP response status code (because one is not able to get status code from response) * @param doc TODO * @param size TODO * @param lastModified TODO * @param trackInfo Tracking information bean which might be updated by resource if resource is implementing trackable * * @return response to the client / browser */ private HttpServletResponse generateResponse(View view, Resource res, HttpServletRequest request, HttpServletResponse response, int statusCode, Document doc, long size, long lastModified, TrackingInformationV1 trackInfo) throws ServletException, IOException { //log.debug("Generate response: " + res.getPath()); // TODO: It seems like no header fields are being set (e.g. Content-Length, ...). Please see below ... // INFO: Check if viewable resource has already created a response if (!view.isResponse()) { if(logAccessIsApplicable(view.getMimeType(), res)) { //log.debug("Mime type '" + view.getMimeType() + "' of request: " + request.getServletPath() + "?" + request.getQueryString()); doLogAccess(request, response, statusCode, res, trackInfo); } log.debug("It seems that resource '" + res.getPath() + "' has directly created the response."); try { if ("true".equals(res.getResourceConfigProperty("yanel:no-cache"))) { log.debug("Set no-cache headers..."); response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1. response.setHeader("Pragma", "no-cache"); // HTTP 1.0. response.setDateHeader("Expires", 0); // Proxies. } } catch(Exception e) { log.error(e, e); } return response; } // INFO: Set mime type and encoding String mimeType = view.getMimeType(); if (view.getEncoding() != null) { mimeType = patchMimeType(mimeType, request); response.setContentType(mimeType + "; charset=" + view.getEncoding()); } else if (res.getConfiguration() != null && res.getConfiguration().getEncoding() != null) { mimeType = patchMimeType(mimeType, request); response.setContentType(mimeType + "; charset=" + res.getConfiguration().getEncoding()); } else { // try to guess if we have to set the default encoding if (mimeType != null && mimeType.startsWith("text") || mimeType.equals("application/xml") || mimeType.equals("application/xhtml+xml") || mimeType.equals("application/atom+xml") || mimeType.equals("application/x-javascript")) { mimeType = patchMimeType(mimeType, request); response.setContentType(mimeType + "; charset=" + DEFAULT_ENCODING); } else { // probably binary mime-type, don't set encoding mimeType = patchMimeType(mimeType, request); response.setContentType(mimeType); } } if(logAccessIsApplicable(mimeType, res)) { //log.debug("Mime type '" + mimeType + "' of request: " + request.getServletPath() + "?" + request.getQueryString()); doLogAccess(request, response, statusCode, res, trackInfo); } // INFO: Set HTTP headers HashMap<?, ?> headers = view.getHttpHeaders(); Iterator<?> iter = headers.keySet().iterator(); while (iter.hasNext()) { String name = (String)iter.next(); String value = (String)headers.get(name); if (log.isDebugEnabled()) { log.debug("set http header: " + name + ": " + value); } response.setHeader(name, value); } try { if ("true".equals(res.getResourceConfigProperty("yanel:no-cache"))) { log.debug("Set no-cache headers..."); response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1. response.setHeader("Pragma", "no-cache"); // HTTP 1.0. response.setDateHeader("Expires", 0); // Proxies. } } catch(Exception e) { log.error(e, e); } // INFO: Confirm DNT (do not track) String dntValue = request.getHeader("DNT"); if (dntValue != null) { response.setHeader("DNT", dntValue); // INFO: See spec about response header at http://tools.ietf.org/html/draft-mayer-do-not-track-00 } else { //log.debug("No DNT (do not track) header set, hence do not echo."); } // Possibly embed toolbar: // TODO: Check if user is authorized to actually see toolbar (Current flaw: Enabled Toolbar, Login, Toolbar is enabled, Logout, Toolbar is still visible!) if (yanelUI.isToolbarEnabled(request)) { // TODO: Check whether resource configuration has toolbar configured as suppressed: if ("suppress".equals(res.getResConfiguration("yanel.toolbar"))) { if (mimeType != null && mimeType.indexOf("html") > 0) { // TODO: What about other query strings or frames or TinyMCE (e.g. link.htm)? if (request.getParameter(YANEL_RESOURCE_USECASE) == null) { // INFO: In the case of a yanel resource usecase do NOT add the toolbar if (toolbarMasterSwitch.equals("on")) { OutputStream os = response.getOutputStream(); try { Usecase usecase = new Usecase(TOOLBAR_USECASE); Realm realm = map.getRealm(request.getServletPath()); Identity identity = getIdentityFromRequest(request, realm); String path = map.getPath(realm, request.getServletPath()); // NOTE: This extra authorization check is necessary within a multi-realm environment, because after activating the toolbar with a query string, the toolbar flag attached to the session will be ignored by doAccessControl(). One could possibly do this check within doAccessControl(), but could be a peformance issue! Or as an alternative one could refactor the code, such that the toolbar session flag is realm aware. if(realm.getPolicyManager().authorize(path, identity, usecase)) { yanelUI.mergeToolbarWithContent(request, response, res, view); return response; } else { log.warn("Toolbar authorization denied (Realm: '" + realm.getName() + "', User: '" + identity.getUsername() + "', Path: '" + path + "')!"); } } catch (Exception e) { String message = "Error merging toolbar into content: " + e.getMessage(); //log.error(message, e); log.error(e, e); Element exceptionElement = (Element) doc.getDocumentElement().appendChild(doc.createElementNS(NAMESPACE, EXCEPTION_TAG_NAME)); exceptionElement.appendChild(doc.createTextNode(message)); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); setYanelOutput(request, response, doc); return response; } } else { log.info("Toolbar has been disabled. Please check web.xml!"); } } else { log.warn("Yanel resource usecase is not null, but set to '" + request.getParameter(YANEL_RESOURCE_USECASE) + "' and hence Yanel toolbar is suppressed/omitted in order to avoid that users are leaving the usecase because they might click on some toolbar menu item."); } } else { log.info("No HTML related mime type: " + mimeType); } } else { log.debug("Toolbar is turned off."); } InputStream is = view.getInputStream(); if (is != null) { try { // Compare If-Modified-Since with lastModified and return 304 without content resp. check on ETag long ifModifiedSince = request.getDateHeader("If-Modified-Since"); if (ifModifiedSince != -1) { //log.debug("Client set 'If-Modified-Since' ..."); if (res instanceof ModifiableV2) { long resourceLastMod = ((ModifiableV2)res).getLastModified(); log.debug("Resource was last modified: " + new Date(resourceLastMod) + ", 'If-Modified-Since' sent by client: " + new Date(ifModifiedSince)); if (resourceLastMod <= ifModifiedSince) { response.setStatus(javax.servlet.http.HttpServletResponse.SC_NOT_MODIFIED); return response; } } else { // TODO: Many resources do not implement ModifiableV2 and hence never return a lastModified and hence the browser will never ask for ifModifiedSince! //log.warn("Resource of path '" + res.getPath() + "' is not ModifiableV2 and hence cannot be cached!"); if (log.isDebugEnabled()) log.debug("Resource of path '" + res.getPath() + "' is not ModifiableV2 and hence cannot be cached!"); } } } catch (Exception e) { log.error(e.getMessage(), e); } if(lastModified >= 0) response.setDateHeader("Last-Modified", lastModified); if(size > 0) { if (log.isDebugEnabled()) log.debug("Size of " + request.getRequestURI() + ": " + size); response.setContentLength((int) size); } else { if (log.isDebugEnabled()) log.debug("No size for " + request.getRequestURI() + ": " + size); } try { // INFO: Check whether InputStream is empty and try to Write content into response byte buffer[] = new byte[8192]; int bytesRead; bytesRead = is.read(buffer); if (bytesRead != -1) { java.io.OutputStream os = response.getOutputStream(); os.write(buffer, 0, bytesRead); while ((bytesRead = is.read(buffer)) != -1) { os.write(buffer, 0, bytesRead); } os.close(); } else { log.warn("Returned content size of request '" + request.getRequestURI() + "' is 0"); } } catch(Exception e) { log.error("Writing into response failed for request '" + request.getRequestURL() + "' (Client: " + getClientAddressOfUser(request) + ")"); // INFO: For example in the case of ClientAbortException log.error(e, e); throw new ServletException(e); } finally { //log.debug("Close InputStream in any case!"); is.close(); // INFO: Make sure to close InputStream, because otherwise we get bugged with open files } return response; } else { String message = "Returned InputStream of request '" + request.getRequestURI() + "' is null!"; Element exceptionElement = (Element) doc.getDocumentElement().appendChild(doc.createElementNS(NAMESPACE, EXCEPTION_TAG_NAME)); exceptionElement.appendChild(doc.createTextNode(message)); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); setYanelOutput(request, response, doc); is.close(); return response; } } /** * @see javax.servlet.GenericServlet#destroy() */ @Override public void destroy() { super.destroy(); log.info("Destroy Yanel instance..."); yanelInstance.destroy(); if (scheduler != null) { try { log.info("Shutdown scheduler ..."); log.warn("DEBUG: Shutdown scheduler ..."); scheduler.shutdown(); //scheduler.shutdown(true); // INFO: true means to wait until all jobs have completed } catch(Exception e) { log.error(e, e); } } else { log.warn("No scheduler instance exists, probably because it is disabled: " + yanelInstance.isSchedulerEnabled()); } log.warn("DEBUG: Shutdown ehcache..."); net.sf.ehcache.CacheManager.create().shutdown(); File shutdownLogFile = new File(System.getProperty("java.io.tmpdir"), "shutdown.log"); log.warn("Trying to shutdown log4j loggers... (if shutdown successful, then loggers won't be available anymore. Hence see shutdown log file '" + shutdownLogFile.getAbsolutePath() + "' for final messages)"); org.apache.log4j.LogManager.shutdown(); // TODO: org.apache.logging.log4j.LogManager.shutdown(); /* INFO: After closing the loggers/appenders, these won't be available anymore, hence the following log statements don't make any sense. log.info("Shutdown of access logger completed."); log.info("Yanel webapp has been shut down: " + new Date()); */ try { if (!shutdownLogFile.exists()) { shutdownLogFile.createNewFile(); } java.io.FileWriter fw= new java.io.FileWriter(shutdownLogFile); java.io.BufferedWriter bw = new java.io.BufferedWriter(fw); bw.write("Yanel webapp has been shut down: " + new Date()); bw.close(); fw.close(); } catch(java.io.FileNotFoundException e) { System.err.println(e.getMessage()); } catch(java.io.IOException e) { System.err.println(e.getMessage()); } } /** * Get usecase. Maps query strings, etc. to usecases, which then can be used for example within access control policies */ private Usecase getUsecase(HttpServletRequest request) { // TODO: Replace hardcoded roles by mapping between roles amd query strings ... Usecase usecase = new Usecase("view"); String yanelResUsecaseValue = request.getParameter(YANEL_RESOURCE_USECASE); if (yanelResUsecaseValue != null) { if (yanelResUsecaseValue.equals("save")) { log.debug("Save data ..."); usecase = new Usecase("write"); } else if (yanelResUsecaseValue.equals("checkin")) { log.debug("Checkin data ..."); usecase = new Usecase("write"); } else if (yanelResUsecaseValue.equals("roll-back")) { log.debug("Roll back to previous revision ..."); usecase = new Usecase("write"); } else if (yanelResUsecaseValue.equals("introspection")) { if(log.isDebugEnabled()) log.debug("Dynamically generated introspection ..."); usecase = new Usecase("introspection"); } else if (yanelResUsecaseValue.equals("checkout")) { log.debug("Checkout data ..."); usecase = new Usecase("open"); } else if (yanelResUsecaseValue.equals("delete")) { log.info("Delete resource (yanel resource usecase delete)"); usecase = new Usecase("delete"); } else { log.warn("No such generic Yanel resource usecase: " + yanelResUsecaseValue + " (maybe some custom resource usecase)"); } } String yanelUsecaseValue = request.getParameter(YANEL_USECASE); if (yanelUsecaseValue != null) { if (yanelUsecaseValue.equals("create")) { log.debug("Create new resource ..."); usecase = new Usecase("resource.create"); } else if (yanelUsecaseValue.equals("policy.read")) { usecase = new Usecase("policy.read"); } else { log.warn("No such generic Yanel usecase: " + yanelUsecaseValue + " (maybe some custom usecase)"); } } String contentType = request.getContentType(); String method = request.getMethod(); if (contentType != null && contentType.indexOf("application/atom+xml") >= 0 && (method.equals(METHOD_PUT) || method.equals(METHOD_POST))) { // TODO: Is posting atom entries different from a general post (see below)?! log.warn("Write/Checkin Atom entry ..."); usecase = new Usecase("write"); // TODO: METHOD_POST is not generally protected, but save, checkin, application/atom+xml are being protected. See doPost(.... } else if (method.equals(METHOD_PUT)) { log.warn("INFO: Upload data using PUT, hence we set the usecase to 'write', which you might have to enable inside the corresponding access policy."); usecase = new Usecase("write"); } else if (method.equals(METHOD_DELETE)) { log.warn("Delete resource (HTTP method delete)"); usecase = new Usecase("delete"); } String workflowTransitionValue = request.getParameter(YANEL_RESOURCE_WORKFLOW_TRANSITION); if (workflowTransitionValue != null) { // TODO: At the moment the authorization of workflow transitions are checked within executeWorkflowTransition or rather workflowable.doTransition(transition, revision) log.warn("Workflow transition is currently handled as view usecase: " + workflowTransitionValue); usecase = new Usecase("view"); // TODO: Return workflow transition ID //usecase = new Usecase(transitionID); } String toolbarValue = request.getParameter("yanel.toolbar"); if (toolbarValue != null && toolbarValue.equals("on")) { log.debug("Turn on toolbar ..."); usecase = new Usecase(TOOLBAR_USECASE); } String yanelPolicyValue = request.getParameter(YANEL_ACCESS_POLICY_USECASE); if (yanelPolicyValue != null) { if (yanelPolicyValue.equals("create")) { usecase = new Usecase("policy.create"); } else if (yanelPolicyValue.equals("read")) { usecase = new Usecase("policy.read"); } else if (yanelPolicyValue.equals("update")) { usecase = new Usecase("policy.update"); } else if (yanelPolicyValue.equals("delete")) { usecase = new Usecase("policy.delete"); } else { log.warn("No such policy usecase: " + yanelPolicyValue); } } String showResourceMeta = request.getParameter(RESOURCE_META_ID_PARAM_NAME); if (showResourceMeta != null) { usecase = new Usecase(RESOURCE_META_ID_PARAM_NAME); } return usecase; } /** * Handle access policy requests (CRUD, whereas delete is not implemented yet!) * @param version Version of policy manager implementation */ private void doAccessPolicyRequest(HttpServletRequest request, HttpServletResponse response, int version) throws ServletException, IOException { try { String viewId = getViewID(request); Realm realm = map.getRealm(request.getServletPath()); ResourceConfiguration rc; if (version == 2) { rc = getGlobalResourceConfiguration("policy-manager-v2_yanel-rc.xml", realm); } else { rc = getGlobalResourceConfiguration("policy-manager_yanel-rc.xml", realm); } String path = map.getPath(realm, request.getServletPath()); if (generateResponseFromRTview(request, response, -1, rc, path)) { return; } log.error("Something went terribly wrong!"); response.getWriter().print("Something went terribly wrong!"); return; } catch(Exception e) { throw new ServletException(e.getMessage(), e); } } /** * Handle delete usecase */ private void handleDeleteUsecase(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String confirmed = request.getParameter("confirmed"); if (confirmed != null) { String path = getResource(request, response).getPath(); log.debug("Really delete resource at " + path); doDelete(request, response); return; } else { response.setStatus(javax.servlet.http.HttpServletResponse.SC_OK); response.setContentType("text/html" + "; charset=" + "UTF-8"); StringBuilder sb = new StringBuilder(); Resource res = getResource(request, response); if (ResourceAttributeHelper.hasAttributeImplemented(res, "Modifiable", "2") || ResourceAttributeHelper.hasAttributeImplemented(res, "Deletable", "1")) { log.info("Delete has not been confirmed by client yet!"); sb = new StringBuilder("<html xmlns=\"http://www.w3.org/1999/xhtml\"><body>Do you really want to delete this page? <a href=\"?" + YANEL_RESOURCE_USECASE + "=delete&confirmed\">YES</a>, <a href=\"" + request.getHeader("referer") + "\">no</a></body></html>"); } else { String message = "Resource '" + res.getPath() + "' cannot be deleted, because it does not implement interface ModifiableV2!"; log.warn(message); sb = new StringBuilder("<html xmlns=\"http://www.w3.org/1999/xhtml\"><body><p>WARNING: " + message + "</p></body></html>"); } PrintWriter w = response.getWriter(); w.print(sb); return; } } /** * Get resource configuration from global location of the realm or if not available there, then from global location of Yanel * * @param resConfigName Filename of resource configuration * @param realm Current realm */ private ResourceConfiguration getGlobalResourceConfiguration(String resConfigName, Realm realm) { return YanelGlobalResourceTypeMatcher.getGlobalResourceConfiguration(resConfigName, realm, servletContextRealPath); } /** * Handle a generic exception. * @param request The request object. * @param response The response object. * @param ex The exception to handle. */ private void handleException(HttpServletRequest request, HttpServletResponse response, Exception ex) { try { Realm realm = yanelInstance.getMap().getRealm(request.getServletPath()); String path = getResource(request, response).getPath(); ResourceConfiguration rc = getGlobalResourceConfiguration("generic-exception-handler_yanel-rc.xml", realm); BasicGenericExceptionHandlerResource resource = (BasicGenericExceptionHandlerResource) yanelInstance.getResourceManager().getResource(getEnvironment(request, response), getRealm(request), path, rc); resource.setException(ex); int statusCode = javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR; response.setStatus(statusCode); boolean hasBeenHandled = generateResponseFromResourceView(request, response, statusCode, resource); if(!hasBeenHandled) { log.error("Generic exception handler is broken!"); log.error("Unable to output/handle the following exception:"); log.error(ex, ex); } } catch (Exception e) { log.error("Generic exception handler is broken!"); log.error("Unable to handle the following exception:"); log.error(ex, ex); log.error("Caught exception while handling the above exception:"); log.error(e, e); } } /** * Generate a graceful 404 response * @param doc Debug/Meta document */ private void do404(HttpServletRequest request, HttpServletResponse response, Document doc, String exceptionMessage) throws ServletException { log404.info("Referer: " + request.getHeader("referer")); log404.warn(request.getRequestURL().toString()); // TODO: Log 404 per realm //org.wyona.yarep.core.Node node = realm.getRepository().getNode("/yanel-logs/404.txt"); String message = "No such node/resource exception: " + exceptionMessage; log.warn(message); Element exceptionElement = (Element) doc.getDocumentElement().appendChild(doc.createElementNS(NAMESPACE, EXCEPTION_TAG_NAME)); exceptionElement.appendChild(doc.createTextNode(message)); exceptionElement.setAttributeNS(NAMESPACE, "status", "404"); response.setStatus(HttpServletResponse.SC_NOT_FOUND); try { Realm realm = yanelInstance.getMap().getRealm(request.getServletPath()); String path = getResource(request, response).getPath(); ResourceConfiguration rc = getGlobalResourceConfiguration("404_yanel-rc.xml", realm); if (generateResponseFromRTview(request, response, HttpServletResponse.SC_NOT_FOUND, rc, path)) { return; } log.error("404 response seems to be broken!"); return; } catch (Exception e) { log.error(e.getMessage(), e); return; } } /** * Check if yanel resource usecase is 'roll back" usecase */ private boolean isRollBack(HttpServletRequest request) { String yanelResUsecase = request.getParameter(YANEL_RESOURCE_USECASE); if (yanelResUsecase != null) { if (yanelResUsecase.equals("roll-back")) return true; } return false; } /** * Check if request comes from Neutron supporting client */ private boolean isClientSupportingNeutron(HttpServletRequest request) { String neutronVersions = request.getHeader("Neutron"); if (neutronVersions != null) { log.info("Neutron version(s) supported by client: " + neutronVersions); return true; } return false; } /** * Respond with introspection */ private void sendIntrospectionAsResponse(Resource res, Document doc, Element rootElement, HttpServletRequest request, HttpServletResponse response) throws ServletException { try { if (ResourceAttributeHelper.hasAttributeImplemented(res, "Introspectable", "1")) { response.setContentType("application/xml"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_OK); response.getWriter().print(((IntrospectableV1)res).getIntrospection()); } else { String message = "Resource '" + res.getPath() + "' is not introspectable!"; log.warn(message); Element exceptionElement = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, EXCEPTION_TAG_NAME)); exceptionElement.appendChild(doc.createTextNode(message)); setYanelOutput(request, response, doc); } return; } catch(Exception e) { log.error(e.getMessage(), e); Element exceptionElement = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, EXCEPTION_TAG_NAME)); exceptionElement.appendChild(doc.createTextNode(e.getMessage())); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); setYanelOutput(request, response, doc); return; } } /** * Set/get meta data re resource */ private Element getResourceMetaData(Resource res, Document doc, Element rootElement) { Element resourceElement = (Element) rootElement.appendChild(doc.createElement("resource")); ResourceConfiguration resConfig = res.getConfiguration(); if (resConfig != null) { Element resConfigElement = (Element) resourceElement.appendChild(doc.createElementNS(NAMESPACE, "config")); resConfigElement.setAttributeNS(NAMESPACE, "rti-name", resConfig.getName()); resConfigElement.setAttributeNS(NAMESPACE, "rti-namespace", resConfig.getNamespace()); } else { Element noResConfigElement = (Element) resourceElement.appendChild(doc.createElementNS(NAMESPACE, "no-config")); } Element realmElement = (Element) resourceElement.appendChild(doc.createElementNS(NAMESPACE, "realm")); realmElement.setAttributeNS(NAMESPACE, "name", res.getRealm().getName()); realmElement.setAttributeNS(NAMESPACE, "rid", res.getRealm().getID()); realmElement.setAttributeNS(NAMESPACE, "prefix", res.getRealm().getMountPoint()); Element identityManagerElement = (Element) realmElement.appendChild(doc.createElementNS(NAMESPACE, "identity-manager")); Element userManagerElement = (Element) identityManagerElement.appendChild(doc.createElementNS(NAMESPACE, "user-manager")); return resourceElement; } /** * Append view descriptors to meta */ private void appendViewDescriptors(Document doc, Element viewElement, ViewDescriptor[] vd) { if (vd != null) { for (int i = 0; i < vd.length; i++) { Element descriptorElement = (Element) viewElement.appendChild(doc.createElement("descriptor")); if (vd[i].getMimeType() != null) { descriptorElement.appendChild(doc.createTextNode(vd[i].getMimeType())); } descriptorElement.setAttributeNS(NAMESPACE, "id", vd[i].getId()); } } else { viewElement.appendChild(doc.createTextNode("No View Descriptors!")); } } /** * Log browser history of each user * @param request TODO * @param response TODO * @param resource Resource which handles the request * @param statusCode HTTP response status code (because one is not able to get status code from response) * @param trackInfo Tracking information bean */ private void doLogAccess(HttpServletRequest request, HttpServletResponse response, int statusCode, Resource resource, TrackingInformationV1 trackInfo) { // TBD: What about a cluster, performance/scalability? See for example http://www.oreillynet.com/cs/user/view/cs_msg/17399 (also see Tomcat conf/server.xml <Valve className="AccessLogValve" and className="FastCommonAccessLogValve") // See apache-tomcat-5.5.33/logs/localhost_access_log.2009-11-07.txt // 127.0.0.1 - - [07/Nov/2009:01:24:09 +0100] "GET /yanel/from-scratch-realm/de/index.html HTTP/1.1" 200 4464 /* Differentiate between hits, pageviews (only html or also PDF, etc.?) and visits (also see http://www.ibm.com/developerworks/web/library/wa-mwt1/) In order to log page-views one can use: - single-pixel method (advantage: also works if javascript is disabled) - JavaScript (similar to Google analytics) - Analyze mime type (advantage: no additional code/requests necessary) - Log analysis (no special tracking required) */ if ("1".equals(request.getHeader("DNT"))) { // INFO: See http://donottrack.us/ if (logDoNotTrack.isDebugEnabled()) { logDoNotTrack.debug("Do not track: " + request.getRemoteAddr()); } return; } try { Realm realm = map.getRealm(request.getServletPath()); String accessLogMessage; if (trackInfo != null) { if (trackInfo.doNotTrack()) { logDoNotTrack.debug("Do not track: " + resource.getPath() + " (Remote address: " + request.getRemoteAddr() + ")"); return; } String[] trackingTags = trackInfo.getTags(); if (trackingTags != null && trackingTags.length > 0) { // INFO: Either/Or, but not both. If you want both, then make sure that that your resource adds its annotations to the tracking information. accessLogMessage = AccessLog.getLogMessage(getRequestURLQS(request, null, false), request, response, realm.getUserTrackingDomain(), trackingTags, ACCESS_LOG_TAG_SEPARATOR); } else { String[] tags = getTagsFromAnnotatableResource(resource, request.getServletPath()); accessLogMessage = AccessLog.getLogMessage(getRequestURLQS(request, null, false), request, response, realm.getUserTrackingDomain(), tags, ACCESS_LOG_TAG_SEPARATOR); } String pageType = trackInfo.getPageType(); if (pageType != null) { accessLogMessage = accessLogMessage + AccessLog.encodeLogField("pt", pageType); } String requestAction = trackInfo.getRequestAction(); if (requestAction != null) { accessLogMessage = accessLogMessage + AccessLog.encodeLogField("ra", requestAction); } // TODO: What if a custom field is overwriting a regular field?! I would suggest that we log a warning and ignore this custom field. HashMap<String, String> customFields = trackInfo.getCustomFields(); if (customFields != null) { for (java.util.Map.Entry field : customFields.entrySet()) { accessLogMessage = accessLogMessage + AccessLog.encodeLogField((String) field.getKey(), (String) field.getValue()); } } } else { String[] tags = getTagsFromAnnotatableResource(resource, request.getServletPath()); accessLogMessage = AccessLog.getLogMessage(getRequestURLQS(request, null, false), request, response, realm.getUserTrackingDomain(), tags, ACCESS_LOG_TAG_SEPARATOR); } // TBD/TODO: What if user has logged out, but still has a persistent cookie?! Identity identity = getIdentityFromRequest(request, realm); if (identity != null && identity.getUsername() != null) { accessLogMessage = accessLogMessage + AccessLog.encodeLogField("u", identity.getUsername()); /* TODO: This does not scale re many users ... User user = realm.getIdentityManager().getUserManager().getUser(identity.getUsername()); // The log should be attached to the user, because realms can share a UserManager, but the UserManager API has no mean to save such data, so how should we do this? // What if realm ID is changing? String logPath = "/yanel-logs/browser-history/" + user.getID() + ".txt"; if (!realm.getRepository().existsNode(logPath)) { org.wyona.yarep.util.YarepUtil.addNodes(realm.getRepository(), logPath, org.wyona.yarep.core.NodeType.RESOURCE); } org.wyona.yarep.core.Node node = realm.getRepository().getNode(logPath); // Stream into node (append log entry, see for example log4j) // 127.0.0.1 - - [07/Nov/2009:01:24:09 +0100] "GET /yanel/from-scratch-realm/de/index.html HTTP/1.1" 200 4464 */ } String clientIP = getClientAddressOfUser(request); String httpAcceptLanguage = request.getHeader("Accept-Language"); if (httpAcceptLanguage != null) { accessLogMessage = accessLogMessage + AccessLog.encodeLogField("a-lang", httpAcceptLanguage); } else { log.warn("Client request (IP: " + clientIP + ") has no Accept-Language header."); } HttpSession session = request.getSession(true); if (session != null) { accessLogMessage = accessLogMessage + AccessLog.encodeLogField("sid", session.getId()); } if (statusCode >= 0) { accessLogMessage = accessLogMessage + AccessLog.encodeLogField("http-status", "" + statusCode); } else { accessLogMessage = accessLogMessage + AccessLog.encodeLogField("http-status", "" + HttpServletResponse.SC_OK); } accessLogMessage = accessLogMessage + AccessLog.encodeLogField("ip", clientIP); logAccess.info(accessLogMessage); //log.debug("Referer: " + request.getHeader(HTTP_REFERRER)); // INFO: Store last accessed page in session such that session manager can show user activity. if(session != null) { session.setAttribute(YANEL_LAST_ACCESS_ATTR, request.getServletPath()); //log.debug("Last access: " + request.getServletPath()); } } catch(Exception e) { // Catch all exceptions, because we do not want to throw exceptions because of possible logging browser history errors log.error(e, e); } } /** * Append revisions and workflow of a resource to the meta document * @param doc Meta document */ private void appendRevisionsAndWorkflow(Document doc, Element resourceElement, Resource res, HttpServletRequest request) throws Exception { WorkflowableV1 workflowableResource = null; Workflow workflow = null; String liveRevisionName = null; if (ResourceAttributeHelper.hasAttributeImplemented(res, "Workflowable", "1")) { workflowableResource = (WorkflowableV1)res; workflow = WorkflowHelper.getWorkflow(res); liveRevisionName = WorkflowHelper.getLiveRevision(res); } UserManager userManager = res.getRealm().getIdentityManager().getUserManager(); if (ResourceAttributeHelper.hasAttributeImplemented(res, "Versionable", "3")) { //log.debug("Resource '" + res.getPath() + "' has VersionableV3 implemented..."); java.util.Iterator<RevisionInformation> it = ((VersionableV3)res).getRevisions(false); if (it != null) { if (it.hasNext()) { Element revisionsElement = (Element) resourceElement.appendChild(doc.createElement(REVISIONS_TAG_NAME)); while(it.hasNext()) { RevisionInformation revisionInfo = (RevisionInformation)it.next(); Element revisionElement = appendRevision(revisionsElement, revisionInfo, userManager); appendWorkflow(revisionElement, workflow, workflowableResource, doc, revisionInfo, liveRevisionName); } } else { resourceElement.appendChild(doc.createElement(NO_REVISIONS_TAG_NAME)); } } else { resourceElement.appendChild(doc.createElement(NO_REVISIONS_TAG_NAME)); } } else if (ResourceAttributeHelper.hasAttributeImplemented(res, "Versionable", "2")) { //log.debug("Resource '" + res.getPath() + "' has VersionableV2 implemented..."); RevisionInformation[] revisionsInfo = ((VersionableV2)res).getRevisions(); if (revisionsInfo != null && revisionsInfo.length > 0) { Element revisionsElement = (Element) resourceElement.appendChild(doc.createElement(REVISIONS_TAG_NAME)); for (int i = revisionsInfo.length - 1; i >= 0; i--) { Element revisionElement = appendRevision(revisionsElement, revisionsInfo[i], userManager); appendWorkflow(revisionElement, workflow, workflowableResource, doc, revisionsInfo[i], liveRevisionName); } } else { resourceElement.appendChild(doc.createElement(NO_REVISIONS_TAG_NAME)); } } else if (ResourceAttributeHelper.hasAttributeImplemented(res, "Versionable", "1")) { log.warn("TODO: Implement VersionableV1 interface, deprecated though!"); String[] revisionIDs = ((VersionableV1)res).getRevisions(); } else { Element notVersionableElement = (Element) resourceElement.appendChild(doc.createElement("not-versionable")); } } /** * Append workflow information to revision listed by meta document */ private void appendWorkflow(Element revisionElement, Workflow workflow, WorkflowableV1 workflowableResource, Document doc, RevisionInformation revisionInfo, String liveRevisionName) throws Exception { if (workflowableResource != null && workflow != null) { Element revisionWorkflowElement = (Element) revisionElement.appendChild(doc.createElement("workflow-state")); String wfState = workflowableResource.getWorkflowState(revisionInfo.getName()); if (wfState == null) { wfState = workflow.getInitialState(); } if (liveRevisionName != null && revisionInfo.getName().equals(liveRevisionName)) { revisionWorkflowElement.appendChild(doc.createTextNode(wfState + " (LIVE)")); } else { revisionWorkflowElement.appendChild(doc.createTextNode(wfState)); } } } /** * Append individual revisions to meta document * @param revisionsEl Parent revisions DOM element * @param ri Detailed information about this particular revision */ private Element appendRevision(Element revisionsEl, RevisionInformation ri, UserManager userManager) { Document doc = revisionsEl.getOwnerDocument(); Element revisionElement = (Element) revisionsEl.appendChild(doc.createElement("revision")); log.debug("Revision: " + ri.getName()); revisionElement.appendChild(XMLHelper.createTextElement(doc, "name", ri.getName(), null)); log.debug("Date: " + ri.getDate()); revisionElement.appendChild(XMLHelper.createTextElement(doc, "date", "" + ri.getDate(), null)); if (ri.getUser() != null) { log.debug("User ID: " + ri.getUser()); revisionElement.appendChild(XMLHelper.createTextElement(doc, "user", ri.getUser(), null)); try { revisionElement.appendChild(XMLHelper.createTextElement(doc, "user-name", userManager.getUser(ri.getUser()).getName(), null)); } catch(Exception e) { log.warn(e, e); } } else { revisionElement.appendChild(doc.createElement("no-user")); } if (ri.getComment() != null) { log.debug("Comment: " + ri.getComment()); revisionElement.appendChild(XMLHelper.createTextElement(doc, "comment", ri.getComment(), null)); } else { revisionElement.appendChild(doc.createElement("no-comment")); } return revisionElement; } /** * Check whether mime type is html, pdf or video * @param mt Mime type */ private boolean isMimeTypeOk(String mt) { // TODO: Add more mime types or rather make it configurable // INFO: Only HTML pages and PDFs etc. should be logged, but no images, CSS, etc. Check the mime-type instead the suffix or use JavaScript or Pixel if (mt.indexOf("html") > 0 || mt.indexOf("pdf") > 0 || mt.indexOf("video") >= 0) { return true; } return false; } /** * Get workflow exception */ private static String getWorkflowException(String message) { StringBuilder sb = new StringBuilder(); sb.append("<?xml version=\"1.0\"?>"); sb.append("<exception xmlns=\"" + org.wyona.yanel.core.workflow.Workflow.NAMESPACE + "\" type=\"" + "workflow" + "\">"); sb.append("<message>" + message + "</message>"); sb.append("</exception>"); return sb.toString(); } /** * Check whether user agent is mobile device and if so, then set mobile flag inside session */ private void doMobile(HttpServletRequest request) { HttpSession session = request.getSession(true); String mobileDevice = (String) session.getAttribute(MOBILE_KEY); if (detectMobilePerRequest || mobileDevice == null) { String userAgent = request.getHeader("User-Agent"); if (userAgent == null) { // log.warn("No user agent available!"); return; } //log.debug("User agent: " + userAgent); // INFO: In order to get the screen size/resolution please see for example http://www.coderanch.com/t/229905/JME/Mobile/Getting-Screen-size-requesting-mobile, whereas the below does not seem to work! //log.debug("User agent screen: " + request.getHeader("UA-Pixels")); // INFO: UA-Pixels, UA-Color, UA-OS, UA-CPU // TBD: Use lower case for comparing device names...whereas please note that we already set the device name inside the session and hence this might be used somewhere and hence create backwards compatibility issues! session.setAttribute(YanelServlet.MOBILE_KEY, "false"); // INFO: First assume user agent is not a mobile device... for (int i = 0; i < mobileDevices.length; i++) { if (matchesMobileDevice(userAgent, mobileDevices[i])) { session.setAttribute(YanelServlet.MOBILE_KEY, mobileDevices[i]); //log.debug("This seems to be a mobile device: " + mobileDevices[i]); break; } } /* if (((String)session.getAttribute(YanelServlet.MOBILE_KEY)).equals("false")) { log.debug("This does not seem to be a mobile device: " + userAgent); } */ } else { //log.debug("Mobile device detection already done."); } } /** * Check whether user agent matches mobile device * @param userAgent User agent, e.g. 'Mozilla/5.0 (Linux; U; Android 2.2.1; en-us; Nexus One Build/FRG83) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1' * @param mobileDevice Mobile device name, e.g. 'iPhone'. One can also specify a combination of words, e.g. 'Android AND Mobile' */ private boolean matchesMobileDevice(String userAgent, String mobileDevice) { // TBD: Use http://wurfl.sourceforge.net/njava/, http://www.cloudfour.com/comparative-speed-of-wurfl-and-device-atlas/, http://www.id.uzh.ch/zinfo/mobileview.html if (mobileDevice.indexOf("AND") > 0) { String[] tokens = org.springframework.util.StringUtils.delimitedListToStringArray(mobileDevice, "AND"); for (int i = 0; i < tokens.length; i++) { String token = tokens[i].trim(); //log.debug("Try to match '" + token + "'..."); if (userAgent.indexOf(token) < 0) { return false; } } return true; } else { if (userAgent.indexOf(mobileDevice) > 0) { return true; } else { return false; } } } /** * Append annotations of resource to page meta document * @param doc Page meta document * @param resource Resource which might has some annotations */ private void appendAnnotations(Document doc, Resource resource) { if (ResourceAttributeHelper.hasAttributeImplemented(resource, "Annotatable", "1")) { AnnotatableV1 anno = (AnnotatableV1) resource; try { String[] tags = anno.getAnnotations(); if (tags != null && tags.length > 0) { //log.debug("Resource has tags: " + tags); Element annotationsElem = doc.createElementNS(NAMESPACE, "annotations"); doc.getDocumentElement().appendChild(annotationsElem); for (int i = 0; i < tags.length; i++) { Element annotationElem = doc.createElementNS(NAMESPACE, "annotation"); annotationElem.appendChild(doc.createTextNode(tags[i])); annotationsElem.appendChild(annotationElem); } } else { Element noAnnotationsYetElem = doc.createElementNS(NAMESPACE, "no-annotations-yet"); noAnnotationsYetElem.setAttribute("annotatable-v1", "true"); doc.getDocumentElement().appendChild(noAnnotationsYetElem); } } catch (Exception ex) { log.error(ex, ex); } } else { if (log.isDebugEnabled()) { log.debug("Resource has no tags yet: " + resource.getPath()); } Element noAnnotationsYetElem = doc.createElementNS(NAMESPACE, "no-annotations-yet"); noAnnotationsYetElem.setAttribute("annotatable-v1", "false"); doc.getDocumentElement().appendChild(noAnnotationsYetElem); } } /** * Append tracking information of resource to page meta document * @param doc Page meta document */ private void appendTrackingInformation(Document doc, TrackingInformationV1 trackInfo) { if (trackInfo != null) { Element trackInfoElem = doc.createElementNS(NAMESPACE, "tracking-info"); doc.getDocumentElement().appendChild(trackInfoElem); String[] trackingTags = trackInfo.getTags(); if (trackingTags != null && trackingTags.length > 0) { Element interestsElem = doc.createElementNS(NAMESPACE, "interests"); trackInfoElem.appendChild(interestsElem); for (int i = 0; i < trackingTags.length; i++) { Element interestElem = doc.createElementNS(NAMESPACE, "interest"); interestElem.appendChild(doc.createTextNode(trackingTags[i])); interestsElem.appendChild(interestElem); } } else { Element noInterestsElem = doc.createElementNS(NAMESPACE, "no-interests-yet"); trackInfoElem.appendChild(noInterestsElem); } String pageType = trackInfo.getPageType(); if (pageType != null) { Element pageTypeElem = doc.createElementNS(NAMESPACE, "page-type"); pageTypeElem.appendChild(doc.createTextNode(pageType)); trackInfoElem.appendChild(pageTypeElem); } String requestAction = trackInfo.getRequestAction(); if (requestAction != null) { Element requestActionElem = doc.createElementNS(NAMESPACE, "request-action"); requestActionElem.appendChild(doc.createTextNode(requestAction)); trackInfoElem.appendChild(requestActionElem); } HashMap<String, String> customFields = trackInfo.getCustomFields(); if (customFields != null) { Element customFieldsElem = doc.createElementNS(NAMESPACE, "custom-fields"); trackInfoElem.appendChild(customFieldsElem); for (java.util.Map.Entry field : customFields.entrySet()) { Element fieldElem = doc.createElementNS(NAMESPACE, "field"); fieldElem.setAttribute("name", (String) field.getKey()); fieldElem.setAttribute("value", (String) field.getValue()); customFieldsElem.appendChild(fieldElem); } } } else { log.debug("No tracking information."); Element noTrackInfoElem = doc.createElementNS(NAMESPACE, "no-tracking-information"); doc.getDocumentElement().appendChild(noTrackInfoElem); } } /** * Determine requested view ID (try to get it from session or query string) */ private String getViewID(HttpServletRequest request) { String viewId = null; String viewIdFromSession = (String) request.getSession(true).getAttribute(VIEW_ID_PARAM_NAME); if (viewIdFromSession != null) { //log.debug("It seems like the view id is set inside session: " + viewIdFromSession); viewId = viewIdFromSession; } if (request.getParameter(VIEW_ID_PARAM_NAME) != null) { viewId = request.getParameter(VIEW_ID_PARAM_NAME); } if (request.getParameter("yanel.format") != null) { // backwards compatible viewId = request.getParameter("yanel.format"); log.warn("For backwards compatibility reasons also consider parameter 'yanel.format', but which is deprecated. Please use '" + VIEW_ID_PARAM_NAME + "' instead."); } //log.debug("Tried to get view id from query string or session attribute: " + viewId); return viewId; } /** * Check whether access logging makes sense * @param mimeType Content type of requested resource * @param resource Resource/controller handling request */ private boolean logAccessIsApplicable(String mimeType, Resource resource) { if(logAccessEnabled) { if (isTrackable(resource) || (mimeType != null && isMimeTypeOk(mimeType))) { return true; } else { if (logDoNotTrack.isDebugEnabled()) { logDoNotTrack.debug("Resource '" + resource.getPath() + "' is neither trackable nor a mime type '" + mimeType + "' which makes sense, hence do not track."); } return false; } } else { if (logDoNotTrack.isDebugEnabled()) { logDoNotTrack.debug("Tracking disabled globally."); } return false; } } /** * Check whether a resource/controller is trackable * @param resource Resource/controller which might has the trackable interface implemented */ private boolean isTrackable(Resource resource) { boolean isTrackable = ResourceAttributeHelper.hasAttributeImplemented(resource, "Trackable", "1"); if (isTrackable) { return true; } else { //logDoNotTrack.debug("Resource '" + resource.getPath() + "' has trackable interface not implemented."); return false; } } /** * Clean meta document */ private void cleanMetaDoc(Document doc) { Element rootElem = doc.getDocumentElement(); org.w3c.dom.NodeList children = rootElem.getChildNodes(); for (int i = children.getLength() - 1; i >= 0; i--) { rootElem.removeChild(children.item(i)); } } /** * Get tags from annotatable resource * @param resource Resource which might provide annotations * @param servletPath Servlet path of requested resource * @return tags/annotations if resource is annotatable, null otherwise */ private String[] getTagsFromAnnotatableResource(Resource resource, String servletPath) { String[] tags = null; if (resource != null) { if (ResourceAttributeHelper.hasAttributeImplemented(resource, "Annotatable", "1")) { AnnotatableV1 anno = (AnnotatableV1) resource; try { tags = anno.getAnnotations(); if (tags != null) { log.debug("Resource '" + resource.getPath() + "' (Servlet path: " + servletPath + ") has '" + tags.length + "' tags."); } } catch (Exception ex) { log.error(ex, ex); } } else { if (log.isDebugEnabled()) { log.debug("Resource has no tags yet: " + resource.getPath()); } } } else { log.debug("Resource is null because access was probably denied or not necessarily initialized: " + servletPath); } return tags; } /** * Get client address of user * @param request Client request * @return original client IP address, e.g. 'TODO' */ private String getClientAddressOfUser(HttpServletRequest request) { String remoteIPAddr = request.getHeader("X-FORWARDED-FOR"); if (remoteIPAddr != null) { // INFO: We do not need to check realm.isProxySet() additionally, because some deployments are using a proxy without having set the Yanel proxy configuration, hence it is sufficient to just check whether an X-FORWARDED-FOR header is set if (remoteIPAddr.indexOf("unknown") >= 0) { log.warn("TODO: Clean remote IP address: " + remoteIPAddr); } } else { if (log.isDebugEnabled()) { log.debug("No such request header: X-FORWARDED-FOR (hence fallback to request.getRemoteAddr())"); // INFO: For example in the case of AJP or if no proxy is used } remoteIPAddr = request.getRemoteAddr(); // INFO: For performance reasons we do not use getRemoteHost(), but rather just use the IP address. } // TODO: What about ", 198.240.213.22, 146.67.140.72" if (remoteIPAddr.indexOf(",") > 0) { // INFO: Comma separated addresses, like for example '172.21.126.179, 89.250.145.138' (see Format of X-Forwarded-For at http://en.wikipedia.org/wiki/X-Forwarded-For) String firstAddress = remoteIPAddr.split(",")[0].trim(); //log.debug("Use the first IP address '" + firstAddress + "' of comma separated list '" + remoteIPAddr + "' ..."); return firstAddress; } else { return remoteIPAddr; } } /** * Generate unique fish tag, such that one can debug individual users * @param request Request containing client ip and session id * @return unique fishtag, e.g. '127.0.0.1_F3194' */ private String getFishTag(HttpServletRequest request) { return getClientAddressOfUser(request) + "_" + request.getSession(true).getId().substring(0, 4); // TBD: org.wyona.yanel.impl.resources.sessionmanager.SessionManagerResource#hashSessionID(String) } /** * Check whether request is a CAS single sign out request (https://wiki.jasig.org/display/casum/single+sign+out#SingleSignOut-Howitworks) * @return true when request is a CAS single sign out request and false otherwise */ private boolean isCASLogoutRequest(HttpServletRequest request) { // INFO: Also see org.wyona.yanel.impl.resources.CASLogoutMatcher if (METHOD_POST.equals(request.getMethod()) && request.getParameter(CAS_LOGOUT_REQUEST_PARAM_NAME) != null) { return true; } else { return false; } } }
src/webapp/src/java/org/wyona/yanel/servlet/YanelServlet.java
/* * See the NOTICE.txt file distributed with * this work for additional information regarding copyright ownership. * Wyona 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.wyona.yanel.servlet; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.net.URL; import java.util.Calendar; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.xml.transform.Source; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.sax.SAXResult; import javax.xml.transform.sax.SAXTransformerFactory; import javax.xml.transform.sax.TransformerHandler; import javax.xml.transform.stream.StreamSource; import org.wyona.commons.xml.XMLHelper; import org.wyona.neutron.XMLExceptionV1; import org.wyona.yanel.core.Environment; import org.wyona.yanel.core.Path; import org.wyona.yanel.core.Resource; import org.wyona.yanel.core.ResourceConfiguration; import org.wyona.yanel.core.ResourceNotFoundException; import org.wyona.yanel.core.ResourceTypeIdentifier; import org.wyona.yanel.core.ResourceTypeRegistry; import org.wyona.yanel.core.StateOfView; import org.wyona.yanel.core.ToolbarState; import org.wyona.yanel.core.Yanel; import org.wyona.yanel.core.api.attributes.AnnotatableV1; import org.wyona.yanel.core.api.attributes.IntrospectableV1; import org.wyona.yanel.core.api.attributes.DeletableV1; import org.wyona.yanel.core.api.attributes.ModifiableV1; import org.wyona.yanel.core.api.attributes.ModifiableV2; import org.wyona.yanel.core.api.attributes.TranslatableV1; import org.wyona.yanel.core.api.attributes.VersionableV1; import org.wyona.yanel.core.api.attributes.VersionableV2; import org.wyona.yanel.core.api.attributes.VersionableV3; import org.wyona.yanel.core.api.attributes.ViewableV1; import org.wyona.yanel.core.api.attributes.ViewableV2; import org.wyona.yanel.core.api.attributes.WorkflowableV1; import org.wyona.yanel.core.api.security.WebAuthenticator; import org.wyona.yanel.core.attributes.versionable.RevisionInformation; import org.wyona.yanel.core.attributes.viewable.View; import org.wyona.yanel.core.attributes.viewable.ViewDescriptor; import org.wyona.yanel.core.attributes.tracking.TrackingInformationV1; import org.wyona.yanel.core.navigation.Node; import org.wyona.yanel.core.navigation.Sitetree; import org.wyona.yanel.core.serialization.SerializerFactory; import org.wyona.yanel.core.source.SourceResolver; import org.wyona.yanel.core.source.YanelStreamSource; import org.wyona.yanel.core.transformation.I18nTransformer2; import org.wyona.yanel.core.util.ConfigurationUtil; import org.wyona.yanel.core.util.DateUtil; import org.wyona.yanel.core.util.HttpServletRequestHelper; import org.wyona.yanel.core.workflow.Transition; import org.wyona.yanel.core.workflow.Workflow; import org.wyona.yanel.core.workflow.WorkflowException; import org.wyona.yanel.core.workflow.WorkflowHelper; import org.wyona.yanel.core.map.Map; import org.wyona.yanel.core.map.Realm; import org.wyona.yanel.core.map.ReverseProxyConfig; import org.wyona.yanel.core.util.ResourceAttributeHelper; import org.wyona.yanel.impl.resources.BasicGenericExceptionHandlerResource; import org.wyona.yanel.servlet.IdentityMap; import org.wyona.yanel.servlet.communication.HttpRequest; import org.wyona.yanel.servlet.communication.HttpResponse; import org.wyona.yanel.servlet.security.impl.AutoLogin; import org.wyona.security.core.api.Identity; import org.wyona.security.core.api.Usecase; import org.wyona.security.core.api.User; import org.wyona.security.core.api.UserManager; import org.apache.log4j.Logger; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.ThreadContext; import org.apache.xalan.transformer.TransformerIdentityImpl; import org.apache.xml.resolver.tools.CatalogResolver; import org.apache.xml.serializer.Serializer; import org.apache.avalon.framework.configuration.Configuration; import org.apache.avalon.framework.configuration.DefaultConfiguration; import org.apache.avalon.framework.configuration.DefaultConfigurationBuilder; import org.apache.avalon.framework.configuration.DefaultConfigurationSerializer; import org.apache.avalon.framework.configuration.MutableConfiguration; import org.apache.commons.io.FilenameUtils; //import org.apache.commons.io.IOUtils; import org.apache.commons.io.output.ByteArrayOutputStream; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.quartz.JobDetail; import org.quartz.Scheduler; import org.quartz.SimpleTrigger; import org.quartz.Trigger; import org.quartz.impl.StdSchedulerFactory; /** * Main entry point of Yanel webapp (see method 'service') */ public class YanelServlet extends HttpServlet { private static org.apache.logging.log4j.Logger log = LogManager.getLogger(YanelServlet.class); private static Logger logAccess = Logger.getLogger(AccessLog.CATEGORY); private static Logger logDoNotTrack = Logger.getLogger("DoNotTrack"); // INFO: For debugging only! private static Logger log404 = Logger.getLogger("404"); private Map map; private Yanel yanelInstance; private Sitetree sitetree; private long MEMORY_GROWTH_THRESHOLD = 300; private String defaultXsltInfoAndException; private String xsltLoginScreenDefault; private boolean displayMostRecentVersion = true; public static final String MOBILE_KEY = "yanel.mobile"; public static final String IDENTITY_MAP_KEY = "identity-map"; private static final String TOOLBAR_USECASE = "toolbar"; //TODO is this the same as YanelAuthoringUI.TOOLBAR_KEY? public static final String NAMESPACE = "http://www.wyona.org/yanel/1.0"; private static final String METHOD_PROPFIND = "PROPFIND"; private static final String METHOD_OPTIONS = "OPTIONS"; private static final String METHOD_GET = "GET"; private static final String METHOD_POST = "POST"; private static final String METHOD_PUT = "PUT"; private static final String METHOD_DELETE = "DELETE"; private static final String HTTP_REFERRER = "Referer"; // ah, misspellings, how I hate thee (http://en.wikipedia.org/wiki/Referer)! private String sslPort = null; private String toolbarMasterSwitch = "off"; private String reservedPrefix; private String servletContextRealPath; private int cacheExpires = 0; private YanelHTMLUI yanelUI; private boolean logAccessEnabled = false; private boolean detectMobilePerRequest = false; public static final String DEFAULT_ENCODING = "UTF-8"; public static final String YANEL_ACCESS_POLICY_USECASE = "yanel.policy"; public static final String YANEL_USECASE = "yanel.usecase"; public static final String YANEL_RESOURCE = "yanel.resource"; public static final String YANEL_RESOURCE_USECASE = YANEL_RESOURCE + ".usecase"; public static final String YANEL_RESOURCE_REVISION = YANEL_RESOURCE + ".revision"; public static final String YANEL_RESOURCE_WORKFLOW_TRANSITION = YANEL_RESOURCE + ".workflow.transition"; public static final String YANEL_RESOURCE_WORKFLOW_TRANSITION_OUTPUT = YANEL_RESOURCE_WORKFLOW_TRANSITION + ".output"; public static final String VIEW_ID_PARAM_NAME = "yanel.resource.viewid"; public static final String RESOURCE_META_ID_PARAM_NAME = "yanel.resource.meta"; public static final String RELEASE_LOCK = "release-lock"; private static final String CONTENT_TYPE_XHTML = "xhtml"; public static final String YANEL_LAST_ACCESS_ATTR = "_yanel-last-access"; private Scheduler scheduler; private String[] mobileDevices; private static String ACCESS_LOG_TAG_SEPARATOR; private static final String REVISIONS_TAG_NAME = "revisions"; private static final String NO_REVISIONS_TAG_NAME = "no-revisions-yet"; private static final String EXCEPTION_TAG_NAME = "exception"; private static final String CAS_LOGOUT_REQUEST_PARAM_NAME = "logoutRequest"; /** * @see javax.servlet.GenericServlet#init(ServletConfig) */ @Override public void init(ServletConfig config) throws ServletException { servletContextRealPath = config.getServletContext().getRealPath("/"); if (config.getInitParameter("memory.growth.threshold") != null) { MEMORY_GROWTH_THRESHOLD = new Long(config.getInitParameter("memory.growth.threshold")).longValue(); } defaultXsltInfoAndException = config.getInitParameter("exception-and-info-screen-xslt"); xsltLoginScreenDefault = config.getInitParameter("login-screen-xslt"); displayMostRecentVersion = new Boolean(config.getInitParameter("workflow.not-live.most-recent-version")).booleanValue(); try { yanelInstance = Yanel.getInstance(); yanelInstance.init(); // TODO: Tell Yanel about alternative directory to look for configuration files, e.g. (File) getServletContext().getAttribute("javax.servlet.context.tempdir") map = yanelInstance.getMapImpl("map"); sitetree = yanelInstance.getSitetreeImpl("repo-navigation"); sslPort = config.getInitParameter("ssl-port"); toolbarMasterSwitch = config.getInitParameter("toolbar-master-switch"); reservedPrefix = yanelInstance.getReservedPrefix(); String expires = config.getInitParameter("static-content-cache-expires"); if (expires != null) { this.cacheExpires = Integer.parseInt(expires); } yanelUI = new YanelHTMLUI(map, reservedPrefix); // TODO: Make this value configurable also per realm or per individual user! logAccessEnabled = new Boolean(config.getInitParameter("log-access")).booleanValue(); String TAG_SEP_PARAM_NAME = "access-log-tag-separator"; if (config.getInitParameter(TAG_SEP_PARAM_NAME) != null) { if (config.getInitParameter(TAG_SEP_PARAM_NAME).equals("SPACE")) { // Note that the leading and trailing space around the parameter value is trimmed, hence we denote the space sign by SPACE. ACCESS_LOG_TAG_SEPARATOR = " "; } else { ACCESS_LOG_TAG_SEPARATOR = config.getInitParameter(TAG_SEP_PARAM_NAME); } } else { ACCESS_LOG_TAG_SEPARATOR = ","; log.warn("No access log tag separator parameter '" + TAG_SEP_PARAM_NAME + "' configured, hence use default: " + ACCESS_LOG_TAG_SEPARATOR); } // TODO: Make this value configurable also per realm or per individual user! if (config.getInitParameter("detect-mobile-per-request") != null) { detectMobilePerRequest = new Boolean(config.getInitParameter("detect-mobile-per-request")).booleanValue(); } if (config.getInitParameter("mobile-devices") != null) { mobileDevices = org.springframework.util.StringUtils.tokenizeToStringArray(config.getInitParameter("mobile-devices"), ",", true, true); } else { mobileDevices = new String[]{"iPhone", "Android"}; log.error("No mobile devices configured! Please make sure to update your web.xml configuration file accordingly. Fallback to hard-coded list: " + mobileDevices); } if (yanelInstance.isSchedulerEnabled()) { try { log.debug("Startup scheduler ..."); scheduler = StdSchedulerFactory.getDefaultScheduler(); Realm[] realms = yanelInstance.getRealmConfiguration().getRealms(); for (int i = 0; i < realms.length; i++) { if (realms[i] instanceof org.wyona.yanel.core.map.RealmWithConfigurationExceptionImpl) { String eMessage = ((org.wyona.yanel.core.map.RealmWithConfigurationExceptionImpl) realms[i]).getConfigurationException().getMessage(); log.error("Realm '" + realms[i].getID() + "' has thrown a configuration exception: " + eMessage); } else { String schedulerJobsPath = "/scheduler-jobs.xml"; if (realms[i].getRepository().existsNode(schedulerJobsPath)) { log.debug("Scheduler jobs config found for realm: " + realms[i].getRepository().getID()); try { // Get and filter scheduler config InputStream istream = realms[i].getRepository().getNode(schedulerJobsPath).getInputStream(); log.debug("Filter scheduler configuration of realm '" + realms[i].getID() + "' by target environment '" + yanelInstance.getTargetEnvironment() + "'..."); istream = ConfigurationUtil.filterEnvironment(istream, yanelInstance.getTargetEnvironment()); Document filteredConfiguration = XMLHelper.readDocument(istream); // INFO: Debug filtered scheduler configuration if (log.isDebugEnabled()) { org.wyona.yarep.core.Node filteredConfigDebugNode = null; if (realms[i].getRepository().existsNode(schedulerJobsPath + ".DEBUG")) { filteredConfigDebugNode = realms[i].getRepository().getNode(schedulerJobsPath + ".DEBUG"); } else { filteredConfigDebugNode = org.wyona.yarep.util.YarepUtil.addNodes(realms[i].getRepository(), schedulerJobsPath + ".DEBUG", org.wyona.yarep.core.NodeType.RESOURCE); } XMLHelper.writeDocument(filteredConfiguration, filteredConfigDebugNode.getOutputStream()); } // INFO: Run scheduler util org.wyona.yanel.impl.scheduler.QuartzSchedulerUtil.schedule(scheduler, filteredConfiguration, realms[i]); } catch(Exception e) { log.error(e, e); // INFO: Log error, but otherwise ignore and keep going ... } } } } /* TODO: Make global scheduler jobs configurable String groupName = "yanel"; JobDetail jobDetail = new JobDetail("heartbeatJob", groupName, org.wyona.yanel.servlet.HeartbeatJob.class); Date startDate = new Date(); Date endDate = null; Trigger trigger = new SimpleTrigger("heartbeatTrigger", groupName, startDate, endDate, SimpleTrigger.REPEAT_INDEFINITELY, 60L * 1000L); scheduler.scheduleJob(jobDetail, trigger); */ scheduler.start(); } catch(Exception e) { log.error(e, e); // INFO: Let's be fault tolerant in case the scheduler should not start } } else { log.info("The scheduler is currently disabled."); } } catch (Exception e) { log.error(e.getMessage(), e); throw new ServletException(e.getMessage(), e); } } /** * @see javax.servlet.http.HttpServlet#service(HttpServletRequest, HttpServletResponse) */ @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // NOTE: Do not add code outside the try-catch block, because otherwise exceptions won't be logged try { Runtime rt = Runtime.getRuntime(); long usedMBefore = getUsedMemory(rt); //log.debug("Memory usage before request processed: " + usedMBefore); ThreadContext.put("id", getFishTag(request)); //String httpAcceptMediaTypes = request.getHeader("Accept"); //String httpAcceptLanguage = request.getHeader("Accept-Language"); if (isCASLogoutRequest(request)) { log.warn("DEBUG: CAS logout request received: " + request.getServletPath()); if (doCASLogout(request, response)) { return; } else { log.error("Logout based on CAS request failed!"); } return; } String yanelUsecase = request.getParameter(YANEL_USECASE); if (yanelUsecase != null && yanelUsecase.equals("logout")) { try { log.debug("Disable auto login..."); // TODO: The cookie is not always deleted! AutoLogin.disableAutoLogin(request, response, getRealm(request).getRepository()); } catch (Exception e) { log.error("Exception while disabling auto login: " + e.getMessage(), e); } // INFO: Logout from Yanel if (doLogout(request, response)) { return; } else { log.error("Logout failed!"); } } else if(yanelUsecase != null && yanelUsecase.equals("create")) { // TODO: Why does that not go through access control? // INFO: Create a new resource if(doCreate(request, response) != null) return; } // Check authorization and if authorization failed, then try to authenticate if (doAccessControl(request, response) != null) { // INFO: Either redirect (after successful authentication) or access denied (and response will contain the login screen) return; } else { if (log.isDebugEnabled()) log.debug("Access granted: " + request.getServletPath()); } // Check for requests re policies String policyRequestPara = request.getParameter(YANEL_ACCESS_POLICY_USECASE); if (policyRequestPara != null) { doAccessPolicyRequest(request, response, 1); return; } else if (yanelUsecase != null && yanelUsecase.equals("policy.read")) { doAccessPolicyRequest(request, response, 2); return; } // Check for requests for global data Resource resource = getResource(request, response); String path = resource.getPath(); if (path.indexOf("/" + reservedPrefix + "/") == 0) { getGlobalData(request, response); return; } String value = request.getParameter(YANEL_RESOURCE_USECASE); // Delete node if (value != null && value.equals("delete")) { handleDeleteUsecase(request, response); return; } // INFO: Check if user agent is mobile device doMobile(request); // Delegate ... String method = request.getMethod(); if (method.equals(METHOD_PROPFIND)) { doPropfind(request, response); } else if (method.equals(METHOD_GET)) { doGet(request, response); } else if (method.equals(METHOD_POST)) { doPost(request, response); } else if (method.equals(METHOD_PUT)) { doPut(request, response); } else if (method.equals(METHOD_DELETE)) { doDelete(request, response); } else if (method.equals(METHOD_OPTIONS)) { doOptions(request, response); } else { log.error("No such method implemented: " + method); response.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED); } long usedMAfter = getUsedMemory(rt); //log.debug("Memory usage after request processed: " + usedMAfter); if ((usedMAfter - usedMBefore) > MEMORY_GROWTH_THRESHOLD) { log.warn("Memory usage increased by '" + MEMORY_GROWTH_THRESHOLD + "' while request '" + getRequestURLQS(request, null, false) + "' was processed!"); } } catch (ServletException e) { log.error(e, e); throw new ServletException(e.getMessage(), e); } catch (IOException e) { log.error(e, e); throw new IOException(e.getMessage()); } finally { ThreadContext.clear(); } // NOTE: This was our last chance to log an exception, hence do not add code outside the try-catch block } /** * Get currently used memory */ private long getUsedMemory(Runtime rt) { return (rt.totalMemory() - rt.freeMemory()) / 1024 / 1024; } /** * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest, HttpServletResponse) */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // INFO: Init session in case it does not exist yet HttpSession session = request.getSession(true); // INFO: Enable or disable toolbar yanelUI.switchToolbar(request); // INFO: Handle workflow transitions String transition = request.getParameter(YANEL_RESOURCE_WORKFLOW_TRANSITION); if (transition != null) { executeWorkflowTransition(request, response, request.getParameter(YANEL_RESOURCE_REVISION), transition); return; } // INFO: Init resource Resource resource = getResource(request, response); // INFO: Check for requests refered by WebDAV String yanelWebDAV = request.getParameter("yanel.webdav"); if(yanelWebDAV != null && yanelWebDAV.equals("propfind1")) { log.info("WebDAV client (" + request.getHeader("User-Agent") + ") requests to \"edit\" a resource: " + resource.getRealm() + ", " + resource.getPath()); //return; } // INFO: Handle first specific Yanel usecase requests and then at the very end all other requests String value = request.getParameter(YANEL_RESOURCE_USECASE); try { if (value != null && value.equals(RELEASE_LOCK)) { log.warn("Try to release lock ..."); if (ResourceAttributeHelper.hasAttributeImplemented(resource, "Versionable", "2")) { VersionableV2 versionable = (VersionableV2)resource; String checkoutUserID = versionable.getCheckoutUserID(); Identity identity = getEnvironment(request, response).getIdentity(); String userID = identity.getUsername(); Usecase usecase = new Usecase(RELEASE_LOCK); String path = resource.getPath(); if (checkoutUserID.equals(userID) || resource.getRealm().getPolicyManager().authorize(path, identity, usecase)) { try { versionable.cancelCheckout(); log.debug("Lock has been released."); response.setStatus(HttpServletResponse.SC_OK); response.setContentType("text/html" + "; charset=" + "UTF-8"); String backToRealm = org.wyona.yanel.core.util.PathUtil.backToRealm(resource.getPath()); StringBuilder sb = new StringBuilder("<html xmlns=\"http://www.w3.org/1999/xhtml\"><body>Lock has been released! back to <a href=\""+backToRealm + resource.getPath() +"\">page</a>.</body></html>"); PrintWriter w = response.getWriter(); w.print(sb); return; } catch (Exception e) { throw new ServletException("Releasing the lock of <" + resource.getPath() + "> failed because of: " + e.getMessage(), e); } } else { String eMessage = "Releasing the lock of '" + resource.getPath() + "' failed because"; if (checkoutUserID.equals(userID)) { eMessage = " user '" + userID + "' has no right to release her/his own lock!"; } else { eMessage = " checkout user '" + checkoutUserID + "' and session user '" + userID + "' are not the same and session user '" + userID + "' has no right to release the lock of the checkout user '" + checkoutUserID + "'!"; } log.warn(eMessage); throw new ServletException(eMessage); } } else { throw new ServletException("Resource '" + resource.getPath() + "' is not VersionableV2!"); } } else if (value != null && value.equals("roll-back")) { log.debug("Roll back ..."); org.wyona.yanel.core.util.VersioningUtil.rollBack(resource, request.getParameter(YANEL_RESOURCE_REVISION), getIdentityFromRequest(request, map.getRealm(request.getServletPath())).getUsername()); // TODO: Send confirmation screen getContent(request, response); return; } else { //log.debug("Handle all other GET requests..."); getContent(request, response); return; } } catch (Exception e) { throw new ServletException(e.getMessage(), e); } } /** * Returns the mime-type according to the given file extension. * Default is application/octet-stream. * @param extension * @return */ private static String guessMimeType(String extension) { String ext = extension.toLowerCase(); if (ext.equals("html") || ext.equals("htm")) return "text/html"; if (ext.equals("css")) return "text/css"; if (ext.equals("txt")) return "text/plain"; if (ext.equals("js")) return "application/x-javascript"; if (ext.equals("jpg") || ext.equals("jpg")) return "image/jpeg"; if (ext.equals("gif")) return "image/gif"; if (ext.equals("pdf")) return "application/pdf"; if (ext.equals("zip")) return "application/zip"; if (ext.equals("htc")) return "text/x-component"; if (ext.equals("svg")) return "image/svg+xml"; // TODO: add more mime types // TODO: and move to MimeTypeUtil return "application/octet-stream"; // default } /** * Generate response from view of resource * @param request TODO * @param response TODO */ private void getContent(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // INFO: Generate "yanel" document in order to collect information in case something should go wrong or some meta information should be requested org.w3c.dom.Document doc = null; try { doc = getDocument(NAMESPACE, "yanel"); } catch (Exception e) { throw new ServletException(e.getMessage(), e); } Element rootElement = doc.getDocumentElement(); rootElement.setAttribute("servlet-context-real-path", servletContextRealPath); Element requestElement = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, "request")); requestElement.setAttributeNS(NAMESPACE, "uri", request.getRequestURI()); requestElement.setAttributeNS(NAMESPACE, "servlet-path", request.getServletPath()); HttpSession session = request.getSession(true); Element sessionElement = (Element) rootElement.appendChild(doc.createElement("session")); sessionElement.setAttribute("id", session.getId()); Enumeration<?> attrNames = session.getAttributeNames(); if (!attrNames.hasMoreElements()) { Element sessionNoAttributesElement = (Element) sessionElement.appendChild(doc.createElement("no-attributes")); } while (attrNames.hasMoreElements()) { String name = (String)attrNames.nextElement(); String value = session.getAttribute(name).toString(); Element sessionAttributeElement = (Element) sessionElement.appendChild(doc.createElement("attribute")); sessionAttributeElement.setAttribute("name", name); sessionAttributeElement.appendChild(doc.createTextNode(value)); } String usecase = request.getParameter(YANEL_RESOURCE_USECASE); Resource res = null; TrackingInformationV1 trackInfo = null; long lastModified = -1; long size = -1; // START first try View view = null; try { Environment environment = getEnvironment(request, response); res = getResource(request, response); if (res != null) { if (isTrackable(res)) { //log.debug("Do track: " + res.getPath()); trackInfo = new TrackingInformationV1(); ((org.wyona.yanel.core.api.attributes.TrackableV1) res).doTrack(trackInfo); //} else { // log.debug("Resource '" + res.getPath() + "' is not trackable."); } // START introspection generation if (usecase != null && usecase.equals("introspection")) { sendIntrospectionAsResponse(res, doc, rootElement, request, response); return; } // END introspection generation Element resourceElement = getResourceMetaData(res, doc, rootElement); Element viewElement = (Element) resourceElement.appendChild(doc.createElement("view")); if (ResourceAttributeHelper.hasAttributeImplemented(res, "Viewable", "1")) { if (log.isDebugEnabled()) log.debug("Resource is viewable V1"); viewElement.setAttributeNS(NAMESPACE, "version", "1"); appendViewDescriptors(doc, viewElement, ((ViewableV1) res).getViewDescriptors()); String viewId = getViewID(request); try { view = ((ViewableV1) res).getView(request, viewId); } catch (org.wyona.yarep.core.NoSuchNodeException e) { String message = e.getMessage(); log.error(message, e); do404(request, response, doc, message); return; } catch (Exception e) { String message = e.getMessage(); log.error(message, e); Element exceptionElement = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, EXCEPTION_TAG_NAME)); exceptionElement.appendChild(doc.createTextNode(message)); exceptionElement.setAttributeNS(NAMESPACE, "status", "500"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); setYanelOutput(request, response, doc); return; } } else if (ResourceAttributeHelper.hasAttributeImplemented(res, "Viewable", "2")) { if (log.isDebugEnabled()) log.debug("Resource '" + res.getPath() + "' is viewable V2"); viewElement.setAttributeNS(NAMESPACE, "version", "2"); appendViewDescriptors(doc, viewElement, ((ViewableV2) res).getViewDescriptors()); if (!((ViewableV2) res).exists()) { log.warn("ViewableV2 resource '" + res.getPath() + "' does not seem to exist, whereas this resource might not implement exists() properly. Yanel does not generate a 404 response for backwards compatibility reasons, because there are various ViewableV2 resources which do not implement exists() properly. As a workaround one might want to use the exists() method within the getView(String) method and throw a ResourceNotFoundException instead."); //do404(request, response, doc, res.getPath()); //return; } try { size = ((ViewableV2) res).getSize(); Element sizeElement = (Element) resourceElement.appendChild(doc.createElement("size")); sizeElement.appendChild(doc.createTextNode(String.valueOf(size))); } catch(ResourceNotFoundException e) { log.error(e, e); // INFO: Let's be fault tolerant such that a 404 can be handled more gracefully further down } String viewId = getViewID(request); try { String revisionName = request.getParameter(YANEL_RESOURCE_REVISION); // NOTE: Check also if usecase is not roll-back, because roll-back is also using the yanel.resource.revision if (revisionName != null && !isRollBack(request)) { if (ResourceAttributeHelper.hasAttributeImplemented(res, "Versionable", "2")) { view = ((VersionableV2) res).getView(viewId, revisionName); } else { log.warn("Resource '" + res.getPath() + "' has not VersionableV2 implemented, hence we cannot generate view for revision: " + revisionName); view = ((ViewableV2) res).getView(viewId); } } else if (environment.getStateOfView().equals(StateOfView.LIVE) && ResourceAttributeHelper.hasAttributeImplemented(res, "Workflowable", "1") && WorkflowHelper.getWorkflow(res) != null) { // TODO: Instead using the WorkflowHelper the Workflowable interface should have a method to check if the resource actually has a workflow assigned, see http://lists.wyona.org/pipermail/yanel-development/2009-June/003709.html // TODO: Check if resource actually exists (see the exist problem above), because even it doesn't exist, the workflowable interfaces can return something although it doesn't really make sense. For example if a resource type is workflowable, but it has no workflow associated with it, then WorkflowHelper.isLive will nevertheless return true, whereas WorkflowHelper.getLiveView will throw an exception! if (!((ViewableV2) res).exists()) { log.warn("No such ViewableV2 resource: " + res.getPath()); log.warn("TODO: It seems like many ViewableV2 resources are not implementing exists() properly!"); do404(request, response, doc, res.getPath()); return; } WorkflowableV1 workflowable = (WorkflowableV1)res; if (workflowable.isLive()) { view = workflowable.getLiveView(viewId); } else { String message = "The viewable (V2) resource '" + res.getPath() + "' is WorkflowableV1, but has not been published yet."; log.warn(message); // TODO: Make this configurable per resource (or rather workflowable interface) or per realm?! if (displayMostRecentVersion) { // INFO: Because of backwards compatibility the default should display the most recent version log.warn("Instead a live/published version, the most recent version will be displayed!"); view = ((ViewableV2) res).getView(viewId); } else { log.warn("Instead a live/published version, a 404 will be displayed!"); // TODO: Instead a 404 one might want to show a different kind of screen do404(request, response, doc, message); return; } } } else { view = ((ViewableV2) res).getView(viewId); } } catch (org.wyona.yarep.core.NoSuchNodeException e) { String message = e.getMessage(); log.warn(message, e); do404(request, response, doc, message); return; } catch (ResourceNotFoundException e) { String message = e.getMessage(); log.warn(message, e); do404(request, response, doc, message); return; } catch(Exception e) { log.error(e, e); handleException(request, response, e); return; } } else { // NO Viewable interface implemented! String message = res.getClass().getName() + " is not viewable! (" + res.getPath() + ", " + res.getRealm() + ")"; log.error(message); Element noViewElement = (Element) resourceElement.appendChild(doc.createElement("not-viewable")); noViewElement.appendChild(doc.createTextNode(res.getClass().getName() + " is not viewable!")); Element exceptionElement = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, EXCEPTION_TAG_NAME)); exceptionElement.appendChild(doc.createTextNode(message)); exceptionElement.setAttributeNS(NAMESPACE, "status", "501"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_NOT_IMPLEMENTED); setYanelOutput(request, response, doc); return; } if (ResourceAttributeHelper.hasAttributeImplemented(res, "Modifiable", "2")) { lastModified = ((ModifiableV2) res).getLastModified(); Element lastModifiedElement = (Element) resourceElement.appendChild(doc.createElement("last-modified")); lastModifiedElement.appendChild(doc.createTextNode(new Date(lastModified).toString())); } else { Element noLastModifiedElement = (Element) resourceElement.appendChild(doc.createElement("no-last-modified")); } // INFO: Get the revisions, but only in the meta usecase (because of performance reasons) if (request.getParameter(RESOURCE_META_ID_PARAM_NAME) != null) { appendRevisionsAndWorkflow(doc, resourceElement, res, request); } if (ResourceAttributeHelper.hasAttributeImplemented(res, "Translatable", "1")) { TranslatableV1 translatable = ((TranslatableV1) res); Element translationsElement = (Element) resourceElement.appendChild(doc.createElement("translations")); String[] languages = translatable.getLanguages(); for (int i=0; i<languages.length; i++) { Element translationElement = (Element) translationsElement.appendChild(doc.createElement("translation")); translationElement.setAttribute("language", languages[i]); String path = translatable.getTranslation(languages[i]).getPath(); translationElement.setAttribute("path", path); } } if (usecase != null && usecase.equals("checkout")) { if(log.isDebugEnabled()) log.debug("Checkout data ..."); if (ResourceAttributeHelper.hasAttributeImplemented(res, "Versionable", "2")) { // NOTE: The code below will throw an exception if the document is checked out already by another user. String userID = environment.getIdentity().getUsername(); VersionableV2 versionable = (VersionableV2)res; if (versionable.isCheckedOut()) { String checkoutUserID = versionable.getCheckoutUserID(); if (checkoutUserID.equals(userID)) { log.warn("Resource " + res.getPath() + " is already checked out by this user: " + checkoutUserID); } else { if (isClientSupportingNeutron(request)) { String eMessage = "Resource '" + res.getPath() + "' is already checked out by another user: " + checkoutUserID; response.setContentType("application/xml"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); // TODO: Checkout date and break-lock (optional) response.getWriter().print(XMLExceptionV1.getCheckoutException(eMessage, res.getPath(), checkoutUserID, null)); return; } else { throw new Exception("Resource '" + res.getPath() + "' is already checked out by another user: " + checkoutUserID); } } } else { versionable.checkout(userID); } } else { log.warn("Acquire lock has not been implemented yet ...!"); // acquireLock(); } } } else { Element resourceIsNullElement = (Element) rootElement.appendChild(doc.createElement("resource-is-null")); } } catch (org.wyona.yarep.core.NoSuchNodeException e) { String message = e.getMessage(); log.warn(message, e); do404(request, response, doc, message); return; } catch (org.wyona.yanel.core.ResourceNotFoundException e) { String message = e.getMessage(); log.warn(message, e); do404(request, response, doc, message); return; } catch (Exception e) { log.error(e, e); handleException(request, response, e); return; } // END first try String meta = request.getParameter(RESOURCE_META_ID_PARAM_NAME); if (meta != null) { if (meta.length() > 0) { if (meta.equals("annotations")) { log.debug("Remove everything from the page meta document except the annotations"); cleanMetaDoc(doc); appendAnnotations(doc, res); appendTrackingInformation(doc, trackInfo); } else { log.warn("TODO: Stripping everything from page meta document but, '" + meta + "' not supported!"); } } else { log.debug("Show all meta"); appendAnnotations(doc, res); appendTrackingInformation(doc, trackInfo); } response.setStatus(javax.servlet.http.HttpServletResponse.SC_OK); setYanelOutput(request, response, doc); return; } if (view != null) { if (generateResponse(view, res, request, response, -1, doc, size, lastModified, trackInfo) != null) { //log.debug("Response has been generated successfully :-)"); return; } else { log.warn("No response has been generated!"); } } else { String message = "View is null!"; Element exceptionElement = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, EXCEPTION_TAG_NAME)); exceptionElement.appendChild(doc.createTextNode(message)); } response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); setYanelOutput(request, response, doc); return; } /** * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest, HttpServletResponse) */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String transition = request.getParameter(YANEL_RESOURCE_WORKFLOW_TRANSITION); if (transition != null) { executeWorkflowTransition(request, response, request.getParameter(YANEL_RESOURCE_REVISION), transition); return; } String value = request.getParameter(YANEL_RESOURCE_USECASE); if (value != null && value.equals("save")) { log.debug("Save data ..."); save(request, response, false); return; } else if (value != null && value.equals("checkin")) { log.debug("Checkin data ..."); save(request, response, true); log.warn("Release lock has not been implemented yet ..."); // releaseLock(); return; } else { log.info("No parameter " + YANEL_RESOURCE_USECASE + "!"); String contentType = request.getContentType(); // TODO: Check for type (see section 9.2 of APP spec (e.g. draft 16) if (contentType != null && contentType.indexOf("application/atom+xml") >= 0) { InputStream in = intercept(request.getInputStream()); // Create new Atom entry try { String atomEntryUniversalName = "<{http://www.wyona.org/yanel/resource/1.0}atom-entry/>"; Realm realm = yanelInstance.getMap().getRealm(request.getServletPath()); String newEntryPath = yanelInstance.getMap().getPath(realm, request.getServletPath() + "/" + new Date().getTime() + ".xml"); log.debug("Realm and Path of new Atom entry: " + realm + " " + newEntryPath); Resource atomEntryResource = yanelInstance.getResourceManager().getResource(getEnvironment(request, response), realm, newEntryPath, new ResourceTypeRegistry().getResourceTypeDefinition(atomEntryUniversalName), new ResourceTypeIdentifier(atomEntryUniversalName, null)); ((ModifiableV2)atomEntryResource).write(in); byte buffer[] = new byte[8192]; int bytesRead; InputStream resourceIn = ((ModifiableV2)atomEntryResource).getInputStream(); OutputStream responseOut = response.getOutputStream(); while ((bytesRead = resourceIn.read(buffer)) != -1) { responseOut.write(buffer, 0, bytesRead); } resourceIn.close(); //responseOut.close(); // TODO: Fix Location ... response.setHeader("Location", "http://ulysses.wyona.org" + newEntryPath); response.setStatus(javax.servlet.http.HttpServletResponse.SC_CREATED); return; } catch (Exception e) { throw new ServletException(e.getMessage(), e); } } // Enable or disable toolbar yanelUI.switchToolbar(request); getContent(request, response); } } /** * Perform the given transition on the indicated revision. * @param request TODO * @param response TODO * @param revision TODO * @param transitionID Workflow transition ID * @throws ServletException * @throws IOException */ private void executeWorkflowTransition(HttpServletRequest request, HttpServletResponse response, String revision, String transitionID) throws ServletException, IOException { Resource resource = getResource(request, response); if (ResourceAttributeHelper.hasAttributeImplemented(resource, "Workflowable", "1")) { WorkflowableV1 workflowable = (WorkflowableV1)resource; try { String outputFormat = request.getParameter(YANEL_RESOURCE_WORKFLOW_TRANSITION_OUTPUT); StringBuilder sb = null; workflowable.doTransition(transitionID, revision); response.setStatus(javax.servlet.http.HttpServletResponse.SC_OK); if (outputFormat != null && CONTENT_TYPE_XHTML.equals(outputFormat.toLowerCase())) { Workflow workflow = WorkflowHelper.getWorkflow(resource); Transition transition = workflow.getTransition(transitionID); String description = transitionID; try { description = transition.getDescription(getLanguage(request, "en")); } catch(Exception e) { log.error(e, e); } response.setContentType("text/html; charset=" + DEFAULT_ENCODING); sb = new StringBuilder("<html xmlns=\"http://www.w3.org/1999/xhtml\"><head><meta http-equiv=\"refresh\" content=\"3;URL='" + request.getHeader(HTTP_REFERRER) + "'\"></head><body><div style=\"text-align: center; font-family: sans-serif;\"><p>&#160;<br/>&#160;<br/>The workflow transition <strong style=\"background-color: #dff0d8;\">&#160;" + description + "&#160;</strong> has been performed.</p><p>Return to <a href=\"" + request.getHeader(HTTP_REFERRER) + "\">the page</a>.</p></div></body></html>"); } else { log.warn("DEBUG: No output format query string parameter '" + YANEL_RESOURCE_WORKFLOW_TRANSITION_OUTPUT + "' has been specified."); response.setContentType("application/xml; charset=" + DEFAULT_ENCODING); sb = new StringBuilder("<?xml version=\"1.0\"?>"); sb.append(workflowable.getWorkflowIntrospection()); } PrintWriter w = response.getWriter(); w.print(sb); } catch (WorkflowException e) { log.error(e, e); response.setContentType("application/xml; charset=" + DEFAULT_ENCODING); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); PrintWriter w = response.getWriter(); w.print(getWorkflowException(e.getMessage())); return; } } else { log.warn("Resource not workflowable: " + resource.getPath()); } } /** * HTTP PUT implementation. */ @Override protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO: Reuse code doPost resp. share code with doPut String value = request.getParameter(YANEL_RESOURCE_USECASE); if (value != null && value.equals("save")) { log.debug("Save data ..."); save(request, response, false); return; } else if (value != null && value.equals("checkin")) { log.debug("Checkin data ..."); save(request, response, true); log.warn("Release lock has not been implemented yet ...!"); // releaseLock(); return; } else { log.debug("No parameter " + YANEL_RESOURCE_USECASE + "!"); String contentType = request.getContentType(); if (contentType != null && contentType.indexOf("application/atom+xml") >= 0) { InputStream in = intercept(request.getInputStream()); // Overwrite existing atom entry try { String atomEntryUniversalName = "<{http://www.wyona.org/yanel/resource/1.0}atom-entry/>"; Realm realm = yanelInstance.getMap().getRealm(request.getServletPath()); String entryPath = yanelInstance.getMap().getPath(realm, request.getServletPath()); log.debug("Realm and Path of new Atom entry: " + realm + " " + entryPath); Resource atomEntryResource = yanelInstance.getResourceManager().getResource(getEnvironment(request, response), realm, entryPath, new ResourceTypeRegistry().getResourceTypeDefinition(atomEntryUniversalName), new ResourceTypeIdentifier(atomEntryUniversalName, null)); // TODO: There seems to be a problem ... ((ModifiableV2)atomEntryResource).write(in); // NOTE: This method does not update updated date /* OutputStream out = ((ModifiableV2)atomEntry).getOutputStream(entryPath); byte buffer[] = new byte[8192]; int bytesRead; while ((bytesRead = in.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); } */ log.info("Atom entry has been saved: " + entryPath); response.setStatus(javax.servlet.http.HttpServletResponse.SC_OK); return; } catch (Exception e) { throw new ServletException(e.getMessage(), e); } } else { Resource resource = getResource(request, response); log.debug("Client (" + request.getHeader("User-Agent") + ") requests to save a resource: " + resource.getRealm() + ", " + resource.getPath()); // TODO: Check whether resource exists! save(request, response, false); return; } } } /** * @see javax.servlet.http.HttpServlet#doDelete(HttpServletRequest, HttpServletResponse); */ @Override protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO: generateResponseFromResourceView(request, response, javax.servlet.http.HttpServletResponse.SC_OK, res); try { Resource res = getResource(request, response); if (ResourceAttributeHelper.hasAttributeImplemented(res, "Modifiable", "2")) { if (((ModifiableV2) res).delete()) { // TODO: Also delete resource config! What about access policies?! log.debug("Resource '" + res + "' has been deleted via ModifiableV2 interface."); setResourceDeletedResponse(res, response); return; } else { log.warn("Deletable (or rather ModifiableV2) resource '" + res + "' could not be deleted!"); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } } else if (ResourceAttributeHelper.hasAttributeImplemented(res, "Deletable", "1")) { // TODO: Finish implementation, set resource input ((DeletableV1) res).delete(null); log.debug("Resource '" + res + "' has been deleted via DeletableV1 interface."); setResourceDeletedResponse(res, response); return; } else { log.error("Resource '" + res + "' has neither interface ModifiableV2 nor DeletableV1 implemented." ); response.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED); return; // QUESTION: According to the spec http://docs.oracle.com/javaee/1.4/api/javax/servlet/http/HttpServlet.html#doDelete%28javax.servlet.http.HttpServletRequest,%20javax.servlet.http.HttpServletResponse%29 one should rather throw a ServletException, right? } } catch (Exception e) { throw new ServletException("Could not delete resource with URL <" + request.getRequestURL() + ">: " + e.getMessage(), e); } } /** * */ private void setResourceDeletedResponse(Resource res, HttpServletResponse response) throws Exception { response.setStatus(HttpServletResponse.SC_OK); response.setContentType("text/html" + "; charset=" + "UTF-8"); String backToRealm = org.wyona.yanel.core.util.PathUtil.backToRealm(res.getPath()); StringBuilder sb = new StringBuilder("<html xmlns=\"http://www.w3.org/1999/xhtml\"><body>Page has been deleted! <a href=\"" + backToRealm + res.getPath().substring(1) +"\">Check</a> or return to <a href=\"" + backToRealm + "\">Homepage</a>.</body></html>"); PrintWriter w = response.getWriter(); w.print(sb); } /** * Resolve resource for a specific request */ private Resource getResource(HttpServletRequest request, HttpServletResponse response) throws ServletException { try { Realm realm = map.getRealm(request.getServletPath()); String path = map.getPath(realm, request.getServletPath()); HttpRequest httpRequest = (HttpRequest)request; HttpResponse httpResponse = new HttpResponse(response); Resource res = yanelInstance.getResourceManager().getResource(getEnvironment(httpRequest, httpResponse), realm, path); return res; } catch (Exception e) { log.error(e, e); throw new ServletException("Could not get resource for request <" + request.getServletPath() + ">: " + e.getMessage(), e); } } /** * Get environment containing identity , client request, etc. */ private Environment getEnvironment(HttpServletRequest request, HttpServletResponse response) throws ServletException { Identity identity; try { Realm realm = map.getRealm(request.getServletPath()); identity = getIdentityFromRequest(request, realm); String stateOfView = StateOfView.AUTHORING; if (yanelUI.isToolbarEnabled(request)) { // TODO: Is this the only criteria? stateOfView = StateOfView.AUTHORING; } else { stateOfView = StateOfView.LIVE; } //log.debug("State of view: " + stateOfView); Environment environment = new Environment(request, response, identity, stateOfView, null); if (yanelUI.isToolbarEnabled(request)) { // INFO: Please note that isToolbarEnabled() also checks whether toolbar is suppressed... environment.setToolbarState(ToolbarState.ON); } else if (yanelUI.isToolbarSuppressed(request)) { environment.setToolbarState(ToolbarState.SUPPRESSED); } else { environment.setToolbarState(ToolbarState.OFF); } return environment; } catch (Exception e) { throw new ServletException(e.getMessage(), e); } } /** * Save data * @param request TODO * @param response TODO * @param doCheckin TODO */ private void save(HttpServletRequest request, HttpServletResponse response, boolean doCheckin) throws ServletException, IOException { log.debug("Save data ..."); Resource resource = getResource(request, response); /* NOTE: Commented because the current default repo implementation does not support versioning yet. if (ResourceAttributeHelper.hasAttributeImplemented(resource, "Versionable", "2")) { try { // check the resource state: Identity identity = getIdentity(request); String userID = identity.getUser().getID(); VersionableV2 versionable = (VersionableV2)resource; if (versionable.isCheckedOut()) { String checkoutUserID = versionable.getCheckoutUserID(); if (!checkoutUserID.equals(userID)) { throw new Exception("Resource is checked out by another user: " + checkoutUserID); } } else { throw new Exception("Resource is not checked out."); } } catch (Exception e) { throw new ServletException(e.getMessage(), e); } } */ InputStream in = request.getInputStream(); // TODO: Should be delegated to resource type, e.g. <{http://...}xml/>! // Check on well-formedness ... String contentType = request.getContentType(); log.debug("Content-Type: " + contentType); if (contentType != null && (contentType.indexOf("application/xml") >= 0 || contentType.indexOf("application/xhtml+xml") >= 0)) { try { in = XMLHelper.isWellFormed(in); } catch(Exception e) { log.error(e, e); response.setContentType("application/xml; charset=" + DEFAULT_ENCODING); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); PrintWriter w = response.getWriter(); w.print(XMLExceptionV1.getDefaultException(XMLExceptionV1.DATA_NOT_WELL_FORMED, e.getMessage())); return; } } else { log.info("No well-formedness check required for content type: " + contentType); } // IMPORTANT TODO: Use ModifiableV2.write(InputStream in) such that resource can modify data during saving resp. check if getOutputStream is equals null and then use write .... OutputStream out = null; Resource res = getResource(request, response); if (ResourceAttributeHelper.hasAttributeImplemented(res, "Modifiable", "1")) { out = ((ModifiableV1) res).getOutputStream(new Path(request.getServletPath())); write(in, out, request, response); } else if (ResourceAttributeHelper.hasAttributeImplemented(res, "Modifiable", "2")) { try { out = ((ModifiableV2) res).getOutputStream(); if (out != null) { write(in, out, request, response); } else { log.warn("INFO: ModifiableV2.getOutputStream() returned null, hence fallback to ModifiableV2.write(InputStream)"); ((ModifiableV2) res).write(in); generateResponseFromResourceView(request, response, javax.servlet.http.HttpServletResponse.SC_OK, res); } } catch (Exception e) { throw new ServletException(e.getMessage(), e); } } else { String message = res.getClass().getName() + " is not modifiable (neither V1 nor V2)!"; log.warn(message); // TODO: Differentiate between Neutron based and other clients ... (Use method isClientSupportingNeutron()) response.setContentType("application/xml; charset=" + DEFAULT_ENCODING); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); PrintWriter w = response.getWriter(); // TODO: This is not really a 'checkin' problem, but rather a general 'save-data' problem, but the Neutron spec does not support such a type: http://neutron.wyona.org/draft-neutron-protocol-v0.html#rfc.section.8 w.print(XMLExceptionV1.getDefaultException(XMLExceptionV1.CHECKIN, message)); } if (doCheckin) { if (ResourceAttributeHelper.hasAttributeImplemented(resource, "Versionable", "2")) { VersionableV2 versionable = (VersionableV2)resource; try { versionable.checkin("updated"); } catch (Exception e) { throw new ServletException("Could not check in resource <" + resource.getPath() + ">: " + e.getMessage(), e); } } } } /** * Check authorization and if not authorized then authenticate. Return null if authorization granted, otherwise return 401 and appropriate response such that client can provide credentials for authentication * * @return Null if access is granted and an authentication response if access is denied */ private HttpServletResponse doAccessControl(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // INFO: Get identity, realm, path Identity identity; Realm realm; String pathWithoutQS; try { realm = map.getRealm(request.getServletPath()); /* TBD: Check whether BASIC might be used and if so, then maybe handle things differently (also see https://github.com/wyona/yanel/issues/41) String authorizationHeader = request.getHeader("Authorization"); if (authorizationHeader != null) { if (authorizationHeader.toUpperCase().startsWith("BASIC")) { */ identity = getIdentityFromRequest(request, realm); //log.warn("DEBUG: Identity retrieved from request (for realm '" + realm.getID() + "'): " + identity); pathWithoutQS = map.getPath(realm, request.getServletPath()); } catch (Exception e) { throw new ServletException(e.getMessage(), e); } // INFO: Try Auto-Login if (identity == null || (identity != null && identity.isWorld())) { //log.debug("Not logged in yet, hence try auto login..."); try { if (AutoLogin.tryAutoLogin(request, response, realm)) { log.debug("Auto login successful, hence set identity inside session..."); String username = AutoLogin.getUsername(request); if (username != null) { User user = realm.getIdentityManager().getUserManager().getUser(username); setIdentity(new Identity(user, user.getEmail()), request.getSession(), realm); } else { log.error("Auto login successful, but no username available!"); } } else { //log.debug("No auto login."); } } catch(Exception e) { log.error(e, e); } } // INFO: Check Authorization boolean authorized = false; Usecase usecase = getUsecase(request); try { if (log.isDebugEnabled()) log.debug("Check authorization: realm: " + realm + ", path: " + pathWithoutQS + ", identity: " + identity + ", Usecase: " + usecase.getName()); authorized = realm.getPolicyManager().authorize(pathWithoutQS, request.getQueryString(), identity, usecase); if (log.isDebugEnabled()) log.debug("Check authorization result: " + authorized); } catch (Exception e) { throw new ServletException(e.getMessage(), e); } if (authorized) { if (identity != null && identity.getUsername() != null) { if (identity.getUsername() != null) { if(log.isDebugEnabled()) log.debug("Access for user '" + identity.getUsername() + "' granted: " + getRequestURLQS(request, null, false)); //response.setHeader("Cache-control", "no-cache"); // INFO: Do not allow browsers to cache content for users which are signed in, but we currently do not use this because of performance reasons. One can set the resource property 'yanel:no-cache' on specific pages though in order to prevent caching of protected pages. Related to this see how a timestamp is appened during logout (see doLogout()) } else { if(log.isDebugEnabled()) log.debug("Access for anonymous user (aka WORLD) granted: " + getRequestURLQS(request, null, false)); } } else { if(log.isDebugEnabled()) log.debug("Access for anonymous user (aka WORLD) granted: " + getRequestURLQS(request, null, false)); } return null; // INFO: Return null in order to indicate that access is granted } else { log.warn("Access denied: " + getRequestURLQS(request, null, false) + " (Path of request: " + pathWithoutQS + "; Identity: " + identity + "; Usecase: " + usecase + ")"); // TODO: Implement HTTP BASIC/DIGEST response (see above) // INFO: If request is not via SSL and SSL is configured, then redirect to SSL connection. if(!request.isSecure()) { if(sslPort != null) { log.info("Redirect to SSL (Port: " + sslPort + ") ..."); try { URL url = new URL(getRequestURLQS(request, null, false).toString()); url = new URL("https", url.getHost(), new Integer(sslPort).intValue(), url.getFile()); if (realm.isProxySet()) { if (realm.getProxySSLPort() >= 0) { log.debug("Use configured port: " + realm.getProxySSLPort()); url = new URL(url.getProtocol(), url.getHost(), new Integer(realm.getProxySSLPort()).intValue(), url.getFile()); } else { log.debug("Use default port: " + url.getDefaultPort()); // NOTE: getDefaultPort depends on the Protocol (e.g. https is 443) url = new URL(url.getProtocol(), url.getHost(), url.getDefaultPort(), url.getFile()); } } log.info("Redirect to SSL: " + url); response.setHeader("Location", url.toString()); // TODO: "Yulup Editor" has a bug re TEMPORARY_REDIRECT //response.setStatus(javax.servlet.http.HttpServletResponse.SC_TEMPORARY_REDIRECT); response.setStatus(javax.servlet.http.HttpServletResponse.SC_MOVED_PERMANENTLY); return response; } catch (Exception e) { log.error(e.getMessage(), e); } } else { log.warn("SSL does not seem to be configured!"); } } else { log.info("This connection is already via SSL."); } if (doAuthenticate(request, response) != null) { log.info("Access denied and not authenticated correctly yet, hence return response of web authenticator..."); /* NOTE: Such a response can have different reasons: - Either no credentials provided yet and web authenticator is generating a response to fetch credentials - Or authentication failed and web authenticator is resending response to fetch again credentials"); - Or authentication was successful and web authenticator sends a redirect */ // TODO: Check "would be mime type", etc.: if (logAccessIsApplicable(view.getMimeType())) { if(logAccessEnabled) { // INFO: Although authorization has been denied and user first needs to authenticate, let's log the request anyway if (usecase != null && usecase.getName().equals("introspection")) { log.debug("Ignore introspection request: " + getRequestURLQS(request, null, false)); } else { log.info("Access denied and authentication not completed yet, hence let's log request '" + getRequestURLQS(request, null, false) + "'"); doLogAccess(request, response, HttpServletResponse.SC_UNAUTHORIZED, null, null); } } //log.debug("Returned status code: " + response.getStatus()); // INFO: Only supported by servlet api 3.0 and higher return response; } else { try { //log.debug("Authentication was successful for user: " + getIdentity(request, map).getUsername()); } catch (Exception e) { log.error(e.getMessage(), e); } URL url = new URL(getRequestURLQS(request, null, false).toString()); if (sslPort != null) { url = new URL("https", url.getHost(), new Integer(sslPort).intValue(), url.getFile()); } // INFO: Hash fragment is set by login screen, e.g. src/resources/login/htdocs/login-screen.xsl String hashFragment = request.getParameter("yanel.login.hash.fragment"); if (hashFragment != null && hashFragment.length() > 0) { log.debug("Hash fragment: " + hashFragment); url = new URL(url.getProtocol(), url.getHost(), url.getPort(), url.getFile() + "#" + hashFragment); } log.warn("DEBUG: Redirect to original request: " + url); //response.sendRedirect(url.toString()); // 302 // TODO: "Yulup Editor" has a bug re TEMPORARY_REDIRECT (or is the problem that the load balancer is rewritting 302 reponses?!) response.setHeader("Location", url.toString()); response.setStatus(javax.servlet.http.HttpServletResponse.SC_MOVED_PERMANENTLY); // 301 //response.setStatus(javax.servlet.http.HttpServletResponse.SC_TEMPORARY_REDIRECT); // 302 return response; } } } /** * Patch request with proxy settings re realm configuration * @param request Request which Yanel received * @param addQS Additonal query string * @param xml Flag whether returned URL should be XML compatible, e.g. re ampersands * @return URL which was received by reverse proxy, e.g. http://www.yanel.org/en/download/index.html instead http://127.0.0.1:8080/yanel/yanel-website/en/download/index.html */ private String getRequestURLQS(HttpServletRequest request, String addQS, boolean xml) { try { return Utils.getRequestURLQS(map.getRealm(request.getServletPath()), request, addQS, xml); } catch(Exception e) { log.error(e.getMessage(), e); return null; } } /** * WebDAV PROPFIND implementation. * * Also see https://svn.apache.org/repos/asf/tomcat/container/branches/tc5.0.x/catalina/src/share/org/apache/catalina/servlets/WebdavServlet.java * Also maybe interesting http://sourceforge.net/projects/openharmonise */ private void doPropfind(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Resource resource = getResource(request, response); //Node node = resource.getRealm().getSitetree().getNode(resource.getPath()); Node node = sitetree.getNode(resource.getRealm(),resource.getPath()); String depth = request.getHeader("Depth"); StringBuffer sb = new StringBuffer("<?xml version=\"1.0\"?>"); sb.append("<multistatus xmlns=\"DAV:\">"); if (depth.equals("0")) { if (node.isCollection()) { sb.append(" <response>"); sb.append(" <href>"+request.getRequestURI()+"</href>"); sb.append(" <propstat>"); sb.append(" <prop>"); sb.append(" <resourcetype><collection/></resourcetype>"); sb.append(" <getcontenttype>httpd/unix-directory</getcontenttype>"); sb.append(" </prop>"); sb.append(" <status>HTTP/1.1 200 OK</status>"); sb.append(" </propstat>"); sb.append(" </response>"); } else if (node.isResource()) { sb.append(" <response>"); sb.append(" <href>"+request.getRequestURI()+"</href>"); sb.append(" <propstat>"); sb.append(" <prop>"); sb.append(" <resourcetype/>"); // TODO: Set mime type of node! sb.append(" <getcontenttype>application/octet-stream</getcontenttype>"); // TODO: Set content length and last modified! sb.append(" <getcontentlength>0</getcontentlength>"); sb.append(" <getlastmodified>1969.02.16</getlastmodified>"); // See http://www.webdav.org/specs/rfc2518.html#PROPERTY_source, http://wiki.zope.org/HiperDom/RoundtripEditingDiscussion sb.append(" <source>\n"); sb.append(" <link>\n"); sb.append(" <src>" + request.getRequestURI() + "</src>\n"); sb.append(" <dst>" + request.getRequestURI() + "?yanel.resource.modifiable.source</dst>\n"); sb.append(" </link>\n"); sb.append(" </source>\n"); sb.append(" </prop>"); sb.append(" <status>HTTP/1.1 200 OK</status>"); sb.append(" </propstat>"); sb.append(" </response>"); } else { log.error("Neither collection nor resource!"); } } else if (depth.equals("1")) { // TODO: Shouldn't one check with isCollection() first?! Node[] children = node.getChildren(); if (children != null) { for (int i = 0; i < children.length; i++) { if (children[i].isCollection()) { sb.append(" <response>\n"); sb.append(" <href>" + request.getRequestURI() + "/" + children[i].getName() + "/</href>\n"); sb.append(" <propstat>\n"); sb.append(" <prop>\n"); sb.append(" <displayname>" + children[i].getName() + "</displayname>\n"); sb.append(" <resourcetype><collection/></resourcetype>\n"); sb.append(" <getcontenttype>httpd/unix-directory</getcontenttype>\n"); sb.append(" </prop>\n"); sb.append(" <status>HTTP/1.1 200 OK</status>\n"); sb.append(" </propstat>\n"); sb.append(" </response>\n"); } else if(children[i].isResource()) { sb.append(" <response>\n"); sb.append(" <href>" + request.getRequestURI() + "/" + children[i].getName() + "?yanel.webdav=propfind1</href>\n"); sb.append(" <propstat>\n"); sb.append(" <prop>\n"); sb.append(" <displayname>" + children[i].getName() + "</displayname>\n"); sb.append(" <resourcetype/>\n"); // TODO: Set mime type of node! sb.append(" <getcontenttype>application/octet-stream</getcontenttype>\n"); // TODO: Set content length and last modified! sb.append(" <getcontentlength>0</getcontentlength>"); sb.append(" <getlastmodified>1969.02.16</getlastmodified>"); // See http://www.webdav.org/specs/rfc2518.html#PROPERTY_source, http://wiki.zope.org/HiperDom/RoundtripEditingDiscussion sb.append(" <source>\n"); sb.append(" <link>\n"); sb.append(" <src>" + request.getRequestURI() + "/" + children[i].getName() + "</src>\n"); sb.append(" <dst>" + request.getRequestURI() + "/" + children[i].getName() + "?yanel.resource.modifiable.source</dst>\n"); sb.append(" </link>\n"); sb.append(" </source>\n"); sb.append(" </prop>\n"); sb.append(" <status>HTTP/1.1 200 OK</status>\n"); sb.append(" </propstat>\n"); sb.append(" </response>\n"); } else { log.error("Neither collection nor resource: " + children[i].getPath()); } } } else { log.warn("No children!"); } } else if (depth.equals("infinity")) { log.warn("TODO: List children and their children and their children ..."); } else { log.error("No such depth: " + depth); } sb.append("</multistatus>"); //response.setStatus(javax.servlet.http.HttpServletResponse.SC_MULTI_STATUS); response.setStatus(207, "Multi-Status"); PrintWriter w = response.getWriter(); w.print(sb); } /** * HTTP OPTIONS implementation. */ @Override protected void doOptions(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setHeader("DAV", "1"); // TODO: Is there anything else to do?! } /** * Authentication * @return null when authentication successful or has already been authenticated, otherwise return response generated by web authenticator */ private HttpServletResponse doAuthenticate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { // TODO/TBD: In the case of HTTP-BASIC/DIGEST one needs to check authentication with every request // TODO: enhance API with flag, e.g. session-based="true/false" // WARNING: One needs to separate doAuthenticate from the login screen generation! //if (getIdentity(request) != null) return null; WebAuthenticator wa = map.getRealm(request.getServletPath()).getWebAuthenticator(); return wa.doAuthenticate(request, response, map, reservedPrefix, xsltLoginScreenDefault, servletContextRealPath, sslPort); } catch (Exception e) { log.error(e.getMessage(), e); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return response; } } /** * Escapes all reserved xml characters (&amp; &lt; &gt; &apos; &quot;) in a string. * @param s input string * @return string with escaped characters */ public static String encodeXML(String s) { s = s.replaceAll("&", "&amp;"); s = s.replaceAll("<", "&lt;"); s = s.replaceAll(">", "&gt;"); s = s.replaceAll("'", "&apos;"); s = s.replaceAll("\"", "&quot;"); return s; } /** * Do CAS logout * @param request Request containing CAS ticket information, e.g. <samlp:LogoutRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" ID="LR-35-Cb0GJEEVItSWd5U2J4SEuzhvJ5uOORPhvG6" Version="2.0" IssueInstant="2014-05-12T10:12:10Z"><saml:NameID xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">@NOT_USED@</saml:NameID><samlp:SessionIndex>ST-37-rAzNSduFbOh7hJyzuNjW-cas01.example.org</samlp:SessionIndex></samlp:LogoutRequest> * @param response TODO * @return true when logout was successful and false otherwise */ private boolean doCASLogout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String body = request.getParameter(CAS_LOGOUT_REQUEST_PARAM_NAME); log.debug("Logout request content: " + body); try { Document doc = XMLHelper.readDocument(new java.io.ByteArrayInputStream(body.getBytes()), false); String id = doc.getDocumentElement().getAttribute("ID"); log.warn("DEBUG: CAS ID: " + id); Element[] sessionIndexEls = XMLHelper.getChildElements(doc.getDocumentElement(), "SessionIndex", "urn:oasis:names:tc:SAML:2.0:protocol"); if (sessionIndexEls != null && sessionIndexEls.length == 1) { String sessionIndex = sessionIndexEls[0].getFirstChild().getNodeValue(); log.warn("DEBUG: CAS SessionIndex: " + sessionIndex); HttpSession[] activeSessions = org.wyona.yanel.servlet.SessionCounter.getActiveSessions(); for (int i = 0; i < activeSessions.length; i++) { //log.debug("Yanel session ID: " + activeSessions[i].getId()); CASTicketsMap casTicketsMap = (CASTicketsMap) activeSessions[i].getAttribute(org.wyona.yanel.servlet.security.impl.CASWebAuthenticatorImpl.CAS_TICKETS_SESSION_NAME); if (casTicketsMap != null && casTicketsMap.containsValue(sessionIndex)) { log.warn("DEBUG: Session '" + activeSessions[i].getId() + "' contains CAS ticket which matches with SessionIndex: " + sessionIndex); removeIdentitiesAndCASTickets(activeSessions[i], casTicketsMap.getRealmId(sessionIndex)); // TODO: Notify other cluster nodes! return true; } else { //log.debug("Session '" + activeSessions[i].getId() + "' has either no CAS tickets or does not does match with SessionIndex."); } } log.warn("SessionIndex '" + sessionIndex + "' did no match any session."); return false; } else { log.error("No CAS SessionIndex element!"); return false; } } catch(Exception e) { log.error(e, e); return false; } } /** * Remove identities and CAS tickets from session * @param session Session containing identities and CAS tickets * @param realmId Realm ID associated with CAS ticket */ private void removeIdentitiesAndCASTickets(HttpSession session, String realmId) { IdentityMap identityMap = (IdentityMap)session.getAttribute(IDENTITY_MAP_KEY); if (identityMap != null) { log.warn("DEBUG: Remove identity associated with realm '" + realmId + "' from session '" + session.getId() + "' ..."); identityMap.remove(realmId); } else { log.warn("No identity map!"); } CASTicketsMap casTicketsMap = (CASTicketsMap)session.getAttribute(org.wyona.yanel.servlet.security.impl.CASWebAuthenticatorImpl.CAS_TICKETS_SESSION_NAME); if (casTicketsMap != null) { log.warn("DEBUG: Remove CAS ticket associated with realm '" + realmId + "' from session '" + session.getId() + "' ..."); casTicketsMap.remove(realmId); } else { log.warn("No CAS tickets map!"); } String casProxyTicket = (String)session.getAttribute(org.wyona.yanel.servlet.security.impl.CASWebAuthenticatorImpl.CAS_PROXY_TICKET_SESSION_NAME); if (casProxyTicket != null) { log.warn("DEBUG: Remove CAS proxy ticket associated with realm '" + realmId + "' from session '" + session.getId() + "' ..."); session.removeAttribute(org.wyona.yanel.servlet.security.impl.CASWebAuthenticatorImpl.CAS_PROXY_TICKET_SESSION_NAME); } else { log.warn("No CAS proxy ticket map!"); } } /** * Do logout * @param request TODO * @param response TODO * @return true if logout was successful (and set a "Redirect response" for a regular logout and a "Neutron response" if auth scheme is Neutron) */ private boolean doLogout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { if (yanelUI.isToolbarEnabled(request)) { // TODO: Check if WORLD has access to the toolbar //if (getRealm().getPolicyManager().authorize(path, new Identity(), new Usecase(TOOLBAR_USECASE))) { yanelUI.disableToolbar(request); //} } WebAuthenticator wa = map.getRealm(request.getServletPath()).getWebAuthenticator(); boolean successfulLogout = wa.doLogout(request, response, map); //int status = response.getStatus(); // INFO: This only works with servlet spec 3.0 (also see http://tomcat.apache.org/whichversion.html) int status = 301; TrackingInformationV1 trackInfo = null; Resource res = null; doLogAccess(request, response, status, res, trackInfo); if (successfulLogout) { // TODO: Add logout to org.wyona.security.core.UserHistory } return successfulLogout; } catch (Exception e) { log.error(e, e); throw new ServletException(e.getMessage(), e); } } /** * Do create a new resource */ private HttpServletResponse doCreate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.error("Not implemented yet!"); return null; } /** * Patches the mimetype of the Content-Type response field because * Microsoft Internet Explorer does not understand application/xhtml+xml * See http://en.wikipedia.org/wiki/Criticisms_of_Internet_Explorer#XHTML * @param mimeType Preferred mime type * @param request Browser request containing Accept information * @return mime type which should be used */ static public String patchMimeType(String mimeType, HttpServletRequest request) throws ServletException, IOException { if (mimeType != null) { String httpAcceptMediaTypes = request.getHeader("Accept"); if (mimeType.equals("application/xhtml+xml") && httpAcceptMediaTypes != null && httpAcceptMediaTypes.indexOf("application/xhtml+xml") < 0) { log.info("Patch contentType with text/html because client (" + request.getHeader("User-Agent") + ") does not seem to understand application/xhtml+xml"); return "text/html"; } else if (mimeType.equals("text/html")) { log.info("Mime type was already set to text/html for request: " + request.getServletPath()); } } else { log.warn("No mime type returned for request: " + request.getServletPath()); } return mimeType; } /** * Intercept InputStream and log content ... */ private InputStream intercept(InputStream in) throws IOException { java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(); byte[] buf = new byte[8192]; int bytesR; while ((bytesR = in.read(buf)) != -1) { baos.write(buf, 0, bytesR); } // Buffer within memory (TODO: Maybe replace with File-buffering ...) // http://www-128.ibm.com/developerworks/java/library/j-io1/ byte[] memBuffer = baos.toByteArray(); log.debug("InputStream: " + baos); return new java.io.ByteArrayInputStream(memBuffer); } /** * Generate a "Yanel" response (page information, 404, internal server error, ...) */ private void setYanelOutput(HttpServletRequest request, HttpServletResponse response, Document doc) throws ServletException { Resource resource = getResource(request, response); String path = resource.getPath(); String backToRealm = org.wyona.yanel.core.util.PathUtil.backToRealm(path); try { String yanelFormat = request.getParameter("yanel.resource.meta.format"); if(yanelFormat != null) { if (yanelFormat.equals("xml")) { response.setContentType("application/xml; charset=" + DEFAULT_ENCODING); XMLHelper.writeDocument(doc, response.getOutputStream()); } else if (yanelFormat.equals("json")) { log.error("TODO: JSON format not implemented yet!"); } else { log.error("No such format '" + yanelFormat + "' supported!"); } } else { String mimeType = patchMimeType("application/xhtml+xml", request); // TODO: doLogAccess response.setContentType(mimeType + "; charset=" + DEFAULT_ENCODING); // create identity transformer which serves as a dom-to-sax transformer TransformerIdentityImpl transformer = new TransformerIdentityImpl(); // INFO: Create xslt transformer: SAXTransformerFactory saxTransformerFactory = (SAXTransformerFactory)SAXTransformerFactory.newInstance(); TransformerHandler xsltTransformer = saxTransformerFactory.newTransformerHandler(new StreamSource(getXsltInfoAndException(resource))); xsltTransformer.getTransformer().setParameter("yanel.back2realm", backToRealm); xsltTransformer.getTransformer().setParameter("yanel.reservedPrefix", reservedPrefix); // create i18n transformer: I18nTransformer2 i18nTransformer = new I18nTransformer2("global", getLanguage(request, yanelInstance.getMap().getRealm(request.getServletPath()).getDefaultLanguage()), yanelInstance.getMap().getRealm(request.getServletPath()).getDefaultLanguage()); CatalogResolver catalogResolver = new CatalogResolver(); i18nTransformer.setEntityResolver(new CatalogResolver()); // create serializer: Serializer serializer = SerializerFactory.getSerializer(SerializerFactory.XHTML_STRICT); // chain everything together (create a pipeline): xsltTransformer.setResult(new SAXResult(i18nTransformer)); i18nTransformer.setResult(new SAXResult(serializer.asContentHandler())); serializer.setOutputStream(response.getOutputStream()); // execute pipeline: transformer.transform(new DOMSource(doc), new SAXResult(xsltTransformer)); } } catch (Exception e) { throw new ServletException(e.getMessage(), e); } } /** * Get XSLT file to render meta information and exception screen */ private File getXsltInfoAndException(Resource resource) { File realmDir = new File(resource.getRealm().getConfigFile().getParent()); File customXslt = org.wyona.commons.io.FileUtil.file(realmDir.getAbsolutePath(), "src" + File.separator + "webapp" + File.separator + defaultXsltInfoAndException); if (customXslt.isFile()) { return customXslt; } else { return org.wyona.commons.io.FileUtil.file(servletContextRealPath, defaultXsltInfoAndException); } } /** * Get language with the following priorization: 1) yanel.meta.language query string parameter, 2) Accept-Language header, 3) Fallback language * @param fallbackLanguage Fallback when neither query string parameter nor Accept-Language header exists */ public static String getLanguage(HttpServletRequest request, String fallbackLanguage) throws Exception { // TODO: Shouldn't this be replaced by Resource.getRequestedLanguage() or Resource.getContentLanguage() ?! String language = request.getParameter("yanel.meta.language"); if (language == null) { language = request.getHeader("Accept-Language"); if (language != null) { int commaIndex = language.indexOf(","); if (commaIndex > 0) { language = language.substring(0, commaIndex); } int dashIndex = language.indexOf("-"); if (dashIndex > 0) { language = language.substring(0, dashIndex); } } } if(language != null && language.length() > 0) { return language; } return fallbackLanguage; } /** * Write to output stream of modifiable resource */ private void write(InputStream in, OutputStream out, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (out != null) { log.debug("Content-Type: " + request.getContentType()); // TODO: Compare mime-type from response with mime-type of resource //if (contentType.equals("text/xml")) { ... } byte[] buffer = new byte[8192]; int bytesRead; while ((bytesRead = in.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); } out.flush(); out.close(); StringBuffer sb = new StringBuffer(); sb.append("<?xml version=\"1.0\"?>"); sb.append("<html>"); sb.append("<body>"); sb.append("<p>Data has been saved ...</p>"); sb.append("</body>"); sb.append("</html>"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_OK); response.setContentType("application/xhtml+xml; charset=" + DEFAULT_ENCODING); PrintWriter w = response.getWriter(); w.print(sb); log.info("Data has been saved ..."); return; } else { log.error("OutputStream is null!"); StringBuffer sb = new StringBuffer(); sb.append("<?xml version=\"1.0\"?>"); sb.append("<html>"); sb.append("<body>"); sb.append("<p>Exception: OutputStream is null!</p>"); sb.append("</body>"); sb.append("</html>"); PrintWriter w = response.getWriter(); w.print(sb); response.setContentType("application/xhtml+xml; charset=" + DEFAULT_ENCODING); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } } /** * @deprecated Use {@link #getIdentity(HttpSession, String)} instead * Get the identity from the HTTP session (associated with the given request) for a specific realm * @param session HTTP session of client * @param realm Realm * @return Identity if one exist, or otherwise null */ public static Identity getIdentity(HttpSession session, Realm realm) throws Exception { return getIdentity(session, realm.getID()); } /** * Get the identity from the HTTP session (associated with the given request) for a specific realm * @param session HTTP session of client * @param realmID Realm ID * @return Identity if one exist, or otherwise null */ public static Identity getIdentity(HttpSession session, String realmID) throws Exception { //log.debug("Get identity from session for realm '" + realmID + "'."); if (session != null) { IdentityMap identityMap = (IdentityMap)session.getAttribute(IDENTITY_MAP_KEY); if (identityMap != null) { Identity identity = (Identity)identityMap.get(realmID); if (identity != null && !identity.isWorld()) { return identity; } else { log.debug("No identity yet for realm '" + realmID + "'."); if (identity != null && identity.isWorld()) { log.debug("Identity is set to world."); } else { log.debug("No identity set at all."); } } } else { log.debug("No identity map yet."); } } else { log.debug("No session yet."); } return null; } /** * Attach the identity to the HTTP session for a specific realm (associated with the given request) * @param session HTTP session of client * @param realm Realm */ public static void setIdentity(Identity identity, HttpSession session, Realm realm) throws Exception { if (session != null) { IdentityMap identityMap = (IdentityMap)session.getAttribute(IDENTITY_MAP_KEY); if (identityMap == null) { identityMap = new IdentityMap(); session.setAttribute(IDENTITY_MAP_KEY, identityMap); } //log.debug("Firstname: " + identity.getFirstname()); identityMap.put(realm.getID(), identity); // INFO: Please note that the constructor Identity(User, String) is resolving group IDs (including parent group IDs) and hence these are "attached" to the session in order to improve performance during authorization checks } else { log.warn("Session is null!"); } } /** * Get the identity from the given request/session (for a specific realm) or via the 'Authorization' HTTP header in the case of BASIC or DIGEST * @param request Client/Servlet request * @param realm Realm * @return Identity if one exist, or otherwise an empty identity (which is considered to be WORLD) */ private Identity getIdentityFromRequest(HttpServletRequest request, Realm realm) throws Exception { // INFO: Please note that the identity normally gets set inside a WebAuthenticator implementation //log.debug("Get identity for request '" + request.getServletPath() + "'."); Identity identity = getIdentity(request.getSession(false), realm.getID()); if (identity != null) { // INFO: Please note that the WORLD identity (or rather an empty identity) is not added to the session (please see further down) //log.debug("Identity from session: " + identity); return identity; } if (yanelInstance.isPreAuthenticationEnabled()) { String preAuthReqHeaderName = yanelInstance.getPreAuthenticationRequestHeaderName(); if (preAuthReqHeaderName != null && request.getHeader(preAuthReqHeaderName) != null) { String preAuthUserName = request.getHeader(preAuthReqHeaderName); log.warn("DEBUG: Pre authenticated user: " + preAuthUserName); String trueID = realm.getIdentityManager().getUserManager().getTrueId(preAuthUserName); User user = realm.getIdentityManager().getUserManager().getUser(trueID); if (user != null) { log.debug("User '" + user.getID() + "' considered pre-authenticated."); identity = new Identity(user, preAuthUserName); setIdentity(identity, request.getSession(true), realm); return identity; } else { log.warn("No such pre-authenticated user '" + preAuthUserName + "', hence set identity to WORLD!"); identity = new Identity(); setIdentity(identity, request.getSession(true), realm); return identity; } } else { log.warn("Pre-authentication enabled, but no request header name set!"); } } /* TODO: Make configurable! if (true) { log.warn("DEBUG: Do not check for BASIC authentication, but set identity to WORLD."); return new Identity(); } */ // HTTP BASIC Authentication (For clients such as for instance Sunbird, OpenOffice or cadaver) // IMPORT NOTE: BASIC Authentication needs to be checked on every request, because clients often do not support session handling String authorizationHeader = request.getHeader("Authorization"); if (log.isDebugEnabled()) log.debug("No identity attached to session, hence check request authorization header: " + authorizationHeader); if (authorizationHeader != null) { if (authorizationHeader.toUpperCase().startsWith("BASIC")) { // Get encoded user and password, comes after "BASIC " String userpassEncoded = authorizationHeader.substring(6); // Decode it, using any base 64 decoder sun.misc.BASE64Decoder dec = new sun.misc.BASE64Decoder(); String userpassDecoded = new String(dec.decodeBuffer(userpassEncoded)); log.debug("Username and Password Decoded: " + userpassDecoded); String[] up = userpassDecoded.split(":"); String username = up[0]; String password = up[1]; log.debug("Get identity from BASIC authorization header and try to authenticate user '" + username + "' for request '" + request.getServletPath() + "'"); try { String trueID = realm.getIdentityManager().getUserManager().getTrueId(username); User user = realm.getIdentityManager().getUserManager().getUser(trueID); if (user != null && user.authenticate(password)) { log.debug("User '" + user.getID() + "' successfully authenticated via BASIC authentication."); identity = new Identity(user, username); setIdentity(identity, request.getSession(true), realm); return identity; } else { log.warn("HTTP BASIC Authentication failed for " + username + " (True ID: '" + trueID + "') and request '" + request.getServletPath() + "', hence set identity to WORLD!"); identity = new Identity(); setIdentity(identity, request.getSession(true), realm); return identity; /* INFO: Do not return unauthorized response, but rather just return 'WORLD' as identity... response.setHeader("WWW-Authenticate", "BASIC realm=\"" + realm.getName() + "\""); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); PrintWriter writer = response.getWriter(); writer.print("BASIC Authentication Failed!"); return response; */ } } catch (Exception e) { throw new ServletException(e.getMessage(), e); } } else if (authorizationHeader.toUpperCase().startsWith("DIGEST")) { log.error("DIGEST is not implemented (Request: " + request.getServletPath() + "), hence set identity to WORLD!"); return new Identity(); /* authorized = false; response.sendError(HttpServletResponse.SC_UNAUTHORIZED); response.setHeader("WWW-Authenticate", "DIGEST realm=\"" + realm.getName() + "\""); PrintWriter writer = response.getWriter(); writer.print("DIGEST is not implemented!"); */ } else { log.warn("No such authorization type implemented: " + authorizationHeader); return new Identity(); } } else { if (log.isDebugEnabled()) log.debug("Neither identity inside session yet nor authorization header based identity for request '" + request.getServletPath() + "', hence set identity to WORLD..."); // TBD: Should we add WORLD identity for performance reasons to the session? return new Identity(); } } /** * Create a DOM Document */ static public Document getDocument(String namespace, String localname) throws Exception { return XMLHelper.createDocument(namespace, localname); } private Realm getRealm(HttpServletRequest request) throws Exception { Realm realm = yanelInstance.getMap().getRealm(request.getServletPath()); return realm; } /** * Generate response using a resource configuration * @param response Response which is being generated/completed * @param statusCode HTTP response status code (because one is not able to get status code from response) * @param rc Resource configuration * @return true if generation of response was successful or return false otherwise */ private boolean generateResponseFromRTview(HttpServletRequest request, HttpServletResponse response, int statusCode, ResourceConfiguration rc, String path) throws ServletException { try { Resource resource = yanelInstance.getResourceManager().getResource(getEnvironment(request, response), getRealm(request), path, rc); return generateResponseFromResourceView(request, response, statusCode, resource); } catch (Exception e) { throw new ServletException(e); } } /** * Generate response using a resource configuration * @param statusCode HTTP response status code (because one is not able to get status code from response) * @param resource Resource * @return true if generation of response was successful or return false otherwise */ private boolean generateResponseFromResourceView(HttpServletRequest request, HttpServletResponse response, int statusCode, Resource resource) throws Exception { String viewId = getViewID(request); View view = ((ViewableV2) resource).getView(viewId); if (view != null) { TrackingInformationV1 trackInfo = null; if (generateResponse(view, resource, request, response, statusCode, getDocument(NAMESPACE, "yanel"), -1, -1, trackInfo) != null) { return true; } } log.warn("No response has been generated: " + resource.getPath()); return false; } /** * Get global data located below reserved prefix */ private void getGlobalData(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Resource resource = getResource(request, response); String path = resource.getPath(); java.util.Map<String, String> properties = new HashMap<String, String>(); final String pathPrefix = "/" + reservedPrefix + "/"; final String ABOUT_PAGE_PATH = pathPrefix + "about.html"; // About Yanel final String ABOUT_REALM_PAGE_PATH = pathPrefix + "about-realm.html"; // About realm final String RESOURCE_TYPES_PATH_PREFIX = pathPrefix + "resource-types/"; //XXX REFACTORME: in the cases where we simply use a resource-type's view // we should implement org.wyona.yanel.core.api.ResourceTypeMatcherV1 ( cf. http://lists.wyona.org/pipermail/yanel-development/2009-June/003749.html ) Realm realm; Environment environment = getEnvironment(request, response); ResourceConfiguration rc; YanelGlobalResourceTypeMatcher RTmatcher = new YanelGlobalResourceTypeMatcher(pathPrefix, servletContextRealPath); try { realm = getRealm(request); rc = RTmatcher.getResourceConfiguration(environment, realm, path); } catch (Exception e) { throw new ServletException(e.getMessage(), e); } if (rc != null) { if (generateResponseFromRTview(request, response, -1, rc, path)) { return; } response.setStatus(javax.servlet.http.HttpServletResponse.SC_NOT_FOUND); return; } else if (path.equals(ABOUT_PAGE_PATH)) { //XXX REFACTORME: we should define an "about" resource-type instead! response.setStatus(javax.servlet.http.HttpServletResponse.SC_OK); response.setHeader("Content-Type", "text/html"); PrintWriter w = response.getWriter(); w.print(About.toHTML(yanelInstance.getVersion(), yanelInstance.getRevision(), yanelInstance.getTargetEnvironment())); return; } else if (path.equals(ABOUT_REALM_PAGE_PATH)) { //XXX REFACTORME: we should define an "about-realm" resource-type instead! response.setStatus(javax.servlet.http.HttpServletResponse.SC_OK); response.setHeader("Content-Type", "text/html"); PrintWriter w = response.getWriter(); w.print(AboutRealm.toHTML(realm)); return; } else if (path.startsWith(RESOURCE_TYPES_PATH_PREFIX)) { final String[] namespaceURI_and_rest = path.substring(RESOURCE_TYPES_PATH_PREFIX.length()).split("::", 2); final String namespaceURI = namespaceURI_and_rest[0]; final String[] name_and_rest = namespaceURI_and_rest[1].split("/", 2); final String name = name_and_rest[0]; // INFO: Decode URL, e.g. /yanel/resource-types/^http:^2f^2fwww.wyona.org^2fyanel^2fresource^2f1.0::user-admin/dummy.css final String decoded_namespaceURI = HttpServletRequestHelper.decodeURIinURLpath('^', namespaceURI); log.debug("decoded_namespaceURI: " + decoded_namespaceURI); if (log.isDebugEnabled()) log.debug("decoded_namespaceURI: "+decoded_namespaceURI); // The request (see resource.getPath()) seems to replace 'http://' or 'http%3a%2f%2f' by 'http:/', so let's change this back final String namespace = ! decoded_namespaceURI.equals(namespaceURI) ? decoded_namespaceURI : namespaceURI.replaceAll("http:/", "http://"); rc = new ResourceConfiguration(name, namespace, properties); try { Resource resourceOfPrefix = yanelInstance.getResourceManager().getResource(environment, realm, path, rc); String htdocsPath; if (name_and_rest[1].startsWith(reservedPrefix + "/")) { htdocsPath = "rtyanelhtdocs:" + name_and_rest[1].substring(reservedPrefix.length()).replace('/', File.separatorChar); } else { htdocsPath = "rthtdocs:" + File.separatorChar + name_and_rest[1].replace('/', File.separatorChar); } SourceResolver resolver = new SourceResolver(resourceOfPrefix); Source source = resolver.resolve(htdocsPath, null); long sourceLastModified = -1; // INFO: Compare If-Modified-Since with lastModified and return 304 without content resp. check on ETag if (source instanceof YanelStreamSource) { sourceLastModified = ((YanelStreamSource) source).getLastModified(); long ifModifiedSince = request.getDateHeader("If-Modified-Since"); if (log.isDebugEnabled()) log.debug("sourceLastModified <= ifModifiedSince: " + sourceLastModified + " <= " + ifModifiedSince); if (ifModifiedSince != -1) { if (sourceLastModified <= ifModifiedSince) { response.setStatus(javax.servlet.http.HttpServletResponse.SC_NOT_MODIFIED); return; } } } InputStream htdocIn = ((StreamSource) source).getInputStream(); if (htdocIn != null) { log.debug("Resource-Type specific data: " + htdocsPath); // TODO: Set more HTTP headers (size, etc.) String mimeType = guessMimeType(FilenameUtils.getExtension(FilenameUtils.getName(htdocsPath))); if(sourceLastModified >= 0) response.setDateHeader("Last-Modified", sourceLastModified); response.setHeader("Content-Type", mimeType); // INFO: Tell the client for how long it should cache the data which will be sent by the response if (cacheExpires != 0) { setExpiresHeader(response, cacheExpires); } byte buffer[] = new byte[8192]; int bytesRead; OutputStream out = response.getOutputStream(); while ((bytesRead = htdocIn.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); } htdocIn.close(); return; } else { log.error("No such file or directory: " + htdocsPath); response.setStatus(javax.servlet.http.HttpServletResponse.SC_NOT_FOUND); return; } } catch (Exception e) { throw new ServletException(e.getMessage(), e); } } else { File globalFile = org.wyona.commons.io.FileUtil.file(servletContextRealPath, "htdocs" + File.separator + path.substring(pathPrefix.length())); if (globalFile.exists()) { //log.debug("Get global file: " + globalFile); // INFO: Compare If-Modified-Since with lastModified and return 304 without content resp. check on ETag long ifModifiedSince = request.getDateHeader("If-Modified-Since"); if (ifModifiedSince != -1) { //log.debug("Last modified '" + globalFile.lastModified() + "' versus If-Modified-Since '" + ifModifiedSince + "'."); if (globalFile.lastModified() <= ifModifiedSince) { response.setStatus(javax.servlet.http.HttpServletResponse.SC_NOT_MODIFIED); return; } } // TODO: Set more HTTP headers (size, etc.) String mimeType = guessMimeType(FilenameUtils.getExtension(globalFile.getName())); response.setHeader("Content-Type", mimeType); response.setDateHeader("Last-Modified", globalFile.lastModified()); // INFO: Tell the client for how long it should cache the data which will be sent by the response if (cacheExpires != 0) { //log.debug("Client should consider the content of '" + globalFile + "' as stale in '" + cacheExpires + "' hours from now on ..."); setExpiresHeader(response, cacheExpires); } else { //log.debug("No cache expires set."); } byte buffer[] = new byte[8192]; int bytesRead; InputStream in = new java.io.FileInputStream(globalFile); OutputStream out = response.getOutputStream(); while ((bytesRead = in.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); } in.close(); return; } else { log.error("No such file or directory: " + globalFile); response.setStatus(javax.servlet.http.HttpServletResponse.SC_NOT_FOUND); return; } } } /** * Set expire date within HTTP header (see https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.21) * @param hours Number of hours from now on, after which the response is considered stale */ private void setExpiresHeader(HttpServletResponse response, int hours) { Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.HOUR_OF_DAY, hours); String expires = DateUtil.formatRFC822GMT(calendar.getTime()); response.setHeader("Expires", expires); } /** * Generate response from a resource view, whereas it will be checked first if the resource already wrote the response (if so, then just return) * * @param view View of resource * @param res Resource which handles the request in order to generate a response * @param request TODO * @param response TODO * @param statusCode HTTP response status code (because one is not able to get status code from response) * @param doc TODO * @param size TODO * @param lastModified TODO * @param trackInfo Tracking information bean which might be updated by resource if resource is implementing trackable * * @return response to the client / browser */ private HttpServletResponse generateResponse(View view, Resource res, HttpServletRequest request, HttpServletResponse response, int statusCode, Document doc, long size, long lastModified, TrackingInformationV1 trackInfo) throws ServletException, IOException { //log.debug("Generate response: " + res.getPath()); // TODO: It seems like no header fields are being set (e.g. Content-Length, ...). Please see below ... // INFO: Check if viewable resource has already created a response if (!view.isResponse()) { if(logAccessIsApplicable(view.getMimeType(), res)) { //log.debug("Mime type '" + view.getMimeType() + "' of request: " + request.getServletPath() + "?" + request.getQueryString()); doLogAccess(request, response, statusCode, res, trackInfo); } log.debug("It seems that resource '" + res.getPath() + "' has directly created the response."); try { if ("true".equals(res.getResourceConfigProperty("yanel:no-cache"))) { log.debug("Set no-cache headers..."); response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1. response.setHeader("Pragma", "no-cache"); // HTTP 1.0. response.setDateHeader("Expires", 0); // Proxies. } } catch(Exception e) { log.error(e, e); } return response; } // INFO: Set mime type and encoding String mimeType = view.getMimeType(); if (view.getEncoding() != null) { mimeType = patchMimeType(mimeType, request); response.setContentType(mimeType + "; charset=" + view.getEncoding()); } else if (res.getConfiguration() != null && res.getConfiguration().getEncoding() != null) { mimeType = patchMimeType(mimeType, request); response.setContentType(mimeType + "; charset=" + res.getConfiguration().getEncoding()); } else { // try to guess if we have to set the default encoding if (mimeType != null && mimeType.startsWith("text") || mimeType.equals("application/xml") || mimeType.equals("application/xhtml+xml") || mimeType.equals("application/atom+xml") || mimeType.equals("application/x-javascript")) { mimeType = patchMimeType(mimeType, request); response.setContentType(mimeType + "; charset=" + DEFAULT_ENCODING); } else { // probably binary mime-type, don't set encoding mimeType = patchMimeType(mimeType, request); response.setContentType(mimeType); } } if(logAccessIsApplicable(mimeType, res)) { //log.debug("Mime type '" + mimeType + "' of request: " + request.getServletPath() + "?" + request.getQueryString()); doLogAccess(request, response, statusCode, res, trackInfo); } // INFO: Set HTTP headers HashMap<?, ?> headers = view.getHttpHeaders(); Iterator<?> iter = headers.keySet().iterator(); while (iter.hasNext()) { String name = (String)iter.next(); String value = (String)headers.get(name); if (log.isDebugEnabled()) { log.debug("set http header: " + name + ": " + value); } response.setHeader(name, value); } try { if ("true".equals(res.getResourceConfigProperty("yanel:no-cache"))) { log.debug("Set no-cache headers..."); response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1. response.setHeader("Pragma", "no-cache"); // HTTP 1.0. response.setDateHeader("Expires", 0); // Proxies. } } catch(Exception e) { log.error(e, e); } // INFO: Confirm DNT (do not track) String dntValue = request.getHeader("DNT"); if (dntValue != null) { response.setHeader("DNT", dntValue); // INFO: See spec about response header at http://tools.ietf.org/html/draft-mayer-do-not-track-00 } else { //log.debug("No DNT (do not track) header set, hence do not echo."); } // Possibly embed toolbar: // TODO: Check if user is authorized to actually see toolbar (Current flaw: Enabled Toolbar, Login, Toolbar is enabled, Logout, Toolbar is still visible!) if (yanelUI.isToolbarEnabled(request)) { // TODO: Check whether resource configuration has toolbar configured as suppressed: if ("suppress".equals(res.getResConfiguration("yanel.toolbar"))) { if (mimeType != null && mimeType.indexOf("html") > 0) { // TODO: What about other query strings or frames or TinyMCE (e.g. link.htm)? if (request.getParameter(YANEL_RESOURCE_USECASE) == null) { // INFO: In the case of a yanel resource usecase do NOT add the toolbar if (toolbarMasterSwitch.equals("on")) { OutputStream os = response.getOutputStream(); try { Usecase usecase = new Usecase(TOOLBAR_USECASE); Realm realm = map.getRealm(request.getServletPath()); Identity identity = getIdentityFromRequest(request, realm); String path = map.getPath(realm, request.getServletPath()); // NOTE: This extra authorization check is necessary within a multi-realm environment, because after activating the toolbar with a query string, the toolbar flag attached to the session will be ignored by doAccessControl(). One could possibly do this check within doAccessControl(), but could be a peformance issue! Or as an alternative one could refactor the code, such that the toolbar session flag is realm aware. if(realm.getPolicyManager().authorize(path, identity, usecase)) { yanelUI.mergeToolbarWithContent(request, response, res, view); return response; } else { log.warn("Toolbar authorization denied (Realm: '" + realm.getName() + "', User: '" + identity.getUsername() + "', Path: '" + path + "')!"); } } catch (Exception e) { String message = "Error merging toolbar into content: " + e.getMessage(); //log.error(message, e); log.error(e, e); Element exceptionElement = (Element) doc.getDocumentElement().appendChild(doc.createElementNS(NAMESPACE, EXCEPTION_TAG_NAME)); exceptionElement.appendChild(doc.createTextNode(message)); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); setYanelOutput(request, response, doc); return response; } } else { log.info("Toolbar has been disabled. Please check web.xml!"); } } else { log.warn("Yanel resource usecase is not null, but set to '" + request.getParameter(YANEL_RESOURCE_USECASE) + "' and hence Yanel toolbar is suppressed/omitted in order to avoid that users are leaving the usecase because they might click on some toolbar menu item."); } } else { log.info("No HTML related mime type: " + mimeType); } } else { log.debug("Toolbar is turned off."); } InputStream is = view.getInputStream(); if (is != null) { try { // Compare If-Modified-Since with lastModified and return 304 without content resp. check on ETag long ifModifiedSince = request.getDateHeader("If-Modified-Since"); if (ifModifiedSince != -1) { //log.debug("Client set 'If-Modified-Since' ..."); if (res instanceof ModifiableV2) { long resourceLastMod = ((ModifiableV2)res).getLastModified(); log.debug("Resource was last modified: " + new Date(resourceLastMod) + ", 'If-Modified-Since' sent by client: " + new Date(ifModifiedSince)); if (resourceLastMod <= ifModifiedSince) { response.setStatus(javax.servlet.http.HttpServletResponse.SC_NOT_MODIFIED); return response; } } else { // TODO: Many resources do not implement ModifiableV2 and hence never return a lastModified and hence the browser will never ask for ifModifiedSince! //log.warn("Resource of path '" + res.getPath() + "' is not ModifiableV2 and hence cannot be cached!"); if (log.isDebugEnabled()) log.debug("Resource of path '" + res.getPath() + "' is not ModifiableV2 and hence cannot be cached!"); } } } catch (Exception e) { log.error(e.getMessage(), e); } if(lastModified >= 0) response.setDateHeader("Last-Modified", lastModified); if(size > 0) { if (log.isDebugEnabled()) log.debug("Size of " + request.getRequestURI() + ": " + size); response.setContentLength((int) size); } else { if (log.isDebugEnabled()) log.debug("No size for " + request.getRequestURI() + ": " + size); } try { // INFO: Check whether InputStream is empty and try to Write content into response byte buffer[] = new byte[8192]; int bytesRead; bytesRead = is.read(buffer); if (bytesRead != -1) { java.io.OutputStream os = response.getOutputStream(); os.write(buffer, 0, bytesRead); while ((bytesRead = is.read(buffer)) != -1) { os.write(buffer, 0, bytesRead); } os.close(); } else { log.warn("Returned content size of request '" + request.getRequestURI() + "' is 0"); } } catch(Exception e) { log.error("Writing into response failed for request '" + request.getRequestURL() + "' (Client: " + getClientAddressOfUser(request) + ")"); // INFO: For example in the case of ClientAbortException log.error(e, e); throw new ServletException(e); } finally { //log.debug("Close InputStream in any case!"); is.close(); // INFO: Make sure to close InputStream, because otherwise we get bugged with open files } return response; } else { String message = "Returned InputStream of request '" + request.getRequestURI() + "' is null!"; Element exceptionElement = (Element) doc.getDocumentElement().appendChild(doc.createElementNS(NAMESPACE, EXCEPTION_TAG_NAME)); exceptionElement.appendChild(doc.createTextNode(message)); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); setYanelOutput(request, response, doc); is.close(); return response; } } /** * @see javax.servlet.GenericServlet#destroy() */ @Override public void destroy() { super.destroy(); log.info("Destroy Yanel instance..."); yanelInstance.destroy(); if (scheduler != null) { try { log.info("Shutdown scheduler ..."); log.warn("DEBUG: Shutdown scheduler ..."); scheduler.shutdown(); //scheduler.shutdown(true); // INFO: true means to wait until all jobs have completed } catch(Exception e) { log.error(e, e); } } else { log.warn("No scheduler instance exists, probably because it is disabled: " + yanelInstance.isSchedulerEnabled()); } log.warn("DEBUG: Shutdown ehcache..."); net.sf.ehcache.CacheManager.create().shutdown(); File shutdownLogFile = new File(System.getProperty("java.io.tmpdir"), "shutdown.log"); log.warn("Trying to shutdown log4j loggers... (if shutdown successful, then loggers won't be available anymore. Hence see shutdown log file '" + shutdownLogFile.getAbsolutePath() + "' for final messages)"); org.apache.log4j.LogManager.shutdown(); // TODO: org.apache.logging.log4j.LogManager.shutdown(); /* INFO: After closing the loggers/appenders, these won't be available anymore, hence the following log statements don't make any sense. log.info("Shutdown of access logger completed."); log.info("Yanel webapp has been shut down: " + new Date()); */ try { if (!shutdownLogFile.exists()) { shutdownLogFile.createNewFile(); } java.io.FileWriter fw= new java.io.FileWriter(shutdownLogFile); java.io.BufferedWriter bw = new java.io.BufferedWriter(fw); bw.write("Yanel webapp has been shut down: " + new Date()); bw.close(); fw.close(); } catch(java.io.FileNotFoundException e) { System.err.println(e.getMessage()); } catch(java.io.IOException e) { System.err.println(e.getMessage()); } } /** * Get usecase. Maps query strings, etc. to usecases, which then can be used for example within access control policies */ private Usecase getUsecase(HttpServletRequest request) { // TODO: Replace hardcoded roles by mapping between roles amd query strings ... Usecase usecase = new Usecase("view"); String yanelResUsecaseValue = request.getParameter(YANEL_RESOURCE_USECASE); if (yanelResUsecaseValue != null) { if (yanelResUsecaseValue.equals("save")) { log.debug("Save data ..."); usecase = new Usecase("write"); } else if (yanelResUsecaseValue.equals("checkin")) { log.debug("Checkin data ..."); usecase = new Usecase("write"); } else if (yanelResUsecaseValue.equals("roll-back")) { log.debug("Roll back to previous revision ..."); usecase = new Usecase("write"); } else if (yanelResUsecaseValue.equals("introspection")) { if(log.isDebugEnabled()) log.debug("Dynamically generated introspection ..."); usecase = new Usecase("introspection"); } else if (yanelResUsecaseValue.equals("checkout")) { log.debug("Checkout data ..."); usecase = new Usecase("open"); } else if (yanelResUsecaseValue.equals("delete")) { log.info("Delete resource (yanel resource usecase delete)"); usecase = new Usecase("delete"); } else { log.warn("No such generic Yanel resource usecase: " + yanelResUsecaseValue + " (maybe some custom resource usecase)"); } } String yanelUsecaseValue = request.getParameter(YANEL_USECASE); if (yanelUsecaseValue != null) { if (yanelUsecaseValue.equals("create")) { log.debug("Create new resource ..."); usecase = new Usecase("resource.create"); } else if (yanelUsecaseValue.equals("policy.read")) { usecase = new Usecase("policy.read"); } else { log.warn("No such generic Yanel usecase: " + yanelUsecaseValue + " (maybe some custom usecase)"); } } String contentType = request.getContentType(); String method = request.getMethod(); if (contentType != null && contentType.indexOf("application/atom+xml") >= 0 && (method.equals(METHOD_PUT) || method.equals(METHOD_POST))) { // TODO: Is posting atom entries different from a general post (see below)?! log.warn("Write/Checkin Atom entry ..."); usecase = new Usecase("write"); // TODO: METHOD_POST is not generally protected, but save, checkin, application/atom+xml are being protected. See doPost(.... } else if (method.equals(METHOD_PUT)) { log.warn("INFO: Upload data using PUT, hence we set the usecase to 'write', which you might have to enable inside the corresponding access policy."); usecase = new Usecase("write"); } else if (method.equals(METHOD_DELETE)) { log.warn("Delete resource (HTTP method delete)"); usecase = new Usecase("delete"); } String workflowTransitionValue = request.getParameter(YANEL_RESOURCE_WORKFLOW_TRANSITION); if (workflowTransitionValue != null) { // TODO: At the moment the authorization of workflow transitions are checked within executeWorkflowTransition or rather workflowable.doTransition(transition, revision) log.warn("Workflow transition is currently handled as view usecase: " + workflowTransitionValue); usecase = new Usecase("view"); // TODO: Return workflow transition ID //usecase = new Usecase(transitionID); } String toolbarValue = request.getParameter("yanel.toolbar"); if (toolbarValue != null && toolbarValue.equals("on")) { log.debug("Turn on toolbar ..."); usecase = new Usecase(TOOLBAR_USECASE); } String yanelPolicyValue = request.getParameter(YANEL_ACCESS_POLICY_USECASE); if (yanelPolicyValue != null) { if (yanelPolicyValue.equals("create")) { usecase = new Usecase("policy.create"); } else if (yanelPolicyValue.equals("read")) { usecase = new Usecase("policy.read"); } else if (yanelPolicyValue.equals("update")) { usecase = new Usecase("policy.update"); } else if (yanelPolicyValue.equals("delete")) { usecase = new Usecase("policy.delete"); } else { log.warn("No such policy usecase: " + yanelPolicyValue); } } String showResourceMeta = request.getParameter(RESOURCE_META_ID_PARAM_NAME); if (showResourceMeta != null) { usecase = new Usecase(RESOURCE_META_ID_PARAM_NAME); } return usecase; } /** * Handle access policy requests (CRUD, whereas delete is not implemented yet!) * @param version Version of policy manager implementation */ private void doAccessPolicyRequest(HttpServletRequest request, HttpServletResponse response, int version) throws ServletException, IOException { try { String viewId = getViewID(request); Realm realm = map.getRealm(request.getServletPath()); ResourceConfiguration rc; if (version == 2) { rc = getGlobalResourceConfiguration("policy-manager-v2_yanel-rc.xml", realm); } else { rc = getGlobalResourceConfiguration("policy-manager_yanel-rc.xml", realm); } String path = map.getPath(realm, request.getServletPath()); if (generateResponseFromRTview(request, response, -1, rc, path)) { return; } log.error("Something went terribly wrong!"); response.getWriter().print("Something went terribly wrong!"); return; } catch(Exception e) { throw new ServletException(e.getMessage(), e); } } /** * Handle delete usecase */ private void handleDeleteUsecase(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String confirmed = request.getParameter("confirmed"); if (confirmed != null) { String path = getResource(request, response).getPath(); log.debug("Really delete resource at " + path); doDelete(request, response); return; } else { response.setStatus(javax.servlet.http.HttpServletResponse.SC_OK); response.setContentType("text/html" + "; charset=" + "UTF-8"); StringBuilder sb = new StringBuilder(); Resource res = getResource(request, response); if (ResourceAttributeHelper.hasAttributeImplemented(res, "Modifiable", "2") || ResourceAttributeHelper.hasAttributeImplemented(res, "Deletable", "1")) { log.info("Delete has not been confirmed by client yet!"); sb = new StringBuilder("<html xmlns=\"http://www.w3.org/1999/xhtml\"><body>Do you really want to delete this page? <a href=\"?" + YANEL_RESOURCE_USECASE + "=delete&confirmed\">YES</a>, <a href=\"" + request.getHeader("referer") + "\">no</a></body></html>"); } else { String message = "Resource '" + res.getPath() + "' cannot be deleted, because it does not implement interface ModifiableV2!"; log.warn(message); sb = new StringBuilder("<html xmlns=\"http://www.w3.org/1999/xhtml\"><body><p>WARNING: " + message + "</p></body></html>"); } PrintWriter w = response.getWriter(); w.print(sb); return; } } /** * Get resource configuration from global location of the realm or if not available there, then from global location of Yanel * * @param resConfigName Filename of resource configuration * @param realm Current realm */ private ResourceConfiguration getGlobalResourceConfiguration(String resConfigName, Realm realm) { return YanelGlobalResourceTypeMatcher.getGlobalResourceConfiguration(resConfigName, realm, servletContextRealPath); } /** * Handle a generic exception. * @param request The request object. * @param response The response object. * @param ex The exception to handle. */ private void handleException(HttpServletRequest request, HttpServletResponse response, Exception ex) { try { Realm realm = yanelInstance.getMap().getRealm(request.getServletPath()); String path = getResource(request, response).getPath(); ResourceConfiguration rc = getGlobalResourceConfiguration("generic-exception-handler_yanel-rc.xml", realm); BasicGenericExceptionHandlerResource resource = (BasicGenericExceptionHandlerResource) yanelInstance.getResourceManager().getResource(getEnvironment(request, response), getRealm(request), path, rc); resource.setException(ex); int statusCode = javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR; response.setStatus(statusCode); boolean hasBeenHandled = generateResponseFromResourceView(request, response, statusCode, resource); if(!hasBeenHandled) { log.error("Generic exception handler is broken!"); log.error("Unable to output/handle the following exception:"); log.error(ex, ex); } } catch (Exception e) { log.error("Generic exception handler is broken!"); log.error("Unable to handle the following exception:"); log.error(ex, ex); log.error("Caught exception while handling the above exception:"); log.error(e, e); } } /** * Generate a graceful 404 response * @param doc Debug/Meta document */ private void do404(HttpServletRequest request, HttpServletResponse response, Document doc, String exceptionMessage) throws ServletException { log404.info("Referer: " + request.getHeader("referer")); log404.warn(request.getRequestURL().toString()); // TODO: Log 404 per realm //org.wyona.yarep.core.Node node = realm.getRepository().getNode("/yanel-logs/404.txt"); String message = "No such node/resource exception: " + exceptionMessage; log.warn(message); Element exceptionElement = (Element) doc.getDocumentElement().appendChild(doc.createElementNS(NAMESPACE, EXCEPTION_TAG_NAME)); exceptionElement.appendChild(doc.createTextNode(message)); exceptionElement.setAttributeNS(NAMESPACE, "status", "404"); response.setStatus(HttpServletResponse.SC_NOT_FOUND); try { Realm realm = yanelInstance.getMap().getRealm(request.getServletPath()); String path = getResource(request, response).getPath(); ResourceConfiguration rc = getGlobalResourceConfiguration("404_yanel-rc.xml", realm); if (generateResponseFromRTview(request, response, HttpServletResponse.SC_NOT_FOUND, rc, path)) { return; } log.error("404 response seems to be broken!"); return; } catch (Exception e) { log.error(e.getMessage(), e); return; } } /** * Check if yanel resource usecase is 'roll back" usecase */ private boolean isRollBack(HttpServletRequest request) { String yanelResUsecase = request.getParameter(YANEL_RESOURCE_USECASE); if (yanelResUsecase != null) { if (yanelResUsecase.equals("roll-back")) return true; } return false; } /** * Check if request comes from Neutron supporting client */ private boolean isClientSupportingNeutron(HttpServletRequest request) { String neutronVersions = request.getHeader("Neutron"); if (neutronVersions != null) { log.info("Neutron version(s) supported by client: " + neutronVersions); return true; } return false; } /** * Respond with introspection */ private void sendIntrospectionAsResponse(Resource res, Document doc, Element rootElement, HttpServletRequest request, HttpServletResponse response) throws ServletException { try { if (ResourceAttributeHelper.hasAttributeImplemented(res, "Introspectable", "1")) { response.setContentType("application/xml"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_OK); response.getWriter().print(((IntrospectableV1)res).getIntrospection()); } else { String message = "Resource '" + res.getPath() + "' is not introspectable!"; log.warn(message); Element exceptionElement = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, EXCEPTION_TAG_NAME)); exceptionElement.appendChild(doc.createTextNode(message)); setYanelOutput(request, response, doc); } return; } catch(Exception e) { log.error(e.getMessage(), e); Element exceptionElement = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, EXCEPTION_TAG_NAME)); exceptionElement.appendChild(doc.createTextNode(e.getMessage())); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); setYanelOutput(request, response, doc); return; } } /** * Set/get meta data re resource */ private Element getResourceMetaData(Resource res, Document doc, Element rootElement) { Element resourceElement = (Element) rootElement.appendChild(doc.createElement("resource")); ResourceConfiguration resConfig = res.getConfiguration(); if (resConfig != null) { Element resConfigElement = (Element) resourceElement.appendChild(doc.createElementNS(NAMESPACE, "config")); resConfigElement.setAttributeNS(NAMESPACE, "rti-name", resConfig.getName()); resConfigElement.setAttributeNS(NAMESPACE, "rti-namespace", resConfig.getNamespace()); } else { Element noResConfigElement = (Element) resourceElement.appendChild(doc.createElementNS(NAMESPACE, "no-config")); } Element realmElement = (Element) resourceElement.appendChild(doc.createElementNS(NAMESPACE, "realm")); realmElement.setAttributeNS(NAMESPACE, "name", res.getRealm().getName()); realmElement.setAttributeNS(NAMESPACE, "rid", res.getRealm().getID()); realmElement.setAttributeNS(NAMESPACE, "prefix", res.getRealm().getMountPoint()); Element identityManagerElement = (Element) realmElement.appendChild(doc.createElementNS(NAMESPACE, "identity-manager")); Element userManagerElement = (Element) identityManagerElement.appendChild(doc.createElementNS(NAMESPACE, "user-manager")); return resourceElement; } /** * Append view descriptors to meta */ private void appendViewDescriptors(Document doc, Element viewElement, ViewDescriptor[] vd) { if (vd != null) { for (int i = 0; i < vd.length; i++) { Element descriptorElement = (Element) viewElement.appendChild(doc.createElement("descriptor")); if (vd[i].getMimeType() != null) { descriptorElement.appendChild(doc.createTextNode(vd[i].getMimeType())); } descriptorElement.setAttributeNS(NAMESPACE, "id", vd[i].getId()); } } else { viewElement.appendChild(doc.createTextNode("No View Descriptors!")); } } /** * Log browser history of each user * @param request TODO * @param response TODO * @param resource Resource which handles the request * @param statusCode HTTP response status code (because one is not able to get status code from response) * @param trackInfo Tracking information bean */ private void doLogAccess(HttpServletRequest request, HttpServletResponse response, int statusCode, Resource resource, TrackingInformationV1 trackInfo) { // TBD: What about a cluster, performance/scalability? See for example http://www.oreillynet.com/cs/user/view/cs_msg/17399 (also see Tomcat conf/server.xml <Valve className="AccessLogValve" and className="FastCommonAccessLogValve") // See apache-tomcat-5.5.33/logs/localhost_access_log.2009-11-07.txt // 127.0.0.1 - - [07/Nov/2009:01:24:09 +0100] "GET /yanel/from-scratch-realm/de/index.html HTTP/1.1" 200 4464 /* Differentiate between hits, pageviews (only html or also PDF, etc.?) and visits (also see http://www.ibm.com/developerworks/web/library/wa-mwt1/) In order to log page-views one can use: - single-pixel method (advantage: also works if javascript is disabled) - JavaScript (similar to Google analytics) - Analyze mime type (advantage: no additional code/requests necessary) - Log analysis (no special tracking required) */ if ("1".equals(request.getHeader("DNT"))) { // INFO: See http://donottrack.us/ if (logDoNotTrack.isDebugEnabled()) { logDoNotTrack.debug("Do not track: " + request.getRemoteAddr()); } return; } try { Realm realm = map.getRealm(request.getServletPath()); String accessLogMessage; if (trackInfo != null) { if (trackInfo.doNotTrack()) { logDoNotTrack.debug("Do not track: " + resource.getPath() + " (Remote address: " + request.getRemoteAddr() + ")"); return; } String[] trackingTags = trackInfo.getTags(); if (trackingTags != null && trackingTags.length > 0) { // INFO: Either/Or, but not both. If you want both, then make sure that that your resource adds its annotations to the tracking information. accessLogMessage = AccessLog.getLogMessage(getRequestURLQS(request, null, false), request, response, realm.getUserTrackingDomain(), trackingTags, ACCESS_LOG_TAG_SEPARATOR); } else { String[] tags = getTagsFromAnnotatableResource(resource, request.getServletPath()); accessLogMessage = AccessLog.getLogMessage(getRequestURLQS(request, null, false), request, response, realm.getUserTrackingDomain(), tags, ACCESS_LOG_TAG_SEPARATOR); } String pageType = trackInfo.getPageType(); if (pageType != null) { accessLogMessage = accessLogMessage + AccessLog.encodeLogField("pt", pageType); } String requestAction = trackInfo.getRequestAction(); if (requestAction != null) { accessLogMessage = accessLogMessage + AccessLog.encodeLogField("ra", requestAction); } // TODO: What if a custom field is overwriting a regular field?! I would suggest that we log a warning and ignore this custom field. HashMap<String, String> customFields = trackInfo.getCustomFields(); if (customFields != null) { for (java.util.Map.Entry field : customFields.entrySet()) { accessLogMessage = accessLogMessage + AccessLog.encodeLogField((String) field.getKey(), (String) field.getValue()); } } } else { String[] tags = getTagsFromAnnotatableResource(resource, request.getServletPath()); accessLogMessage = AccessLog.getLogMessage(getRequestURLQS(request, null, false), request, response, realm.getUserTrackingDomain(), tags, ACCESS_LOG_TAG_SEPARATOR); } // TBD/TODO: What if user has logged out, but still has a persistent cookie?! Identity identity = getIdentityFromRequest(request, realm); if (identity != null && identity.getUsername() != null) { accessLogMessage = accessLogMessage + AccessLog.encodeLogField("u", identity.getUsername()); /* TODO: This does not scale re many users ... User user = realm.getIdentityManager().getUserManager().getUser(identity.getUsername()); // The log should be attached to the user, because realms can share a UserManager, but the UserManager API has no mean to save such data, so how should we do this? // What if realm ID is changing? String logPath = "/yanel-logs/browser-history/" + user.getID() + ".txt"; if (!realm.getRepository().existsNode(logPath)) { org.wyona.yarep.util.YarepUtil.addNodes(realm.getRepository(), logPath, org.wyona.yarep.core.NodeType.RESOURCE); } org.wyona.yarep.core.Node node = realm.getRepository().getNode(logPath); // Stream into node (append log entry, see for example log4j) // 127.0.0.1 - - [07/Nov/2009:01:24:09 +0100] "GET /yanel/from-scratch-realm/de/index.html HTTP/1.1" 200 4464 */ } String clientIP = getClientAddressOfUser(request); String httpAcceptLanguage = request.getHeader("Accept-Language"); if (httpAcceptLanguage != null) { accessLogMessage = accessLogMessage + AccessLog.encodeLogField("a-lang", httpAcceptLanguage); } else { log.warn("Client request (IP: " + clientIP + ") has no Accept-Language header."); } HttpSession session = request.getSession(true); if (session != null) { accessLogMessage = accessLogMessage + AccessLog.encodeLogField("sid", session.getId()); } if (statusCode >= 0) { accessLogMessage = accessLogMessage + AccessLog.encodeLogField("http-status", "" + statusCode); } else { accessLogMessage = accessLogMessage + AccessLog.encodeLogField("http-status", "" + HttpServletResponse.SC_OK); } accessLogMessage = accessLogMessage + AccessLog.encodeLogField("ip", clientIP); logAccess.info(accessLogMessage); //log.debug("Referer: " + request.getHeader(HTTP_REFERRER)); // INFO: Store last accessed page in session such that session manager can show user activity. if(session != null) { session.setAttribute(YANEL_LAST_ACCESS_ATTR, request.getServletPath()); //log.debug("Last access: " + request.getServletPath()); } } catch(Exception e) { // Catch all exceptions, because we do not want to throw exceptions because of possible logging browser history errors log.error(e, e); } } /** * Append revisions and workflow of a resource to the meta document * @param doc Meta document */ private void appendRevisionsAndWorkflow(Document doc, Element resourceElement, Resource res, HttpServletRequest request) throws Exception { WorkflowableV1 workflowableResource = null; Workflow workflow = null; String liveRevisionName = null; if (ResourceAttributeHelper.hasAttributeImplemented(res, "Workflowable", "1")) { workflowableResource = (WorkflowableV1)res; workflow = WorkflowHelper.getWorkflow(res); liveRevisionName = WorkflowHelper.getLiveRevision(res); } UserManager userManager = res.getRealm().getIdentityManager().getUserManager(); if (ResourceAttributeHelper.hasAttributeImplemented(res, "Versionable", "3")) { //log.debug("Resource '" + res.getPath() + "' has VersionableV3 implemented..."); java.util.Iterator<RevisionInformation> it = ((VersionableV3)res).getRevisions(false); if (it != null) { if (it.hasNext()) { Element revisionsElement = (Element) resourceElement.appendChild(doc.createElement(REVISIONS_TAG_NAME)); while(it.hasNext()) { RevisionInformation revisionInfo = (RevisionInformation)it.next(); Element revisionElement = appendRevision(revisionsElement, revisionInfo, userManager); appendWorkflow(revisionElement, workflow, workflowableResource, doc, revisionInfo, liveRevisionName); } } else { resourceElement.appendChild(doc.createElement(NO_REVISIONS_TAG_NAME)); } } else { resourceElement.appendChild(doc.createElement(NO_REVISIONS_TAG_NAME)); } } else if (ResourceAttributeHelper.hasAttributeImplemented(res, "Versionable", "2")) { //log.debug("Resource '" + res.getPath() + "' has VersionableV2 implemented..."); RevisionInformation[] revisionsInfo = ((VersionableV2)res).getRevisions(); if (revisionsInfo != null && revisionsInfo.length > 0) { Element revisionsElement = (Element) resourceElement.appendChild(doc.createElement(REVISIONS_TAG_NAME)); for (int i = revisionsInfo.length - 1; i >= 0; i--) { Element revisionElement = appendRevision(revisionsElement, revisionsInfo[i], userManager); appendWorkflow(revisionElement, workflow, workflowableResource, doc, revisionsInfo[i], liveRevisionName); } } else { resourceElement.appendChild(doc.createElement(NO_REVISIONS_TAG_NAME)); } } else if (ResourceAttributeHelper.hasAttributeImplemented(res, "Versionable", "1")) { log.warn("TODO: Implement VersionableV1 interface, deprecated though!"); String[] revisionIDs = ((VersionableV1)res).getRevisions(); } else { Element notVersionableElement = (Element) resourceElement.appendChild(doc.createElement("not-versionable")); } } /** * Append workflow information to revision listed by meta document */ private void appendWorkflow(Element revisionElement, Workflow workflow, WorkflowableV1 workflowableResource, Document doc, RevisionInformation revisionInfo, String liveRevisionName) throws Exception { if (workflowableResource != null && workflow != null) { Element revisionWorkflowElement = (Element) revisionElement.appendChild(doc.createElement("workflow-state")); String wfState = workflowableResource.getWorkflowState(revisionInfo.getName()); if (wfState == null) { wfState = workflow.getInitialState(); } if (liveRevisionName != null && revisionInfo.getName().equals(liveRevisionName)) { revisionWorkflowElement.appendChild(doc.createTextNode(wfState + " (LIVE)")); } else { revisionWorkflowElement.appendChild(doc.createTextNode(wfState)); } } } /** * Append individual revisions to meta document * @param revisionsEl Parent revisions DOM element * @param ri Detailed information about this particular revision */ private Element appendRevision(Element revisionsEl, RevisionInformation ri, UserManager userManager) { Document doc = revisionsEl.getOwnerDocument(); Element revisionElement = (Element) revisionsEl.appendChild(doc.createElement("revision")); log.debug("Revision: " + ri.getName()); revisionElement.appendChild(XMLHelper.createTextElement(doc, "name", ri.getName(), null)); log.debug("Date: " + ri.getDate()); revisionElement.appendChild(XMLHelper.createTextElement(doc, "date", "" + ri.getDate(), null)); if (ri.getUser() != null) { log.debug("User ID: " + ri.getUser()); revisionElement.appendChild(XMLHelper.createTextElement(doc, "user", ri.getUser(), null)); try { revisionElement.appendChild(XMLHelper.createTextElement(doc, "user-name", userManager.getUser(ri.getUser()).getName(), null)); } catch(Exception e) { log.warn(e, e); } } else { revisionElement.appendChild(doc.createElement("no-user")); } if (ri.getComment() != null) { log.debug("Comment: " + ri.getComment()); revisionElement.appendChild(XMLHelper.createTextElement(doc, "comment", ri.getComment(), null)); } else { revisionElement.appendChild(doc.createElement("no-comment")); } return revisionElement; } /** * Check whether mime type is html, pdf or video * @param mt Mime type */ private boolean isMimeTypeOk(String mt) { // TODO: Add more mime types or rather make it configurable // INFO: Only HTML pages and PDFs etc. should be logged, but no images, CSS, etc. Check the mime-type instead the suffix or use JavaScript or Pixel if (mt.indexOf("html") > 0 || mt.indexOf("pdf") > 0 || mt.indexOf("video") >= 0) { return true; } return false; } /** * Get workflow exception */ private static String getWorkflowException(String message) { StringBuilder sb = new StringBuilder(); sb.append("<?xml version=\"1.0\"?>"); sb.append("<exception xmlns=\"" + org.wyona.yanel.core.workflow.Workflow.NAMESPACE + "\" type=\"" + "workflow" + "\">"); sb.append("<message>" + message + "</message>"); sb.append("</exception>"); return sb.toString(); } /** * Check whether user agent is mobile device and if so, then set mobile flag inside session */ private void doMobile(HttpServletRequest request) { HttpSession session = request.getSession(true); String mobileDevice = (String) session.getAttribute(MOBILE_KEY); if (detectMobilePerRequest || mobileDevice == null) { String userAgent = request.getHeader("User-Agent"); if (userAgent == null) { // log.warn("No user agent available!"); return; } //log.debug("User agent: " + userAgent); // INFO: In order to get the screen size/resolution please see for example http://www.coderanch.com/t/229905/JME/Mobile/Getting-Screen-size-requesting-mobile, whereas the below does not seem to work! //log.debug("User agent screen: " + request.getHeader("UA-Pixels")); // INFO: UA-Pixels, UA-Color, UA-OS, UA-CPU // TBD: Use lower case for comparing device names...whereas please note that we already set the device name inside the session and hence this might be used somewhere and hence create backwards compatibility issues! session.setAttribute(YanelServlet.MOBILE_KEY, "false"); // INFO: First assume user agent is not a mobile device... for (int i = 0; i < mobileDevices.length; i++) { if (matchesMobileDevice(userAgent, mobileDevices[i])) { session.setAttribute(YanelServlet.MOBILE_KEY, mobileDevices[i]); //log.debug("This seems to be a mobile device: " + mobileDevices[i]); break; } } /* if (((String)session.getAttribute(YanelServlet.MOBILE_KEY)).equals("false")) { log.debug("This does not seem to be a mobile device: " + userAgent); } */ } else { //log.debug("Mobile device detection already done."); } } /** * Check whether user agent matches mobile device * @param userAgent User agent, e.g. 'Mozilla/5.0 (Linux; U; Android 2.2.1; en-us; Nexus One Build/FRG83) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1' * @param mobileDevice Mobile device name, e.g. 'iPhone'. One can also specify a combination of words, e.g. 'Android AND Mobile' */ private boolean matchesMobileDevice(String userAgent, String mobileDevice) { // TBD: Use http://wurfl.sourceforge.net/njava/, http://www.cloudfour.com/comparative-speed-of-wurfl-and-device-atlas/, http://www.id.uzh.ch/zinfo/mobileview.html if (mobileDevice.indexOf("AND") > 0) { String[] tokens = org.springframework.util.StringUtils.delimitedListToStringArray(mobileDevice, "AND"); for (int i = 0; i < tokens.length; i++) { String token = tokens[i].trim(); //log.debug("Try to match '" + token + "'..."); if (userAgent.indexOf(token) < 0) { return false; } } return true; } else { if (userAgent.indexOf(mobileDevice) > 0) { return true; } else { return false; } } } /** * Append annotations of resource to page meta document * @param doc Page meta document * @param resource Resource which might has some annotations */ private void appendAnnotations(Document doc, Resource resource) { if (ResourceAttributeHelper.hasAttributeImplemented(resource, "Annotatable", "1")) { AnnotatableV1 anno = (AnnotatableV1) resource; try { String[] tags = anno.getAnnotations(); if (tags != null && tags.length > 0) { //log.debug("Resource has tags: " + tags); Element annotationsElem = doc.createElementNS(NAMESPACE, "annotations"); doc.getDocumentElement().appendChild(annotationsElem); for (int i = 0; i < tags.length; i++) { Element annotationElem = doc.createElementNS(NAMESPACE, "annotation"); annotationElem.appendChild(doc.createTextNode(tags[i])); annotationsElem.appendChild(annotationElem); } } else { Element noAnnotationsYetElem = doc.createElementNS(NAMESPACE, "no-annotations-yet"); noAnnotationsYetElem.setAttribute("annotatable-v1", "true"); doc.getDocumentElement().appendChild(noAnnotationsYetElem); } } catch (Exception ex) { log.error(ex, ex); } } else { if (log.isDebugEnabled()) { log.debug("Resource has no tags yet: " + resource.getPath()); } Element noAnnotationsYetElem = doc.createElementNS(NAMESPACE, "no-annotations-yet"); noAnnotationsYetElem.setAttribute("annotatable-v1", "false"); doc.getDocumentElement().appendChild(noAnnotationsYetElem); } } /** * Append tracking information of resource to page meta document * @param doc Page meta document */ private void appendTrackingInformation(Document doc, TrackingInformationV1 trackInfo) { if (trackInfo != null) { Element trackInfoElem = doc.createElementNS(NAMESPACE, "tracking-info"); doc.getDocumentElement().appendChild(trackInfoElem); String[] trackingTags = trackInfo.getTags(); if (trackingTags != null && trackingTags.length > 0) { Element interestsElem = doc.createElementNS(NAMESPACE, "interests"); trackInfoElem.appendChild(interestsElem); for (int i = 0; i < trackingTags.length; i++) { Element interestElem = doc.createElementNS(NAMESPACE, "interest"); interestElem.appendChild(doc.createTextNode(trackingTags[i])); interestsElem.appendChild(interestElem); } } else { Element noInterestsElem = doc.createElementNS(NAMESPACE, "no-interests-yet"); trackInfoElem.appendChild(noInterestsElem); } String pageType = trackInfo.getPageType(); if (pageType != null) { Element pageTypeElem = doc.createElementNS(NAMESPACE, "page-type"); pageTypeElem.appendChild(doc.createTextNode(pageType)); trackInfoElem.appendChild(pageTypeElem); } String requestAction = trackInfo.getRequestAction(); if (requestAction != null) { Element requestActionElem = doc.createElementNS(NAMESPACE, "request-action"); requestActionElem.appendChild(doc.createTextNode(requestAction)); trackInfoElem.appendChild(requestActionElem); } HashMap<String, String> customFields = trackInfo.getCustomFields(); if (customFields != null) { Element customFieldsElem = doc.createElementNS(NAMESPACE, "custom-fields"); trackInfoElem.appendChild(customFieldsElem); for (java.util.Map.Entry field : customFields.entrySet()) { Element fieldElem = doc.createElementNS(NAMESPACE, "field"); fieldElem.setAttribute("name", (String) field.getKey()); fieldElem.setAttribute("value", (String) field.getValue()); customFieldsElem.appendChild(fieldElem); } } } else { log.debug("No tracking information."); Element noTrackInfoElem = doc.createElementNS(NAMESPACE, "no-tracking-information"); doc.getDocumentElement().appendChild(noTrackInfoElem); } } /** * Determine requested view ID (try to get it from session or query string) */ private String getViewID(HttpServletRequest request) { String viewId = null; String viewIdFromSession = (String) request.getSession(true).getAttribute(VIEW_ID_PARAM_NAME); if (viewIdFromSession != null) { //log.debug("It seems like the view id is set inside session: " + viewIdFromSession); viewId = viewIdFromSession; } if (request.getParameter(VIEW_ID_PARAM_NAME) != null) { viewId = request.getParameter(VIEW_ID_PARAM_NAME); } if (request.getParameter("yanel.format") != null) { // backwards compatible viewId = request.getParameter("yanel.format"); log.warn("For backwards compatibility reasons also consider parameter 'yanel.format', but which is deprecated. Please use '" + VIEW_ID_PARAM_NAME + "' instead."); } //log.debug("Tried to get view id from query string or session attribute: " + viewId); return viewId; } /** * Check whether access logging makes sense * @param mimeType Content type of requested resource * @param resource Resource/controller handling request */ private boolean logAccessIsApplicable(String mimeType, Resource resource) { if(logAccessEnabled) { if (isTrackable(resource) || (mimeType != null && isMimeTypeOk(mimeType))) { return true; } else { if (logDoNotTrack.isDebugEnabled()) { logDoNotTrack.debug("Resource '" + resource.getPath() + "' is neither trackable nor a mime type '" + mimeType + "' which makes sense, hence do not track."); } return false; } } else { if (logDoNotTrack.isDebugEnabled()) { logDoNotTrack.debug("Tracking disabled globally."); } return false; } } /** * Check whether a resource/controller is trackable * @param resource Resource/controller which might has the trackable interface implemented */ private boolean isTrackable(Resource resource) { boolean isTrackable = ResourceAttributeHelper.hasAttributeImplemented(resource, "Trackable", "1"); if (isTrackable) { return true; } else { //logDoNotTrack.debug("Resource '" + resource.getPath() + "' has trackable interface not implemented."); return false; } } /** * Clean meta document */ private void cleanMetaDoc(Document doc) { Element rootElem = doc.getDocumentElement(); org.w3c.dom.NodeList children = rootElem.getChildNodes(); for (int i = children.getLength() - 1; i >= 0; i--) { rootElem.removeChild(children.item(i)); } } /** * Get tags from annotatable resource * @param resource Resource which might provide annotations * @param servletPath Servlet path of requested resource * @return tags/annotations if resource is annotatable, null otherwise */ private String[] getTagsFromAnnotatableResource(Resource resource, String servletPath) { String[] tags = null; if (resource != null) { if (ResourceAttributeHelper.hasAttributeImplemented(resource, "Annotatable", "1")) { AnnotatableV1 anno = (AnnotatableV1) resource; try { tags = anno.getAnnotations(); if (tags != null) { log.debug("Resource '" + resource.getPath() + "' (Servlet path: " + servletPath + ") has '" + tags.length + "' tags."); } } catch (Exception ex) { log.error(ex, ex); } } else { if (log.isDebugEnabled()) { log.debug("Resource has no tags yet: " + resource.getPath()); } } } else { log.debug("Resource is null because access was probably denied or not necessarily initialized: " + servletPath); } return tags; } /** * Get client address of user * @param request Client request * @return original client IP address, e.g. 'TODO' */ private String getClientAddressOfUser(HttpServletRequest request) { String remoteIPAddr = request.getHeader("X-FORWARDED-FOR"); if (remoteIPAddr != null) { // INFO: We do not need to check realm.isProxySet() additionally, because some deployments are using a proxy without having set the Yanel proxy configuration, hence it is sufficient to just check whether an X-FORWARDED-FOR header is set if (remoteIPAddr.indexOf("unknown") >= 0) { log.warn("TODO: Clean remote IP address: " + remoteIPAddr); } } else { if (log.isDebugEnabled()) { log.debug("No such request header: X-FORWARDED-FOR (hence fallback to request.getRemoteAddr())"); // INFO: For example in the case of AJP or if no proxy is used } remoteIPAddr = request.getRemoteAddr(); // INFO: For performance reasons we do not use getRemoteHost(), but rather just use the IP address. } // TODO: What about ", 198.240.213.22, 146.67.140.72" if (remoteIPAddr.indexOf(",") > 0) { // INFO: Comma separated addresses, like for example '172.21.126.179, 89.250.145.138' (see Format of X-Forwarded-For at http://en.wikipedia.org/wiki/X-Forwarded-For) String firstAddress = remoteIPAddr.split(",")[0].trim(); //log.debug("Use the first IP address '" + firstAddress + "' of comma separated list '" + remoteIPAddr + "' ..."); return firstAddress; } else { return remoteIPAddr; } } /** * Generate unique fish tag, such that one can debug individual users * @param request Request containing client ip and session id * @return unique fishtag, e.g. '127.0.0.1_F3194' */ private String getFishTag(HttpServletRequest request) { return getClientAddressOfUser(request) + "_" + request.getSession(true).getId().substring(0, 4); // TBD: org.wyona.yanel.impl.resources.sessionmanager.SessionManagerResource#hashSessionID(String) } /** * Check whether request is a CAS single sign out request (https://wiki.jasig.org/display/casum/single+sign+out#SingleSignOut-Howitworks) * @return true when request is a CAS single sign out request and false otherwise */ private boolean isCASLogoutRequest(HttpServletRequest request) { // INFO: Also see org.wyona.yanel.impl.resources.CASLogoutMatcher if (METHOD_POST.equals(request.getMethod()) && request.getParameter(CAS_LOGOUT_REQUEST_PARAM_NAME) != null) { return true; } else { return false; } } }
use java.util.Base64.Decoder instead sun.misc.BASE64Decoder
src/webapp/src/java/org/wyona/yanel/servlet/YanelServlet.java
use java.util.Base64.Decoder instead sun.misc.BASE64Decoder
<ide><path>rc/webapp/src/java/org/wyona/yanel/servlet/YanelServlet.java <ide> } <ide> */ <ide> <del> // HTTP BASIC Authentication (For clients such as for instance Sunbird, OpenOffice or cadaver) <add> // HTTP BASIC Authentication (For clients such as for instance Thunderbird Lightning, OpenOffice or cadaver) <ide> // IMPORT NOTE: BASIC Authentication needs to be checked on every request, because clients often do not support session handling <ide> String authorizationHeader = request.getHeader("Authorization"); <ide> if (log.isDebugEnabled()) log.debug("No identity attached to session, hence check request authorization header: " + authorizationHeader); <ide> if (authorizationHeader.toUpperCase().startsWith("BASIC")) { <ide> // Get encoded user and password, comes after "BASIC " <ide> String userpassEncoded = authorizationHeader.substring(6); <del> // Decode it, using any base 64 decoder <del> sun.misc.BASE64Decoder dec = new sun.misc.BASE64Decoder(); <del> String userpassDecoded = new String(dec.decodeBuffer(userpassEncoded)); <del> log.debug("Username and Password Decoded: " + userpassDecoded); <add> // INFO: Decode it, using base 64 decoder <add> <add> // DEPRECATED <add> //sun.misc.BASE64Decoder dec = new sun.misc.BASE64Decoder(); <add> //String userpassDecoded = new String(dec.decodeBuffer(userpassEncoded)); <add> <add> java.util.Base64.Decoder decoder = java.util.Base64.getMimeDecoder(); <add> String userpassDecoded = new String(decoder.decode(userpassEncoded)); <add> <add> log.debug("Username and Password decoded: " + userpassDecoded); <add> <ide> String[] up = userpassDecoded.split(":"); <ide> String username = up[0]; <ide> String password = up[1];
JavaScript
mit
428597092f9649c7f4651eed59fe0d9d368e97de
0
skifaster/supertags,skifaster/supertags
SuperTags.Controller = new ClassX.extend(SuperTags.Class, function(base) { this.parseTags = function(text, options) { if(!this.token || this.token == "") { this.storeItemTag(text); return {originalText: text, modifiedText: text, tags: this.currentItemTags} } var newTagsSpacesRegEx = new RegExp(this.token + "[\\[\\({)](.+?)[\\]\\)}]","g"); var newSimpleTagsRegEx = new RegExp(this.token + "[a-z\\d-]+","g"); var cleanNewTagsRegEx = new RegExp(this.token + "[\\[\\({\\]\\)}]", "g"); var cleanCloseRegEx = new RegExp(/[\]\)\}]/g) var newSpaceTags = text.match(newTagsSpacesRegEx); var modifiedText = text; var remainingText = text; var ctx = this; if(newSpaceTags) { newSpaceTags.forEach(function (word) { var newHashTag = word.replace(cleanNewTagsRegEx, ""); newHashTag = newHashTag.replace(cleanCloseRegEx, ""); var tagDoc = {name: newHashTag}; if(ctx._cl) { ctx.saveNewTag({name: newHashTag}) } modifiedText = modifiedText.replace(word, ctx.token + newHashTag); remainingText = modifiedText.replace(ctx.token + newHashTag); ctx.storeItemTag(newHashTag) ctx.raiseEvent("tag", {callee: 'controller', action: 'newTagParsed', label: ctx.fieldName, tags: newHashTag}); }); } var tagsRemoved = []; this.currentItemTags.forEach(function (tag) { if(text.indexOf(tag) < 0 && text[text.indexOf(tag)-2] && text[text.indexOf(tag)-2] == ctx.token) { tagsRemoved.push(tag); } else { remainingText = remainingText.replace(ctx.token + tag, ""); } }); this.currentItemTags = _.difference(this.currentItemTags,tagsRemoved); var newSimpleTags = remainingText.match(newSimpleTagsRegEx); if(newSimpleTags) { newSimpleTags = _.difference(newSimpleTags, this.currentItemTags); newSimpleTags.forEach(function (tag) { var newHashTag = tag.replace(ctx.token,""); if(ctx._cl) { ctx.saveNewTag({name: newHashTag}) } ctx.storeItemTag(newHashTag); ctx.raiseEvent("tag", {callee: 'controller', action: 'newTagParsed', label: ctx.fieldName, tags: newHashTag}); }); } return {originalText: text, modifiedText: modifiedText, tags: this.currentItemTags}; } this.tagItem = function(item, additionalTags) { var res = null; if(additionalTags != null) { this.currentItemTags.push(additionalTags); } if(this.currentItemTags.length > 0) { this.raiseEvent("tag", {callee: 'controller', action: 'tagAdded', label: this.fieldName, tags: this.currentItemTags}); } if(_.isString(item)) { res = {}; res["item"] = item; res[this.fieldName] = this.currentItemTags; } else if(_.isObject(item)) { res = item; if(this.parentObj) { res[this.parentObj] = res[this.parentObj] || {}; if(res[this.parentObj][this.fieldName]) { var merge = _.union(res[this.parentObj][this.fieldName], this.currentItemTags); res[this.parentObj][this.fieldName] = merge; } else { res[this.parentObj][this.fieldName] = this.currentItemTags; } } else { res[this.fieldName] = this.currentItemTags } } this.clearAllTags(); return res; } this.saveNewTag = function(tagObj) { if(!this._cl) { return; } if(!this.tagExists(tagObj.name)) { var ctx = this; Meteor.call('SuperTags/saveNewTag-'+this.fieldName, tagObj, function (error, result) { ctx.raiseEvent("tag", {callee: 'controller', action: 'newTagSaved', label: this.fieldName, tags: tagObj}); }); } } this.findSingleTag = function(selector) { return this._cl.findOne(selector); } this.tagExists = function(name) { var tagDoc = this.findSingleTag({name: name}); if(tagDoc) return true; return false; } this.storeItemTag = function(tagName) { this.currentItemTags.push(tagName); } this.clearAllTags = function() { this.raiseEvent("tag", {callee: 'controller', action: 'tagsCleard', label: this.fieldName}); this.currentItemTags = []; } this.constructor = function Controller(options) { base.constructor.call(this, options); this.name = options.initTemplate; this.fieldName = options.label; this.parseField = options.parseField; this.token = options.token; this._cl = options.collection; this.currentItemTags = []; this.parentObj = options.parentObj; this.highlight = options.highlight; this.__ctx = this; this.itemCollection = options.itemCollection; if(this.parentObj) { this.mongoField = this.parentObj + "." + this.fieldName; } else { this.mongoField = this.fieldName; } } })
lib/js/supertags.controller.js
SuperTags.Controller = new ClassX.extend(SuperTags.Class, function(base) { this.parseTags = function(text, options) { console.log('parsing tags') if(!this.token || this.token == "") { this.storeItemTag(text); console.log('no token?') return {originalText: text, modifiedText: text, tags: this.currentItemTags} } console.log('f1') var newTagsSpacesRegEx = new RegExp(this.token + "[\\[\\({)](.+?)[\\]\\)}]","g"); var newSimpleTagsRegEx = new RegExp(this.token + "[a-z\\d-]+","g"); var cleanNewTagsRegEx = new RegExp(this.token + "[\\[\\({\\]\\)}]", "g"); var cleanCloseRegEx = new RegExp(/[\]\)\}]/g) var newSpaceTags = text.match(newTagsSpacesRegEx); var modifiedText = text; var remainingText = text; var ctx = this; if(newSpaceTags) { newSpaceTags.forEach(function (word) { var newHashTag = word.replace(cleanNewTagsRegEx, ""); newHashTag = newHashTag.replace(cleanCloseRegEx, ""); var tagDoc = {name: newHashTag}; if(ctx._cl) { console.log('no cl returning') ctx.saveNewTag({name: newHashTag}) } modifiedText = modifiedText.replace(word, ctx.token + newHashTag); remainingText = modifiedText.replace(ctx.token + newHashTag); ctx.storeItemTag(newHashTag) ctx.raiseEvent("tag", {callee: 'controller', action: 'newTagParsed', label: ctx.fieldName, tags: newHashTag}); }); } var tagsRemoved = []; this.currentItemTags.forEach(function (tag) { if(text.indexOf(tag) < 0 && text[text.indexOf(tag)-2] && text[text.indexOf(tag)-2] == ctx.token) { tagsRemoved.push(tag); } else { remainingText = remainingText.replace(ctx.token + tag, ""); } }); this.currentItemTags = _.difference(this.currentItemTags,tagsRemoved); var newSimpleTags = remainingText.match(newSimpleTagsRegEx); if(newSimpleTags) { newSimpleTags = _.difference(newSimpleTags, this.currentItemTags); console.log('new simple tag') newSimpleTags.forEach(function (tag) { var newHashTag = tag.replace(ctx.token,""); console.log('cl is ...', ctx._cl) if(ctx._cl) { console.log('no cl returning') ctx.saveNewTag({name: newHashTag}) } ctx.storeItemTag(newHashTag); ctx.raiseEvent("tag", {callee: 'controller', action: 'newTagParsed', label: ctx.fieldName, tags: newHashTag}); }); } return {originalText: text, modifiedText: modifiedText, tags: this.currentItemTags}; } this.tagItem = function(item, additionalTags) { var res = null; if(additionalTags != null) { this.currentItemTags.push(additionalTags); } if(this.currentItemTags.length > 0) { this.raiseEvent("tag", {callee: 'controller', action: 'tagAdded', label: this.fieldName, tags: this.currentItemTags}); } if(_.isString(item)) { res = {}; res["item"] = item; res[this.fieldName] = this.currentItemTags; } else if(_.isObject(item)) { res = item; if(this.parentObj) { res[this.parentObj] = res[this.parentObj] || {}; if(res[this.parentObj][this.fieldName]) { var merge = _.union(res[this.parentObj][this.fieldName], this.currentItemTags); res[this.parentObj][this.fieldName] = merge; } else { res[this.parentObj][this.fieldName] = this.currentItemTags; } } else { res[this.fieldName] = this.currentItemTags } } this.clearAllTags(); return res; } this.saveNewTag = function(tagObj) { if(!this._cl) { console.log('no cl returning') return; } console.log('trying to save ...') if(!this.tagExists(tagObj.name)) { var ctx = this; Meteor.call('SuperTags/saveNewTag-'+this.fieldName, tagObj, function (error, result) { ctx.raiseEvent("tag", {callee: 'controller', action: 'newTagSaved', label: this.fieldName, tags: tagObj}); }); } } this.findSingleTag = function(selector) { return this._cl.findOne(selector); } this.tagExists = function(name) { var tagDoc = this.findSingleTag({name: name}); if(tagDoc) return true; return false; } this.storeItemTag = function(tagName) { this.currentItemTags.push(tagName); } this.clearAllTags = function() { this.raiseEvent("tag", {callee: 'controller', action: 'tagsCleard', label: this.fieldName}); this.currentItemTags = []; } this.constructor = function Controller(options) { base.constructor.call(this, options); console.log('options', options) this.name = options.initTemplate; this.fieldName = options.label; this.parseField = options.parseField; this.token = options.token; this._cl = options.collection; this.currentItemTags = []; this.parentObj = options.parentObj; this.highlight = options.highlight; this.__ctx = this; this.itemCollection = options.itemCollection; if(this.parentObj) { this.mongoField = this.parentObj + "." + this.fieldName; } else { this.mongoField = this.fieldName; } } })
Bug fixes and updated readme
lib/js/supertags.controller.js
Bug fixes and updated readme
<ide><path>ib/js/supertags.controller.js <ide> SuperTags.Controller = new ClassX.extend(SuperTags.Class, function(base) { <ide> <ide> this.parseTags = function(text, options) { <del>console.log('parsing tags') <add> <ide> if(!this.token || this.token == "") { <ide> this.storeItemTag(text); <del>console.log('no token?') <add> <ide> return {originalText: text, modifiedText: text, tags: this.currentItemTags} <ide> } <del>console.log('f1') <add> <ide> var newTagsSpacesRegEx = new RegExp(this.token + "[\\[\\({)](.+?)[\\]\\)}]","g"); <ide> var newSimpleTagsRegEx = new RegExp(this.token + "[a-z\\d-]+","g"); <ide> var cleanNewTagsRegEx = new RegExp(this.token + "[\\[\\({\\]\\)}]", "g"); <ide> var tagDoc = {name: newHashTag}; <ide> <ide> if(ctx._cl) { <del> console.log('no cl returning') <ide> <ide> ctx.saveNewTag({name: newHashTag}) <ide> } <ide> <ide> if(newSimpleTags) { <ide> newSimpleTags = _.difference(newSimpleTags, this.currentItemTags); <del>console.log('new simple tag') <ide> newSimpleTags.forEach(function (tag) { <ide> var newHashTag = tag.replace(ctx.token,""); <del> console.log('cl is ...', ctx._cl) <ide> if(ctx._cl) { <del> console.log('no cl returning') <del> <ide> ctx.saveNewTag({name: newHashTag}) <ide> } <ide> ctx.storeItemTag(newHashTag); <ide> <ide> this.saveNewTag = function(tagObj) { <ide> if(!this._cl) { <del> console.log('no cl returning') <ide> return; <ide> } <del> console.log('trying to save ...') <ide> <ide> if(!this.tagExists(tagObj.name)) { <ide> var ctx = this; <ide> <ide> this.constructor = function Controller(options) { <ide> base.constructor.call(this, options); <del>console.log('options', options) <ide> this.name = options.initTemplate; <ide> this.fieldName = options.label; <ide> this.parseField = options.parseField;
Java
apache-2.0
920801f9109de6e97916275de492dbad0be30875
0
pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus
/** * Copyright 2007-2008 University Of Southern California * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.isi.pegasus.planner.refiner.createdir; import edu.isi.pegasus.planner.catalog.site.classes.SiteStore; import edu.isi.pegasus.planner.classes.ADag; import edu.isi.pegasus.planner.classes.Job; import edu.isi.pegasus.planner.classes.PegasusBag; import edu.isi.pegasus.common.logging.LogManager; import edu.isi.pegasus.planner.partitioner.graph.Graph; import java.util.HashSet; import java.util.Set; import java.util.Iterator; /** * The interface that defines how the cleanup job is invoked and created. * * @author Karan Vahi * @version $Revision$ */ public abstract class AbstractStrategy implements Strategy { /** * Constant suffix for the names of the create directory nodes. */ public static final String CREATE_DIR_SUFFIX = "_cdir"; /** * Constant prefix for the names of the create directory nodes. */ public static final String CREATE_DIR_PREFIX = "create_dir_"; /** * The handle to the logging object, that is used to log the messages. */ protected LogManager mLogger; /** * The job prefix that needs to be applied to the job file basenames. */ protected String mJobPrefix; /** * Whether we want to use dirmanager or mkdir directly. */ protected boolean mUseMkdir; /** * The implementation instance that is used to create a create dir job. */ protected Implementation mImpl; /** * The Site Store handle. */ protected SiteStore mSiteStore; /** * Intializes the class. * * @param bag bag of initialization objects * @param impl the implementation instance that creates create dir job */ public void initialize( PegasusBag bag, Implementation impl ){ mImpl = impl; mJobPrefix = bag.getPlannerOptions().getJobnamePrefix(); mLogger = bag.getLogger(); mSiteStore = bag.getHandleToSiteStore(); //in case of staging of executables/worker package //we use mkdir directly mUseMkdir = bag.getPegasusProperties().transferWorkerPackage(); } /** * It returns the name of the create directory job, that is to be assigned. * The name takes into account the workflow name while constructing it, as * that is thing that can guarentee uniqueness of name in case of deferred * planning. * * @param dag the workflow to which the create dir jobs are being added. * @param pool the execution pool for which the create directory job * is responsible. * * @return String corresponding to the name of the job. */ public String getCreateDirJobName( ADag dag, String pool){ StringBuffer sb = new StringBuffer(); sb.append( AbstractStrategy.CREATE_DIR_PREFIX ); //append the job prefix if specified in options at runtime if ( mJobPrefix != null ) { sb.append( mJobPrefix ); } sb.append( dag.dagInfo.nameOfADag).append("_"). append( dag.dagInfo.index).append("_"); //sb.append(pool).append(this.CREATE_DIR_SUFFIX); sb.append( pool ); return sb.toString(); } /** * Retrieves the sites for which the create dir jobs need to be created. * It returns all the sites where the compute jobs have been scheduled. * * * @return a Set containing a list of siteID's of the sites where the * dag has to be run. */ protected Set getCreateDirSites( ADag dag ){ Set set = new HashSet(); for( Iterator it = dag.vJobSubInfos.iterator();it.hasNext();){ Job job = (Job)it.next(); //add to the set only if the job is //being run in the work directory //this takes care of local site create dir if( job.runInWorkDirectory()){ set.add( job.getStagingSiteHandle() ); } } //remove the stork pool set.remove("stork"); return set; } }
src/edu/isi/pegasus/planner/refiner/createdir/AbstractStrategy.java
/** * Copyright 2007-2008 University Of Southern California * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.isi.pegasus.planner.refiner.createdir; import edu.isi.pegasus.planner.catalog.site.classes.SiteStore; import edu.isi.pegasus.planner.classes.ADag; import edu.isi.pegasus.planner.classes.Job; import edu.isi.pegasus.planner.classes.PegasusBag; import edu.isi.pegasus.common.logging.LogManager; import edu.isi.pegasus.planner.partitioner.graph.Graph; import java.util.HashSet; import java.util.Set; import java.util.Iterator; /** * The interface that defines how the cleanup job is invoked and created. * * @author Karan Vahi * @version $Revision$ */ public abstract class AbstractStrategy implements Strategy { /** * Constant suffix for the names of the create directory nodes. */ public static final String CREATE_DIR_SUFFIX = "_cdir"; /** * Constant prefix for the names of the create directory nodes. */ public static final String CREATE_DIR_PREFIX = "create_dir_"; /** * The handle to the logging object, that is used to log the messages. */ protected LogManager mLogger; /** * The job prefix that needs to be applied to the job file basenames. */ protected String mJobPrefix; /** * Whether we want to use dirmanager or mkdir directly. */ protected boolean mUseMkdir; /** * The implementation instance that is used to create a create dir job. */ protected Implementation mImpl; /** * The Site Store handle. */ protected SiteStore mSiteStore; /** * Intializes the class. * * @param bag bag of initialization objects * @param impl the implementation instance that creates create dir job */ public void initialize( PegasusBag bag, Implementation impl ){ mImpl = impl; mJobPrefix = bag.getPlannerOptions().getJobnamePrefix(); mLogger = bag.getLogger(); mSiteStore = bag.getHandleToSiteStore(); //in case of staging of executables/worker package //we use mkdir directly mUseMkdir = bag.getPegasusProperties().transferWorkerPackage(); } /** * It returns the name of the create directory job, that is to be assigned. * The name takes into account the workflow name while constructing it, as * that is thing that can guarentee uniqueness of name in case of deferred * planning. * * @param dag the workflow to which the create dir jobs are being added. * @param pool the execution pool for which the create directory job * is responsible. * * @return String corresponding to the name of the job. */ public String getCreateDirJobName( ADag dag, String pool){ StringBuffer sb = new StringBuffer(); sb.append( AbstractStrategy.CREATE_DIR_PREFIX ); //append the job prefix if specified in options at runtime if ( mJobPrefix != null ) { sb.append( mJobPrefix ); } sb.append( dag.dagInfo.nameOfADag).append("_"). append( dag.dagInfo.index).append("_"); //sb.append(pool).append(this.CREATE_DIR_SUFFIX); sb.append( pool ); return sb.toString(); } /** * Retrieves the sites for which the create dir jobs need to be created. * It returns all the sites where the compute jobs have been scheduled. * * * @return a Set containing a list of siteID's of the sites where the * dag has to be run. */ protected Set getCreateDirSites( ADag dag ){ Set set = new HashSet(); for( Iterator it = dag.vJobSubInfos.iterator();it.hasNext();){ Job job = (Job)it.next(); //add to the set only if the job is //being run in the work directory //this takes care of local site create dir if( job.getJobType() == Job.COMPUTE_JOB && job.runInWorkDirectory()){ set.add( job.getStagingSiteHandle() ); } } //remove the stork pool set.remove("stork"); return set; } }
JIRA PM-494 The DAX and DAG jobs should also be associated with teh create dir job on local site/staging site. This is similar to behavior in 3.1
src/edu/isi/pegasus/planner/refiner/createdir/AbstractStrategy.java
JIRA PM-494
<ide><path>rc/edu/isi/pegasus/planner/refiner/createdir/AbstractStrategy.java <ide> //add to the set only if the job is <ide> //being run in the work directory <ide> //this takes care of local site create dir <del> if( job.getJobType() == Job.COMPUTE_JOB && job.runInWorkDirectory()){ <add> if( job.runInWorkDirectory()){ <ide> set.add( job.getStagingSiteHandle() ); <ide> } <ide> }
Java
apache-2.0
f76035aae2171911137ea2f06178113ec8ab5739
0
jaamsim/jaamsim,jaamsim/jaamsim,jaamsim/jaamsim,jaamsim/jaamsim
/* * JaamSim Discrete Event Simulation * Copyright (C) 2016-2021 JaamSim Software 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.jaamsim.basicsim; import java.io.File; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.concurrent.atomic.AtomicLong; import com.jaamsim.Graphics.DisplayEntity; import com.jaamsim.Graphics.EntityLabel; import com.jaamsim.Samples.SampleExpression; import com.jaamsim.StringProviders.StringProvExpression; import com.jaamsim.SubModels.CompoundEntity; import com.jaamsim.SubModels.SubModel; import com.jaamsim.SubModels.SubModelClone; import com.jaamsim.Thresholds.ThresholdUser; import com.jaamsim.datatypes.IntegerVector; import com.jaamsim.events.Conditional; import com.jaamsim.events.EventHandle; import com.jaamsim.events.EventManager; import com.jaamsim.events.EventTimeListener; import com.jaamsim.events.ProcessTarget; import com.jaamsim.input.ExpError; import com.jaamsim.input.Input; import com.jaamsim.input.InputAgent; import com.jaamsim.input.InputErrorException; import com.jaamsim.input.KeywordIndex; import com.jaamsim.input.NamedExpressionListInput; import com.jaamsim.input.ParseContext; import com.jaamsim.math.Vec3d; import com.jaamsim.states.StateEntity; import com.jaamsim.ui.EventViewer; import com.jaamsim.ui.LogBox; import com.jaamsim.units.DimensionlessUnit; import com.jaamsim.units.DistanceUnit; import com.jaamsim.units.TimeUnit; import com.jaamsim.units.Unit; public class JaamSimModel implements EventTimeListener { // Perform debug only entity list validation logic private static final boolean VALIDATE_ENT_LIST = false; private static final Object createLock = new Object(); private static JaamSimModel createModel = null; private final EventManager eventManager; private Simulation simulation; private String name; private int scenarioNumber; // labels each scenario when multiple scenarios are being made private IntegerVector scenarioIndexList; private int replicationNumber; private RunListener runListener; // notifies the SimRun that the run has ended private GUIListener gui; private final AtomicLong entityCount = new AtomicLong(0); private final HashMap<String, Entity> namedEntities = new HashMap<>(100); private final HashMap<Class<? extends Unit>, Unit> preferredUnit = new HashMap<>(); // Note, entityList is an empty list node used to identify the end of the list // The first real entity is at entityList.next.ent private final EntityListNode entityList = new EntityListNode(); private int numLiveEnts; private File configFile; // present configuration file private File reportDir; // directory for the output reports private boolean batchRun; // true if the run is to be terminated automatically private boolean scriptMode; // TRUE if script mode (command line) is specified private boolean sessionEdited; // TRUE if any inputs have been changed after loading a configuration file private boolean recordEditsFound; // TRUE if the "RecordEdits" marker is found in the configuration file private boolean recordEdits; // TRUE if input changes are to be marked as edited private FileEntity logFile; private int numErrors = 0; private int numWarnings = 0; private long lastTickForTrace = -1L; private long preDefinedEntityCount = 0L; // Number of entities after loading autoload.cfg private final HashMap<String, String> stringCache = new HashMap<>(); private final ArrayList<ObjectType> objectTypes = new ArrayList<>(); private final HashMap<Class<? extends Entity>, ObjectType> objectTypeMap = new HashMap<>(); private final SimCalendar calendar = new SimCalendar(); private long startMillis; // start time in milliseonds from the epoch private boolean calendarUsed; // records whether the calendar has been used private boolean reloadReqd; // indicates that the simulation must be saved and reloaded private int simState; /** model was executed, but no configuration performed */ public static final int SIM_STATE_LOADED = 0; /** essential model elements created, no configuration performed */ public static final int SIM_STATE_UNCONFIGURED = 1; /** model has been configured, not started */ public static final int SIM_STATE_CONFIGURED = 2; /** model is presently executing events */ public static final int SIM_STATE_RUNNING = 3; /** model has run, but presently is paused */ public static final int SIM_STATE_PAUSED = 4; /** model is paused but cannot be resumed */ public static final int SIM_STATE_ENDED = 5; public JaamSimModel() { this(""); } public JaamSimModel(String name) { eventManager = new EventManager("DefaultEventManager"); eventManager.setTimeListener(this); simulation = null; this.name = name; scenarioNumber = 1; replicationNumber = 1; scenarioIndexList = new IntegerVector(); scenarioIndexList.add(1); } public JaamSimModel(JaamSimModel sm) { this(sm.name); autoLoad(); simulation = getSimulation(); setRecordEdits(true); configFile = sm.configFile; reportDir = sm.reportDir; // Ensure that 'getReportDirectory' works correctly for an Example Model if (reportDir == null && configFile == null) reportDir = new File(sm.getReportDirectory()); // Create the new entities in the same order as the original model for (Entity ent : sm.getClonesOfIterator(Entity.class)) { if (!ent.isRegistered()) break; if (ent.isPreDefined() || getNamedEntity(ent.getName()) != null) continue; // Generate all the sub-model components when the first one is found if (ent.isGenerated() && ent.getParent() instanceof SubModelClone) { Entity clone = getNamedEntity(ent.getParent().getName()); SubModel proto = ((SubModelClone) ent.getParent()).getPrototype(); if (clone == null || proto == null) continue; KeywordIndex kw = InputAgent.formatInput("Prototype", proto.getName()); InputAgent.apply(clone, kw); continue; } // Define the new object defineEntity(ent.getObjectType().getName(), ent.getName()); } // Prepare a sorted list of registered entities on which to set inputs ArrayList<Entity> entityList = new ArrayList<>(); for (Entity ent : sm.getClonesOfIterator(Entity.class)) { if (!ent.isRegistered()) break; if (ent instanceof ObjectType) continue; entityList.add(ent); } Collections.sort(entityList, InputAgent.subModelSortOrder); // Stub definitions for (Entity ent : entityList) { if (ent.isGenerated()) continue; NamedExpressionListInput in = (NamedExpressionListInput) ent.getInput("CustomOutputList"); if (in == null || in.isDefault()) continue; Entity newEnt = getNamedEntity(ent.getName()); if (newEnt == null) throw new ErrorException("New entity not found: %s", ent.getName()); KeywordIndex kw = InputAgent.formatInput(in.getKeyword(), in.getStubDefinition()); InputAgent.apply(newEnt, kw); } ParseContext context = null; if (sm.getConfigFile() != null) { URI uri = sm.getConfigFile().getParentFile().toURI(); context = new ParseContext(uri, null); } // Copy the early inputs to the new entities in the specified sequence of inputs for (String key : InputAgent.EARLY_KEYWORDS) { for (Entity ent : entityList) { Entity newEnt = getNamedEntity(ent.getName()); if (newEnt == null) throw new ErrorException("New entity not found: %s", ent.getName()); newEnt.copyInput(ent, key, context, false); } } // Copy the normal inputs to the new entities for (Entity ent : entityList) { Entity newEnt = getNamedEntity(ent.getName()); if (newEnt == null) throw new ErrorException("New entity not found: %s", ent.getName()); for (Input<?> in : ent.getEditableInputs()) { if (in.isSynonym() || InputAgent.isEarlyInput(in)) continue; String key = in.getKeyword(); newEnt.copyInput(ent, key, context, false); } } // Complete the preparation of the sub-model clones postLoad(); // Verify that the new JaamSimModel is an exact copy if (!this.isCopyOf(sm)) throw new ErrorException("Copied JaamSimModel does not match the original"); } /** * Returns whether this JaamSimModel is a copy of the specified model. * Avoids the complexities of overriding the equals method. * @param sm - JaamSimModel to be compared * @return true if the model is a copy */ public boolean isCopyOf(JaamSimModel sm) { // Loop through the two sets of entities in parallel ClonesOfIterable<Entity> itr0 = sm.getClonesOfIterator(Entity.class); ClonesOfIterable<Entity> itr1 = this.getClonesOfIterator(Entity.class); while (itr0.hasNext() || itr1.hasNext()) { Entity ent0 = itr0.hasNext() ? itr0.next() : null; Entity ent1 = itr1.hasNext() ? itr1.next() : null; if (ent0 == null || ent1 == null || !ent0.isRegistered() || !ent1.isRegistered()) continue; // Verify that the entity list contains the same sequence of objects if (!ent1.isCopyOf(ent0)) { System.out.format("Entity lists do not match: ent0=%s, ent1=%s%n", ent0, ent1); return false; } } return true; } public void setName(String str) { name = str; } public final void setRunListener(RunListener l) { runListener = l; } public final RunListener getRunListener() { return runListener; } public void setGUIListener(GUIListener l) { gui = l; } public GUIListener getGUIListener() { return gui; } @Override public void tickUpdate(long tick) { if (gui == null) return; gui.tickUpdate(tick); } @Override public void timeRunning() { if (gui == null) return; gui.timeRunning(); } @Override public void handleError(Throwable t) { if (isMultipleRuns() && runListener != null) { runListener.handleError(t); return; } if (gui == null) return; gui.handleError(t); } public int getSimState() { return simState; } public void setSimState(int state) { simState = state; } public String getName() { return name; } /** * Deletes all the objects in the present model and prepares the JaamSimModel to load a new * input file using the autoLoad() and configure() methods. */ public void clear() { eventManager.clear(); eventManager.setTraceListener(null); // Reset the GUI inputs maintained by the Simulation entity if (getSimulation() != null) { getSimulation().clear(); } EntityListNode listNode = entityList.next; while(listNode != entityList) { Entity curEnt = listNode.ent; if (!curEnt.isDead()) { curEnt.kill(); } listNode = listNode.next; } // Reset calendar calendar.setGregorian(false); startMillis = 0L; calendarUsed = false; reloadReqd = false; // Clear the 'simulation' property simulation = null; // close warning/error trace file closeLogFile(); stringCache.clear(); // Reset the run number and run indices scenarioNumber = 1; replicationNumber = 1; configFile = null; reportDir = null; setSessionEdited(false); recordEditsFound = false; numErrors = 0; numWarnings = 0; lastTickForTrace = -1L; } public final String internString(String str) { synchronized (stringCache) { String ret = stringCache.get(str); if (ret == null) { stringCache.put(str, str); ret = str; } return ret; } } /** * Pre-loads the simulation model with built-in objects such as Simulation and Units. */ public void autoLoad() { // Load the autoload.cfg file setRecordEdits(false); InputAgent.readResource(this, "<res>/inputs/autoload.cfg"); // Save the number of entities created by the autoload.cfg file preDefinedEntityCount = getTailEntity().getEntityNumber(); } /** * Loads the specified configuration file to create the objects in the model. * The autoLoad() method must be executed first. * @param file - configuration file * @throws URISyntaxException */ public void configure(File file) throws URISyntaxException { configFile = file; openLogFile(); InputAgent.loadConfigurationFile(this, file); name = file.getName(); // The session is not considered to be edited after loading a configuration file setSessionEdited(false); // Save and close the input trace file if (numWarnings == 0 && numErrors == 0) { closeLogFile(); // Open a fresh log file for the simulation run openLogFile(); } } /** * Performs any additional actions that are required for each entity after a new configuration * file has been loaded. Performed prior to validation. */ public void postLoad() { for (Entity each : getClonesOfIterator(Entity.class)) { each.postLoad(); } } /** * Performs consistency checks on the model inputs. * @return true if no validation errors were found */ public boolean validate() { for (Entity each : getClonesOfIterator(Entity.class)) { try { each.validate(); } catch (Throwable t) { if (gui != null) { gui.handleInputError(t, each); } else { System.out.format("Validation Error - %s: %s%n", each.getName(), t.getMessage()); } return false; } } return true; } /** * Starts the simulation model on a new thread. */ public void start() { //System.out.format("%s.start%n", this); double pauseTime = getSimulation().getPauseTime(); start(pauseTime); } public void start(double pauseTime) { boolean bool = validate(); if (!bool) return; prepareReportDirectory(); eventManager.clear(); // Set up any tracing to be performed eventManager.setTraceListener(null); if (getSimulation().traceEvents()) { String evtName = configFile.getParentFile() + File.separator + getRunName() + ".evt"; EventRecorder rec = new EventRecorder(evtName); eventManager.setTraceListener(rec); } else if (getSimulation().verifyEvents()) { String evtName = configFile.getParentFile() + File.separator + getRunName() + ".evt"; EventTracer trc = new EventTracer(evtName); eventManager.setTraceListener(trc); } else if (getSimulation().isEventViewerVisible()) { eventManager.setTraceListener(EventViewer.getInstance()); } eventManager.setTickLength(getSimulation().getTickLength()); startRun(pauseTime); } void initRun() { eventManager.scheduleProcessExternal(0, 0, false, new InitModelTarget(this), null); } /** * Starts a single simulation run. */ public void startRun(double pauseTime) { initRun(); resume(pauseTime); } /** * Performs the first stage of initialization for each entity. */ public void earlyInit() { thresholdChangedTarget.users.clear(); for (Entity each : getClonesOfIterator(Entity.class)) { each.earlyInit(); } } /** * Performs the second stage of initialization for each entity. */ public void lateInit() { for (Entity each : getClonesOfIterator(Entity.class)) { each.lateInit(); } } /** * Performs the start-up procedure for each entity. */ public void startUp() { double startTime = getSimulation().getStartTime(); long startTicks = eventManager.secondsToNearestTick(startTime); for (Entity each : getClonesOfIterator(Entity.class)) { if (!each.isActive()) continue; EventManager.scheduleTicks(startTicks, 0, true, new StartUpTarget(each), null); } } /** * Performs the shut down procedure for each entity. */ public void close() { for (Entity each : getClonesOfIterator(Entity.class)) { each.close(); } } public void doPauseCondition() { if (getSimulation().isPauseConditionSet()) EventManager.scheduleUntil(pauseModelTarget, pauseCondition, null); } private final PauseModelTarget pauseModelTarget = new PauseModelTarget(this); private final Conditional pauseCondition = new Conditional() { @Override public boolean evaluate() { double simTime = EventManager.simSeconds(); return getSimulation().isPauseConditionSatisfied(simTime); } }; /** * Reset the statistics for each entity. */ public void clearStatistics() { for (Entity ent : getClonesOfIterator(Entity.class)) { if (!ent.isActive()) continue; ent.clearStatistics(); } // Reset state statistics for (StateEntity each : getClonesOfIterator(StateEntity.class)) { if (!each.isActive()) continue; each.collectInitializationStats(); } } /** * Suspends model execution at the present simulation time. */ public void pause() { //System.out.format("%s.pause%n", this); eventManager.pause(); } /** * Resumes a paused simulation model. * The model will continue execution until the specified simulation time at which the model * will be paused. * Events scheduled at the next pause time will not be executed until the model is resumed. * @param simTime - next pause time */ public void resume(double simTime) { eventManager.resume(eventManager.secondsToNearestTick(simTime)); } /** * Executes the end of run method for each entity. */ public void doEnd() { for (Entity each : getClonesOfIterator(Entity.class)) { if (!each.isActive()) continue; each.doEnd(); } } /** * Sets the simulation time to zero and re-initializes the model. * The start() method can be used to begin a new simulation run. */ public void reset() { eventManager.pause(); eventManager.clear(); killGeneratedEntities(); // Perform earlyInit for (Entity each : getClonesOfIterator(Entity.class)) { // Try/catch is required because some earlyInit methods use simTime which is only // available from a process thread, which is not the case when called from endRun try { each.earlyInit(); } catch (Exception e) {} } // Perform lateInit for (Entity each : getClonesOfIterator(Entity.class)) { // Try/catch is required because some lateInit methods use simTime which is only // available from a process thread, which is not the case when called from endRun try { each.lateInit(); } catch (Exception e) {} } } /** * Prepares the model for the next simulation run number. */ public void endRun() { // Execute the end of run method for each entity doEnd(); // Stop the model pause(); // Notify the run manager if (runListener != null) runListener.runEnded(null); } /** * Destroys the entities that were generated during the present simulation run. */ public void killGeneratedEntities() { EntityListNode curNode = entityList.next; while(curNode != entityList) { Entity curEnt = curNode.ent; if (!curEnt.isDead() && !curEnt.testFlag(Entity.FLAG_RETAINED)) { curEnt.kill(); } curNode = curNode.next; } } /** * Ends a set of simulation runs. */ public void end() { // Close warning/error trace file LogBox.logLine("Made it to do end at"); closeLogFile(); // Always terminate the run when in batch mode if (isBatchRun() || getSimulation().getExitAtStop()) { if (gui != null) gui.exit(0); System.exit(0); } pause(); } /** * Returns whether events are being executed. * @return true if the events are being executed */ public boolean isRunning() { return eventManager.isRunning(); } /** * Returns the present simulation time in seconds. * @return simulation time */ public double getSimTime() { return eventManager.ticksToSeconds(eventManager.getTicks()); } public long getSimTicks() { return eventManager.getTicks(); } /** * Evaluates the specified expression and returns its value as a string. * Any type of result can be returned by the expression, including an entity or an array. * If it returns a number, it must be dimensionless. * @param expString - expression to be evaluated * @return expression value as a string */ public String getStringValue(String expString) { double simTime = getSimTime(); try { Class<? extends Unit> unitType = DimensionlessUnit.class; Entity thisEnt = getSimulation(); StringProvExpression strProv = new StringProvExpression(expString, thisEnt, unitType); return strProv.getNextString(simTime); } catch (ExpError e) { return "Cannot evaluate"; } } /** * Evaluates the specified expression and returns its value. * The expression must return a dimensionless number. * All other types of expressions return NaN. * @param expString - expression to be evaluated * @return expression value */ public double getDoubleValue(String expString) { double simTime = getSimTime(); try { Class<? extends Unit> unitType = DimensionlessUnit.class; Entity thisEnt = getSimulation(); SampleExpression sampleExp = new SampleExpression(expString, thisEnt, unitType); return sampleExp.getNextSample(simTime); } catch (ExpError e) { return Double.NaN; } } /** * Creates a new entity for the specified type and name. * If the name already used, "_1", "_2", etc. will be appended to the name until an unused * name is found. * @param type - type of entity to be created * @param name - absolute name for the created entity */ public void defineEntity(String type, String name) { try { Class<? extends Entity> klass = Input.parseEntityType(this, type); InputAgent.defineEntityWithUniqueName(this, klass, name, "_", true); } catch (InputErrorException e) { return; } } /** * Sets the input for the specified entity and keyword to the specified string. * @param entName - name of the entity whose input is to be set * @param keyword - input keyword whose value is to be set * @param arg - input string as it would appear in the Input Editor */ public void setInput(String entName, String keyword, String arg) { setRecordEdits(true); Entity ent = getNamedEntity(entName); KeywordIndex kw = InputAgent.formatInput(keyword, arg); InputAgent.apply(ent, kw); } /** * Writes the inputs for the simulation model to the specified file. * @param file - file to which the model inputs are to be saved */ public void save(File file) { InputAgent.printNewConfigurationFileWithName(this, file); configFile = file; name = file.getName(); } public EventManager getEventManager() { return eventManager; } void setSimulation(Simulation sim) { simulation = sim; } public Simulation getSimulation() { return simulation; } public boolean isMultipleRuns() { return getSimulation().getNumberOfRuns() > 1; } public boolean isFirstRun() { return isFirstScenario() && replicationNumber == 1; } public boolean isLastRun() { return isLastScenario() && replicationNumber == getSimulation().getNumberOfReplications(); } public boolean isFirstScenario() { return scenarioNumber == getSimulation().getStartingScenarioNumber(); } public boolean isLastScenario() { return scenarioNumber >= getSimulation().getEndingScenarioNumber(); } /** * Returns the run indices that correspond to a given run number. * @param n - run number. * @param rangeList - maximum value for each index. * @return run indices. */ public static IntegerVector getRunIndexList(int n, IntegerVector rangeList) { if (rangeList.size() == 0) { IntegerVector indexList = new IntegerVector(1); indexList.add(n); return indexList; } IntegerVector indexList = new IntegerVector(rangeList.size()); indexList.fillWithEntriesOf(rangeList.size(), 0); int denom = 1; for (int i=rangeList.size()-1; i>=0; i--) { indexList.set(i, (n-1)/denom % rangeList.get(i) + 1); denom *= rangeList.get(i); } return indexList; } /** * Returns the run number that corresponds to a given set of run indices. * @param indexList - run indices. * @param rangeList - maximum value for each index. * @return run number. */ public static int getRunNumber(IntegerVector indexList, IntegerVector rangeList) { int n = 1; int factor = 1; for (int i=indexList.size()-1; i>=0; i--) { n += (indexList.get(i)-1)*factor; factor *= rangeList.get(i); } return n; } /** * Returns the input format used to specify a set of scenario indices. * @param indexList - scenario indices. * @return scenario code. */ public static String getScenarioCode(IntegerVector indexList) { StringBuilder sb = new StringBuilder(); sb.append(indexList.get(0)); for (int i=1; i<indexList.size(); i++) { sb.append("-").append(indexList.get(i)); } return sb.toString(); } public void setScenarioNumber(int n) { scenarioNumber = n; setScenarioIndexList(); } public void setScenarioIndexList() { scenarioIndexList = getRunIndexList(scenarioNumber, getSimulation().getScenarioIndexDefinitionList()); } public int getScenarioNumber() { return scenarioNumber; } public IntegerVector getScenarioIndexList() { return scenarioIndexList; } public String getScenarioCode() { return getScenarioCode(scenarioIndexList); } public void setReplicationNumber(int n) { replicationNumber = n; } public int getReplicationNumber() { return replicationNumber; } public int getRunNumber() { int numberOfReplications = getSimulation().getNumberOfReplications(); return (scenarioNumber - 1) * numberOfReplications + replicationNumber; } public String getRunHeader() { return String.format("##### SCENARIO %s - REPLICATION %s #####", getScenarioCode(), replicationNumber); } final long getNextEntityID() { return entityCount.incrementAndGet(); } public final Entity getNamedEntity(String name) { if (name.contains(".")) { String[] names = name.split("\\."); return getEntityFromNames(names); } synchronized (namedEntities) { return namedEntities.get(name); } } public final Entity getEntity(String name) { Entity ret = getNamedEntity(name); if (ret != null) return ret; for (Entity ent: getClonesOfIterator(Entity.class)) { if (ent.getName().equals(name)) { return ent; } } return null; } // Get an entity from a chain of names, descending into the tree of children public final Entity getEntityFromNames(String[] names) { Entity currEnt = getSimulation(); for (String name: names) { if (currEnt == null) { return null; } currEnt = currEnt.getChild(name); } return currEnt; } public final long getEntitySequence() { long seq = (long)numLiveEnts << 32; seq += entityCount.get(); return seq; } public final Entity idToEntity(long id) { synchronized (namedEntities) { EntityListNode curNode = entityList.next; while(true) { if (curNode == entityList) { return null; } Entity curEnt = curNode.ent; if (curEnt != null && curEnt.getEntityNumber() == id) { return curEnt; } curNode = curNode.next; } } } static JaamSimModel getCreateModel() { synchronized (createLock) { JaamSimModel mod = createModel; createModel = null; return mod; } } /** * Creates a new entity. * @param proto - class for the entity * @param name - entity local name * @param parent - entity's parent * @param added - true if the entity was defined after the 'RecordEdits' flag * @param gen - true if the entity was created during the execution of the simulation * @param reg - true if the entity is included in the namedEntities HashMap * @param retain - true if the entity is retained when the model is reset between runs * @return new entity */ public final <T extends Entity> T createInstance(Class<T> proto, String name, Entity parent, boolean added, boolean gen, boolean reg, boolean retain) { T ent = createInstance(proto); if (ent == null) return null; // Set the entity type if (added) ent.setFlag(Entity.FLAG_ADDED); if (gen) ent.setFlag(Entity.FLAG_GENERATED); if (reg) ent.setFlag(Entity.FLAG_REGISTERED); if (retain) ent.setFlag(Entity.FLAG_RETAINED); ent.parent = parent; ent.entityName = name; if (reg) addNamedEntity(ent); // Create any objects associated with this entity and set their inputs // (These objects and their inputs are not be marked as 'edited' to avoid having them saved // to the input file) boolean bool = isRecordEdits(); setRecordEdits(false); ent.postDefine(); setRecordEdits(bool); return ent; } public final <T extends Entity> T createInstance(Class<T> proto) { T ent = null; try { synchronized (createLock) { createModel = this; ent = proto.newInstance(); } addInstance(ent); } catch (Throwable e) {} return ent; } public final void addNamedEntity(Entity ent) { if (ent.parent != null) { ent.parent.addChild(ent); return; } synchronized (namedEntities) { if (namedEntities.get(ent.entityName) != null) throw new ErrorException("Entity name: %s is already in use.", ent.entityName); namedEntities.put(ent.entityName, ent); } } public final void removeNamedEntity(Entity ent) { if (ent.parent != null) { ent.parent.removeChild(ent); return; } synchronized (namedEntities) { if (namedEntities.remove(ent.entityName) != ent) throw new ErrorException("Named Entities Internal Consistency error"); } } /** * Changes the specified entity's name. * @param ent - entity to be renamed * @param newName - new local name for the entity */ final void renameEntity(Entity ent, String newName) { if (!ent.isRegistered()) { ent.entityName = newName; return; } if (ent.entityName != null) { removeNamedEntity(ent); } ent.entityName = newName; addNamedEntity(ent); } private void validateEntList() { if (!VALIDATE_ENT_LIST) { return; } synchronized(namedEntities) { // Count the number of live entities and make sure all entity numbers are increasing // Also, check that the lastEnt reference is correct int numEntities = 0; long lastEntNum = -1; int numDeadEntities = 0; if (entityList.ent != null) { assert(false); throw new ErrorException("Entity List Validation Error!"); } EntityListNode curNode = entityList.next; EntityListNode lastNode = entityList; while (curNode != null && curNode != entityList) { Entity curEnt = curNode.ent; if (!curEnt.isDead()) { numEntities++; } else { numDeadEntities++; } if (curEnt.getEntityNumber() <= lastEntNum) { assert(false); throw new ErrorException("Entity List Validation Error!"); } if (curNode.prev != lastNode) { assert(false); throw new ErrorException("Entity List Validation Error!"); } lastEntNum = curEnt.getEntityNumber(); lastNode = curNode; curNode = curNode.next; } if (numEntities != numLiveEnts) { assert(false); throw new ErrorException("Entity List Validation Error!"); } if (this.entityList.prev != lastNode) { assert(false); throw new ErrorException("Entity List Validation Error!"); } if (numDeadEntities > 0) { assert(false); throw new ErrorException("Entity List Validation Error!"); } if (curNode == null) { assert(false); throw new ErrorException("Entity List Validation Error!"); } // Scan the list backwards curNode = entityList.prev; lastNode = entityList; numEntities = 0; lastEntNum = Long.MAX_VALUE; while (curNode != null && curNode != entityList) { Entity curEnt = curNode.ent; if (!curEnt.isDead()) { numEntities++; } else { numDeadEntities++; } if (curEnt.getEntityNumber() >= lastEntNum) { assert(false); throw new ErrorException("Entity List Validation Error!"); } if (curNode.next != lastNode) { assert(false); throw new ErrorException("Entity List Validation Error!"); } lastEntNum = curEnt.getEntityNumber(); lastNode = curNode; curNode = curNode.prev; } if (numEntities != numLiveEnts) { assert(false); throw new ErrorException("Entity List Validation Error!"); } if (this.entityList.next != lastNode) { assert(false); throw new ErrorException("Entity List Validation Error!"); } if (numDeadEntities > 0) { assert(false); throw new ErrorException("Entity List Validation Error!"); } if (curNode == null) { assert(false); throw new ErrorException("Entity List Validation Error!"); } } // synchronized(namedEntities) } final void addInstance(Entity e) { synchronized(namedEntities) { validateEntList(); numLiveEnts++; EntityListNode newNode = new EntityListNode(e); EntityListNode oldLast = entityList.prev; newNode.prev = oldLast; newNode.next = entityList; oldLast.next = newNode; entityList.prev = newNode; validateEntList(); } } final void restoreInstance(Entity e) { synchronized (namedEntities) { validateEntList(); numLiveEnts++; // Scan through the linked list to find the place to insert this entity // This is slow, but should only happen due to user actions long entNum = e.getEntityNumber(); EntityListNode curNode = entityList.next; while(true) { Entity nextEnt = curNode.next.ent; if (nextEnt == null || nextEnt.getEntityNumber() > entNum) { // End of the list or at the correct location // Insert a new node after curNode EntityListNode newNode = new EntityListNode(e); newNode.next = curNode.next; newNode.prev = curNode; curNode.next = newNode; newNode.next.prev = newNode; validateEntList(); return; } curNode = curNode.next; } } } final void removeInstance(Entity e) { synchronized (namedEntities) { validateEntList(); numLiveEnts--; if (e.isRegistered()) removeNamedEntity(e); e.entityName = null; e.setFlag(Entity.FLAG_DEAD); EntityListNode listNode = e.listNode; // Break the link to the list e.listNode = null; listNode.ent = null; listNode.next.prev = listNode.prev; listNode.prev.next = listNode.next; // Note, leaving the nodes next and prev pointers intact so that any outstanding iterators // can finish traversing the list validateEntList(); } } /** * Returns an Iterator that loops over the instances of the specified class. It does not * include instances of any sub-classes of the class. * The specified class must be a sub-class of Entity. * @param proto - specified class * @return Iterator for instances of the class */ public <T extends Entity> InstanceIterable<T> getInstanceIterator(Class<T> proto){ return new InstanceIterable<>(this, proto); } /** * Returns an Iterator that loops over the instances of the specified class and its * sub-classes. * The specified class must be a sub-class of Entity. * @param proto - specified class * @return Iterator for instances of the class and its sub-classes */ public <T extends Entity> ClonesOfIterable<T> getClonesOfIterator(Class<T> proto){ return new ClonesOfIterable<>(this, proto); } /** * Returns an iterator that loops over the instances of the specified class and its * sub-classes, but of only those classes that implement the specified interface. * The specified class must be a sub-class of Entity. * @param proto - specified class * @param iface - specified interface * @return Iterator for instances of the class and its sub-classes that implement the specified interface */ public <T extends Entity> ClonesOfIterableInterface<T> getClonesOfIterator(Class<T> proto, Class<?> iface){ return new ClonesOfIterableInterface<>(this, proto, iface); } // Note, these methods should only be called by EntityIterator and some unit tests public final Entity getHeadEntity() { return entityList.next.ent; } public final Entity getTailEntity() { return entityList.prev.ent; } public final EntityListNode getEntityList() { return entityList; } public void addObjectType(ObjectType ot) { synchronized (objectTypes) { objectTypes.add(ot); objectTypeMap.put(ot.getJavaClass(), ot); } } public void removeObjectType(ObjectType ot) { synchronized (objectTypes) { objectTypes.remove(ot); objectTypeMap.remove(ot.getJavaClass()); } } public ArrayList<ObjectType> getObjectTypes() { synchronized (objectTypes) { return objectTypes; } } public ObjectType getObjectTypeForClass(Class<? extends Entity> klass) { synchronized (objectTypes) { return objectTypeMap.get(klass); } } private final EventHandle thresholdChangedHandle = new EventHandle(); private final ThresholdChangedTarget thresholdChangedTarget = new ThresholdChangedTarget(); private static class ThresholdChangedTarget extends ProcessTarget { public final ArrayList<ThresholdUser> users = new ArrayList<>(); public ThresholdChangedTarget() {} @Override public void process() { for (int i = 0; i < users.size(); i++) { users.get(i).thresholdChanged(); } users.clear(); } @Override public String getDescription() { return "UpdateAllThresholdUsers"; } } public void updateThresholdUsers(ArrayList<ThresholdUser> userList) { for (ThresholdUser user : userList) { if (!thresholdChangedTarget.users.contains(user)) thresholdChangedTarget.users.add(user); } if (!thresholdChangedTarget.users.isEmpty() && !thresholdChangedHandle.isScheduled()) EventManager.scheduleTicks(0, 2, false, thresholdChangedTarget, thresholdChangedHandle); } /** * Returns the present configuration file. * Null is returned if no configuration file has been loaded or saved yet. * @return present configuration file */ public File getConfigFile() { return configFile; } /** * Returns the name of the simulation run. * For example, if the model name is "case1.cfg", then the run name is "case1". * @return name of the simulation run */ public String getRunName() { int index = name.lastIndexOf('.'); if (index == -1) return name; return name.substring(0, index); } private String getReportDirectory() { if (reportDir != null) return reportDir.getPath(); if (configFile != null) return configFile.getParentFile().getPath(); if (gui != null && gui.getDefaultFolder() != null) return gui.getDefaultFolder(); return null; } /** * Returns the path to the report file with the specified extension for this model. * Returns null if the file path cannot be constructed. * @param ext - file extension, e.g. ".dat" * @return file path */ public String getReportFileName(String ext) { String dir = getReportDirectory(); if (dir == null) return null; StringBuilder sb = new StringBuilder(); sb.append(dir); sb.append(File.separator); sb.append(getRunName()); sb.append(ext); return sb.toString(); } public void setReportDirectory(File dir) { reportDir = dir; if (reportDir == null) return; if (!reportDir.exists() && !reportDir.mkdirs()) throw new InputErrorException("Was unable to create the Report Directory: %s", reportDir.toString()); } public void prepareReportDirectory() { if (reportDir != null) reportDir.mkdirs(); } public void setBatchRun(boolean bool) { batchRun = bool; } public boolean isBatchRun() { return batchRun; } public void setScriptMode(boolean bool) { scriptMode = bool; } public boolean isScriptMode() { return scriptMode; } public void setSessionEdited(boolean bool) { sessionEdited = bool; } public boolean isSessionEdited() { return sessionEdited; } /** * Specifies whether a RecordEdits marker was found in the present configuration file. * @param bool - TRUE if a RecordEdits marker was found. */ public void setRecordEditsFound(boolean bool) { recordEditsFound = bool; } /** * Indicates whether a RecordEdits marker was found in the present configuration file. * @return - TRUE if a RecordEdits marker was found. */ public boolean isRecordEditsFound() { return recordEditsFound; } /** * Sets the "RecordEdits" mode for the InputAgent. * @param bool - boolean value for the RecordEdits mode */ public void setRecordEdits(boolean bool) { recordEdits = bool; } /** * Returns the "RecordEdits" mode for the InputAgent. * <p> * When RecordEdits is TRUE, any model inputs that are changed and any objects that * are defined are marked as "edited". When FALSE, model inputs and object * definitions are marked as "unedited". * <p> * RecordEdits mode is used to determine the way JaamSim saves a configuration file * through the graphical user interface. Object definitions and model inputs * that are marked as unedited will be copied exactly as they appear in the original * configuration file that was first loaded. Object definitions and model inputs * that are marked as edited will be generated automatically by the program. * * @return the RecordEdits mode for the InputAgent. */ public boolean isRecordEdits() { return recordEdits; } public FileEntity getLogFile() { return logFile; } public void openLogFile() { String logFileName = getRunName() + ".log"; URI logURI = null; logFile = null; try { URI confURI = configFile.toURI(); logURI = confURI.resolve(new URI(null, logFileName, null)); // The new URI here effectively escapes the file name File f = new File(logURI.getPath()); if (f.exists() && !f.delete()) throw new Exception("Cannot delete an existing log file."); logFile = new FileEntity(f); } catch( Exception e ) { InputAgent.logWarning(this, "Could not create log file.%n%s", e.getMessage()); } } public void closeLogFile() { if (logFile == null) return; logFile.close(); // Delete the log file if no errors or warnings were recorded if (numErrors == 0 && numWarnings == 0) { logFile.delete(); } logFile = null; } public void logMessage(String msg) { if (logFile == null) return; logFile.write(msg); logFile.newLine(); logFile.flush(); } public void recordError() { numErrors++; } public int getNumErrors() { return numErrors; } public void recordWarning() { numWarnings++; } public int getNumWarnings() { return numWarnings; } public final void trace(int indent, Entity ent, String fmt, Object... args) { // Print a TIME header every time time has advanced EventManager evt = EventManager.current(); long traceTick = evt.getTicks(); if (lastTickForTrace != traceTick) { double unitFactor = this.getDisplayedUnitFactor(TimeUnit.class); String unitString = this.getDisplayedUnit(TimeUnit.class); System.out.format(" \nTIME = %.6f %s, TICKS = %d\n", evt.ticksToSeconds(traceTick) / unitFactor, unitString, traceTick); lastTickForTrace = traceTick; } // Create an indent string to space the lines StringBuilder str = new StringBuilder(""); for (int i = 0; i < indent; i++) str.append(" "); // Append the Entity name if provided if (ent != null) str.append(ent.getName()).append(":"); str.append(String.format(fmt, args)); System.out.println(str.toString()); System.out.flush(); } public boolean isPreDefinedEntity(Entity ent) { return ent.getEntityNumber() <= preDefinedEntityCount; } /** * Sets the inputs for the calendar. The simulation can use the usual Gregorian calendar with * leap years or it can use a simplified calendar with a fixed 365 days per year. * @param bool - true for the Gregorian calendar, false for the simple calendar * @param date - calendar date corresponding to zero simulation time */ public void setCalendar(boolean bool, SimDate date) { if (calendarUsed) reloadReqd = true; calendar.setGregorian(bool); startMillis = calendar.getTimeInMillis(date.year, date.month - 1, date.dayOfMonth, date.hourOfDay, date.minute, date.second, date.millisecond); } /** * Returns whether the model must be saved and reloaded before it can be executed. * This can occur when the calendar type (simple vs. Gregorian) or start date has * been changed AFTER one or more calendar date inputs has been converted to simulation * time using the previous calendar inputs. * @return true if the model must be saved and reloaded */ public boolean isReloadReqd() { return reloadReqd; } /** * Returns the simulation time corresponding to the specified date. * @param year - year * @param month - month (0 - 11) * @param dayOfMonth - day of the month (1 - 31) * @param hourOfDay - hour of the day (0 - 23) * @param minute - minutes (0 - 59) * @param second - seconds (0 - 59) * @param ms - millisecond (0 - 999) * @return time in milliseconds from the epoch */ public long getCalendarMillis(int year, int month, int dayOfMonth, int hourOfDay, int minute, int second, int ms) { calendarUsed = true; return calendar.getTimeInMillis(year, month, dayOfMonth, hourOfDay, minute, second, ms); } /** * Returns the simulation time in seconds that corresponds to the specified time in * milliseconds from the epoch. * @param millis - milliseconds from the epoch * @return simulation time in seconds */ public double calendarMillisToSimTime(long millis) { return (millis - startMillis) / 1000.0d; } /** * Returns the time in milliseconds from the epoch that corresponds to the specified * simulation time. * @param simTime - simulation time in seconds * @return milliseconds from the epoch */ public long simTimeToCalendarMillis(double simTime) { return Math.round(simTime * 1000.0d) + startMillis; } /** * Returns the date corresponding to the specified time in milliseconds from the epoch. * @param millis - time in milliseconds from the epoch * @return date for the specified time */ public synchronized Date getCalendarDate(long millis) { synchronized (calendar) { calendar.setTimeInMillis(millis); return calendar.getTime(); } } /** * Returns the calendar date and time for the specified time in milliseconds from the epoch. * @param millis - time in milliseconds from the epoch * @return SimDate for the specified time */ public SimDate getSimDate(long millis) { synchronized (calendar) { calendar.setTimeInMillis(millis); return calendar.getSimDate(); } } /** * Returns the day of week for the specified time in milliseconds from the epoch. * @param millis - time in milliseconds from the epoch * @return day of week (Sunday = 1, Monday = 2, ..., Saturday = 7) */ public int getDayOfWeek(long millis) { synchronized (calendar) { if (calendar.isGregorian()) { calendar.setTimeInMillis(millis); return calendar.get(Calendar.DAY_OF_WEEK); } calendar.setTimeInMillis(startMillis); long simDay = (millis - startMillis)/(1000*60*60*24); return (int) ((calendar.get(Calendar.DAY_OF_WEEK) - 1 + simDay) % 7L) + 1; } } public final void setPreferredUnitList(ArrayList<? extends Unit> list) { ArrayList<String> utList = Unit.getUnitTypeList(this); // Set the preferred units in the list for (Unit u : list) { Class<? extends Unit> ut = u.getClass(); this.setPreferredUnit(ut, u); utList.remove(ut.getSimpleName()); } // Clear the entries for unit types that were not in the list for (String utName : utList) { Class<? extends Unit> ut = Input.parseUnitType(this, utName); preferredUnit.remove(ut); } } public final void setPreferredUnit(Class<? extends Unit> type, Unit u) { if (u.getName().equals(Unit.getSIUnit(type))) { preferredUnit.remove(type); return; } preferredUnit.put(type, u); } public final ArrayList<Unit> getPreferredUnitList() { return new ArrayList<>(preferredUnit.values()); } public final <T extends Unit> Unit getPreferredUnit(Class<T> type) { return preferredUnit.get(type); } public final <T extends Unit> String getDisplayedUnit(Class<T> ut) { Unit u = this.getPreferredUnit(ut); if (u == null) return Unit.getSIUnit(ut); return u.getName(); } public final <T extends Unit> double getDisplayedUnitFactor(Class<T> ut) { Unit u = this.getPreferredUnit(ut); if (u == null) return 1.0; return u.getConversionFactorToSI(); } public KeywordIndex formatVec3dInput(String keyword, Vec3d point, Class<? extends Unit> ut) { double factor = getDisplayedUnitFactor(ut); String unitStr = getDisplayedUnit(ut); return InputAgent.formatVec3dInput(keyword, point, factor, unitStr); } public KeywordIndex formatPointsInputs(String keyword, ArrayList<Vec3d> points, Vec3d offset) { double factor = getDisplayedUnitFactor(DistanceUnit.class); String unitStr = getDisplayedUnit(DistanceUnit.class); return InputAgent.formatPointsInputs(keyword, points, offset, factor, unitStr); } public void showTemporaryLabels(boolean bool) { for (DisplayEntity ent : getClonesOfIterator(DisplayEntity.class)) { if (!EntityLabel.canLabel(ent)) continue; EntityLabel.showTemporaryLabel(ent, bool && ent.getShow() && ent.isMovable(), false); } } public void showSubModels(boolean bool) { for (CompoundEntity submodel : getClonesOfIterator(CompoundEntity.class)) { submodel.showTemporaryComponents(bool); } } @Override public String toString() { return name; } }
src/main/java/com/jaamsim/basicsim/JaamSimModel.java
/* * JaamSim Discrete Event Simulation * Copyright (C) 2016-2021 JaamSim Software 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.jaamsim.basicsim; import java.io.File; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.concurrent.atomic.AtomicLong; import com.jaamsim.Graphics.DisplayEntity; import com.jaamsim.Graphics.EntityLabel; import com.jaamsim.Samples.SampleExpression; import com.jaamsim.StringProviders.StringProvExpression; import com.jaamsim.SubModels.CompoundEntity; import com.jaamsim.SubModels.SubModel; import com.jaamsim.SubModels.SubModelClone; import com.jaamsim.Thresholds.ThresholdUser; import com.jaamsim.datatypes.IntegerVector; import com.jaamsim.events.Conditional; import com.jaamsim.events.EventHandle; import com.jaamsim.events.EventManager; import com.jaamsim.events.EventTimeListener; import com.jaamsim.events.ProcessTarget; import com.jaamsim.input.ExpError; import com.jaamsim.input.Input; import com.jaamsim.input.InputAgent; import com.jaamsim.input.InputErrorException; import com.jaamsim.input.KeywordIndex; import com.jaamsim.input.NamedExpressionListInput; import com.jaamsim.input.ParseContext; import com.jaamsim.math.Vec3d; import com.jaamsim.states.StateEntity; import com.jaamsim.ui.EventViewer; import com.jaamsim.ui.LogBox; import com.jaamsim.units.DimensionlessUnit; import com.jaamsim.units.DistanceUnit; import com.jaamsim.units.TimeUnit; import com.jaamsim.units.Unit; public class JaamSimModel implements EventTimeListener { // Perform debug only entity list validation logic private static final boolean VALIDATE_ENT_LIST = false; private static final Object createLock = new Object(); private static JaamSimModel createModel = null; private final EventManager eventManager; private Simulation simulation; private String name; private int scenarioNumber; // labels each scenario when multiple scenarios are being made private IntegerVector scenarioIndexList; private int replicationNumber; private RunListener runListener; // notifies the SimRun that the run has ended private GUIListener gui; private final AtomicLong entityCount = new AtomicLong(0); private final HashMap<String, Entity> namedEntities = new HashMap<>(100); private final HashMap<Class<? extends Unit>, Unit> preferredUnit = new HashMap<>(); // Note, entityList is an empty list node used to identify the end of the list // The first real entity is at entityList.next.ent private final EntityListNode entityList = new EntityListNode(); private int numLiveEnts; private File configFile; // present configuration file private File reportDir; // directory for the output reports private boolean batchRun; // true if the run is to be terminated automatically private boolean scriptMode; // TRUE if script mode (command line) is specified private boolean sessionEdited; // TRUE if any inputs have been changed after loading a configuration file private boolean recordEditsFound; // TRUE if the "RecordEdits" marker is found in the configuration file private boolean recordEdits; // TRUE if input changes are to be marked as edited private FileEntity logFile; private int numErrors = 0; private int numWarnings = 0; private long lastTickForTrace = -1L; private long preDefinedEntityCount = 0L; // Number of entities after loading autoload.cfg private final HashMap<String, String> stringCache = new HashMap<>(); private final ArrayList<ObjectType> objectTypes = new ArrayList<>(); private final HashMap<Class<? extends Entity>, ObjectType> objectTypeMap = new HashMap<>(); private final SimCalendar calendar = new SimCalendar(); private long startMillis; // start time in milliseonds from the epoch private boolean calendarUsed; // records whether the calendar has been used private boolean reloadReqd; // indicates that the simulation must be saved and reloaded private int simState; /** model was executed, but no configuration performed */ public static final int SIM_STATE_LOADED = 0; /** essential model elements created, no configuration performed */ public static final int SIM_STATE_UNCONFIGURED = 1; /** model has been configured, not started */ public static final int SIM_STATE_CONFIGURED = 2; /** model is presently executing events */ public static final int SIM_STATE_RUNNING = 3; /** model has run, but presently is paused */ public static final int SIM_STATE_PAUSED = 4; /** model is paused but cannot be resumed */ public static final int SIM_STATE_ENDED = 5; public JaamSimModel() { this(""); } public JaamSimModel(String name) { eventManager = new EventManager("DefaultEventManager"); eventManager.setTimeListener(this); simulation = null; this.name = name; scenarioNumber = 1; replicationNumber = 1; scenarioIndexList = new IntegerVector(); scenarioIndexList.add(1); } public JaamSimModel(JaamSimModel sm) { this(sm.name); autoLoad(); simulation = getSimulation(); setRecordEdits(true); configFile = sm.configFile; reportDir = sm.reportDir; // Ensure that 'getReportDirectory' works correctly for an Example Model if (reportDir == null && configFile == null) reportDir = new File(sm.getReportDirectory()); // Create the new entities in the same order as the original model for (Entity ent : sm.getClonesOfIterator(Entity.class)) { if (!ent.isRegistered()) break; if (ent.isPreDefined() || getNamedEntity(ent.getName()) != null) continue; // Generate all the sub-model components when the first one is found if (ent.isGenerated()) { if (ent.getParent() instanceof SubModelClone) { Entity clone = getNamedEntity(ent.getParent().getName()); SubModel proto = ((SubModelClone) ent.getParent()).getPrototype(); if (clone == null || proto == null) continue; KeywordIndex kw = InputAgent.formatInput("Prototype", proto.getName()); InputAgent.apply(clone, kw); } continue; } // Define the new object defineEntity(ent.getObjectType().getName(), ent.getName()); } // Prepare a sorted list of registered entities on which to set inputs ArrayList<Entity> entityList = new ArrayList<>(); for (Entity ent : sm.getClonesOfIterator(Entity.class)) { if (!ent.isRegistered()) break; if (ent instanceof ObjectType) continue; entityList.add(ent); } Collections.sort(entityList, InputAgent.subModelSortOrder); // Stub definitions for (Entity ent : entityList) { if (ent.isGenerated()) continue; NamedExpressionListInput in = (NamedExpressionListInput) ent.getInput("CustomOutputList"); if (in == null || in.isDefault()) continue; Entity newEnt = getNamedEntity(ent.getName()); if (newEnt == null) throw new ErrorException("New entity not found: %s", ent.getName()); KeywordIndex kw = InputAgent.formatInput(in.getKeyword(), in.getStubDefinition()); InputAgent.apply(newEnt, kw); } ParseContext context = null; if (sm.getConfigFile() != null) { URI uri = sm.getConfigFile().getParentFile().toURI(); context = new ParseContext(uri, null); } // Copy the early inputs to the new entities in the specified sequence of inputs for (String key : InputAgent.EARLY_KEYWORDS) { for (Entity ent : entityList) { Entity newEnt = getNamedEntity(ent.getName()); if (newEnt == null) throw new ErrorException("New entity not found: %s", ent.getName()); newEnt.copyInput(ent, key, context, false); } } // Copy the normal inputs to the new entities for (Entity ent : entityList) { Entity newEnt = getNamedEntity(ent.getName()); if (newEnt == null) throw new ErrorException("New entity not found: %s", ent.getName()); for (Input<?> in : ent.getEditableInputs()) { if (in.isSynonym() || InputAgent.isEarlyInput(in)) continue; String key = in.getKeyword(); newEnt.copyInput(ent, key, context, false); } } // Complete the preparation of the sub-model clones postLoad(); // Verify that the new JaamSimModel is an exact copy if (!this.isCopyOf(sm)) throw new ErrorException("Copied JaamSimModel does not match the original"); } /** * Returns whether this JaamSimModel is a copy of the specified model. * Avoids the complexities of overriding the equals method. * @param sm - JaamSimModel to be compared * @return true if the model is a copy */ public boolean isCopyOf(JaamSimModel sm) { // Loop through the two sets of entities in parallel ClonesOfIterable<Entity> itr0 = sm.getClonesOfIterator(Entity.class); ClonesOfIterable<Entity> itr1 = this.getClonesOfIterator(Entity.class); while (itr0.hasNext() || itr1.hasNext()) { Entity ent0 = itr0.hasNext() ? itr0.next() : null; Entity ent1 = itr1.hasNext() ? itr1.next() : null; if (ent0 == null || ent1 == null || !ent0.isRegistered() || !ent1.isRegistered()) continue; // Verify that the entity list contains the same sequence of objects if (!ent1.isCopyOf(ent0)) { System.out.format("Entity lists do not match: ent0=%s, ent1=%s%n", ent0, ent1); return false; } } return true; } public void setName(String str) { name = str; } public final void setRunListener(RunListener l) { runListener = l; } public final RunListener getRunListener() { return runListener; } public void setGUIListener(GUIListener l) { gui = l; } public GUIListener getGUIListener() { return gui; } @Override public void tickUpdate(long tick) { if (gui == null) return; gui.tickUpdate(tick); } @Override public void timeRunning() { if (gui == null) return; gui.timeRunning(); } @Override public void handleError(Throwable t) { if (isMultipleRuns() && runListener != null) { runListener.handleError(t); return; } if (gui == null) return; gui.handleError(t); } public int getSimState() { return simState; } public void setSimState(int state) { simState = state; } public String getName() { return name; } /** * Deletes all the objects in the present model and prepares the JaamSimModel to load a new * input file using the autoLoad() and configure() methods. */ public void clear() { eventManager.clear(); eventManager.setTraceListener(null); // Reset the GUI inputs maintained by the Simulation entity if (getSimulation() != null) { getSimulation().clear(); } EntityListNode listNode = entityList.next; while(listNode != entityList) { Entity curEnt = listNode.ent; if (!curEnt.isDead()) { curEnt.kill(); } listNode = listNode.next; } // Reset calendar calendar.setGregorian(false); startMillis = 0L; calendarUsed = false; reloadReqd = false; // Clear the 'simulation' property simulation = null; // close warning/error trace file closeLogFile(); stringCache.clear(); // Reset the run number and run indices scenarioNumber = 1; replicationNumber = 1; configFile = null; reportDir = null; setSessionEdited(false); recordEditsFound = false; numErrors = 0; numWarnings = 0; lastTickForTrace = -1L; } public final String internString(String str) { synchronized (stringCache) { String ret = stringCache.get(str); if (ret == null) { stringCache.put(str, str); ret = str; } return ret; } } /** * Pre-loads the simulation model with built-in objects such as Simulation and Units. */ public void autoLoad() { // Load the autoload.cfg file setRecordEdits(false); InputAgent.readResource(this, "<res>/inputs/autoload.cfg"); // Save the number of entities created by the autoload.cfg file preDefinedEntityCount = getTailEntity().getEntityNumber(); } /** * Loads the specified configuration file to create the objects in the model. * The autoLoad() method must be executed first. * @param file - configuration file * @throws URISyntaxException */ public void configure(File file) throws URISyntaxException { configFile = file; openLogFile(); InputAgent.loadConfigurationFile(this, file); name = file.getName(); // The session is not considered to be edited after loading a configuration file setSessionEdited(false); // Save and close the input trace file if (numWarnings == 0 && numErrors == 0) { closeLogFile(); // Open a fresh log file for the simulation run openLogFile(); } } /** * Performs any additional actions that are required for each entity after a new configuration * file has been loaded. Performed prior to validation. */ public void postLoad() { for (Entity each : getClonesOfIterator(Entity.class)) { each.postLoad(); } } /** * Performs consistency checks on the model inputs. * @return true if no validation errors were found */ public boolean validate() { for (Entity each : getClonesOfIterator(Entity.class)) { try { each.validate(); } catch (Throwable t) { if (gui != null) { gui.handleInputError(t, each); } else { System.out.format("Validation Error - %s: %s%n", each.getName(), t.getMessage()); } return false; } } return true; } /** * Starts the simulation model on a new thread. */ public void start() { //System.out.format("%s.start%n", this); double pauseTime = getSimulation().getPauseTime(); start(pauseTime); } public void start(double pauseTime) { boolean bool = validate(); if (!bool) return; prepareReportDirectory(); eventManager.clear(); // Set up any tracing to be performed eventManager.setTraceListener(null); if (getSimulation().traceEvents()) { String evtName = configFile.getParentFile() + File.separator + getRunName() + ".evt"; EventRecorder rec = new EventRecorder(evtName); eventManager.setTraceListener(rec); } else if (getSimulation().verifyEvents()) { String evtName = configFile.getParentFile() + File.separator + getRunName() + ".evt"; EventTracer trc = new EventTracer(evtName); eventManager.setTraceListener(trc); } else if (getSimulation().isEventViewerVisible()) { eventManager.setTraceListener(EventViewer.getInstance()); } eventManager.setTickLength(getSimulation().getTickLength()); startRun(pauseTime); } void initRun() { eventManager.scheduleProcessExternal(0, 0, false, new InitModelTarget(this), null); } /** * Starts a single simulation run. */ public void startRun(double pauseTime) { initRun(); resume(pauseTime); } /** * Performs the first stage of initialization for each entity. */ public void earlyInit() { thresholdChangedTarget.users.clear(); for (Entity each : getClonesOfIterator(Entity.class)) { each.earlyInit(); } } /** * Performs the second stage of initialization for each entity. */ public void lateInit() { for (Entity each : getClonesOfIterator(Entity.class)) { each.lateInit(); } } /** * Performs the start-up procedure for each entity. */ public void startUp() { double startTime = getSimulation().getStartTime(); long startTicks = eventManager.secondsToNearestTick(startTime); for (Entity each : getClonesOfIterator(Entity.class)) { if (!each.isActive()) continue; EventManager.scheduleTicks(startTicks, 0, true, new StartUpTarget(each), null); } } /** * Performs the shut down procedure for each entity. */ public void close() { for (Entity each : getClonesOfIterator(Entity.class)) { each.close(); } } public void doPauseCondition() { if (getSimulation().isPauseConditionSet()) EventManager.scheduleUntil(pauseModelTarget, pauseCondition, null); } private final PauseModelTarget pauseModelTarget = new PauseModelTarget(this); private final Conditional pauseCondition = new Conditional() { @Override public boolean evaluate() { double simTime = EventManager.simSeconds(); return getSimulation().isPauseConditionSatisfied(simTime); } }; /** * Reset the statistics for each entity. */ public void clearStatistics() { for (Entity ent : getClonesOfIterator(Entity.class)) { if (!ent.isActive()) continue; ent.clearStatistics(); } // Reset state statistics for (StateEntity each : getClonesOfIterator(StateEntity.class)) { if (!each.isActive()) continue; each.collectInitializationStats(); } } /** * Suspends model execution at the present simulation time. */ public void pause() { //System.out.format("%s.pause%n", this); eventManager.pause(); } /** * Resumes a paused simulation model. * The model will continue execution until the specified simulation time at which the model * will be paused. * Events scheduled at the next pause time will not be executed until the model is resumed. * @param simTime - next pause time */ public void resume(double simTime) { eventManager.resume(eventManager.secondsToNearestTick(simTime)); } /** * Executes the end of run method for each entity. */ public void doEnd() { for (Entity each : getClonesOfIterator(Entity.class)) { if (!each.isActive()) continue; each.doEnd(); } } /** * Sets the simulation time to zero and re-initializes the model. * The start() method can be used to begin a new simulation run. */ public void reset() { eventManager.pause(); eventManager.clear(); killGeneratedEntities(); // Perform earlyInit for (Entity each : getClonesOfIterator(Entity.class)) { // Try/catch is required because some earlyInit methods use simTime which is only // available from a process thread, which is not the case when called from endRun try { each.earlyInit(); } catch (Exception e) {} } // Perform lateInit for (Entity each : getClonesOfIterator(Entity.class)) { // Try/catch is required because some lateInit methods use simTime which is only // available from a process thread, which is not the case when called from endRun try { each.lateInit(); } catch (Exception e) {} } } /** * Prepares the model for the next simulation run number. */ public void endRun() { // Execute the end of run method for each entity doEnd(); // Stop the model pause(); // Notify the run manager if (runListener != null) runListener.runEnded(null); } /** * Destroys the entities that were generated during the present simulation run. */ public void killGeneratedEntities() { EntityListNode curNode = entityList.next; while(curNode != entityList) { Entity curEnt = curNode.ent; if (!curEnt.isDead() && !curEnt.testFlag(Entity.FLAG_RETAINED)) { curEnt.kill(); } curNode = curNode.next; } } /** * Ends a set of simulation runs. */ public void end() { // Close warning/error trace file LogBox.logLine("Made it to do end at"); closeLogFile(); // Always terminate the run when in batch mode if (isBatchRun() || getSimulation().getExitAtStop()) { if (gui != null) gui.exit(0); System.exit(0); } pause(); } /** * Returns whether events are being executed. * @return true if the events are being executed */ public boolean isRunning() { return eventManager.isRunning(); } /** * Returns the present simulation time in seconds. * @return simulation time */ public double getSimTime() { return eventManager.ticksToSeconds(eventManager.getTicks()); } public long getSimTicks() { return eventManager.getTicks(); } /** * Evaluates the specified expression and returns its value as a string. * Any type of result can be returned by the expression, including an entity or an array. * If it returns a number, it must be dimensionless. * @param expString - expression to be evaluated * @return expression value as a string */ public String getStringValue(String expString) { double simTime = getSimTime(); try { Class<? extends Unit> unitType = DimensionlessUnit.class; Entity thisEnt = getSimulation(); StringProvExpression strProv = new StringProvExpression(expString, thisEnt, unitType); return strProv.getNextString(simTime); } catch (ExpError e) { return "Cannot evaluate"; } } /** * Evaluates the specified expression and returns its value. * The expression must return a dimensionless number. * All other types of expressions return NaN. * @param expString - expression to be evaluated * @return expression value */ public double getDoubleValue(String expString) { double simTime = getSimTime(); try { Class<? extends Unit> unitType = DimensionlessUnit.class; Entity thisEnt = getSimulation(); SampleExpression sampleExp = new SampleExpression(expString, thisEnt, unitType); return sampleExp.getNextSample(simTime); } catch (ExpError e) { return Double.NaN; } } /** * Creates a new entity for the specified type and name. * If the name already used, "_1", "_2", etc. will be appended to the name until an unused * name is found. * @param type - type of entity to be created * @param name - absolute name for the created entity */ public void defineEntity(String type, String name) { try { Class<? extends Entity> klass = Input.parseEntityType(this, type); InputAgent.defineEntityWithUniqueName(this, klass, name, "_", true); } catch (InputErrorException e) { return; } } /** * Sets the input for the specified entity and keyword to the specified string. * @param entName - name of the entity whose input is to be set * @param keyword - input keyword whose value is to be set * @param arg - input string as it would appear in the Input Editor */ public void setInput(String entName, String keyword, String arg) { setRecordEdits(true); Entity ent = getNamedEntity(entName); KeywordIndex kw = InputAgent.formatInput(keyword, arg); InputAgent.apply(ent, kw); } /** * Writes the inputs for the simulation model to the specified file. * @param file - file to which the model inputs are to be saved */ public void save(File file) { InputAgent.printNewConfigurationFileWithName(this, file); configFile = file; name = file.getName(); } public EventManager getEventManager() { return eventManager; } void setSimulation(Simulation sim) { simulation = sim; } public Simulation getSimulation() { return simulation; } public boolean isMultipleRuns() { return getSimulation().getNumberOfRuns() > 1; } public boolean isFirstRun() { return isFirstScenario() && replicationNumber == 1; } public boolean isLastRun() { return isLastScenario() && replicationNumber == getSimulation().getNumberOfReplications(); } public boolean isFirstScenario() { return scenarioNumber == getSimulation().getStartingScenarioNumber(); } public boolean isLastScenario() { return scenarioNumber >= getSimulation().getEndingScenarioNumber(); } /** * Returns the run indices that correspond to a given run number. * @param n - run number. * @param rangeList - maximum value for each index. * @return run indices. */ public static IntegerVector getRunIndexList(int n, IntegerVector rangeList) { if (rangeList.size() == 0) { IntegerVector indexList = new IntegerVector(1); indexList.add(n); return indexList; } IntegerVector indexList = new IntegerVector(rangeList.size()); indexList.fillWithEntriesOf(rangeList.size(), 0); int denom = 1; for (int i=rangeList.size()-1; i>=0; i--) { indexList.set(i, (n-1)/denom % rangeList.get(i) + 1); denom *= rangeList.get(i); } return indexList; } /** * Returns the run number that corresponds to a given set of run indices. * @param indexList - run indices. * @param rangeList - maximum value for each index. * @return run number. */ public static int getRunNumber(IntegerVector indexList, IntegerVector rangeList) { int n = 1; int factor = 1; for (int i=indexList.size()-1; i>=0; i--) { n += (indexList.get(i)-1)*factor; factor *= rangeList.get(i); } return n; } /** * Returns the input format used to specify a set of scenario indices. * @param indexList - scenario indices. * @return scenario code. */ public static String getScenarioCode(IntegerVector indexList) { StringBuilder sb = new StringBuilder(); sb.append(indexList.get(0)); for (int i=1; i<indexList.size(); i++) { sb.append("-").append(indexList.get(i)); } return sb.toString(); } public void setScenarioNumber(int n) { scenarioNumber = n; setScenarioIndexList(); } public void setScenarioIndexList() { scenarioIndexList = getRunIndexList(scenarioNumber, getSimulation().getScenarioIndexDefinitionList()); } public int getScenarioNumber() { return scenarioNumber; } public IntegerVector getScenarioIndexList() { return scenarioIndexList; } public String getScenarioCode() { return getScenarioCode(scenarioIndexList); } public void setReplicationNumber(int n) { replicationNumber = n; } public int getReplicationNumber() { return replicationNumber; } public int getRunNumber() { int numberOfReplications = getSimulation().getNumberOfReplications(); return (scenarioNumber - 1) * numberOfReplications + replicationNumber; } public String getRunHeader() { return String.format("##### SCENARIO %s - REPLICATION %s #####", getScenarioCode(), replicationNumber); } final long getNextEntityID() { return entityCount.incrementAndGet(); } public final Entity getNamedEntity(String name) { if (name.contains(".")) { String[] names = name.split("\\."); return getEntityFromNames(names); } synchronized (namedEntities) { return namedEntities.get(name); } } public final Entity getEntity(String name) { Entity ret = getNamedEntity(name); if (ret != null) return ret; for (Entity ent: getClonesOfIterator(Entity.class)) { if (ent.getName().equals(name)) { return ent; } } return null; } // Get an entity from a chain of names, descending into the tree of children public final Entity getEntityFromNames(String[] names) { Entity currEnt = getSimulation(); for (String name: names) { if (currEnt == null) { return null; } currEnt = currEnt.getChild(name); } return currEnt; } public final long getEntitySequence() { long seq = (long)numLiveEnts << 32; seq += entityCount.get(); return seq; } public final Entity idToEntity(long id) { synchronized (namedEntities) { EntityListNode curNode = entityList.next; while(true) { if (curNode == entityList) { return null; } Entity curEnt = curNode.ent; if (curEnt != null && curEnt.getEntityNumber() == id) { return curEnt; } curNode = curNode.next; } } } static JaamSimModel getCreateModel() { synchronized (createLock) { JaamSimModel mod = createModel; createModel = null; return mod; } } /** * Creates a new entity. * @param proto - class for the entity * @param name - entity local name * @param parent - entity's parent * @param added - true if the entity was defined after the 'RecordEdits' flag * @param gen - true if the entity was created during the execution of the simulation * @param reg - true if the entity is included in the namedEntities HashMap * @param retain - true if the entity is retained when the model is reset between runs * @return new entity */ public final <T extends Entity> T createInstance(Class<T> proto, String name, Entity parent, boolean added, boolean gen, boolean reg, boolean retain) { T ent = createInstance(proto); if (ent == null) return null; // Set the entity type if (added) ent.setFlag(Entity.FLAG_ADDED); if (gen) ent.setFlag(Entity.FLAG_GENERATED); if (reg) ent.setFlag(Entity.FLAG_REGISTERED); if (retain) ent.setFlag(Entity.FLAG_RETAINED); ent.parent = parent; ent.entityName = name; if (reg) addNamedEntity(ent); // Create any objects associated with this entity and set their inputs // (These objects and their inputs are not be marked as 'edited' to avoid having them saved // to the input file) boolean bool = isRecordEdits(); setRecordEdits(false); ent.postDefine(); setRecordEdits(bool); return ent; } public final <T extends Entity> T createInstance(Class<T> proto) { T ent = null; try { synchronized (createLock) { createModel = this; ent = proto.newInstance(); } addInstance(ent); } catch (Throwable e) {} return ent; } public final void addNamedEntity(Entity ent) { if (ent.parent != null) { ent.parent.addChild(ent); return; } synchronized (namedEntities) { if (namedEntities.get(ent.entityName) != null) throw new ErrorException("Entity name: %s is already in use.", ent.entityName); namedEntities.put(ent.entityName, ent); } } public final void removeNamedEntity(Entity ent) { if (ent.parent != null) { ent.parent.removeChild(ent); return; } synchronized (namedEntities) { if (namedEntities.remove(ent.entityName) != ent) throw new ErrorException("Named Entities Internal Consistency error"); } } /** * Changes the specified entity's name. * @param ent - entity to be renamed * @param newName - new local name for the entity */ final void renameEntity(Entity ent, String newName) { if (!ent.isRegistered()) { ent.entityName = newName; return; } if (ent.entityName != null) { removeNamedEntity(ent); } ent.entityName = newName; addNamedEntity(ent); } private void validateEntList() { if (!VALIDATE_ENT_LIST) { return; } synchronized(namedEntities) { // Count the number of live entities and make sure all entity numbers are increasing // Also, check that the lastEnt reference is correct int numEntities = 0; long lastEntNum = -1; int numDeadEntities = 0; if (entityList.ent != null) { assert(false); throw new ErrorException("Entity List Validation Error!"); } EntityListNode curNode = entityList.next; EntityListNode lastNode = entityList; while (curNode != null && curNode != entityList) { Entity curEnt = curNode.ent; if (!curEnt.isDead()) { numEntities++; } else { numDeadEntities++; } if (curEnt.getEntityNumber() <= lastEntNum) { assert(false); throw new ErrorException("Entity List Validation Error!"); } if (curNode.prev != lastNode) { assert(false); throw new ErrorException("Entity List Validation Error!"); } lastEntNum = curEnt.getEntityNumber(); lastNode = curNode; curNode = curNode.next; } if (numEntities != numLiveEnts) { assert(false); throw new ErrorException("Entity List Validation Error!"); } if (this.entityList.prev != lastNode) { assert(false); throw new ErrorException("Entity List Validation Error!"); } if (numDeadEntities > 0) { assert(false); throw new ErrorException("Entity List Validation Error!"); } if (curNode == null) { assert(false); throw new ErrorException("Entity List Validation Error!"); } // Scan the list backwards curNode = entityList.prev; lastNode = entityList; numEntities = 0; lastEntNum = Long.MAX_VALUE; while (curNode != null && curNode != entityList) { Entity curEnt = curNode.ent; if (!curEnt.isDead()) { numEntities++; } else { numDeadEntities++; } if (curEnt.getEntityNumber() >= lastEntNum) { assert(false); throw new ErrorException("Entity List Validation Error!"); } if (curNode.next != lastNode) { assert(false); throw new ErrorException("Entity List Validation Error!"); } lastEntNum = curEnt.getEntityNumber(); lastNode = curNode; curNode = curNode.prev; } if (numEntities != numLiveEnts) { assert(false); throw new ErrorException("Entity List Validation Error!"); } if (this.entityList.next != lastNode) { assert(false); throw new ErrorException("Entity List Validation Error!"); } if (numDeadEntities > 0) { assert(false); throw new ErrorException("Entity List Validation Error!"); } if (curNode == null) { assert(false); throw new ErrorException("Entity List Validation Error!"); } } // synchronized(namedEntities) } final void addInstance(Entity e) { synchronized(namedEntities) { validateEntList(); numLiveEnts++; EntityListNode newNode = new EntityListNode(e); EntityListNode oldLast = entityList.prev; newNode.prev = oldLast; newNode.next = entityList; oldLast.next = newNode; entityList.prev = newNode; validateEntList(); } } final void restoreInstance(Entity e) { synchronized (namedEntities) { validateEntList(); numLiveEnts++; // Scan through the linked list to find the place to insert this entity // This is slow, but should only happen due to user actions long entNum = e.getEntityNumber(); EntityListNode curNode = entityList.next; while(true) { Entity nextEnt = curNode.next.ent; if (nextEnt == null || nextEnt.getEntityNumber() > entNum) { // End of the list or at the correct location // Insert a new node after curNode EntityListNode newNode = new EntityListNode(e); newNode.next = curNode.next; newNode.prev = curNode; curNode.next = newNode; newNode.next.prev = newNode; validateEntList(); return; } curNode = curNode.next; } } } final void removeInstance(Entity e) { synchronized (namedEntities) { validateEntList(); numLiveEnts--; if (e.isRegistered()) removeNamedEntity(e); e.entityName = null; e.setFlag(Entity.FLAG_DEAD); EntityListNode listNode = e.listNode; // Break the link to the list e.listNode = null; listNode.ent = null; listNode.next.prev = listNode.prev; listNode.prev.next = listNode.next; // Note, leaving the nodes next and prev pointers intact so that any outstanding iterators // can finish traversing the list validateEntList(); } } /** * Returns an Iterator that loops over the instances of the specified class. It does not * include instances of any sub-classes of the class. * The specified class must be a sub-class of Entity. * @param proto - specified class * @return Iterator for instances of the class */ public <T extends Entity> InstanceIterable<T> getInstanceIterator(Class<T> proto){ return new InstanceIterable<>(this, proto); } /** * Returns an Iterator that loops over the instances of the specified class and its * sub-classes. * The specified class must be a sub-class of Entity. * @param proto - specified class * @return Iterator for instances of the class and its sub-classes */ public <T extends Entity> ClonesOfIterable<T> getClonesOfIterator(Class<T> proto){ return new ClonesOfIterable<>(this, proto); } /** * Returns an iterator that loops over the instances of the specified class and its * sub-classes, but of only those classes that implement the specified interface. * The specified class must be a sub-class of Entity. * @param proto - specified class * @param iface - specified interface * @return Iterator for instances of the class and its sub-classes that implement the specified interface */ public <T extends Entity> ClonesOfIterableInterface<T> getClonesOfIterator(Class<T> proto, Class<?> iface){ return new ClonesOfIterableInterface<>(this, proto, iface); } // Note, these methods should only be called by EntityIterator and some unit tests public final Entity getHeadEntity() { return entityList.next.ent; } public final Entity getTailEntity() { return entityList.prev.ent; } public final EntityListNode getEntityList() { return entityList; } public void addObjectType(ObjectType ot) { synchronized (objectTypes) { objectTypes.add(ot); objectTypeMap.put(ot.getJavaClass(), ot); } } public void removeObjectType(ObjectType ot) { synchronized (objectTypes) { objectTypes.remove(ot); objectTypeMap.remove(ot.getJavaClass()); } } public ArrayList<ObjectType> getObjectTypes() { synchronized (objectTypes) { return objectTypes; } } public ObjectType getObjectTypeForClass(Class<? extends Entity> klass) { synchronized (objectTypes) { return objectTypeMap.get(klass); } } private final EventHandle thresholdChangedHandle = new EventHandle(); private final ThresholdChangedTarget thresholdChangedTarget = new ThresholdChangedTarget(); private static class ThresholdChangedTarget extends ProcessTarget { public final ArrayList<ThresholdUser> users = new ArrayList<>(); public ThresholdChangedTarget() {} @Override public void process() { for (int i = 0; i < users.size(); i++) { users.get(i).thresholdChanged(); } users.clear(); } @Override public String getDescription() { return "UpdateAllThresholdUsers"; } } public void updateThresholdUsers(ArrayList<ThresholdUser> userList) { for (ThresholdUser user : userList) { if (!thresholdChangedTarget.users.contains(user)) thresholdChangedTarget.users.add(user); } if (!thresholdChangedTarget.users.isEmpty() && !thresholdChangedHandle.isScheduled()) EventManager.scheduleTicks(0, 2, false, thresholdChangedTarget, thresholdChangedHandle); } /** * Returns the present configuration file. * Null is returned if no configuration file has been loaded or saved yet. * @return present configuration file */ public File getConfigFile() { return configFile; } /** * Returns the name of the simulation run. * For example, if the model name is "case1.cfg", then the run name is "case1". * @return name of the simulation run */ public String getRunName() { int index = name.lastIndexOf('.'); if (index == -1) return name; return name.substring(0, index); } private String getReportDirectory() { if (reportDir != null) return reportDir.getPath(); if (configFile != null) return configFile.getParentFile().getPath(); if (gui != null && gui.getDefaultFolder() != null) return gui.getDefaultFolder(); return null; } /** * Returns the path to the report file with the specified extension for this model. * Returns null if the file path cannot be constructed. * @param ext - file extension, e.g. ".dat" * @return file path */ public String getReportFileName(String ext) { String dir = getReportDirectory(); if (dir == null) return null; StringBuilder sb = new StringBuilder(); sb.append(dir); sb.append(File.separator); sb.append(getRunName()); sb.append(ext); return sb.toString(); } public void setReportDirectory(File dir) { reportDir = dir; if (reportDir == null) return; if (!reportDir.exists() && !reportDir.mkdirs()) throw new InputErrorException("Was unable to create the Report Directory: %s", reportDir.toString()); } public void prepareReportDirectory() { if (reportDir != null) reportDir.mkdirs(); } public void setBatchRun(boolean bool) { batchRun = bool; } public boolean isBatchRun() { return batchRun; } public void setScriptMode(boolean bool) { scriptMode = bool; } public boolean isScriptMode() { return scriptMode; } public void setSessionEdited(boolean bool) { sessionEdited = bool; } public boolean isSessionEdited() { return sessionEdited; } /** * Specifies whether a RecordEdits marker was found in the present configuration file. * @param bool - TRUE if a RecordEdits marker was found. */ public void setRecordEditsFound(boolean bool) { recordEditsFound = bool; } /** * Indicates whether a RecordEdits marker was found in the present configuration file. * @return - TRUE if a RecordEdits marker was found. */ public boolean isRecordEditsFound() { return recordEditsFound; } /** * Sets the "RecordEdits" mode for the InputAgent. * @param bool - boolean value for the RecordEdits mode */ public void setRecordEdits(boolean bool) { recordEdits = bool; } /** * Returns the "RecordEdits" mode for the InputAgent. * <p> * When RecordEdits is TRUE, any model inputs that are changed and any objects that * are defined are marked as "edited". When FALSE, model inputs and object * definitions are marked as "unedited". * <p> * RecordEdits mode is used to determine the way JaamSim saves a configuration file * through the graphical user interface. Object definitions and model inputs * that are marked as unedited will be copied exactly as they appear in the original * configuration file that was first loaded. Object definitions and model inputs * that are marked as edited will be generated automatically by the program. * * @return the RecordEdits mode for the InputAgent. */ public boolean isRecordEdits() { return recordEdits; } public FileEntity getLogFile() { return logFile; } public void openLogFile() { String logFileName = getRunName() + ".log"; URI logURI = null; logFile = null; try { URI confURI = configFile.toURI(); logURI = confURI.resolve(new URI(null, logFileName, null)); // The new URI here effectively escapes the file name File f = new File(logURI.getPath()); if (f.exists() && !f.delete()) throw new Exception("Cannot delete an existing log file."); logFile = new FileEntity(f); } catch( Exception e ) { InputAgent.logWarning(this, "Could not create log file.%n%s", e.getMessage()); } } public void closeLogFile() { if (logFile == null) return; logFile.close(); // Delete the log file if no errors or warnings were recorded if (numErrors == 0 && numWarnings == 0) { logFile.delete(); } logFile = null; } public void logMessage(String msg) { if (logFile == null) return; logFile.write(msg); logFile.newLine(); logFile.flush(); } public void recordError() { numErrors++; } public int getNumErrors() { return numErrors; } public void recordWarning() { numWarnings++; } public int getNumWarnings() { return numWarnings; } public final void trace(int indent, Entity ent, String fmt, Object... args) { // Print a TIME header every time time has advanced EventManager evt = EventManager.current(); long traceTick = evt.getTicks(); if (lastTickForTrace != traceTick) { double unitFactor = this.getDisplayedUnitFactor(TimeUnit.class); String unitString = this.getDisplayedUnit(TimeUnit.class); System.out.format(" \nTIME = %.6f %s, TICKS = %d\n", evt.ticksToSeconds(traceTick) / unitFactor, unitString, traceTick); lastTickForTrace = traceTick; } // Create an indent string to space the lines StringBuilder str = new StringBuilder(""); for (int i = 0; i < indent; i++) str.append(" "); // Append the Entity name if provided if (ent != null) str.append(ent.getName()).append(":"); str.append(String.format(fmt, args)); System.out.println(str.toString()); System.out.flush(); } public boolean isPreDefinedEntity(Entity ent) { return ent.getEntityNumber() <= preDefinedEntityCount; } /** * Sets the inputs for the calendar. The simulation can use the usual Gregorian calendar with * leap years or it can use a simplified calendar with a fixed 365 days per year. * @param bool - true for the Gregorian calendar, false for the simple calendar * @param date - calendar date corresponding to zero simulation time */ public void setCalendar(boolean bool, SimDate date) { if (calendarUsed) reloadReqd = true; calendar.setGregorian(bool); startMillis = calendar.getTimeInMillis(date.year, date.month - 1, date.dayOfMonth, date.hourOfDay, date.minute, date.second, date.millisecond); } /** * Returns whether the model must be saved and reloaded before it can be executed. * This can occur when the calendar type (simple vs. Gregorian) or start date has * been changed AFTER one or more calendar date inputs has been converted to simulation * time using the previous calendar inputs. * @return true if the model must be saved and reloaded */ public boolean isReloadReqd() { return reloadReqd; } /** * Returns the simulation time corresponding to the specified date. * @param year - year * @param month - month (0 - 11) * @param dayOfMonth - day of the month (1 - 31) * @param hourOfDay - hour of the day (0 - 23) * @param minute - minutes (0 - 59) * @param second - seconds (0 - 59) * @param ms - millisecond (0 - 999) * @return time in milliseconds from the epoch */ public long getCalendarMillis(int year, int month, int dayOfMonth, int hourOfDay, int minute, int second, int ms) { calendarUsed = true; return calendar.getTimeInMillis(year, month, dayOfMonth, hourOfDay, minute, second, ms); } /** * Returns the simulation time in seconds that corresponds to the specified time in * milliseconds from the epoch. * @param millis - milliseconds from the epoch * @return simulation time in seconds */ public double calendarMillisToSimTime(long millis) { return (millis - startMillis) / 1000.0d; } /** * Returns the time in milliseconds from the epoch that corresponds to the specified * simulation time. * @param simTime - simulation time in seconds * @return milliseconds from the epoch */ public long simTimeToCalendarMillis(double simTime) { return Math.round(simTime * 1000.0d) + startMillis; } /** * Returns the date corresponding to the specified time in milliseconds from the epoch. * @param millis - time in milliseconds from the epoch * @return date for the specified time */ public synchronized Date getCalendarDate(long millis) { synchronized (calendar) { calendar.setTimeInMillis(millis); return calendar.getTime(); } } /** * Returns the calendar date and time for the specified time in milliseconds from the epoch. * @param millis - time in milliseconds from the epoch * @return SimDate for the specified time */ public SimDate getSimDate(long millis) { synchronized (calendar) { calendar.setTimeInMillis(millis); return calendar.getSimDate(); } } /** * Returns the day of week for the specified time in milliseconds from the epoch. * @param millis - time in milliseconds from the epoch * @return day of week (Sunday = 1, Monday = 2, ..., Saturday = 7) */ public int getDayOfWeek(long millis) { synchronized (calendar) { if (calendar.isGregorian()) { calendar.setTimeInMillis(millis); return calendar.get(Calendar.DAY_OF_WEEK); } calendar.setTimeInMillis(startMillis); long simDay = (millis - startMillis)/(1000*60*60*24); return (int) ((calendar.get(Calendar.DAY_OF_WEEK) - 1 + simDay) % 7L) + 1; } } public final void setPreferredUnitList(ArrayList<? extends Unit> list) { ArrayList<String> utList = Unit.getUnitTypeList(this); // Set the preferred units in the list for (Unit u : list) { Class<? extends Unit> ut = u.getClass(); this.setPreferredUnit(ut, u); utList.remove(ut.getSimpleName()); } // Clear the entries for unit types that were not in the list for (String utName : utList) { Class<? extends Unit> ut = Input.parseUnitType(this, utName); preferredUnit.remove(ut); } } public final void setPreferredUnit(Class<? extends Unit> type, Unit u) { if (u.getName().equals(Unit.getSIUnit(type))) { preferredUnit.remove(type); return; } preferredUnit.put(type, u); } public final ArrayList<Unit> getPreferredUnitList() { return new ArrayList<>(preferredUnit.values()); } public final <T extends Unit> Unit getPreferredUnit(Class<T> type) { return preferredUnit.get(type); } public final <T extends Unit> String getDisplayedUnit(Class<T> ut) { Unit u = this.getPreferredUnit(ut); if (u == null) return Unit.getSIUnit(ut); return u.getName(); } public final <T extends Unit> double getDisplayedUnitFactor(Class<T> ut) { Unit u = this.getPreferredUnit(ut); if (u == null) return 1.0; return u.getConversionFactorToSI(); } public KeywordIndex formatVec3dInput(String keyword, Vec3d point, Class<? extends Unit> ut) { double factor = getDisplayedUnitFactor(ut); String unitStr = getDisplayedUnit(ut); return InputAgent.formatVec3dInput(keyword, point, factor, unitStr); } public KeywordIndex formatPointsInputs(String keyword, ArrayList<Vec3d> points, Vec3d offset) { double factor = getDisplayedUnitFactor(DistanceUnit.class); String unitStr = getDisplayedUnit(DistanceUnit.class); return InputAgent.formatPointsInputs(keyword, points, offset, factor, unitStr); } public void showTemporaryLabels(boolean bool) { for (DisplayEntity ent : getClonesOfIterator(DisplayEntity.class)) { if (!EntityLabel.canLabel(ent)) continue; EntityLabel.showTemporaryLabel(ent, bool && ent.getShow() && ent.isMovable(), false); } } public void showSubModels(boolean bool) { for (CompoundEntity submodel : getClonesOfIterator(CompoundEntity.class)) { submodel.showTemporaryComponents(bool); } } @Override public String toString() { return name; } }
JS: simplify the SubModelClone logic for the JaamSimModel copy constructor Signed-off-by: Harry King <[email protected]>
src/main/java/com/jaamsim/basicsim/JaamSimModel.java
JS: simplify the SubModelClone logic for the JaamSimModel copy constructor
<ide><path>rc/main/java/com/jaamsim/basicsim/JaamSimModel.java <ide> continue; <ide> <ide> // Generate all the sub-model components when the first one is found <del> if (ent.isGenerated()) { <del> if (ent.getParent() instanceof SubModelClone) { <del> Entity clone = getNamedEntity(ent.getParent().getName()); <del> SubModel proto = ((SubModelClone) ent.getParent()).getPrototype(); <del> if (clone == null || proto == null) <del> continue; <del> KeywordIndex kw = InputAgent.formatInput("Prototype", proto.getName()); <del> InputAgent.apply(clone, kw); <del> } <add> if (ent.isGenerated() && ent.getParent() instanceof SubModelClone) { <add> Entity clone = getNamedEntity(ent.getParent().getName()); <add> SubModel proto = ((SubModelClone) ent.getParent()).getPrototype(); <add> if (clone == null || proto == null) <add> continue; <add> KeywordIndex kw = InputAgent.formatInput("Prototype", proto.getName()); <add> InputAgent.apply(clone, kw); <ide> continue; <ide> } <ide>
Java
bsd-3-clause
9c8f3e14e7e18de56ceddf91f9b80112122a3999
0
erhs-53-hackers/Robo2012
package edu.wpi.first.wpilibj.templates; /** * * @author Nick */ public class RoboMap { /* Digital Output*/ public static final int MOTOR1 = 1; public static final int MOTOR2 = 2; public static final int MOTOR3 = 3; public static final int MOTOR4 = 4; public static final int LAUNCH_MOTOR = 5; public static final int BRIDGE_MOTOR = 7; public static final int LAUNCH_LIMIT = 8; public static final int LAUNCH_TURN = 9; public static final int ULTRASONIC_ECHO = 10; /* Digital Output 2 */ public static final int COLLECT_MOTOR = 10; /* Digital Input */ public static final int ULTRASONIC_PING = 1; /* Digital I/O */ public static final int LAUNCH_ENCODER1 = 9; public static final int LAUNCH_ENCODER2 = 10; /* Analog */ public static final int AUTO_POT = 3; public static final int TELO_POT = 2; public static final int GYRO = 1; public static final int BATTERY_METER = 4; //not actually used in code public static final int ULTRASONIC = 5; /* USB */ public static final int JOYSTICK1 = 1; public static final int JOYSTICK2 = 2; public static final int JOYSTICK3 = 3; }
src/edu/wpi/first/wpilibj/templates/RoboMap.java
package edu.wpi.first.wpilibj.templates; /** * * @author Nick */ public class RoboMap { /* Digital Output*/ public static final int MOTOR1 = 1; public static final int MOTOR2 = 2; public static final int MOTOR3 = 3; public static final int MOTOR4 = 4; public static final int LAUNCH_MOTOR = 5; public static final int LOAD_MOTOR = 6; public static final int BRIDGE_MOTOR = 7; public static final int LAUNCH_LIMIT = 8; public static final int LAUNCH_TURN = 9; public static final int ULTRASONIC_ECHO = 10; /* Digital Output 2 */ public static final int COLLECT_MOTOR = 10; /* Digital Input */ public static final int ULTRASONIC_PING = 1; /* Digital I/O */ public static final int LAUNCH_ENCODER1 = 9; public static final int LAUNCH_ENCODER2 = 10; /* Analog */ public static final int AUTO_POT = 3; public static final int TELO_POT = 2; public static final int GYRO = 1; public static final int BATTERY_METER = 4; //not actually used in code public static final int ULTRASONIC = 5; /* USB */ public static final int JOYSTICK1 = 1; public static final int JOYSTICK2 = 2; public static final int JOYSTICK3 = 3; }
removing port
src/edu/wpi/first/wpilibj/templates/RoboMap.java
removing port
<ide><path>rc/edu/wpi/first/wpilibj/templates/RoboMap.java <ide> public static final int MOTOR3 = 3; <ide> public static final int MOTOR4 = 4; <ide> public static final int LAUNCH_MOTOR = 5; <del> public static final int LOAD_MOTOR = 6; <ide> public static final int BRIDGE_MOTOR = 7; <ide> public static final int LAUNCH_LIMIT = 8; <ide> public static final int LAUNCH_TURN = 9;
Java
bsd-2-clause
error: pathspec 'src/main/java/com/yubico/jaas/impl/YubikeyToUserLDAPMap.java' did not match any file(s) known to git
5f7e4059c12d8a8f87f259a176e5e36bd0f330e9
1
Yubico/yubico-java-client,Yubico/yubico-java-client
/* * Copyright 2011, Yubico AB. All rights reserved. * This file is derivative work from YubikeyToUserMapImpl.java in the * Yubico Java client. The following copyright applies to the * derivative work: * Copyright 2011, Université de Lausanne. 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.yubico.jaas.impl; import com.yubico.jaas.YubikeyToUserMap; import edu.vt.middleware.ldap.Ldap; import edu.vt.middleware.ldap.LdapConfig; import edu.vt.middleware.ldap.SearchFilter; import java.util.Iterator; import java.util.Map; import javax.naming.NamingException; import javax.naming.directory.Attributes; import javax.naming.directory.SearchResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Class to verify that a user is the rightful owner of a YubiKey. * * This implementation uses a LDAP directory to look up the Yubikey's * publicId and fetch the associated username. * * @author Etienne Dysli <[email protected]> */ public class YubikeyToUserLDAPMap implements YubikeyToUserMap { /* Supported JAAS configuration options */ /** Enable verification of Yubikey owner (default: true) */ public static final String OPTION_YUBICO_VERIFY_YK_OWNER = "verify_yubikey_owner"; /** Name of the LDAP attribute containing the Yubikey publicId (default: empty) */ public static final String OPTION_YUBICO_LDAP_PUBLICID_ATTRIBUTE = "ldap_publicid_attribute"; /** Name of the LDAP attribute containing the username (default: "uid") */ public static final String OPTION_YUBICO_LDAP_USERNAME_ATTRIBUTE = "ldap_username_attribute"; /** URL of the LDAP directory (default: empty) */ public static final String OPTION_LDAP_URL = "ldap_url"; /** Base DN for LDAP searches (default: empty) */ public static final String OPTION_LDAP_BASE_DN = "ldap_base_dn"; /** DN used to log into the LDAP directory (default: empty) */ public static final String OPTION_LDAP_BIND_DN = "ldap_bind_dn"; /** Password for the bind DN (default: empty) */ public static final String OPTION_LDAP_BIND_CREDENTIAL = "ldap_bind_credential"; private boolean verify_yubikey_owner = true; private String publicid_attribute = ""; private String username_attribute = "uid"; private String ldap_url = ""; private String ldap_base_dn = ""; private String ldap_bind_dn = ""; private String ldap_bind_credential = ""; private Ldap ldap; private final Logger log = LoggerFactory.getLogger(YubikeyToUserLDAPMap.class); /** {@inheritDoc} */ public boolean is_right_user(String username, String publicId) { log.trace("In is_right_user()"); if (!this.verify_yubikey_owner) { log.debug("YubiKey owner verification disabled, returning 'true'"); return true; } String ykuser = null; try { SearchFilter filter = new SearchFilter("({0}={1})", new String[]{this.publicid_attribute, publicId}); log.debug("Searching for YubiKey publicId with filter: {}", filter.toString()); Iterator<SearchResult> results = ldap.search(filter, new String[]{this.username_attribute}); if (results.hasNext()) { Attributes results_attributes = results.next().getAttributes(); log.debug("Found attributes: {}", results_attributes.toString()); ykuser = results_attributes.get(this.username_attribute).get().toString(); } else { log.debug("No search results"); } } catch (NamingException ex) { log.error(ex.getMessage(), ex); return false; } if (ykuser != null) { if (!ykuser.equals(username)) { log.info("YubiKey " + publicId + " registered to user {}, NOT {}", ykuser, username); return false; } else { log.info("YubiKey " + publicId + " registered to user {}", ykuser); return true; } } else { log.info("No record of YubiKey {} found. Returning 'false'.", publicId); return false; } } /** {@inheritDoc} */ public final void setOptions(Map<String, ?> options) { /* Is verification of YubiKey owners enabled? */ this.verify_yubikey_owner = true; if (options.get(OPTION_YUBICO_VERIFY_YK_OWNER) != null) { if ("false".equals(options.get(OPTION_YUBICO_VERIFY_YK_OWNER).toString())) { this.verify_yubikey_owner = false; } } if (options.get(OPTION_YUBICO_LDAP_PUBLICID_ATTRIBUTE) != null) { this.publicid_attribute = options.get(OPTION_YUBICO_LDAP_PUBLICID_ATTRIBUTE).toString(); } if (options.get(OPTION_YUBICO_LDAP_USERNAME_ATTRIBUTE) != null) { this.username_attribute = options.get(OPTION_YUBICO_LDAP_USERNAME_ATTRIBUTE).toString(); } if (options.get(OPTION_LDAP_URL) != null) { this.ldap_url = options.get(OPTION_LDAP_URL).toString(); } if (options.get(OPTION_LDAP_BASE_DN) != null) { this.ldap_base_dn = options.get(OPTION_LDAP_BASE_DN).toString(); } if (options.get(OPTION_LDAP_BIND_DN) != null) { this.ldap_bind_dn = options.get(OPTION_LDAP_BIND_DN).toString(); } if (options.get(OPTION_LDAP_BIND_CREDENTIAL) != null) { this.ldap_bind_credential = options.get(OPTION_LDAP_BIND_CREDENTIAL).toString(); } LdapConfig config = new LdapConfig(this.ldap_url, this.ldap_base_dn); config.setBindDn(this.ldap_bind_dn); config.setBindCredential(this.ldap_bind_credential); this.ldap = new Ldap(config); } }
src/main/java/com/yubico/jaas/impl/YubikeyToUserLDAPMap.java
new LDAP usermap backend
src/main/java/com/yubico/jaas/impl/YubikeyToUserLDAPMap.java
new LDAP usermap backend
<ide><path>rc/main/java/com/yubico/jaas/impl/YubikeyToUserLDAPMap.java <add>/* <add> * Copyright 2011, Yubico AB. All rights reserved. <add> * This file is derivative work from YubikeyToUserMapImpl.java in the <add> * Yubico Java client. The following copyright applies to the <add> * derivative work: <add> * Copyright 2011, Université de Lausanne. All rights reserved. <add> * <add> * Redistribution and use in source and binary forms, with or without <add> * modification, are permitted provided that the following conditions <add> * are met: <add> * <add> * * Redistributions of source code must retain the above copyright <add> * notice, this list of conditions and the following disclaimer. <add> * <add> * * Redistributions in binary form must reproduce the above copyright <add> * notice, this list of conditions and the following disclaimer in <add> * the documentation and/or other materials provided with the <add> * distribution. <add> * <add> * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS <add> * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT <add> * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS <add> * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE <add> * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, <add> * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES <add> * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR <add> * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) <add> * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, <add> * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) <add> * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED <add> * OF THE POSSIBILITY OF SUCH DAMAGE. <add> */ <add> <add>package com.yubico.jaas.impl; <add> <add>import com.yubico.jaas.YubikeyToUserMap; <add>import edu.vt.middleware.ldap.Ldap; <add>import edu.vt.middleware.ldap.LdapConfig; <add>import edu.vt.middleware.ldap.SearchFilter; <add>import java.util.Iterator; <add>import java.util.Map; <add>import javax.naming.NamingException; <add>import javax.naming.directory.Attributes; <add>import javax.naming.directory.SearchResult; <add>import org.slf4j.Logger; <add>import org.slf4j.LoggerFactory; <add> <add>/** <add> * Class to verify that a user is the rightful owner of a YubiKey. <add> * <add> * This implementation uses a LDAP directory to look up the Yubikey's <add> * publicId and fetch the associated username. <add> * <add> * @author Etienne Dysli <[email protected]> <add> */ <add>public class YubikeyToUserLDAPMap implements YubikeyToUserMap { <add> /* Supported JAAS configuration options */ <add> /** Enable verification of Yubikey owner (default: true) */ <add> public static final String OPTION_YUBICO_VERIFY_YK_OWNER = "verify_yubikey_owner"; <add> /** Name of the LDAP attribute containing the Yubikey publicId (default: empty) */ <add> public static final String OPTION_YUBICO_LDAP_PUBLICID_ATTRIBUTE = "ldap_publicid_attribute"; <add> /** Name of the LDAP attribute containing the username (default: "uid") */ <add> public static final String OPTION_YUBICO_LDAP_USERNAME_ATTRIBUTE = "ldap_username_attribute"; <add> /** URL of the LDAP directory (default: empty) */ <add> public static final String OPTION_LDAP_URL = "ldap_url"; <add> /** Base DN for LDAP searches (default: empty) */ <add> public static final String OPTION_LDAP_BASE_DN = "ldap_base_dn"; <add> /** DN used to log into the LDAP directory (default: empty) */ <add> public static final String OPTION_LDAP_BIND_DN = "ldap_bind_dn"; <add> /** Password for the bind DN (default: empty) */ <add> public static final String OPTION_LDAP_BIND_CREDENTIAL = "ldap_bind_credential"; <add> private boolean verify_yubikey_owner = true; <add> private String publicid_attribute = ""; <add> private String username_attribute = "uid"; <add> private String ldap_url = ""; <add> private String ldap_base_dn = ""; <add> private String ldap_bind_dn = ""; <add> private String ldap_bind_credential = ""; <add> private Ldap ldap; <add> private final Logger log = LoggerFactory.getLogger(YubikeyToUserLDAPMap.class); <add> <add> /** {@inheritDoc} */ <add> public boolean is_right_user(String username, String publicId) { <add> log.trace("In is_right_user()"); <add> if (!this.verify_yubikey_owner) { <add> log.debug("YubiKey owner verification disabled, returning 'true'"); <add> return true; <add> } <add> String ykuser = null; <add> try { <add> SearchFilter filter = new SearchFilter("({0}={1})", new String[]{this.publicid_attribute, publicId}); <add> log.debug("Searching for YubiKey publicId with filter: {}", filter.toString()); <add> Iterator<SearchResult> results = ldap.search(filter, new String[]{this.username_attribute}); <add> if (results.hasNext()) { <add> Attributes results_attributes = results.next().getAttributes(); <add> log.debug("Found attributes: {}", results_attributes.toString()); <add> ykuser = results_attributes.get(this.username_attribute).get().toString(); <add> } else { <add> log.debug("No search results"); <add> } <add> } catch (NamingException ex) { <add> log.error(ex.getMessage(), ex); <add> return false; <add> } <add> if (ykuser != null) { <add> if (!ykuser.equals(username)) { <add> log.info("YubiKey " + publicId + " registered to user {}, NOT {}", ykuser, username); <add> return false; <add> } else { <add> log.info("YubiKey " + publicId + " registered to user {}", ykuser); <add> return true; <add> } <add> } else { <add> log.info("No record of YubiKey {} found. Returning 'false'.", publicId); <add> return false; <add> } <add> } <add> <add> /** {@inheritDoc} */ <add> public final void setOptions(Map<String, ?> options) { <add> /* Is verification of YubiKey owners enabled? */ <add> this.verify_yubikey_owner = true; <add> if (options.get(OPTION_YUBICO_VERIFY_YK_OWNER) != null) { <add> if ("false".equals(options.get(OPTION_YUBICO_VERIFY_YK_OWNER).toString())) { <add> this.verify_yubikey_owner = false; <add> } <add> } <add> if (options.get(OPTION_YUBICO_LDAP_PUBLICID_ATTRIBUTE) != null) { <add> this.publicid_attribute = options.get(OPTION_YUBICO_LDAP_PUBLICID_ATTRIBUTE).toString(); <add> } <add> if (options.get(OPTION_YUBICO_LDAP_USERNAME_ATTRIBUTE) != null) { <add> this.username_attribute = options.get(OPTION_YUBICO_LDAP_USERNAME_ATTRIBUTE).toString(); <add> } <add> if (options.get(OPTION_LDAP_URL) != null) { <add> this.ldap_url = options.get(OPTION_LDAP_URL).toString(); <add> } <add> if (options.get(OPTION_LDAP_BASE_DN) != null) { <add> this.ldap_base_dn = options.get(OPTION_LDAP_BASE_DN).toString(); <add> } <add> if (options.get(OPTION_LDAP_BIND_DN) != null) { <add> this.ldap_bind_dn = options.get(OPTION_LDAP_BIND_DN).toString(); <add> } <add> if (options.get(OPTION_LDAP_BIND_CREDENTIAL) != null) { <add> this.ldap_bind_credential = options.get(OPTION_LDAP_BIND_CREDENTIAL).toString(); <add> } <add> LdapConfig config = new LdapConfig(this.ldap_url, this.ldap_base_dn); <add> config.setBindDn(this.ldap_bind_dn); <add> config.setBindCredential(this.ldap_bind_credential); <add> this.ldap = new Ldap(config); <add> } <add>}
Java
lgpl-2.1
0788fdc5f15932db5bab3c3ad74314292357bf47
0
ontometrics/ontokettle,juanmjacobs/kettle,juanmjacobs/kettle,juanmjacobs/kettle,ontometrics/ontokettle,ontometrics/ontokettle,cwarden/kettle,cwarden/kettle,cwarden/kettle
package be.ibridge.kettle.trans.step.excelinput; import be.ibridge.kettle.core.Const; import be.ibridge.kettle.trans.Trans; import be.ibridge.kettle.trans.TransMeta; import be.ibridge.kettle.trans.step.KettleStepUseCase; import be.ibridge.kettle.trans.step.errorhandling.FileErrorHandlerMissingFiles; public class ExcelInputReplayTest extends KettleStepUseCase { public void testInputOKIgnoreErrorsTrueStrictFalse() throws Exception { directory = "test/useCases/replay/excelInputReplayGoodIgnoreTrueStrictFalse/"; expectFiles(directory, 2); meta = new TransMeta(directory + "transform.ktr"); trans = new Trans(log, meta); boolean ok = trans.execute(null); assertTrue(ok); trans.waitUntilFinished(); trans.endProcessing("end"); //$NON-NLS-1$ assertEquals(0, trans.getErrors()); // Changed from 2 to 4: if you don't want to have the .line files, you don't specify them. // So, ignore=true will create the .line files, one per sheet: 2 extra files = 4 files. // expectFiles(directory, 4); } public void testInputOKIgnoreErrorsTrue() throws Exception { directory = "test/useCases/replay/excelInputReplayGoodIgnoreTrue/"; expectFiles(directory, 2); meta = new TransMeta(directory + "transform.ktr"); trans = new Trans(log, meta); boolean ok = trans.execute(null); assertTrue(ok); trans.waitUntilFinished(); trans.endProcessing("end"); //$NON-NLS-1$ assertEquals(0, trans.getErrors()); expectFiles(directory, 2); } public void testInputOKIgnoreErrorsFalse() throws Exception { directory = "test/useCases/replay/excelInputReplayGoodIgnoreFalse/"; expectFiles(directory, 2); meta = new TransMeta(directory + "transform.ktr"); trans = new Trans(log, meta); boolean ok = trans.execute(null); assertTrue(ok); trans.waitUntilFinished(); trans.endProcessing("end"); //$NON-NLS-1$ assertEquals(0, trans.getErrors()); expectFiles(directory, 2); } public void testInputErrorIgnoreErrorRequiredNoFiles() throws Exception { directory = "test/useCases/replay/excelInputErrorIgnoreErrorRequiredNoFiles/"; expectFiles(directory, 1); meta = new TransMeta(directory + "transform.ktr"); trans = new Trans(log, meta); boolean ok = trans.execute(null); assertTrue(ok); trans.waitUntilFinished(); trans.endProcessing("end"); //$NON-NLS-1$ assertEquals(0, trans.getErrors()); expectFiles(directory, 2); expectContent(directory + "input.xls." + getDateFormatted() + ".error", FileErrorHandlerMissingFiles.THIS_FILE_DOES_NOT_EXIST + Const.CR); } public void testInputErrorIgnoreErrorsFalse() throws Exception { directory = "test/useCases/replay/excelInputReplayErrorIgnoreFalse/"; expectFiles(directory, 2); meta = new TransMeta(directory + "transform.ktr"); trans = new Trans(log, meta); boolean ok = trans.execute(null); assertTrue(ok); trans.waitUntilFinished(); trans.endProcessing("end"); //$NON-NLS-1$ assertEquals(1, trans.getErrors()); expectFiles(directory, 2); } public void testInputErrorIgnoreErrorsTrue() throws Exception { directory = "test/useCases/replay/excelInputReplayErrorIgnoreTrue/"; expectFiles(directory, 2); meta = new TransMeta(directory + "transform.ktr"); trans = new Trans(log, meta); boolean ok = trans.execute(null); assertTrue(ok); trans.waitUntilFinished(); trans.endProcessing("end"); //$NON-NLS-1$ assertEquals(0, trans.getErrors()); expectFiles(directory, 4); expectContent(directory + "input.xls_Sheet1." + getDateFormatted() + ".line", "2" + Const.CR + "19" + Const.CR); expectContent(directory + "input.xls_Sheet2." + getDateFormatted() + ".line", "10" + Const.CR + "17" + Const.CR); } public void testInputErrorIgnoreErrorsTrueRowNrOnly() throws Exception { directory = "test/useCases/replay/excelInputReplayErrorIgnoreTrueRowNrOnly/"; expectFiles(directory, 2); meta = new TransMeta(directory + "transform.ktr"); trans = new Trans(log, meta); boolean ok = trans.execute(null); assertTrue(ok); trans.waitUntilFinished(); trans.endProcessing("end"); //$NON-NLS-1$ assertEquals(0, trans.getErrors()); expectFiles(directory, 4); expectContent(directory + "input.xls_Sheet1." + getDateFormatted() + ".line", "2" + Const.CR + "19" + Const.CR); expectContent(directory + "input.xls_Sheet2." + getDateFormatted() + ".line", "10" + Const.CR + "17" + Const.CR); } public void testInputErrorIgnoreErrorsTrueErrorOnly() throws Exception { directory = "test/useCases/replay/excelInputReplayErrorIgnoreTrueErrorOnly/"; expectFiles(directory, 2); meta = new TransMeta(directory + "transform.ktr"); trans = new Trans(log, meta); boolean ok = trans.execute(null); assertTrue(ok); trans.waitUntilFinished(); trans.endProcessing("end"); //$NON-NLS-1$ assertEquals(0, trans.getErrors()); expectFiles(directory, 3); expectContent( directory + "input2.xls." + getDateFormatted() + ".error", FileErrorHandlerMissingFiles.THIS_FILE_DOES_NOT_EXIST + Const.CR); } public void testInputOutputSkipErrorLineFalse() throws Exception { directory = "test/useCases/replay/excelInputOutputSkipErrorLineFalse/"; expectFiles(directory, 2); meta = new TransMeta(directory + "transform.ktr"); trans = new Trans(log, meta); boolean ok = trans.execute(null); assertTrue(ok); trans.waitUntilFinished(); trans.endProcessing("end"); //$NON-NLS-1$ assertEquals(0, trans.getErrors()); expectFiles(directory, 4); expectContent(directory + "input.xls_Sheet1." + getDateFormatted() + ".line", "3" + Const.CR + "6" + Const.CR); expectContent(directory + "result.out", "name;age" + Const.CR + "john; 23" + Const.CR + "dennis; 0" + Const.CR + "ward; 15" + Const.CR + "john; 24" + Const.CR + "roel; 0" + Const.CR + "ward; 16" + Const.CR + "john; 25" + Const.CR); } public void testInputOutputSkipErrorLineTrue() throws Exception { directory = "test/useCases/replay/excelInputOutputSkipErrorLineTrue/"; expectFiles(directory, 2); meta = new TransMeta(directory + "transform.ktr"); trans = new Trans(log, meta); boolean ok = trans.execute(null); assertTrue(ok); trans.waitUntilFinished(); trans.endProcessing("end"); //$NON-NLS-1$ assertEquals(0, trans.getErrors()); expectFiles(directory, 4); expectContent(directory + "input.xls_Sheet1." + getDateFormatted() + ".line", "3" + Const.CR + "6" + Const.CR); expectContent(directory + "result.out", "name;age" + Const.CR + "john; 23" + Const.CR + "ward; 15" + Const.CR + "john; 24" + Const.CR + "ward; 16" + Const.CR + "john; 25" + Const.CR); } public void testReplayErrorOnly() throws Exception { directory = "test/useCases/replay/excelInputDoReplayErrorOnly/"; expectFiles(directory, 6); meta = new TransMeta(directory + "transform.ktr"); trans = new Trans(log, meta); trans.setReplayDate(getReplayDate()); boolean ok = trans.execute(null); assertTrue(ok); trans.waitUntilFinished(); trans.endProcessing("end"); //$NON-NLS-1$ assertEquals(0, trans.getErrors()); expectFiles(directory, 9); expectContent(directory + "input3.xls_Sheet1." + getDateFormatted() + ".line", "6" + Const.CR + "10" + Const.CR + "14" + Const.CR + "17" + Const.CR + "18" + Const.CR); expectContent(directory + "input3.xls_Sheet2." + getDateFormatted() + ".line", "12" + Const.CR); expectContent(directory + "input3.xls_Sheet3." + getDateFormatted() + ".line", "6" + Const.CR + "10" + Const.CR + "14" + Const.CR + "17" + Const.CR + "18" + Const.CR); } public void testReplayErrorOnlyWildcards() throws Exception { directory = "test/useCases/replay/excelInputDoReplayErrorOnlyWildcards/"; expectFiles(directory, 6); meta = new TransMeta(directory + "transform.ktr"); trans = new Trans(log, meta); trans.setReplayDate(getReplayDate()); boolean ok = trans.execute(null); assertTrue(ok); trans.waitUntilFinished(); trans.endProcessing("end"); //$NON-NLS-1$ assertEquals(0, trans.getErrors()); expectFiles(directory, 9); expectContent(directory + "input3.xls_Sheet1." + getDateFormatted() + ".line", "6" + Const.CR + "10" + Const.CR + "14" + Const.CR + "17" + Const.CR + "18" + Const.CR); expectContent(directory + "input3.xls_Sheet2." + getDateFormatted() + ".line", "12" + Const.CR); expectContent(directory + "input3.xls_Sheet3." + getDateFormatted() + ".line", "6" + Const.CR + "10" + Const.CR + "14" + Const.CR + "17" + Const.CR + "18" + Const.CR); } public void testReplayMultipleFiles() throws Exception { directory = "test/useCases/replay/excelInputDoReplayMultipleFiles/"; expectFiles(directory, 11); meta = new TransMeta(directory + "transform.ktr"); trans = new Trans(log, meta); trans.setReplayDate(getReplayDate()); boolean ok = trans.execute(null); assertTrue(ok); trans.waitUntilFinished(); trans.endProcessing("end"); //$NON-NLS-1$ assertEquals(0, trans.getErrors()); expectFiles(directory, 14); expectContent(directory + "input1.xls_sh2." + getDateFormatted() + ".line", "18" + Const.CR); expectContent(directory + "input3.xls_sh1." + getDateFormatted() + ".line", "7" + Const.CR + "8" + Const.CR); expectContent(directory + "input3.xls_sh3." + getDateFormatted() + ".line", "14" + Const.CR + "18" + Const.CR); } public void testReplayMixed() throws Exception { directory = "test/useCases/replay/excelInputDoReplayMixed/"; expectFiles(directory, 14); meta = new TransMeta(directory + "transform.ktr"); trans = new Trans(log, meta); trans.setReplayDate(getReplayDate()); boolean ok = trans.execute(null); assertTrue(ok); trans.waitUntilFinished(); trans.endProcessing("end"); //$NON-NLS-1$ assertEquals(0, trans.getErrors()); expectFiles(directory, 20); expectContent(directory + "input1.xls_sh2." + getDateFormatted() + ".line", "18" + Const.CR); expectContent(directory + "input3.xls_sh1." + getDateFormatted() + ".line", "7" + Const.CR + "8" + Const.CR); expectContent(directory + "input3.xls_sh3." + getDateFormatted() + ".line", "14" + Const.CR + "18" + Const.CR); expectContent(directory + "input4.xls_sh1." + getDateFormatted() + ".line", "7" + Const.CR + "8" + Const.CR); expectContent(directory + "input4.xls_sh3." + getDateFormatted() + ".line", "13" + Const.CR + "14" + Const.CR + "18" + Const.CR); expectContent( directory + "input5.xls." + getDateFormatted() + ".error", FileErrorHandlerMissingFiles.THIS_FILE_DOES_NOT_EXIST + Const.CR); } public void testReplay() throws Exception { directory = "test/useCases/replay/excelInputDoReplay/"; expectFiles(directory, 3); meta = new TransMeta(directory + "transform.ktr"); trans = new Trans(log, meta); trans.setReplayDate(getReplayDate()); boolean ok = trans.execute(null); assertTrue(ok); trans.waitUntilFinished(); trans.endProcessing("end"); //$NON-NLS-1$ assertEquals(0, trans.getErrors()); expectFiles(directory, 4); expectContent(directory + "input.xls_sh2." + getDateFormatted() + ".line", "7" + Const.CR + "18" + Const.CR); } public String getFileExtension() { return "xls"; } }
test/useCases/replay/be/ibridge/kettle/trans/step/excelinput/ExcelInputReplayTest.java
package be.ibridge.kettle.trans.step.excelinput; import be.ibridge.kettle.core.Const; import be.ibridge.kettle.trans.Trans; import be.ibridge.kettle.trans.TransMeta; import be.ibridge.kettle.trans.step.KettleStepUseCase; import be.ibridge.kettle.trans.step.errorhandling.FileErrorHandlerMissingFiles; public class ExcelInputReplayTest extends KettleStepUseCase { public void testInputOKIgnoreErrorsTrueStrictFalse() throws Exception { directory = "test/useCases/replay/excelInputReplayGoodIgnoreTrueStrictFalse/"; expectFiles(directory, 2); meta = new TransMeta(directory + "transform.ktr"); trans = new Trans(log, meta); boolean ok = trans.execute(null); assertTrue(ok); trans.waitUntilFinished(); trans.endProcessing("end"); //$NON-NLS-1$ assertEquals(0, trans.getErrors()); expectFiles(directory, 2); } public void testInputOKIgnoreErrorsTrue() throws Exception { directory = "test/useCases/replay/excelInputReplayGoodIgnoreTrue/"; expectFiles(directory, 2); meta = new TransMeta(directory + "transform.ktr"); trans = new Trans(log, meta); boolean ok = trans.execute(null); assertTrue(ok); trans.waitUntilFinished(); trans.endProcessing("end"); //$NON-NLS-1$ assertEquals(0, trans.getErrors()); expectFiles(directory, 2); } public void testInputOKIgnoreErrorsFalse() throws Exception { directory = "test/useCases/replay/excelInputReplayGoodIgnoreFalse/"; expectFiles(directory, 2); meta = new TransMeta(directory + "transform.ktr"); trans = new Trans(log, meta); boolean ok = trans.execute(null); assertTrue(ok); trans.waitUntilFinished(); trans.endProcessing("end"); //$NON-NLS-1$ assertEquals(0, trans.getErrors()); expectFiles(directory, 2); } public void testInputErrorIgnoreErrorRequiredNoFiles() throws Exception { directory = "test/useCases/replay/excelInputErrorIgnoreErrorRequiredNoFiles/"; expectFiles(directory, 1); meta = new TransMeta(directory + "transform.ktr"); trans = new Trans(log, meta); boolean ok = trans.execute(null); assertTrue(ok); trans.waitUntilFinished(); trans.endProcessing("end"); //$NON-NLS-1$ assertEquals(0, trans.getErrors()); expectFiles(directory, 2); expectContent(directory + "input.xls." + getDateFormatted() + ".error", FileErrorHandlerMissingFiles.THIS_FILE_DOES_NOT_EXIST + Const.CR); } public void testInputErrorIgnoreErrorsFalse() throws Exception { directory = "test/useCases/replay/excelInputReplayErrorIgnoreFalse/"; expectFiles(directory, 2); meta = new TransMeta(directory + "transform.ktr"); trans = new Trans(log, meta); boolean ok = trans.execute(null); assertTrue(ok); trans.waitUntilFinished(); trans.endProcessing("end"); //$NON-NLS-1$ assertEquals(1, trans.getErrors()); expectFiles(directory, 2); } public void testInputErrorIgnoreErrorsTrue() throws Exception { directory = "test/useCases/replay/excelInputReplayErrorIgnoreTrue/"; expectFiles(directory, 2); meta = new TransMeta(directory + "transform.ktr"); trans = new Trans(log, meta); boolean ok = trans.execute(null); assertTrue(ok); trans.waitUntilFinished(); trans.endProcessing("end"); //$NON-NLS-1$ assertEquals(0, trans.getErrors()); expectFiles(directory, 4); expectContent(directory + "input.xls_Sheet1." + getDateFormatted() + ".line", "2" + Const.CR + "19" + Const.CR); expectContent(directory + "input.xls_Sheet2." + getDateFormatted() + ".line", "10" + Const.CR + "17" + Const.CR); } public void testInputErrorIgnoreErrorsTrueRowNrOnly() throws Exception { directory = "test/useCases/replay/excelInputReplayErrorIgnoreTrueRowNrOnly/"; expectFiles(directory, 2); meta = new TransMeta(directory + "transform.ktr"); trans = new Trans(log, meta); boolean ok = trans.execute(null); assertTrue(ok); trans.waitUntilFinished(); trans.endProcessing("end"); //$NON-NLS-1$ assertEquals(0, trans.getErrors()); expectFiles(directory, 4); expectContent(directory + "input.xls_Sheet1." + getDateFormatted() + ".line", "2" + Const.CR + "19" + Const.CR); expectContent(directory + "input.xls_Sheet2." + getDateFormatted() + ".line", "10" + Const.CR + "17" + Const.CR); } public void testInputErrorIgnoreErrorsTrueErrorOnly() throws Exception { directory = "test/useCases/replay/excelInputReplayErrorIgnoreTrueErrorOnly/"; expectFiles(directory, 2); meta = new TransMeta(directory + "transform.ktr"); trans = new Trans(log, meta); boolean ok = trans.execute(null); assertTrue(ok); trans.waitUntilFinished(); trans.endProcessing("end"); //$NON-NLS-1$ assertEquals(0, trans.getErrors()); expectFiles(directory, 3); expectContent( directory + "input2.xls." + getDateFormatted() + ".error", FileErrorHandlerMissingFiles.THIS_FILE_DOES_NOT_EXIST + Const.CR); } public void testInputOutputSkipErrorLineFalse() throws Exception { directory = "test/useCases/replay/excelInputOutputSkipErrorLineFalse/"; expectFiles(directory, 2); meta = new TransMeta(directory + "transform.ktr"); trans = new Trans(log, meta); boolean ok = trans.execute(null); assertTrue(ok); trans.waitUntilFinished(); trans.endProcessing("end"); //$NON-NLS-1$ assertEquals(0, trans.getErrors()); expectFiles(directory, 4); expectContent(directory + "input.xls_Sheet1." + getDateFormatted() + ".line", "3" + Const.CR + "6" + Const.CR); expectContent(directory + "result.out", "name;age" + Const.CR + "john; 23" + Const.CR + "dennis; 0" + Const.CR + "ward; 15" + Const.CR + "john; 24" + Const.CR + "roel; 0" + Const.CR + "ward; 16" + Const.CR + "john; 25" + Const.CR); } public void testInputOutputSkipErrorLineTrue() throws Exception { directory = "test/useCases/replay/excelInputOutputSkipErrorLineTrue/"; expectFiles(directory, 2); meta = new TransMeta(directory + "transform.ktr"); trans = new Trans(log, meta); boolean ok = trans.execute(null); assertTrue(ok); trans.waitUntilFinished(); trans.endProcessing("end"); //$NON-NLS-1$ assertEquals(0, trans.getErrors()); expectFiles(directory, 4); expectContent(directory + "input.xls_Sheet1." + getDateFormatted() + ".line", "3" + Const.CR + "6" + Const.CR); expectContent(directory + "result.out", "name;age" + Const.CR + "john; 23" + Const.CR + "ward; 15" + Const.CR + "john; 24" + Const.CR + "ward; 16" + Const.CR + "john; 25" + Const.CR); } public void testReplayErrorOnly() throws Exception { directory = "test/useCases/replay/excelInputDoReplayErrorOnly/"; expectFiles(directory, 6); meta = new TransMeta(directory + "transform.ktr"); trans = new Trans(log, meta); trans.setReplayDate(getReplayDate()); boolean ok = trans.execute(null); assertTrue(ok); trans.waitUntilFinished(); trans.endProcessing("end"); //$NON-NLS-1$ assertEquals(0, trans.getErrors()); expectFiles(directory, 9); expectContent(directory + "input3.xls_Sheet1." + getDateFormatted() + ".line", "6" + Const.CR + "10" + Const.CR + "14" + Const.CR + "17" + Const.CR + "18" + Const.CR); expectContent(directory + "input3.xls_Sheet2." + getDateFormatted() + ".line", "12" + Const.CR); expectContent(directory + "input3.xls_Sheet3." + getDateFormatted() + ".line", "6" + Const.CR + "10" + Const.CR + "14" + Const.CR + "17" + Const.CR + "18" + Const.CR); } public void testReplayErrorOnlyWildcards() throws Exception { directory = "test/useCases/replay/excelInputDoReplayErrorOnlyWildcards/"; expectFiles(directory, 6); meta = new TransMeta(directory + "transform.ktr"); trans = new Trans(log, meta); trans.setReplayDate(getReplayDate()); boolean ok = trans.execute(null); assertTrue(ok); trans.waitUntilFinished(); trans.endProcessing("end"); //$NON-NLS-1$ assertEquals(0, trans.getErrors()); expectFiles(directory, 9); expectContent(directory + "input3.xls_Sheet1." + getDateFormatted() + ".line", "6" + Const.CR + "10" + Const.CR + "14" + Const.CR + "17" + Const.CR + "18" + Const.CR); expectContent(directory + "input3.xls_Sheet2." + getDateFormatted() + ".line", "12" + Const.CR); expectContent(directory + "input3.xls_Sheet3." + getDateFormatted() + ".line", "6" + Const.CR + "10" + Const.CR + "14" + Const.CR + "17" + Const.CR + "18" + Const.CR); } public void testReplayMultipleFiles() throws Exception { directory = "test/useCases/replay/excelInputDoReplayMultipleFiles/"; expectFiles(directory, 11); meta = new TransMeta(directory + "transform.ktr"); trans = new Trans(log, meta); trans.setReplayDate(getReplayDate()); boolean ok = trans.execute(null); assertTrue(ok); trans.waitUntilFinished(); trans.endProcessing("end"); //$NON-NLS-1$ assertEquals(0, trans.getErrors()); expectFiles(directory, 14); expectContent(directory + "input1.xls_sh2." + getDateFormatted() + ".line", "18" + Const.CR); expectContent(directory + "input3.xls_sh1." + getDateFormatted() + ".line", "7" + Const.CR + "8" + Const.CR); expectContent(directory + "input3.xls_sh3." + getDateFormatted() + ".line", "14" + Const.CR + "18" + Const.CR); } public void testReplayMixed() throws Exception { directory = "test/useCases/replay/excelInputDoReplayMixed/"; expectFiles(directory, 14); meta = new TransMeta(directory + "transform.ktr"); trans = new Trans(log, meta); trans.setReplayDate(getReplayDate()); boolean ok = trans.execute(null); assertTrue(ok); trans.waitUntilFinished(); trans.endProcessing("end"); //$NON-NLS-1$ assertEquals(0, trans.getErrors()); expectFiles(directory, 20); expectContent(directory + "input1.xls_sh2." + getDateFormatted() + ".line", "18" + Const.CR); expectContent(directory + "input3.xls_sh1." + getDateFormatted() + ".line", "7" + Const.CR + "8" + Const.CR); expectContent(directory + "input3.xls_sh3." + getDateFormatted() + ".line", "14" + Const.CR + "18" + Const.CR); expectContent(directory + "input4.xls_sh1." + getDateFormatted() + ".line", "7" + Const.CR + "8" + Const.CR); expectContent(directory + "input4.xls_sh3." + getDateFormatted() + ".line", "13" + Const.CR + "14" + Const.CR + "18" + Const.CR); expectContent( directory + "input5.xls." + getDateFormatted() + ".error", FileErrorHandlerMissingFiles.THIS_FILE_DOES_NOT_EXIST + Const.CR); } public void testReplay() throws Exception { directory = "test/useCases/replay/excelInputDoReplay/"; expectFiles(directory, 3); meta = new TransMeta(directory + "transform.ktr"); trans = new Trans(log, meta); trans.setReplayDate(getReplayDate()); boolean ok = trans.execute(null); assertTrue(ok); trans.waitUntilFinished(); trans.endProcessing("end"); //$NON-NLS-1$ assertEquals(0, trans.getErrors()); expectFiles(directory, 4); expectContent(directory + "input.xls_sh2." + getDateFormatted() + ".line", "7" + Const.CR + "18" + Const.CR); } public String getFileExtension() { return "xls"; } }
Number of expected files changed from 2 to 4: if you don't want to have the .line files, you don't specify them. So, ignore=true will create the .line files, one per sheet: 2 extra files = 4 files. git-svn-id: 9499f031eb5c9fb9d11553a06c92651e5446d292@866 5fb7f6ec-07c1-534a-b4ca-9155e429e800
test/useCases/replay/be/ibridge/kettle/trans/step/excelinput/ExcelInputReplayTest.java
Number of expected files changed from 2 to 4: if you don't want to have the .line files, you don't specify them. So, ignore=true will create the .line files, one per sheet: 2 extra files = 4 files.
<ide><path>est/useCases/replay/be/ibridge/kettle/trans/step/excelinput/ExcelInputReplayTest.java <ide> trans.waitUntilFinished(); <ide> trans.endProcessing("end"); //$NON-NLS-1$ <ide> assertEquals(0, trans.getErrors()); <del> expectFiles(directory, 2); <add> <add> // Changed from 2 to 4: if you don't want to have the .line files, you don't specify them. <add> // So, ignore=true will create the .line files, one per sheet: 2 extra files = 4 files. <add> // <add> expectFiles(directory, 4); <ide> } <ide> <ide> public void testInputOKIgnoreErrorsTrue() throws Exception {
Java
apache-2.0
5f6245fe713ff9ac46beaf6bc5d93cc5984f7570
0
gentics/mesh,gentics/mesh,gentics/mesh,gentics/mesh
package com.gentics.mesh.core.data.root.impl; import static com.gentics.mesh.core.data.relationship.GraphPermission.CREATE_PERM; import static com.gentics.mesh.core.data.relationship.GraphPermission.READ_PERM; import static com.gentics.mesh.core.data.relationship.GraphPermission.READ_PUBLISHED_PERM; import static com.gentics.mesh.core.data.relationship.GraphRelationships.HAS_NODE; import static com.gentics.mesh.core.data.relationship.GraphRelationships.HAS_NODE_ROOT; import static com.gentics.mesh.core.data.relationship.GraphRelationships.PROJECT_KEY_PROPERTY; import static com.gentics.mesh.core.rest.common.ContainerType.DRAFT; import static com.gentics.mesh.core.rest.common.ContainerType.PUBLISHED; import static com.gentics.mesh.core.rest.error.Errors.error; import static com.gentics.mesh.madl.index.EdgeIndexDefinition.edgeIndex; import static com.gentics.mesh.util.StreamUtil.toStream; import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST; import static io.netty.handler.codec.http.HttpResponseStatus.FORBIDDEN; import static io.netty.handler.codec.http.HttpResponseStatus.NOT_FOUND; import static org.apache.commons.lang3.StringUtils.isEmpty; import java.util.List; import java.util.Set; import java.util.stream.Stream; import org.apache.commons.lang3.StringUtils; import com.gentics.madl.index.IndexHandler; import com.gentics.madl.type.TypeHandler; import com.gentics.mesh.cli.BootstrapInitializer; import com.gentics.mesh.context.BulkActionContext; import com.gentics.mesh.context.InternalActionContext; import com.gentics.mesh.core.data.Branch; import com.gentics.mesh.core.data.Language; import com.gentics.mesh.core.data.MeshAuthUser; import com.gentics.mesh.core.data.NodeGraphFieldContainer; import com.gentics.mesh.core.data.Project; import com.gentics.mesh.core.data.Role; import com.gentics.mesh.core.data.User; import com.gentics.mesh.core.data.dao.UserDaoWrapper; import com.gentics.mesh.core.data.generic.MeshVertexImpl; import com.gentics.mesh.core.data.impl.GraphFieldContainerEdgeImpl; import com.gentics.mesh.core.data.impl.ProjectImpl; import com.gentics.mesh.core.data.node.Node; import com.gentics.mesh.core.data.node.impl.NodeImpl; import com.gentics.mesh.core.data.page.TransformablePage; import com.gentics.mesh.core.data.page.impl.DynamicTransformableStreamPageImpl; import com.gentics.mesh.core.data.relationship.GraphPermission; import com.gentics.mesh.core.data.root.NodeRoot; import com.gentics.mesh.core.data.root.UserRoot; import com.gentics.mesh.core.data.schema.SchemaContainer; import com.gentics.mesh.core.data.schema.SchemaContainerVersion; import com.gentics.mesh.core.db.Tx; import com.gentics.mesh.core.rest.common.ContainerType; import com.gentics.mesh.core.rest.node.NodeCreateRequest; import com.gentics.mesh.core.rest.schema.SchemaReferenceInfo; import com.gentics.mesh.event.EventQueueBatch; import com.gentics.mesh.json.JsonUtil; import com.gentics.mesh.madl.traversal.TraversalResult; import com.gentics.mesh.parameter.PagingParameters; import com.syncleus.ferma.FramedTransactionalGraph; import com.tinkerpop.blueprints.Vertex; import io.vertx.core.logging.Logger; import io.vertx.core.logging.LoggerFactory; /** * @see NodeRoot */ public class NodeRootImpl extends AbstractRootVertex<Node> implements NodeRoot { private static final Logger log = LoggerFactory.getLogger(NodeRootImpl.class); public static void init(TypeHandler type, IndexHandler index) { type.createVertexType(NodeRootImpl.class, MeshVertexImpl.class); index.createIndex(edgeIndex(HAS_NODE).withInOut().withOut()); } @Override public Class<? extends Node> getPersistanceClass() { return NodeImpl.class; } @Override public String getRootLabel() { return HAS_NODE; } @Override public TransformablePage<? extends Node> findAll(InternalActionContext ac, PagingParameters pagingInfo) { ContainerType type = ContainerType.forVersion(ac.getVersioningParameters().getVersion()); return new DynamicTransformableStreamPageImpl<>(findAllStream(ac, type), pagingInfo); } @Override public TraversalResult<? extends Node> findAll() { Project project = getProject(); return project.findNodes(); } private Project getProject() { return in(HAS_NODE_ROOT, ProjectImpl.class).next(); } @Override public Stream<? extends Node> findAllStream(InternalActionContext ac, GraphPermission perm) { MeshAuthUser user = ac.getUser(); String branchUuid = ac.getBranch().getUuid(); UserDaoWrapper userDao = mesh().boot().userDao(); return findAll(ac.getProject().getUuid()) .filter(item -> { boolean hasRead = userDao.hasPermissionForId(user, item.getId(), READ_PERM); if (hasRead) { return true; } else { // Check whether the node is published. In this case we need to check the read publish perm. boolean isPublishedForBranch = GraphFieldContainerEdgeImpl.matchesBranchAndType(item.getId(), branchUuid, PUBLISHED); if (isPublishedForBranch) { return userDao.hasPermissionForId(user, item.getId(), READ_PUBLISHED_PERM); } } return false; }) .map(vertex -> graph.frameElementExplicit(vertex, getPersistanceClass())); } /** * Finds all nodes of a project. * * @param projectUuid * @return */ private Stream<Vertex> findAll(String projectUuid) { return toStream(db().getVertices( NodeImpl.class, new String[] { PROJECT_KEY_PROPERTY }, new Object[] { projectUuid })); } private Stream<? extends Node> findAllStream(InternalActionContext ac, ContainerType type) { MeshAuthUser user = ac.getUser(); FramedTransactionalGraph graph = Tx.get().getGraph(); Branch branch = ac.getBranch(); String branchUuid = branch.getUuid(); UserDaoWrapper userDao = mesh().boot().userDao(); return findAll(ac.getProject().getUuid()).filter(item -> { // Check whether the node has at least one content of the type in the selected branch - Otherwise the node should be skipped return GraphFieldContainerEdgeImpl.matchesBranchAndType(item.getId(), branchUuid, type); }).filter(item -> { boolean hasRead = userDao.hasPermissionForId(user, item.getId(), READ_PERM); if (hasRead) { return true; } else if (type == PUBLISHED) { // Check whether the node is published. In this case we need to check the read publish perm. boolean isPublishedForBranch = GraphFieldContainerEdgeImpl.matchesBranchAndType(item.getId(), branchUuid, PUBLISHED); if (isPublishedForBranch) { return userDao.hasPermissionForId(user, item.getId(), READ_PUBLISHED_PERM); } } return false; }) .map(vertex -> graph.frameElementExplicit(vertex, getPersistanceClass())); } @Override public Node findByUuid(String uuid) { return getProject().findNode(uuid); } @Override public Node loadObjectByUuid(InternalActionContext ac, String uuid, GraphPermission perm, boolean errorIfNotFound) { Node element = findByUuid(uuid); if (!errorIfNotFound && element == null) { return null; } UserRoot userRoot = mesh().boot().userDao(); if (element == null) { throw error(NOT_FOUND, "object_not_found_for_uuid", uuid); } MeshAuthUser requestUser = ac.getUser(); if (perm == READ_PUBLISHED_PERM) { Branch branch = ac.getBranch(element.getProject()); List<String> requestedLanguageTags = ac.getNodeParameters().getLanguageList(options()); NodeGraphFieldContainer fieldContainer = element.findVersion(requestedLanguageTags, branch.getUuid(), ac.getVersioningParameters().getVersion()); if (fieldContainer == null) { throw error(NOT_FOUND, "node_error_published_not_found_for_uuid_branch_language", uuid, String.join(",", requestedLanguageTags), branch.getUuid()); } // Additionally check whether the read published permission could grant read // perm for published nodes boolean isPublished = fieldContainer.isPublished(branch.getUuid()); if (isPublished && userRoot.hasPermission(requestUser, element, READ_PUBLISHED_PERM)) { return element; // The container could be a draft. Check whether READ perm is granted. } else if (!isPublished && userRoot.hasPermission(requestUser, element, READ_PERM)) { return element; } else { throw error(FORBIDDEN, "error_missing_perm", uuid, READ_PUBLISHED_PERM.getRestPerm().getName()); } } else if (userRoot.hasPermission(requestUser, element, perm)) { return element; } throw error(FORBIDDEN, "error_missing_perm", uuid, perm.getRestPerm().getName()); } @Override public Node create(User creator, SchemaContainerVersion version, Project project, String uuid) { // TODO check whether the mesh node is in fact a folder node. NodeImpl node = getGraph().addFramedVertex(NodeImpl.class); if (uuid != null) { node.setUuid(uuid); } node.setSchemaContainer(version.getSchemaContainer()); // TODO is this a duplicate? - Maybe we should only store the project assignment // in one way? node.setProject(project); node.setCreator(creator); node.setCreationTimestamp(); return node; } @Override public void delete(BulkActionContext bac) { getElement().remove(); } /** * Create a new node using the specified schema container. * * @param ac * @param schemaVersion * @param batch * @param uuid * @return */ // TODO use schema container version instead of container private Node createNode(InternalActionContext ac, SchemaContainerVersion schemaVersion, EventQueueBatch batch, String uuid) { Project project = ac.getProject(); MeshAuthUser requestUser = ac.getUser(); BootstrapInitializer boot = mesh().boot(); UserDaoWrapper userRoot = boot.userDao(); NodeCreateRequest requestModel = ac.fromJson(NodeCreateRequest.class); if (requestModel.getParentNode() == null || isEmpty(requestModel.getParentNode().getUuid())) { throw error(BAD_REQUEST, "node_missing_parentnode_field"); } if (isEmpty(requestModel.getLanguage())) { throw error(BAD_REQUEST, "node_no_languagecode_specified"); } // Load the parent node in order to create the node Node parentNode = project.getNodeRoot().loadObjectByUuid(ac, requestModel.getParentNode().getUuid(), CREATE_PERM); Branch branch = ac.getBranch(); // BUG: Don't use the latest version. Use the version which is linked to the // branch! Node node = parentNode.create(requestUser, schemaVersion, project, branch, uuid); // Add initial permissions to the created node userRoot.inheritRolePermissions(requestUser, parentNode, node); // Create the language specific graph field container for the node Language language = Tx.get().data().languageDao().findByLanguageTag(requestModel.getLanguage()); if (language == null) { throw error(BAD_REQUEST, "language_not_found", requestModel.getLanguage()); } NodeGraphFieldContainer container = node.createGraphFieldContainer(language.getLanguageTag(), branch, requestUser); container.updateFieldsFromRest(ac, requestModel.getFields()); batch.add(node.onCreated()); batch.add(container.onCreated(branch.getUuid(), DRAFT)); // Check for webroot input data consistency (PUT on webroot) String webrootSegment = ac.get("WEBROOT_SEGMENT_NAME"); if (webrootSegment != null) { String current = container.getSegmentFieldValue(); if (!webrootSegment.equals(current)) { throw error(BAD_REQUEST, "webroot_error_segment_field_mismatch", webrootSegment, current); } } if (requestModel.getTags() != null) { node.updateTags(ac, batch, requestModel.getTags()); } return node; } @Override public Node create(InternalActionContext ac, EventQueueBatch batch, String uuid) { // Override any given version parameter. Creation is always scoped to drafts ac.getVersioningParameters().setVersion("draft"); Project project = ac.getProject(); MeshAuthUser requestUser = ac.getUser(); Branch branch = ac.getBranch(); UserDaoWrapper userDao = mesh().boot().userDao(); String body = ac.getBodyAsString(); // 1. Extract the schema information from the given JSON SchemaReferenceInfo schemaInfo = JsonUtil.readValue(body, SchemaReferenceInfo.class); boolean missingSchemaInfo = schemaInfo.getSchema() == null || (StringUtils.isEmpty(schemaInfo.getSchema().getUuid()) && StringUtils.isEmpty(schemaInfo.getSchema().getName())); if (missingSchemaInfo) { throw error(BAD_REQUEST, "error_schema_parameter_missing"); } if (!isEmpty(schemaInfo.getSchema().getUuid())) { // 2. Use schema reference by uuid first SchemaContainer schemaByUuid = project.getSchemaContainerRoot().loadObjectByUuid(ac, schemaInfo.getSchema().getUuid(), READ_PERM); SchemaContainerVersion schemaVersion = branch.findLatestSchemaVersion(schemaByUuid); if (schemaVersion == null) { throw error(BAD_REQUEST, "schema_error_schema_not_linked_to_branch", schemaByUuid.getName(), branch.getName(), project.getName()); } return createNode(ac, schemaVersion, batch, uuid); } // 3. Or just schema reference by name if (!isEmpty(schemaInfo.getSchema().getName())) { SchemaContainer schemaByName = project.getSchemaContainerRoot() .findByName(schemaInfo.getSchema().getName()); if (schemaByName != null) { String schemaName = schemaByName.getName(); String schemaUuid = schemaByName.getUuid(); if (userDao.hasPermission(requestUser, schemaByName, READ_PERM)) { SchemaContainerVersion schemaVersion = branch.findLatestSchemaVersion(schemaByName); if (schemaVersion == null) { throw error(BAD_REQUEST, "schema_error_schema_not_linked_to_branch", schemaByName.getName(), branch.getName(), project.getName()); } return createNode(ac, schemaVersion, batch, uuid); } else { throw error(FORBIDDEN, "error_missing_perm", schemaUuid + "/" + schemaName, READ_PERM.getRestPerm().getName()); } } else { throw error(NOT_FOUND, "schema_not_found", schemaInfo.getSchema().getName()); } } else { throw error(BAD_REQUEST, "error_schema_parameter_missing"); } } @Override public void applyPermissions(EventQueueBatch batch, Role role, boolean recursive, Set<GraphPermission> permissionsToGrant, Set<GraphPermission> permissionsToRevoke) { if (recursive) { for (Node node : findAll()) { // We don't need to recursively handle the permissions for each node again since // this call will already affect all nodes. node.applyPermissions(batch, role, false, permissionsToGrant, permissionsToRevoke); } } applyVertexPermissions(batch, role, permissionsToGrant, permissionsToRevoke); } }
core/src/main/java/com/gentics/mesh/core/data/root/impl/NodeRootImpl.java
package com.gentics.mesh.core.data.root.impl; import static com.gentics.mesh.core.data.relationship.GraphPermission.CREATE_PERM; import static com.gentics.mesh.core.data.relationship.GraphPermission.READ_PERM; import static com.gentics.mesh.core.data.relationship.GraphPermission.READ_PUBLISHED_PERM; import static com.gentics.mesh.core.data.relationship.GraphRelationships.HAS_NODE; import static com.gentics.mesh.core.data.relationship.GraphRelationships.HAS_NODE_ROOT; import static com.gentics.mesh.core.data.relationship.GraphRelationships.PROJECT_KEY_PROPERTY; import static com.gentics.mesh.core.rest.common.ContainerType.DRAFT; import static com.gentics.mesh.core.rest.common.ContainerType.PUBLISHED; import static com.gentics.mesh.core.rest.error.Errors.error; import static com.gentics.mesh.madl.index.EdgeIndexDefinition.edgeIndex; import static com.gentics.mesh.util.StreamUtil.toStream; import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST; import static io.netty.handler.codec.http.HttpResponseStatus.FORBIDDEN; import static io.netty.handler.codec.http.HttpResponseStatus.NOT_FOUND; import static org.apache.commons.lang3.StringUtils.isEmpty; import java.util.List; import java.util.Set; import java.util.stream.Stream; import org.apache.commons.lang3.StringUtils; import com.gentics.madl.index.IndexHandler; import com.gentics.madl.type.TypeHandler; import com.gentics.mesh.cli.BootstrapInitializer; import com.gentics.mesh.context.BulkActionContext; import com.gentics.mesh.context.InternalActionContext; import com.gentics.mesh.core.data.Branch; import com.gentics.mesh.core.data.Language; import com.gentics.mesh.core.data.MeshAuthUser; import com.gentics.mesh.core.data.NodeGraphFieldContainer; import com.gentics.mesh.core.data.Project; import com.gentics.mesh.core.data.Role; import com.gentics.mesh.core.data.User; import com.gentics.mesh.core.data.dao.UserDaoWrapper; import com.gentics.mesh.core.data.generic.MeshVertexImpl; import com.gentics.mesh.core.data.impl.GraphFieldContainerEdgeImpl; import com.gentics.mesh.core.data.impl.ProjectImpl; import com.gentics.mesh.core.data.node.Node; import com.gentics.mesh.core.data.node.impl.NodeImpl; import com.gentics.mesh.core.data.page.TransformablePage; import com.gentics.mesh.core.data.page.impl.DynamicTransformableStreamPageImpl; import com.gentics.mesh.core.data.relationship.GraphPermission; import com.gentics.mesh.core.data.root.NodeRoot; import com.gentics.mesh.core.data.root.UserRoot; import com.gentics.mesh.core.data.schema.SchemaContainer; import com.gentics.mesh.core.data.schema.SchemaContainerVersion; import com.gentics.mesh.core.db.Tx; import com.gentics.mesh.core.rest.common.ContainerType; import com.gentics.mesh.core.rest.node.NodeCreateRequest; import com.gentics.mesh.core.rest.schema.SchemaReferenceInfo; import com.gentics.mesh.event.EventQueueBatch; import com.gentics.mesh.json.JsonUtil; import com.gentics.mesh.madl.traversal.TraversalResult; import com.gentics.mesh.parameter.PagingParameters; import com.syncleus.ferma.FramedTransactionalGraph; import com.tinkerpop.blueprints.Vertex; import io.vertx.core.logging.Logger; import io.vertx.core.logging.LoggerFactory; /** * @see NodeRoot */ public class NodeRootImpl extends AbstractRootVertex<Node> implements NodeRoot { private static final Logger log = LoggerFactory.getLogger(NodeRootImpl.class); public static void init(TypeHandler type, IndexHandler index) { type.createVertexType(NodeRootImpl.class, MeshVertexImpl.class); index.createIndex(edgeIndex(HAS_NODE).withInOut().withOut()); } @Override public Class<? extends Node> getPersistanceClass() { return NodeImpl.class; } @Override public String getRootLabel() { return HAS_NODE; } @Override public TransformablePage<? extends Node> findAll(InternalActionContext ac, PagingParameters pagingInfo) { ContainerType type = ContainerType.forVersion(ac.getVersioningParameters().getVersion()); return new DynamicTransformableStreamPageImpl<>(findAllStream(ac, type), pagingInfo); } @Override public TraversalResult<? extends Node> findAll() { Project project = getProject(); return project.findNodes(); } private Project getProject() { return in(HAS_NODE_ROOT, ProjectImpl.class).next(); } @Override public Stream<? extends Node> findAllStream(InternalActionContext ac, GraphPermission perm) { MeshAuthUser user = ac.getUser(); String branchUuid = ac.getBranch().getUuid(); UserDaoWrapper userDao = mesh().boot().userDao(); return findAll(ac.getProject().getUuid()) .filter(item -> { boolean hasRead = userDao.hasPermissionForId(user, item.getId(), READ_PERM); if (hasRead) { return true; } else { // Check whether the node is published. In this case we need to check the read publish perm. boolean isPublishedForBranch = GraphFieldContainerEdgeImpl.matchesBranchAndType(item.getId(), branchUuid, PUBLISHED); if (isPublishedForBranch) { return userDao.hasPermissionForId(user, item.getId(), READ_PUBLISHED_PERM); } } return false; }) .map(vertex -> graph.frameElementExplicit(vertex, getPersistanceClass())); } /** * Finds all nodes of a project. * @param projectUuid * @return */ private Stream<Vertex> findAll(String projectUuid) { return toStream(db().getVertices( NodeImpl.class, new String[]{PROJECT_KEY_PROPERTY}, new Object[]{projectUuid} )); } private Stream<? extends Node> findAllStream(InternalActionContext ac, ContainerType type) { MeshAuthUser user = ac.getUser(); FramedTransactionalGraph graph = Tx.get().getGraph(); Branch branch = ac.getBranch(); String branchUuid = branch.getUuid(); UserDaoWrapper userDao = mesh().boot().userDao(); return findAll(ac.getProject().getUuid()).filter(item -> { // Check whether the node has at least one content of the type in the selected branch - Otherwise the node should be skipped return GraphFieldContainerEdgeImpl.matchesBranchAndType(item.getId(), branchUuid, type); }).filter(item -> { boolean hasRead = userDao.hasPermissionForId(user, item.getId(), READ_PERM); if (hasRead) { return true; } else if (type == PUBLISHED) { // Check whether the node is published. In this case we need to check the read publish perm. boolean isPublishedForBranch = GraphFieldContainerEdgeImpl.matchesBranchAndType(item.getId(), branchUuid, PUBLISHED); if (isPublishedForBranch) { return userDao.hasPermissionForId(user, item.getId(), READ_PUBLISHED_PERM); } } return false; }) .map(vertex -> graph.frameElementExplicit(vertex, getPersistanceClass())); } @Override public Node findByUuid(String uuid) { return getProject().findNode(uuid); } @Override public Node loadObjectByUuid(InternalActionContext ac, String uuid, GraphPermission perm) { Node element = findByUuid(uuid); UserRoot userRoot = mesh().boot().userDao(); if (element == null) { throw error(NOT_FOUND, "object_not_found_for_uuid", uuid); } MeshAuthUser requestUser = ac.getUser(); if (perm == READ_PUBLISHED_PERM) { Branch branch = ac.getBranch(element.getProject()); List<String> requestedLanguageTags = ac.getNodeParameters().getLanguageList(options()); NodeGraphFieldContainer fieldContainer = element.findVersion(requestedLanguageTags, branch.getUuid(), ac.getVersioningParameters().getVersion()); if (fieldContainer == null) { throw error(NOT_FOUND, "node_error_published_not_found_for_uuid_branch_language", uuid, String.join(",", requestedLanguageTags), branch.getUuid()); } // Additionally check whether the read published permission could grant read // perm for published nodes boolean isPublished = fieldContainer.isPublished(branch.getUuid()); if (isPublished && userRoot.hasPermission(requestUser, element, READ_PUBLISHED_PERM)) { return element; // The container could be a draft. Check whether READ perm is granted. } else if (!isPublished && userRoot.hasPermission(requestUser, element, READ_PERM)) { return element; } else { throw error(FORBIDDEN, "error_missing_perm", uuid, READ_PUBLISHED_PERM.getRestPerm().getName()); } } else if (userRoot.hasPermission(requestUser, element, perm)) { return element; } throw error(FORBIDDEN, "error_missing_perm", uuid, perm.getRestPerm().getName()); } @Override public Node create(User creator, SchemaContainerVersion version, Project project, String uuid) { // TODO check whether the mesh node is in fact a folder node. NodeImpl node = getGraph().addFramedVertex(NodeImpl.class); if (uuid != null) { node.setUuid(uuid); } node.setSchemaContainer(version.getSchemaContainer()); // TODO is this a duplicate? - Maybe we should only store the project assignment // in one way? node.setProject(project); node.setCreator(creator); node.setCreationTimestamp(); return node; } @Override public void delete(BulkActionContext bac) { getElement().remove(); } /** * Create a new node using the specified schema container. * * @param ac * @param schemaVersion * @param batch * @param uuid * @return */ // TODO use schema container version instead of container private Node createNode(InternalActionContext ac, SchemaContainerVersion schemaVersion, EventQueueBatch batch, String uuid) { Project project = ac.getProject(); MeshAuthUser requestUser = ac.getUser(); BootstrapInitializer boot = mesh().boot(); UserDaoWrapper userRoot = boot.userDao(); NodeCreateRequest requestModel = ac.fromJson(NodeCreateRequest.class); if (requestModel.getParentNode() == null || isEmpty(requestModel.getParentNode().getUuid())) { throw error(BAD_REQUEST, "node_missing_parentnode_field"); } if (isEmpty(requestModel.getLanguage())) { throw error(BAD_REQUEST, "node_no_languagecode_specified"); } // Load the parent node in order to create the node Node parentNode = project.getNodeRoot().loadObjectByUuid(ac, requestModel.getParentNode().getUuid(), CREATE_PERM); Branch branch = ac.getBranch(); // BUG: Don't use the latest version. Use the version which is linked to the // branch! Node node = parentNode.create(requestUser, schemaVersion, project, branch, uuid); // Add initial permissions to the created node userRoot.inheritRolePermissions(requestUser, parentNode, node); // Create the language specific graph field container for the node Language language = Tx.get().data().languageDao().findByLanguageTag(requestModel.getLanguage()); if (language == null) { throw error(BAD_REQUEST, "language_not_found", requestModel.getLanguage()); } NodeGraphFieldContainer container = node.createGraphFieldContainer(language.getLanguageTag(), branch, requestUser); container.updateFieldsFromRest(ac, requestModel.getFields()); batch.add(node.onCreated()); batch.add(container.onCreated(branch.getUuid(), DRAFT)); // Check for webroot input data consistency (PUT on webroot) String webrootSegment = ac.get("WEBROOT_SEGMENT_NAME"); if (webrootSegment != null) { String current = container.getSegmentFieldValue(); if (!webrootSegment.equals(current)) { throw error(BAD_REQUEST, "webroot_error_segment_field_mismatch", webrootSegment, current); } } if (requestModel.getTags() != null) { node.updateTags(ac, batch, requestModel.getTags()); } return node; } @Override public Node create(InternalActionContext ac, EventQueueBatch batch, String uuid) { // Override any given version parameter. Creation is always scoped to drafts ac.getVersioningParameters().setVersion("draft"); Project project = ac.getProject(); MeshAuthUser requestUser = ac.getUser(); Branch branch = ac.getBranch(); UserDaoWrapper userDao = mesh().boot().userDao(); String body = ac.getBodyAsString(); // 1. Extract the schema information from the given JSON SchemaReferenceInfo schemaInfo = JsonUtil.readValue(body, SchemaReferenceInfo.class); boolean missingSchemaInfo = schemaInfo.getSchema() == null || (StringUtils.isEmpty(schemaInfo.getSchema().getUuid()) && StringUtils.isEmpty(schemaInfo.getSchema().getName())); if (missingSchemaInfo) { throw error(BAD_REQUEST, "error_schema_parameter_missing"); } if (!isEmpty(schemaInfo.getSchema().getUuid())) { // 2. Use schema reference by uuid first SchemaContainer schemaByUuid = project.getSchemaContainerRoot().loadObjectByUuid(ac, schemaInfo.getSchema().getUuid(), READ_PERM); SchemaContainerVersion schemaVersion = branch.findLatestSchemaVersion(schemaByUuid); if (schemaVersion == null) { throw error(BAD_REQUEST, "schema_error_schema_not_linked_to_branch", schemaByUuid.getName(), branch.getName(), project.getName()); } return createNode(ac, schemaVersion, batch, uuid); } // 3. Or just schema reference by name if (!isEmpty(schemaInfo.getSchema().getName())) { SchemaContainer schemaByName = project.getSchemaContainerRoot() .findByName(schemaInfo.getSchema().getName()); if (schemaByName != null) { String schemaName = schemaByName.getName(); String schemaUuid = schemaByName.getUuid(); if (userDao.hasPermission(requestUser, schemaByName, READ_PERM)) { SchemaContainerVersion schemaVersion = branch.findLatestSchemaVersion(schemaByName); if (schemaVersion == null) { throw error(BAD_REQUEST, "schema_error_schema_not_linked_to_branch", schemaByName.getName(), branch.getName(), project.getName()); } return createNode(ac, schemaVersion, batch, uuid); } else { throw error(FORBIDDEN, "error_missing_perm", schemaUuid + "/" + schemaName, READ_PERM.getRestPerm().getName()); } } else { throw error(NOT_FOUND, "schema_not_found", schemaInfo.getSchema().getName()); } } else { throw error(BAD_REQUEST, "error_schema_parameter_missing"); } } @Override public void applyPermissions(EventQueueBatch batch, Role role, boolean recursive, Set<GraphPermission> permissionsToGrant, Set<GraphPermission> permissionsToRevoke) { if (recursive) { for (Node node : findAll()) { // We don't need to recursively handle the permissions for each node again since // this call will already affect all nodes. node.applyPermissions(batch, role, false, permissionsToGrant, permissionsToRevoke); } } applyVertexPermissions(batch, role, permissionsToGrant, permissionsToRevoke); } }
Fix another regression
core/src/main/java/com/gentics/mesh/core/data/root/impl/NodeRootImpl.java
Fix another regression
<ide><path>ore/src/main/java/com/gentics/mesh/core/data/root/impl/NodeRootImpl.java <ide> <ide> /** <ide> * Finds all nodes of a project. <add> * <ide> * @param projectUuid <ide> * @return <ide> */ <ide> private Stream<Vertex> findAll(String projectUuid) { <ide> return toStream(db().getVertices( <ide> NodeImpl.class, <del> new String[]{PROJECT_KEY_PROPERTY}, <del> new Object[]{projectUuid} <del> )); <add> new String[] { PROJECT_KEY_PROPERTY }, <add> new Object[] { projectUuid })); <ide> } <ide> <ide> private Stream<? extends Node> findAllStream(InternalActionContext ac, ContainerType type) { <ide> } <ide> return false; <ide> }) <del> .map(vertex -> graph.frameElementExplicit(vertex, getPersistanceClass())); <add> .map(vertex -> graph.frameElementExplicit(vertex, getPersistanceClass())); <ide> } <ide> <ide> @Override <ide> } <ide> <ide> @Override <del> public Node loadObjectByUuid(InternalActionContext ac, String uuid, GraphPermission perm) { <add> public Node loadObjectByUuid(InternalActionContext ac, String uuid, GraphPermission perm, boolean errorIfNotFound) { <ide> Node element = findByUuid(uuid); <add> if (!errorIfNotFound && element == null) { <add> return null; <add> } <ide> UserRoot userRoot = mesh().boot().userDao(); <ide> if (element == null) { <ide> throw error(NOT_FOUND, "object_not_found_for_uuid", uuid); <ide> <ide> List<String> requestedLanguageTags = ac.getNodeParameters().getLanguageList(options()); <ide> NodeGraphFieldContainer fieldContainer = element.findVersion(requestedLanguageTags, branch.getUuid(), <del> ac.getVersioningParameters().getVersion()); <add> ac.getVersioningParameters().getVersion()); <ide> <ide> if (fieldContainer == null) { <ide> throw error(NOT_FOUND, "node_error_published_not_found_for_uuid_branch_language", uuid, <del> String.join(",", requestedLanguageTags), branch.getUuid()); <add> String.join(",", requestedLanguageTags), branch.getUuid()); <ide> } <ide> // Additionally check whether the read published permission could grant read <ide> // perm for published nodes <ide> */ <ide> // TODO use schema container version instead of container <ide> private Node createNode(InternalActionContext ac, SchemaContainerVersion schemaVersion, EventQueueBatch batch, <del> String uuid) { <add> String uuid) { <ide> Project project = ac.getProject(); <ide> MeshAuthUser requestUser = ac.getUser(); <ide> BootstrapInitializer boot = mesh().boot(); <ide> <ide> // Load the parent node in order to create the node <ide> Node parentNode = project.getNodeRoot().loadObjectByUuid(ac, requestModel.getParentNode().getUuid(), <del> CREATE_PERM); <add> CREATE_PERM); <ide> Branch branch = ac.getBranch(); <ide> // BUG: Don't use the latest version. Use the version which is linked to the <ide> // branch! <ide> // 1. Extract the schema information from the given JSON <ide> SchemaReferenceInfo schemaInfo = JsonUtil.readValue(body, SchemaReferenceInfo.class); <ide> boolean missingSchemaInfo = schemaInfo.getSchema() == null <del> || (StringUtils.isEmpty(schemaInfo.getSchema().getUuid()) <del> && StringUtils.isEmpty(schemaInfo.getSchema().getName())); <add> || (StringUtils.isEmpty(schemaInfo.getSchema().getUuid()) <add> && StringUtils.isEmpty(schemaInfo.getSchema().getName())); <ide> if (missingSchemaInfo) { <ide> throw error(BAD_REQUEST, "error_schema_parameter_missing"); <ide> } <ide> if (!isEmpty(schemaInfo.getSchema().getUuid())) { <ide> // 2. Use schema reference by uuid first <ide> SchemaContainer schemaByUuid = project.getSchemaContainerRoot().loadObjectByUuid(ac, <del> schemaInfo.getSchema().getUuid(), READ_PERM); <add> schemaInfo.getSchema().getUuid(), READ_PERM); <ide> SchemaContainerVersion schemaVersion = branch.findLatestSchemaVersion(schemaByUuid); <ide> if (schemaVersion == null) { <ide> throw error(BAD_REQUEST, "schema_error_schema_not_linked_to_branch", schemaByUuid.getName(), branch.getName(), project.getName()); <ide> // 3. Or just schema reference by name <ide> if (!isEmpty(schemaInfo.getSchema().getName())) { <ide> SchemaContainer schemaByName = project.getSchemaContainerRoot() <del> .findByName(schemaInfo.getSchema().getName()); <add> .findByName(schemaInfo.getSchema().getName()); <ide> if (schemaByName != null) { <ide> String schemaName = schemaByName.getName(); <ide> String schemaUuid = schemaByName.getUuid(); <ide> if (userDao.hasPermission(requestUser, schemaByName, READ_PERM)) { <ide> SchemaContainerVersion schemaVersion = branch.findLatestSchemaVersion(schemaByName); <ide> if (schemaVersion == null) { <del> throw error(BAD_REQUEST, "schema_error_schema_not_linked_to_branch", schemaByName.getName(), branch.getName(), project.getName()); <add> throw error(BAD_REQUEST, "schema_error_schema_not_linked_to_branch", schemaByName.getName(), branch.getName(), <add> project.getName()); <ide> } <ide> return createNode(ac, schemaVersion, batch, uuid); <ide> } else { <ide> <ide> @Override <ide> public void applyPermissions(EventQueueBatch batch, Role role, boolean recursive, <del> Set<GraphPermission> permissionsToGrant, Set<GraphPermission> permissionsToRevoke) { <add> Set<GraphPermission> permissionsToGrant, Set<GraphPermission> permissionsToRevoke) { <ide> if (recursive) { <ide> for (Node node : findAll()) { <ide> // We don't need to recursively handle the permissions for each node again since
Java
apache-2.0
cdc8c0776f78d1652986d74e221f17759e376594
0
spinnaker/clouddriver,duftler/clouddriver,ajordens/clouddriver,ajordens/clouddriver,ajordens/clouddriver,spinnaker/clouddriver,ajordens/clouddriver,spinnaker/clouddriver,duftler/clouddriver,duftler/clouddriver,duftler/clouddriver
package com.netflix.spinnaker.clouddriver.titus.deploy.description; import com.fasterxml.jackson.annotation.JsonIgnore; import com.netflix.spinnaker.clouddriver.deploy.DeployDescription; import com.netflix.spinnaker.clouddriver.orchestration.SagaContextAware; import com.netflix.spinnaker.clouddriver.orchestration.events.OperationEvent; import com.netflix.spinnaker.clouddriver.security.resources.ApplicationNameable; import com.netflix.spinnaker.clouddriver.titus.client.model.DisruptionBudget; import com.netflix.spinnaker.clouddriver.titus.client.model.Efs; import com.netflix.spinnaker.clouddriver.titus.client.model.MigrationPolicy; import com.netflix.spinnaker.clouddriver.titus.client.model.ServiceJobProcesses; import com.netflix.spinnaker.clouddriver.titus.client.model.SubmitJobRequest; import com.netflix.spinnaker.clouddriver.titus.model.DockerImage; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.annotation.Nonnull; import javax.annotation.Nullable; import lombok.Data; import lombok.extern.slf4j.Slf4j; @Slf4j public class TitusDeployDescription extends AbstractTitusCredentialsDescription implements DeployDescription, ApplicationNameable, SagaContextAware { private String region; private String subnet; private List<String> zones = new ArrayList<>(); private List<String> securityGroups = new ArrayList<>(); private List<String> targetGroups = new ArrayList<>(); private List<String> softConstraints; private List<String> hardConstraints; private String application; private String stack; private String freeFormDetails; private String imageId; private Capacity capacity = new Capacity(); private Resources resources = new Resources(); private Map<String, String> env = new LinkedHashMap<>(); private Map<String, String> labels = new LinkedHashMap<>(); private Map<String, String> containerAttributes = new LinkedHashMap<>(); private String entryPoint; private String iamProfile; private String capacityGroup; private String user; private Boolean inService; private String jobType; private int retries; private int runtimeLimitSecs; private List<String> interestingHealthProviderNames = new ArrayList<>(); private MigrationPolicy migrationPolicy; private Boolean copySourceScalingPoliciesAndActions = true; private Integer sequence; private DisruptionBudget disruptionBudget; private SubmitJobRequest.Constraints constraints = new SubmitJobRequest.Constraints(); private ServiceJobProcesses serviceJobProcesses; @JsonIgnore private SagaContext sagaContext; /** * Will be overridden by any the label {@code PrepareTitusDeploy.USE_APPLICATION_DEFAULT_SG_LABEL} * * <p>TODO(rz): Redundant; migrate off this property or the label (pref to migrate off the label) */ @Deprecated private boolean useApplicationDefaultSecurityGroup = true; /** * If false, the newly created server group will not pick up scaling policies and actions from an * ancestor group */ private boolean copySourceScalingPolicies = true; private List<OperationEvent> events = new ArrayList<>(); private Source source = new Source(); private Efs efs; @Override public Collection<String> getApplications() { return Arrays.asList(application); } @Override public void setSagaContext(SagaContext sagaContext) { this.sagaContext = sagaContext; } @Nullable public SagaContext getSagaContext() { return sagaContext; } /** For Jackson deserialization. */ public void setApplications(List<String> applications) { if (!applications.isEmpty()) { application = applications.get(0); } } @Nonnull public SubmitJobRequest toSubmitJobRequest( @Nonnull DockerImage dockerImage, @Nonnull String jobName, String user) { final SubmitJobRequest.SubmitJobRequestBuilder submitJobRequest = SubmitJobRequest.builder() .jobName(jobName) .user(user) .application(application) .dockerImageName(dockerImage.getImageName()) .instancesMin(capacity.getMin()) .instancesMax(capacity.getMax()) .instancesDesired(capacity.getDesired()) .cpu(resources.getCpu()) .memory(resources.getMemory()) .sharedMemory(resources.getSharedMemory()) .disk(resources.getDisk()) .retries(retries) .runtimeLimitSecs(runtimeLimitSecs) .gpu(resources.getGpu()) .networkMbps(resources.getNetworkMbps()) .efs(efs) .ports(resources.getPorts()) .env(env) .allocateIpAddress(resources.isAllocateIpAddress()) .stack(stack) .detail(freeFormDetails) .entryPoint(entryPoint) .iamProfile(iamProfile) .capacityGroup(capacityGroup) .labels(labels) .inService(inService) .migrationPolicy(migrationPolicy) .credentials(getCredentials().getName()) .containerAttributes(containerAttributes) .disruptionBudget(disruptionBudget) .serviceJobProcesses(serviceJobProcesses); if (!securityGroups.isEmpty()) { submitJobRequest.securityGroups(securityGroups); } if (dockerImage.getImageDigest() != null) { submitJobRequest.dockerDigest(dockerImage.getImageDigest()); } else { submitJobRequest.dockerImageVersion(dockerImage.getImageVersion()); } /** * Titus api now supports the ability to set key/value for hard & soft constraints, but the * original interface we supported was just a list of keys, to make this change backwards * compatible we give preference to they\ constraints key/value map vs soft & hard constraints * list */ if (constraints.getHard() != null || constraints.getSoft() != null) { submitJobRequest.containerConstraints(constraints); } else { log.warn("Use of deprecated constraints payload: {}-{}", application, stack); List<SubmitJobRequest.Constraint> constraints = new ArrayList<>(); if (hardConstraints != null) { hardConstraints.forEach(c -> constraints.add(SubmitJobRequest.Constraint.hard(c))); } if (softConstraints != null) { softConstraints.forEach(c -> constraints.add(SubmitJobRequest.Constraint.soft(c))); } submitJobRequest.constraints(constraints); } if (jobType != null) { submitJobRequest.jobType(jobType); } return submitJobRequest.build(); } @Data public static class Capacity { private int min; private int max; private int desired; } @Data public static class Resources { private int cpu; private int memory; private int sharedMemory; private int disk; private int gpu; private int networkMbps; private int[] ports; private boolean allocateIpAddress; } @Data public static class Source { private String account; private String region; private String asgName; private boolean useSourceCapacity; } public String getRegion() { return region; } public void setRegion(String region) { this.region = region; } public String getSubnet() { return subnet; } public void setSubnet(String subnet) { this.subnet = subnet; } public List<String> getZones() { return zones; } public void setZones(List<String> zones) { this.zones = zones; } public List<String> getSecurityGroups() { return securityGroups; } public void setSecurityGroups(List<String> securityGroups) { this.securityGroups = securityGroups; } public List<String> getTargetGroups() { return targetGroups; } public void setTargetGroups(List<String> targetGroups) { this.targetGroups = targetGroups; } public List<String> getSoftConstraints() { return softConstraints; } public void setSoftConstraints(List<String> softConstraints) { this.softConstraints = softConstraints; } public List<String> getHardConstraints() { return hardConstraints; } public void setHardConstraints(List<String> hardConstraints) { this.hardConstraints = hardConstraints; } public String getApplication() { return application; } public void setApplication(String application) { this.application = application; } public String getStack() { return stack; } public void setStack(String stack) { this.stack = stack; } public String getFreeFormDetails() { return freeFormDetails; } public void setFreeFormDetails(String freeFormDetails) { this.freeFormDetails = freeFormDetails; } public String getImageId() { return imageId; } public void setImageId(String imageId) { this.imageId = imageId; } public Capacity getCapacity() { return capacity; } public void setCapacity(Capacity capacity) { this.capacity = capacity; } public Resources getResources() { return resources; } public void setResources(Resources resources) { this.resources = resources; } public Map<String, String> getEnv() { return env; } public void setEnv(Map<String, String> env) { this.env = env; } public Map<String, String> getLabels() { return labels; } public void setLabels(Map<String, String> labels) { this.labels = labels; } public Map<String, String> getContainerAttributes() { return containerAttributes; } public void setContainerAttributes(Map<String, String> containerAttributes) { this.containerAttributes = containerAttributes; } public String getEntryPoint() { return entryPoint; } public void setEntryPoint(String entryPoint) { this.entryPoint = entryPoint; } public String getIamProfile() { return iamProfile; } public void setIamProfile(String iamProfile) { this.iamProfile = iamProfile; } public String getCapacityGroup() { return capacityGroup; } public void setCapacityGroup(String capacityGroup) { this.capacityGroup = capacityGroup; } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public Boolean getInService() { return inService; } public void setInService(Boolean inService) { this.inService = inService; } public String getJobType() { return jobType; } public void setJobType(String jobType) { this.jobType = jobType; } public int getRetries() { return retries; } public void setRetries(int retries) { this.retries = retries; } public int getRuntimeLimitSecs() { return runtimeLimitSecs; } public void setRuntimeLimitSecs(int runtimeLimitSecs) { this.runtimeLimitSecs = runtimeLimitSecs; } public List<String> getInterestingHealthProviderNames() { return interestingHealthProviderNames; } public void setInterestingHealthProviderNames(List<String> interestingHealthProviderNames) { this.interestingHealthProviderNames = interestingHealthProviderNames; } public MigrationPolicy getMigrationPolicy() { return migrationPolicy; } public void setMigrationPolicy(MigrationPolicy migrationPolicy) { this.migrationPolicy = migrationPolicy; } public Boolean getCopySourceScalingPoliciesAndActions() { return copySourceScalingPoliciesAndActions; } public void setCopySourceScalingPoliciesAndActions(Boolean copySourceScalingPoliciesAndActions) { this.copySourceScalingPoliciesAndActions = copySourceScalingPoliciesAndActions; } public Integer getSequence() { return sequence; } public void setSequence(Integer sequence) { this.sequence = sequence; } public DisruptionBudget getDisruptionBudget() { return disruptionBudget; } public void setDisruptionBudget(DisruptionBudget disruptionBudget) { this.disruptionBudget = disruptionBudget; } public SubmitJobRequest.Constraints getConstraints() { return constraints; } public void setConstraints(SubmitJobRequest.Constraints constraints) { this.constraints = constraints; } public ServiceJobProcesses getServiceJobProcesses() { return serviceJobProcesses; } public void setServiceJobProcesses(ServiceJobProcesses serviceJobProcesses) { this.serviceJobProcesses = serviceJobProcesses; } public boolean isUseApplicationDefaultSecurityGroup() { return useApplicationDefaultSecurityGroup; } public void setUseApplicationDefaultSecurityGroup(boolean useApplicationDefaultSecurityGroup) { this.useApplicationDefaultSecurityGroup = useApplicationDefaultSecurityGroup; } public boolean isCopySourceScalingPolicies() { return copySourceScalingPolicies; } public void setCopySourceScalingPolicies(boolean copySourceScalingPolicies) { this.copySourceScalingPolicies = copySourceScalingPolicies; } @Override public List<OperationEvent> getEvents() { return events; } public void setEvents(List<OperationEvent> events) { this.events = events; } public Source getSource() { return source; } public void setSource(Source source) { this.source = source; } public Efs getEfs() { return efs; } public void setEfs(Efs efs) { this.efs = efs; } }
clouddriver-titus/src/main/groovy/com/netflix/spinnaker/clouddriver/titus/deploy/description/TitusDeployDescription.java
package com.netflix.spinnaker.clouddriver.titus.deploy.description; import com.fasterxml.jackson.annotation.JsonIgnore; import com.netflix.spinnaker.clouddriver.deploy.DeployDescription; import com.netflix.spinnaker.clouddriver.orchestration.SagaContextAware; import com.netflix.spinnaker.clouddriver.orchestration.events.OperationEvent; import com.netflix.spinnaker.clouddriver.security.resources.ApplicationNameable; import com.netflix.spinnaker.clouddriver.titus.client.model.DisruptionBudget; import com.netflix.spinnaker.clouddriver.titus.client.model.Efs; import com.netflix.spinnaker.clouddriver.titus.client.model.MigrationPolicy; import com.netflix.spinnaker.clouddriver.titus.client.model.ServiceJobProcesses; import com.netflix.spinnaker.clouddriver.titus.client.model.SubmitJobRequest; import com.netflix.spinnaker.clouddriver.titus.model.DockerImage; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.annotation.Nonnull; import javax.annotation.Nullable; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.extern.slf4j.Slf4j; @Slf4j @Data @EqualsAndHashCode(callSuper = true) public class TitusDeployDescription extends AbstractTitusCredentialsDescription implements DeployDescription, ApplicationNameable, SagaContextAware { private String region; private String subnet; private List<String> zones = new ArrayList<>(); private List<String> securityGroups = new ArrayList<>(); private List<String> targetGroups = new ArrayList<>(); private List<String> softConstraints; private List<String> hardConstraints; private String application; private String stack; private String freeFormDetails; private String imageId; private Capacity capacity = new Capacity(); private Resources resources = new Resources(); private Map<String, String> env = new LinkedHashMap<>(); private Map<String, String> labels = new LinkedHashMap<>(); private Map<String, String> containerAttributes = new LinkedHashMap<>(); private String entryPoint; private String iamProfile; private String capacityGroup; private String user; private Boolean inService; private String jobType; private int retries; private int runtimeLimitSecs; private List<String> interestingHealthProviderNames = new ArrayList<>(); private MigrationPolicy migrationPolicy; private Boolean copySourceScalingPoliciesAndActions = true; private Integer sequence; private DisruptionBudget disruptionBudget; private SubmitJobRequest.Constraints constraints = new SubmitJobRequest.Constraints(); private ServiceJobProcesses serviceJobProcesses; private SagaContext sagaContext; /** * Will be overridden by any the label {@code PrepareTitusDeploy.USE_APPLICATION_DEFAULT_SG_LABEL} * * <p>TODO(rz): Redundant; migrate off this property or the label (pref to migrate off the label) */ @Deprecated private boolean useApplicationDefaultSecurityGroup = true; /** * If false, the newly created server group will not pick up scaling policies and actions from an * ancestor group */ private boolean copySourceScalingPolicies = true; private List<OperationEvent> events = new ArrayList<>(); private Source source = new Source(); private Efs efs; @Override public Collection<String> getApplications() { return Arrays.asList(application); } @JsonIgnore @Override public void setSagaContext(SagaContext sagaContext) { this.sagaContext = sagaContext; } @JsonIgnore @Nullable public SagaContext getSagaContext() { return sagaContext; } /** For Jackson deserialization. */ public void setApplications(List<String> applications) { if (!applications.isEmpty()) { application = applications.get(0); } } @Nonnull public SubmitJobRequest toSubmitJobRequest( @Nonnull DockerImage dockerImage, @Nonnull String jobName, String user) { final SubmitJobRequest.SubmitJobRequestBuilder submitJobRequest = SubmitJobRequest.builder() .jobName(jobName) .user(user) .application(application) .dockerImageName(dockerImage.getImageName()) .instancesMin(capacity.getMin()) .instancesMax(capacity.getMax()) .instancesDesired(capacity.getDesired()) .cpu(resources.getCpu()) .memory(resources.getMemory()) .sharedMemory(resources.getSharedMemory()) .disk(resources.getDisk()) .retries(retries) .runtimeLimitSecs(runtimeLimitSecs) .gpu(resources.getGpu()) .networkMbps(resources.getNetworkMbps()) .efs(efs) .ports(resources.getPorts()) .env(env) .allocateIpAddress(resources.isAllocateIpAddress()) .stack(stack) .detail(freeFormDetails) .entryPoint(entryPoint) .iamProfile(iamProfile) .capacityGroup(capacityGroup) .labels(labels) .inService(inService) .migrationPolicy(migrationPolicy) .credentials(getCredentials().getName()) .containerAttributes(containerAttributes) .disruptionBudget(disruptionBudget) .serviceJobProcesses(serviceJobProcesses); if (!securityGroups.isEmpty()) { submitJobRequest.securityGroups(securityGroups); } if (dockerImage.getImageDigest() != null) { submitJobRequest.dockerDigest(dockerImage.getImageDigest()); } else { submitJobRequest.dockerImageVersion(dockerImage.getImageVersion()); } /** * Titus api now supports the ability to set key/value for hard & soft constraints, but the * original interface we supported was just a list of keys, to make this change backwards * compatible we give preference to they\ constraints key/value map vs soft & hard constraints * list */ if (constraints.getHard() != null || constraints.getSoft() != null) { submitJobRequest.containerConstraints(constraints); } else { log.warn("Use of deprecated constraints payload: {}-{}", application, stack); List<SubmitJobRequest.Constraint> constraints = new ArrayList<>(); if (hardConstraints != null) { hardConstraints.forEach(c -> constraints.add(SubmitJobRequest.Constraint.hard(c))); } if (softConstraints != null) { softConstraints.forEach(c -> constraints.add(SubmitJobRequest.Constraint.soft(c))); } submitJobRequest.constraints(constraints); } if (jobType != null) { submitJobRequest.jobType(jobType); } return submitJobRequest.build(); } @Data public static class Capacity { private int min; private int max; private int desired; } @Data public static class Resources { private int cpu; private int memory; private int sharedMemory; private int disk; private int gpu; private int networkMbps; private int[] ports; private boolean allocateIpAddress; } @Data public static class Source { private String account; private String region; private String asgName; private boolean useSourceCapacity; } }
fix(titus): Scorched earth removing Lombok for Jackson compat (#4083)
clouddriver-titus/src/main/groovy/com/netflix/spinnaker/clouddriver/titus/deploy/description/TitusDeployDescription.java
fix(titus): Scorched earth removing Lombok for Jackson compat (#4083)
<ide><path>louddriver-titus/src/main/groovy/com/netflix/spinnaker/clouddriver/titus/deploy/description/TitusDeployDescription.java <ide> import javax.annotation.Nonnull; <ide> import javax.annotation.Nullable; <ide> import lombok.Data; <del>import lombok.EqualsAndHashCode; <ide> import lombok.extern.slf4j.Slf4j; <ide> <ide> @Slf4j <del>@Data <del>@EqualsAndHashCode(callSuper = true) <ide> public class TitusDeployDescription extends AbstractTitusCredentialsDescription <ide> implements DeployDescription, ApplicationNameable, SagaContextAware { <ide> private String region; <ide> private DisruptionBudget disruptionBudget; <ide> private SubmitJobRequest.Constraints constraints = new SubmitJobRequest.Constraints(); <ide> private ServiceJobProcesses serviceJobProcesses; <del> private SagaContext sagaContext; <add> @JsonIgnore private SagaContext sagaContext; <ide> <ide> /** <ide> * Will be overridden by any the label {@code PrepareTitusDeploy.USE_APPLICATION_DEFAULT_SG_LABEL} <ide> return Arrays.asList(application); <ide> } <ide> <del> @JsonIgnore <ide> @Override <ide> public void setSagaContext(SagaContext sagaContext) { <ide> this.sagaContext = sagaContext; <ide> } <ide> <del> @JsonIgnore <ide> @Nullable <ide> public SagaContext getSagaContext() { <ide> return sagaContext; <ide> private String asgName; <ide> private boolean useSourceCapacity; <ide> } <add> <add> public String getRegion() { <add> return region; <add> } <add> <add> public void setRegion(String region) { <add> this.region = region; <add> } <add> <add> public String getSubnet() { <add> return subnet; <add> } <add> <add> public void setSubnet(String subnet) { <add> this.subnet = subnet; <add> } <add> <add> public List<String> getZones() { <add> return zones; <add> } <add> <add> public void setZones(List<String> zones) { <add> this.zones = zones; <add> } <add> <add> public List<String> getSecurityGroups() { <add> return securityGroups; <add> } <add> <add> public void setSecurityGroups(List<String> securityGroups) { <add> this.securityGroups = securityGroups; <add> } <add> <add> public List<String> getTargetGroups() { <add> return targetGroups; <add> } <add> <add> public void setTargetGroups(List<String> targetGroups) { <add> this.targetGroups = targetGroups; <add> } <add> <add> public List<String> getSoftConstraints() { <add> return softConstraints; <add> } <add> <add> public void setSoftConstraints(List<String> softConstraints) { <add> this.softConstraints = softConstraints; <add> } <add> <add> public List<String> getHardConstraints() { <add> return hardConstraints; <add> } <add> <add> public void setHardConstraints(List<String> hardConstraints) { <add> this.hardConstraints = hardConstraints; <add> } <add> <add> public String getApplication() { <add> return application; <add> } <add> <add> public void setApplication(String application) { <add> this.application = application; <add> } <add> <add> public String getStack() { <add> return stack; <add> } <add> <add> public void setStack(String stack) { <add> this.stack = stack; <add> } <add> <add> public String getFreeFormDetails() { <add> return freeFormDetails; <add> } <add> <add> public void setFreeFormDetails(String freeFormDetails) { <add> this.freeFormDetails = freeFormDetails; <add> } <add> <add> public String getImageId() { <add> return imageId; <add> } <add> <add> public void setImageId(String imageId) { <add> this.imageId = imageId; <add> } <add> <add> public Capacity getCapacity() { <add> return capacity; <add> } <add> <add> public void setCapacity(Capacity capacity) { <add> this.capacity = capacity; <add> } <add> <add> public Resources getResources() { <add> return resources; <add> } <add> <add> public void setResources(Resources resources) { <add> this.resources = resources; <add> } <add> <add> public Map<String, String> getEnv() { <add> return env; <add> } <add> <add> public void setEnv(Map<String, String> env) { <add> this.env = env; <add> } <add> <add> public Map<String, String> getLabels() { <add> return labels; <add> } <add> <add> public void setLabels(Map<String, String> labels) { <add> this.labels = labels; <add> } <add> <add> public Map<String, String> getContainerAttributes() { <add> return containerAttributes; <add> } <add> <add> public void setContainerAttributes(Map<String, String> containerAttributes) { <add> this.containerAttributes = containerAttributes; <add> } <add> <add> public String getEntryPoint() { <add> return entryPoint; <add> } <add> <add> public void setEntryPoint(String entryPoint) { <add> this.entryPoint = entryPoint; <add> } <add> <add> public String getIamProfile() { <add> return iamProfile; <add> } <add> <add> public void setIamProfile(String iamProfile) { <add> this.iamProfile = iamProfile; <add> } <add> <add> public String getCapacityGroup() { <add> return capacityGroup; <add> } <add> <add> public void setCapacityGroup(String capacityGroup) { <add> this.capacityGroup = capacityGroup; <add> } <add> <add> public String getUser() { <add> return user; <add> } <add> <add> public void setUser(String user) { <add> this.user = user; <add> } <add> <add> public Boolean getInService() { <add> return inService; <add> } <add> <add> public void setInService(Boolean inService) { <add> this.inService = inService; <add> } <add> <add> public String getJobType() { <add> return jobType; <add> } <add> <add> public void setJobType(String jobType) { <add> this.jobType = jobType; <add> } <add> <add> public int getRetries() { <add> return retries; <add> } <add> <add> public void setRetries(int retries) { <add> this.retries = retries; <add> } <add> <add> public int getRuntimeLimitSecs() { <add> return runtimeLimitSecs; <add> } <add> <add> public void setRuntimeLimitSecs(int runtimeLimitSecs) { <add> this.runtimeLimitSecs = runtimeLimitSecs; <add> } <add> <add> public List<String> getInterestingHealthProviderNames() { <add> return interestingHealthProviderNames; <add> } <add> <add> public void setInterestingHealthProviderNames(List<String> interestingHealthProviderNames) { <add> this.interestingHealthProviderNames = interestingHealthProviderNames; <add> } <add> <add> public MigrationPolicy getMigrationPolicy() { <add> return migrationPolicy; <add> } <add> <add> public void setMigrationPolicy(MigrationPolicy migrationPolicy) { <add> this.migrationPolicy = migrationPolicy; <add> } <add> <add> public Boolean getCopySourceScalingPoliciesAndActions() { <add> return copySourceScalingPoliciesAndActions; <add> } <add> <add> public void setCopySourceScalingPoliciesAndActions(Boolean copySourceScalingPoliciesAndActions) { <add> this.copySourceScalingPoliciesAndActions = copySourceScalingPoliciesAndActions; <add> } <add> <add> public Integer getSequence() { <add> return sequence; <add> } <add> <add> public void setSequence(Integer sequence) { <add> this.sequence = sequence; <add> } <add> <add> public DisruptionBudget getDisruptionBudget() { <add> return disruptionBudget; <add> } <add> <add> public void setDisruptionBudget(DisruptionBudget disruptionBudget) { <add> this.disruptionBudget = disruptionBudget; <add> } <add> <add> public SubmitJobRequest.Constraints getConstraints() { <add> return constraints; <add> } <add> <add> public void setConstraints(SubmitJobRequest.Constraints constraints) { <add> this.constraints = constraints; <add> } <add> <add> public ServiceJobProcesses getServiceJobProcesses() { <add> return serviceJobProcesses; <add> } <add> <add> public void setServiceJobProcesses(ServiceJobProcesses serviceJobProcesses) { <add> this.serviceJobProcesses = serviceJobProcesses; <add> } <add> <add> public boolean isUseApplicationDefaultSecurityGroup() { <add> return useApplicationDefaultSecurityGroup; <add> } <add> <add> public void setUseApplicationDefaultSecurityGroup(boolean useApplicationDefaultSecurityGroup) { <add> this.useApplicationDefaultSecurityGroup = useApplicationDefaultSecurityGroup; <add> } <add> <add> public boolean isCopySourceScalingPolicies() { <add> return copySourceScalingPolicies; <add> } <add> <add> public void setCopySourceScalingPolicies(boolean copySourceScalingPolicies) { <add> this.copySourceScalingPolicies = copySourceScalingPolicies; <add> } <add> <add> @Override <add> public List<OperationEvent> getEvents() { <add> return events; <add> } <add> <add> public void setEvents(List<OperationEvent> events) { <add> this.events = events; <add> } <add> <add> public Source getSource() { <add> return source; <add> } <add> <add> public void setSource(Source source) { <add> this.source = source; <add> } <add> <add> public Efs getEfs() { <add> return efs; <add> } <add> <add> public void setEfs(Efs efs) { <add> this.efs = efs; <add> } <ide> }
Java
apache-2.0
c224728d796d9b1180e8fb700b45836abb53848d
0
thomasdarimont/spring-security,Peter32/spring-security,justinedelson/spring-security,MatthiasWinzeler/spring-security,jgrandja/spring-security,dsyer/spring-security,mrkingybc/spring-security,xingguang2013/spring-security,jmnarloch/spring-security,olezhuravlev/spring-security,spring-projects/spring-security,driftman/spring-security,mparaz/spring-security,zhaoqin102/spring-security,chinazhaoht/spring-security,jmnarloch/spring-security,cyratech/spring-security,wkorando/spring-security,liuguohua/spring-security,olezhuravlev/spring-security,diegofernandes/spring-security,hippostar/spring-security,raindev/spring-security,jgrandja/spring-security,kazuki43zoo/spring-security,SanjayUser/SpringSecurityPro,mdeinum/spring-security,SanjayUser/SpringSecurityPro,adairtaosy/spring-security,mdeinum/spring-security,rwinch/spring-security,raindev/spring-security,jgrandja/spring-security,kazuki43zoo/spring-security,cyratech/spring-security,zshift/spring-security,justinedelson/spring-security,yinhe402/spring-security,thomasdarimont/spring-security,wkorando/spring-security,djechelon/spring-security,follow99/spring-security,diegofernandes/spring-security,adairtaosy/spring-security,eddumelendez/spring-security,wkorando/spring-security,tekul/spring-security,dsyer/spring-security,ollie314/spring-security,mounb/spring-security,follow99/spring-security,izeye/spring-security,caiwenshu/spring-security,dsyer/spring-security,driftman/spring-security,xingguang2013/spring-security,zshift/spring-security,fhanik/spring-security,cyratech/spring-security,izeye/spring-security,Krasnyanskiy/spring-security,wkorando/spring-security,justinedelson/spring-security,likaiwalkman/spring-security,SanjayUser/SpringSecurityPro,ractive/spring-security,olezhuravlev/spring-security,xingguang2013/spring-security,vitorgv/spring-security,yinhe402/spring-security,ajdinhedzic/spring-security,thomasdarimont/spring-security,follow99/spring-security,zhaoqin102/spring-security,caiwenshu/spring-security,izeye/spring-security,mdeinum/spring-security,Krasnyanskiy/spring-security,jgrandja/spring-security,zshift/spring-security,eddumelendez/spring-security,rwinch/spring-security,Peter32/spring-security,rwinch/spring-security,rwinch/spring-security,spring-projects/spring-security,liuguohua/spring-security,pwheel/spring-security,liuguohua/spring-security,tekul/spring-security,jmnarloch/spring-security,vitorgv/spring-security,olezhuravlev/spring-security,dsyer/spring-security,caiwenshu/spring-security,Xcorpio/spring-security,mounb/spring-security,pkdevbox/spring-security,ractive/spring-security,fhanik/spring-security,rwinch/spring-security,forestqqqq/spring-security,eddumelendez/spring-security,mrkingybc/spring-security,Peter32/spring-security,SanjayUser/SpringSecurityPro,spring-projects/spring-security,wilkinsona/spring-security,Peter32/spring-security,vitorgv/spring-security,forestqqqq/spring-security,dsyer/spring-security,Krasnyanskiy/spring-security,wilkinsona/spring-security,pkdevbox/spring-security,follow99/spring-security,pwheel/spring-security,zgscwjm/spring-security,ractive/spring-security,pkdevbox/spring-security,eddumelendez/spring-security,thomasdarimont/spring-security,likaiwalkman/spring-security,cyratech/spring-security,kazuki43zoo/spring-security,kazuki43zoo/spring-security,wilkinsona/spring-security,likaiwalkman/spring-security,mparaz/spring-security,zgscwjm/spring-security,izeye/spring-security,pwheel/spring-security,chinazhaoht/spring-security,hippostar/spring-security,vitorgv/spring-security,chinazhaoht/spring-security,pwheel/spring-security,mrkingybc/spring-security,fhanik/spring-security,panchenko/spring-security,mounb/spring-security,raindev/spring-security,ajdinhedzic/spring-security,ajdinhedzic/spring-security,olezhuravlev/spring-security,driftman/spring-security,SanjayUser/SpringSecurityPro,yinhe402/spring-security,pkdevbox/spring-security,panchenko/spring-security,forestqqqq/spring-security,mparaz/spring-security,driftman/spring-security,zshift/spring-security,ajdinhedzic/spring-security,fhanik/spring-security,djechelon/spring-security,panchenko/spring-security,Krasnyanskiy/spring-security,adairtaosy/spring-security,xingguang2013/spring-security,zhaoqin102/spring-security,rwinch/spring-security,spring-projects/spring-security,zgscwjm/spring-security,raindev/spring-security,jmnarloch/spring-security,diegofernandes/spring-security,Xcorpio/spring-security,hippostar/spring-security,justinedelson/spring-security,diegofernandes/spring-security,chinazhaoht/spring-security,ollie314/spring-security,fhanik/spring-security,caiwenshu/spring-security,mdeinum/spring-security,tekul/spring-security,mparaz/spring-security,kazuki43zoo/spring-security,pwheel/spring-security,panchenko/spring-security,mounb/spring-security,spring-projects/spring-security,ractive/spring-security,Xcorpio/spring-security,djechelon/spring-security,likaiwalkman/spring-security,spring-projects/spring-security,Xcorpio/spring-security,djechelon/spring-security,djechelon/spring-security,ollie314/spring-security,adairtaosy/spring-security,MatthiasWinzeler/spring-security,mrkingybc/spring-security,spring-projects/spring-security,MatthiasWinzeler/spring-security,thomasdarimont/spring-security,liuguohua/spring-security,zhaoqin102/spring-security,jgrandja/spring-security,tekul/spring-security,eddumelendez/spring-security,jgrandja/spring-security,fhanik/spring-security,ollie314/spring-security,yinhe402/spring-security,wilkinsona/spring-security,forestqqqq/spring-security,zgscwjm/spring-security,MatthiasWinzeler/spring-security,hippostar/spring-security
/* Copyright 2004 Acegi Technology Pty Limited * * 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 net.sf.acegisecurity.adapters.resin; import com.caucho.http.security.AbstractAuthenticator; import net.sf.acegisecurity.Authentication; import net.sf.acegisecurity.AuthenticationException; import net.sf.acegisecurity.AuthenticationManager; import net.sf.acegisecurity.adapters.PrincipalAcegiUserToken; import net.sf.acegisecurity.providers.UsernamePasswordAuthenticationToken; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.context.support.ClassPathXmlApplicationContext; import java.security.Principal; import java.util.Map; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Adapter to enable Resin to authenticate via the Acegi Security System for * Spring. * * <p> * Returns a {@link PrincipalAcegiUserToken} to Resin's authentication system, * which is subsequently available via * <code>HttpServletRequest.getUserPrincipal()</code>. * </p> * * @author Ben Alex * @version $Id$ */ public class ResinAcegiAuthenticator extends AbstractAuthenticator { //~ Static fields/initializers ============================================= private static final Log logger = LogFactory.getLog(ResinAcegiAuthenticator.class); //~ Instance fields ======================================================== private AuthenticationManager authenticationManager; private String appContextLocation; private String key; //~ Methods ================================================================ public void setAppContextLocation(String appContextLocation) { this.appContextLocation = appContextLocation; } public String getAppContextLocation() { return appContextLocation; } public void setKey(String key) { this.key = key; } public String getKey() { return key; } public boolean isUserInRole(HttpServletRequest request, HttpServletResponse response, ServletContext application, Principal principal, String role) { if (!(principal instanceof PrincipalAcegiUserToken)) { if (logger.isWarnEnabled()) { logger.warn( "Expected passed principal to be of type PrincipalAcegiUserToken"); } return false; } PrincipalAcegiUserToken test = (PrincipalAcegiUserToken) principal; return test.isUserInRole(role); } public void init() throws ServletException { super.init(); if ((appContextLocation == null) || "".equals(appContextLocation)) { throw new ServletException("appContextLocation must be defined"); } if ((key == null) || "".equals(key)) { throw new ServletException("key must be defined"); } if (Thread.currentThread().getContextClassLoader().getResource(appContextLocation) == null) { throw new ServletException("Cannot locate " + appContextLocation); } ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(appContextLocation); Map beans = ctx.getBeansOfType(AuthenticationManager.class, true, true); if (beans.size() == 0) { throw new ServletException( "Bean context must contain at least one bean of type AuthenticationManager"); } String beanName = (String) beans.keySet().iterator().next(); authenticationManager = (AuthenticationManager) beans.get(beanName); logger.info("ResinAcegiAuthenticator Started"); } protected Principal loginImpl(String username, String credentials) { if (username == null) { return null; } if (credentials == null) { credentials = ""; } Authentication request = new UsernamePasswordAuthenticationToken(username, credentials); Authentication response = null; try { response = authenticationManager.authenticate(request); } catch (AuthenticationException failed) { if (logger.isDebugEnabled()) { logger.debug("Authentication request for user: " + username + " failed: " + failed.toString()); } return null; } return new PrincipalAcegiUserToken(this.key, response.getPrincipal().toString(), response.getCredentials().toString(), response.getAuthorities()); } protected Principal loginImpl(HttpServletRequest request, HttpServletResponse response, ServletContext application, String userName, String password) throws ServletException { return loginImpl(userName, password); } }
adapters/resin/src/main/java/org/acegisecurity/adapters/resin/ResinAcegiAuthenticator.java
/* Copyright 2004 Acegi Technology Pty Limited * * 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 net.sf.acegisecurity.adapters.resin; import com.caucho.http.security.AbstractAuthenticator; import com.caucho.vfs.Path; import net.sf.acegisecurity.Authentication; import net.sf.acegisecurity.AuthenticationException; import net.sf.acegisecurity.AuthenticationManager; import net.sf.acegisecurity.adapters.PrincipalAcegiUserToken; import net.sf.acegisecurity.providers.UsernamePasswordAuthenticationToken; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.context.support.FileSystemXmlApplicationContext; import java.io.File; import java.security.Principal; import java.util.Map; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Adapter to enable Resin to authenticate via the Acegi Security System for * Spring. * * <p> * Returns a {@link PrincipalAcegiUserToken} to Resin's authentication system, * which is subsequently available via * <code>HttpServletRequest.getUserPrincipal()</code>. * </p> * * @author Ben Alex * @version $Id$ */ public class ResinAcegiAuthenticator extends AbstractAuthenticator { //~ Static fields/initializers ============================================= private static final Log logger = LogFactory.getLog(ResinAcegiAuthenticator.class); //~ Instance fields ======================================================== private AuthenticationManager authenticationManager; private Path appContextLocation; private String key; //~ Methods ================================================================ public void setAppContextLocation(Path appContextLocation) { this.appContextLocation = appContextLocation; } public Path getAppContextLocation() { return appContextLocation; } public void setKey(String key) { this.key = key; } public String getKey() { return key; } public boolean isUserInRole(HttpServletRequest request, HttpServletResponse response, ServletContext application, Principal principal, String role) { if (!(principal instanceof PrincipalAcegiUserToken)) { if (logger.isWarnEnabled()) { logger.warn( "Expected passed principal to be of type PrincipalSpringUserToken but was " + principal.getClass().getName()); } return false; } PrincipalAcegiUserToken test = (PrincipalAcegiUserToken) principal; return test.isUserInRole(role); } public void init() throws ServletException { super.init(); if (appContextLocation == null) { throw new ServletException("appContextLocation must be defined"); } if (key == null) { throw new ServletException("key must be defined"); } File xml = new File(appContextLocation.getPath()); if (!xml.exists()) { throw new ServletException( "appContextLocation does not seem to exist - try specifying WEB-INF/resin-springsecurity.xml"); } FileSystemXmlApplicationContext ctx = new FileSystemXmlApplicationContext(xml .getAbsolutePath()); Map beans = ctx.getBeansOfType(AuthenticationManager.class, true, true); if (beans.size() == 0) { throw new ServletException( "Bean context must contain at least one bean of type AuthenticationManager"); } String beanName = (String) beans.keySet().iterator().next(); authenticationManager = (AuthenticationManager) beans.get(beanName); logger.info("ResinSpringAuthenticator Started"); } protected Principal loginImpl(String username, String credentials) { if (username == null) { return null; } if (credentials == null) { credentials = ""; } Authentication request = new UsernamePasswordAuthenticationToken(username, credentials); Authentication response = null; try { response = authenticationManager.authenticate(request); } catch (AuthenticationException failed) { if (logger.isDebugEnabled()) { logger.debug("Authentication request for user: " + username + " failed: " + failed.toString()); } return null; } return new PrincipalAcegiUserToken(this.key, response.getPrincipal().toString(), response.getCredentials().toString(), response.getAuthorities()); } protected Principal loginImpl(HttpServletRequest request, HttpServletResponse response, ServletContext application, String userName, String password) throws ServletException { return loginImpl(userName, password); } }
Changed appContextLocation to use a String (to enable unit testing), fixed logger outputs, improved handling of nulls and empty Strings.
adapters/resin/src/main/java/org/acegisecurity/adapters/resin/ResinAcegiAuthenticator.java
Changed appContextLocation to use a String (to enable unit testing), fixed logger outputs, improved handling of nulls and empty Strings.
<ide><path>dapters/resin/src/main/java/org/acegisecurity/adapters/resin/ResinAcegiAuthenticator.java <ide> <ide> import com.caucho.http.security.AbstractAuthenticator; <ide> <del>import com.caucho.vfs.Path; <del> <ide> import net.sf.acegisecurity.Authentication; <ide> import net.sf.acegisecurity.AuthenticationException; <ide> import net.sf.acegisecurity.AuthenticationManager; <ide> import org.apache.commons.logging.Log; <ide> import org.apache.commons.logging.LogFactory; <ide> <del>import org.springframework.context.support.FileSystemXmlApplicationContext; <del> <del>import java.io.File; <add>import org.springframework.context.support.ClassPathXmlApplicationContext; <ide> <ide> import java.security.Principal; <ide> <ide> //~ Instance fields ======================================================== <ide> <ide> private AuthenticationManager authenticationManager; <del> private Path appContextLocation; <add> private String appContextLocation; <ide> private String key; <ide> <ide> //~ Methods ================================================================ <ide> <del> public void setAppContextLocation(Path appContextLocation) { <add> public void setAppContextLocation(String appContextLocation) { <ide> this.appContextLocation = appContextLocation; <ide> } <ide> <del> public Path getAppContextLocation() { <add> public String getAppContextLocation() { <ide> return appContextLocation; <ide> } <ide> <ide> if (!(principal instanceof PrincipalAcegiUserToken)) { <ide> if (logger.isWarnEnabled()) { <ide> logger.warn( <del> "Expected passed principal to be of type PrincipalSpringUserToken but was " <del> + principal.getClass().getName()); <add> "Expected passed principal to be of type PrincipalAcegiUserToken"); <ide> } <ide> <ide> return false; <ide> public void init() throws ServletException { <ide> super.init(); <ide> <del> if (appContextLocation == null) { <add> if ((appContextLocation == null) || "".equals(appContextLocation)) { <ide> throw new ServletException("appContextLocation must be defined"); <ide> } <ide> <del> if (key == null) { <add> if ((key == null) || "".equals(key)) { <ide> throw new ServletException("key must be defined"); <ide> } <ide> <del> File xml = new File(appContextLocation.getPath()); <del> <del> if (!xml.exists()) { <del> throw new ServletException( <del> "appContextLocation does not seem to exist - try specifying WEB-INF/resin-springsecurity.xml"); <add> if (Thread.currentThread().getContextClassLoader().getResource(appContextLocation) == null) { <add> throw new ServletException("Cannot locate " + appContextLocation); <ide> } <ide> <del> FileSystemXmlApplicationContext ctx = new FileSystemXmlApplicationContext(xml <del> .getAbsolutePath()); <add> ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(appContextLocation); <ide> Map beans = ctx.getBeansOfType(AuthenticationManager.class, true, true); <ide> <ide> if (beans.size() == 0) { <ide> <ide> String beanName = (String) beans.keySet().iterator().next(); <ide> authenticationManager = (AuthenticationManager) beans.get(beanName); <del> logger.info("ResinSpringAuthenticator Started"); <add> logger.info("ResinAcegiAuthenticator Started"); <ide> } <ide> <ide> protected Principal loginImpl(String username, String credentials) {
Java
mit
914b81e05210d7a65bf908862ceffca93f3f215b
0
debugchannel/debugchannel-java-client
package channeldebug; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStreamReader; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.*; public class ChannelDebug { private final String USER_AGENT = "Mozilla/5.0"; private URL url; private final static String SCALAR_KEY = "scalar"; public ChannelDebug(String host, int port, String channel) { try { url = new URL(String.format("%s:%s/%s", host, port, channel)); } catch(MalformedURLException e) { throw new RuntimeException(e); } } public void log(Object object) { try { sendPost(object); }catch (Exception e) { throw new RuntimeException(e); } } // HTTP POST request private void sendPost(Object object) throws Exception { HttpURLConnection con = (HttpURLConnection) url.openConnection(); //add reuqest header con.setRequestMethod("POST"); con.setRequestProperty("User-Agent", USER_AGENT); con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); con.setRequestProperty("Accept", "application/json"); con.setRequestProperty("Content-Type", "application/json"); Gson gson = new GsonBuilder().serializeNulls().create(); //String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345"; Object normalisedObject = wrap(normalise(object)); System.out.println(normalisedObject); String urlParameters = gson.toJson(normalisedObject); // Send post request con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); System.out.println(String.format(gson.toJson(normalisedObject))); wr.writeBytes(urlParameters); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); System.out.println("\nSending 'POST' request to URL : " + url); System.out.println("Post parameters : " + urlParameters); System.out.println("Response Code : " + responseCode); BufferedReader in = new BufferedReader( new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); //print result System.out.println(response.toString()); } private Object normalise(Object object) { if(null == object) { return null; } if(isPrimitive(object)) { Map<String, Object> map = new HashMap<String, Object>(); map.put(SCALAR_KEY, object); return map; } try { Map<String, Object> map = new HashMap<String, Object>(); Map<String, Object> properties = new HashMap<String, Object>(); Map<String, Object> statics = new HashMap<String, Object>(); Map<String, Object> constants = new HashMap<String, Object>(); for(Field field : object.getClass().getDeclaredFields()) { field.setAccessible(true); int modifiers = field.getModifiers(); Object fieldValue = field.get(object); Map<String, Object> fieldMap; if(Modifier.isFinal(modifiers)) { fieldMap = constants; } else if(Modifier.isStatic(modifiers)) { fieldMap = statics; } else { fieldMap = properties; } if(fieldValue == null) { fieldMap.put(field.getName(), null); } else if(isPrimitive(field.get(object))) { fieldMap.put(field.getName(), field.get(object)); } else { fieldMap.put(field.getName(), normalise(field.get(object))); } } map.put("class", getClassChain(object.getClass())); map.put("properties", properties); map.put("static", statics); map.put("constants", constants); map.put("methods", getMethods(object.getClass())); return map; }catch(Exception e) { throw new RuntimeException(e); } } private Object wrap(Object object) { Map<String, Object> wrapper = new HashMap<String, Object>(); List<Object> args = new LinkedList<Object>(); args.add(object); wrapper.put("handler", "object"); wrapper.put("args", args); wrapper.put("stacktrace", new LinkedList<Object>()); return wrapper; } private Object getClassChain(Class<?> clazz) { List<String> superClasses = new LinkedList<String>(); do { superClasses.add(clazz.getName()); clazz = clazz.getSuperclass(); } while(clazz != null && !clazz.equals(Object.class)); superClasses.add(Object.class.getName()); return superClasses; } private Object getMethods(Class<?> clazz) { Map<String, List<String>> methodArguments = new HashMap<String, List<String>>(); for(Method method : clazz.getDeclaredMethods()) { List<String> parameters = new LinkedList<String>(); for(Class<?> parameterType : method.getParameterTypes()) { parameters.add(parameterType.getName()); } methodArguments.put(method.getName(), parameters); } return methodArguments; } private boolean isPrimitive(Object o) { return isWrapperType(o.getClass()); } private static boolean isWrapperType(Class<?> clazz) { return getWrapperTypes().contains(clazz); } private static Set<Class<?>> getWrapperTypes() { Set<Class<?>> ret = new HashSet<Class<?>>(); ret.add(Boolean.class); ret.add(Character.class); ret.add(Byte.class); ret.add(Short.class); ret.add(Integer.class); ret.add(Long.class); ret.add(Float.class); ret.add(Double.class); ret.add(Void.class); ret.add(String.class); return ret; } }
src/channeldebug/ChannelDebug.java
package channeldebug; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStreamReader; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.*; public class ChannelDebug { private final String USER_AGENT = "Mozilla/5.0"; private URL url; private final static String SCALAR_KEY = "scalar"; public ChannelDebug(String host, int port, String channel) { try { url = new URL(String.format("%s:%s/%s", host, port, channel)); } catch(MalformedURLException e) { throw new RuntimeException(e); } } public void log(Object object) { try { sendPost(object); }catch (Exception e) { throw new RuntimeException(e); } } // HTTP POST request private void sendPost(Object object) throws Exception { HttpURLConnection con = (HttpURLConnection) url.openConnection(); //add reuqest header con.setRequestMethod("POST"); con.setRequestProperty("User-Agent", USER_AGENT); con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); con.setRequestProperty("Accept", "application/json"); con.setRequestProperty("Content-Type", "application/json"); Gson gson = new GsonBuilder().serializeNulls().create(); //String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345"; Object normalisedObject = wrap(normalise(object)); System.out.println(normalisedObject); String urlParameters = gson.toJson(normalisedObject); // Send post request con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); System.out.println(String.format(gson.toJson(normalisedObject))); wr.writeBytes(urlParameters); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); System.out.println("\nSending 'POST' request to URL : " + url); System.out.println("Post parameters : " + urlParameters); System.out.println("Response Code : " + responseCode); BufferedReader in = new BufferedReader( new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); //print result System.out.println(response.toString()); } private Object normalise(Object object) { if(isPrimitive(object)) { Map<String, Object> map = new HashMap<String, Object>(); map.put(SCALAR_KEY, object); return map; } try { Map<String, Object> map = new HashMap<String, Object>(); Map<String, Object> properties = new HashMap<String, Object>(); Map<String, Object> statics = new HashMap<String, Object>(); Map<String, Object> constants = new HashMap<String, Object>(); for(Field field : object.getClass().getDeclaredFields()) { field.setAccessible(true); int modifiers = field.getModifiers(); Object fieldValue = field.get(object); Map<String, Object> fieldMap; if(Modifier.isFinal(modifiers)) { fieldMap = constants; } else if(Modifier.isStatic(modifiers)) { fieldMap = statics; } else { fieldMap = properties; } if(fieldValue == null) { fieldMap.put(field.getName(), null); } else if(isPrimitive(field.get(object))) { fieldMap.put(field.getName(), field.get(object)); } else { fieldMap.put(field.getName(), normalise(field.get(object))); } } map.put("class", getClassChain(object.getClass())); map.put("properties", properties); map.put("static", statics); map.put("constants", constants); map.put("methods", getMethods(object.getClass())); return map; }catch(Exception e) { throw new RuntimeException(e); } } private Object wrap(Object object) { Map<String, Object> wrapper = new HashMap<String, Object>(); List<Object> args = new LinkedList<Object>(); args.add(object); wrapper.put("handler", "object"); wrapper.put("args", args); wrapper.put("stacktrace", new LinkedList<Object>()); return wrapper; } private Object getClassChain(Class<?> clazz) { List<String> superClasses = new LinkedList<String>(); do { superClasses.add(clazz.getName()); clazz = clazz.getSuperclass(); } while(!clazz.equals(Object.class)); superClasses.add(Object.class.getName()); return superClasses; } private Object getMethods(Class<?> clazz) { Map<String, List<String>> methodArguments = new HashMap<String, List<String>>(); for(Method method : clazz.getDeclaredMethods()) { List<String> parameters = new LinkedList<String>(); for(Class<?> parameterType : method.getParameterTypes()) { parameters.add(parameterType.getName()); } methodArguments.put(method.getName(), parameters); } return methodArguments; } private boolean isPrimitive(Object o) { return isWrapperType(o.getClass()); } private static boolean isWrapperType(Class<?> clazz) { return getWrapperTypes().contains(clazz); } private static Set<Class<?>> getWrapperTypes() { Set<Class<?>> ret = new HashSet<Class<?>>(); ret.add(Boolean.class); ret.add(Character.class); ret.add(Byte.class); ret.add(Short.class); ret.add(Integer.class); ret.add(Long.class); ret.add(Float.class); ret.add(Double.class); ret.add(Void.class); ret.add(String.class); return ret; } }
fixed bug
src/channeldebug/ChannelDebug.java
fixed bug
<ide><path>rc/channeldebug/ChannelDebug.java <ide> <ide> private Object normalise(Object object) <ide> { <add> if(null == object) { <add> return null; <add> } <add> <ide> if(isPrimitive(object)) { <ide> Map<String, Object> map = new HashMap<String, Object>(); <ide> map.put(SCALAR_KEY, object); <ide> do { <ide> superClasses.add(clazz.getName()); <ide> clazz = clazz.getSuperclass(); <del> } while(!clazz.equals(Object.class)); <add> } while(clazz != null && !clazz.equals(Object.class)); <ide> superClasses.add(Object.class.getName()); <ide> return superClasses; <ide> }
JavaScript
apache-2.0
9533b7fac304a6fd616034e72510aa45411ef809
0
Gawdl3y/discord.js-commando,Gawdl3y/discord.js-commando,Gawdl3y/discord.js-commando
const SettingProvider = require('./base'); /** * Uses an SQLite database to store settings with guilds * @extends {SettingProvider} */ class SQLiteProvider extends SettingProvider { /** * @external SQLiteDatabase * @see {@link https://www.npmjs.com/package/sqlite} */ /** * @param {SQLiteDatabase} db Database for the provider */ constructor(db) { super(); /** * Database that will be used for storing/retrieving settings * @type {SQLiteDatabase} */ this.db = db; /** * Client that the provider is for (set once the client is ready, after using {@link Client#setProvider}) * @type {?CommandoClient} */ this.client = null; /** * Settings cached in memory, mapped by guild ID (or 'global') * @type {Map} * @private */ this.settings = new Map(); /** * Prepared statement to insert or replace a settings row * @type {SQLiteStatement} * @private */ this.insertOrReplaceStmt = null; /** * Prepared statement to delete an entire settings row * @type {SQLiteStatement} * @private */ this.deleteStmt = null; /** * @external SQLiteStatement * @see {@link https://www.npmjs.com/package/sqlite} */ } async init(client) { this.client = client; await this.db.run('CREATE TABLE IF NOT EXISTS settings (guild INTEGER PRIMARY KEY, settings TEXT)'); // Load all settings const rows = await this.db.all('SELECT CAST(guild as TEXT) as guild, settings FROM settings'); for(const row of rows) { const settings = JSON.parse(row.settings); this.settings.set(row.guild || 'global', settings); if(row.guild !== 'global' && !client.guilds.has(row.guild)) continue; this.setupGuild(row.guild || 'global', settings); } // Prepare statements const statements = await Promise.all([ this.db.prepare('INSERT OR REPLACE INTO settings VALUES(?, ?)'), this.db.prepare('DELETE FROM settings WHERE guild = ?') ]); this.insertOrReplaceStmt = statements[0]; this.deleteStmt = statements[1]; // Listen for changes client .on('commandPrefixChange', (guild, prefix) => this.set(guild, 'prefix', prefix)) .on('commandStatusChange', (guild, command, enabled) => this.set(guild, `cmd-${command.name}`, enabled)) .on('groupStatusChange', (guild, group, enabled) => this.set(guild, `grp-${group.name}`, enabled)) .on('guildCreate', guild => { const settings = this.settings.get(guild.id); if(!settings) return; this.setupGuild(guild.id, settings); }) .on('commandRegistered', command => { for(const [guild, settings] of this.settings) { if(guild !== 'global' && !client.guilds.has(guild)) continue; this.setupGuildCommand(client.guilds.get(guild), command, settings); } }) .on('groupRegistered', group => { for(const [guild, settings] of this.settings) { if(guild !== 'global' && !client.guilds.has(guild)) continue; this.setupGuildGroup(client.guilds.get(guild), group, settings); } }); } async destroy() { // do nothing } get(guild, key, defVal) { const settings = this.settings.get(this.constructor.getGuildID(guild)); return settings ? settings[key] || defVal : defVal; } async set(guild, key, val) { guild = this.constructor.getGuildID(guild); let settings = this.settings.get(guild); if(!settings) { settings = {}; this.settings.set(guild, settings); } settings[key] = val; await this.insertOrReplaceStmt.run(guild !== 'global' ? guild : null, JSON.stringify(settings)); return val; } async remove(guild, key) { guild = this.constructor.getGuildID(guild); const settings = this.settings.get(guild); if(!settings || typeof settings[key] === 'undefined') return undefined; const val = settings[key]; settings[key] = undefined; await this.insertOrReplaceStmt.run(guild !== 'global' ? guild : null, JSON.stringify(settings)); return val; } async clear(guild) { guild = this.constructor.getGuildID(guild); const settings = this.settings.get(guild); if(!settings) return; await this.deleteStmt.run(guild !== 'global' ? guild : null); } /** * Loads all settings for a guild * @param {string} guild Guild ID to load the settings of (or 'global') * @param {Object} settings Settings to load * @private */ setupGuild(guild, settings) { if(typeof guild !== 'string') throw new TypeError('The guild must be a guild ID or "global".'); guild = this.client.guilds.get(guild) || null; // Load the command prefix if(settings.prefix) { if(guild) guild._commandPrefix = settings.prefix; else this.client._commandPrefix = settings.prefix; } // Load all command statuses for(const command of this.client.registry.commands.values()) { this.setupGuildCommand(guild, command, settings); } // Load all group statuses for(const group of this.client.registry.groups.values()) { this.setupGuildGroup(guild, group, settings); } } /** * Sets up a command's status in a guild from the guild's settings * @param {?Guild} guild Guild to set the status in * @param {Command} command Command to set the status of * @param {Object} settings Settings of the guild * @private */ setupGuildCommand(guild, command, settings) { if(typeof settings[`cmd-${command.name}`] === 'undefined') return; if(guild) { if(!guild._commandsEnabled) guild._commandsEnabled = {}; guild._commandsEnabled[command.name] = settings[`cmd-${command.name}`]; } else { command._globalEnabled = settings[`cmd-${command.name}`]; } } /** * Sets up a group's status in a guild from the guild's settings * @param {?Guild} guild Guild to set the status in * @param {CommandGroup} group Group to set the status of * @param {Object} settings Settings of the guild * @private */ setupGuildGroup(guild, group, settings) { if(typeof settings[`grp-${group.name}`] === 'undefined') return; if(guild) { if(!guild._groupsEnabled) guild._groupsEnabled = {}; guild._groupsEnabled[group.name] = settings[`grp-${group.name}`]; } else { group._globalEnabled = settings[`grp-${group.name}`]; } } } module.exports = SQLiteProvider;
src/providers/sqlite.js
const SettingProvider = require('./base'); /** * Uses an SQLite database to store settings with guilds * @extends {SettingProvider} */ class SQLiteProvider extends SettingProvider { /** * @external SQLiteDatabase * @see {@link https://www.npmjs.com/package/sqlite} */ /** * @param {SQLiteDatabase} db Database for the provider */ constructor(db) { super(); /** * Database that will be used for storing/retrieving settings * @type {SQLiteDatabase} */ this.db = db; /** * Client that the provider is for (set once the client is ready, after using {@link Client#setProvider}) * @type {?CommandoClient} */ this.client = null; /** * Settings cached in memory, mapped by guild ID (or 'global') * @type {Map} * @private */ this.settings = new Map(); /** * Prepared statement to insert or replace a settings row * @type {SQLiteStatement} * @private */ this.insertOrReplaceStmt = null; /** * Prepared statement to delete an entire settings row * @type {SQLiteStatement} * @private */ this.deleteStmt = null; /** * @external SQLiteStatement * @see {@link https://www.npmjs.com/package/sqlite} */ } async init(client) { this.client = client; await this.db.run('CREATE TABLE IF NOT EXISTS settings (guild INTEGER PRIMARY KEY, settings TEXT)'); // Load all settings const rows = await this.db.all('SELECT CAST(guild as TEXT) as guild, settings FROM settings'); for(const row of rows) { const settings = JSON.parse(row.settings); this.settings.set(row.guild || 'global', settings); if(row.guild !== 'global' && !client.guilds.has(row.guild)) continue; this.setupGuild(row.guild || 'global', settings); } // Prepare statements const statements = await Promise.all([ this.db.prepare('INSERT OR REPLACE INTO settings VALUES(?, ?)'), this.db.prepare('DELETE FROM settings WHERE guild = ?') ]); this.insertOrReplaceStmt = statements[0]; this.deleteStmt = statements[1]; // Listen for changes client .on('commandPrefixChange', (guild, prefix) => this.set(guild, 'prefix', prefix)) .on('commandStatusChange', (guild, command, enabled) => this.set(guild, `cmd-${command.name}`, enabled)) .on('groupStatusChange', (guild, group, enabled) => this.set(guild, `grp-${group.name}`, enabled)) .on('commandRegistered', command => { for(const [guild, settings] of this.settings) { if(!client.guilds.has(guild)) continue; if(typeof settings[`cmd-${command.name}`] !== 'undefined') { command.setEnabledIn(guild, settings[`cmd-${command.name}`]); } } }) .on('guildCreate', guild => { const settings = this.settings.get(guild.id); if(!settings) return; this.setupGuild(guild.id, settings); }); } async destroy() { // do nothing } get(guild, key, defVal) { const settings = this.settings.get(this.constructor.getGuildID(guild)); return settings ? settings[key] || defVal : defVal; } async set(guild, key, val) { guild = this.constructor.getGuildID(guild); let settings = this.settings.get(guild); if(!settings) { settings = {}; this.settings.set(guild, settings); } settings[key] = val; await this.insertOrReplaceStmt.run(guild !== 'global' ? guild : null, JSON.stringify(settings)); return val; } async remove(guild, key) { guild = this.constructor.getGuildID(guild); const settings = this.settings.get(guild); if(!settings || typeof settings[key] === 'undefined') return undefined; const val = settings[key]; settings[key] = undefined; await this.insertOrReplaceStmt.run(guild !== 'global' ? guild : null, JSON.stringify(settings)); return val; } async clear(guild) { guild = this.constructor.getGuildID(guild); const settings = this.settings.get(guild); if(!settings) return; await this.deleteStmt.run(guild !== 'global' ? guild : null); } /** * Loads all settings for a guild * @param {string} guild Guild ID to load the settings of (or 'global') * @param {Object} settings Settings to load * @private */ setupGuild(guild, settings) { if(typeof guild !== 'string') throw new TypeError('The guild must be a guild ID or "global".'); guild = this.client.guilds.get(guild) || null; // Load the command prefix if(settings.prefix) { if(!guild) this.client.commandPrefix = settings.prefix; else guild.commandPrefix = settings.prefix; } // Load all command statuses for(const command of this.client.registry.commands.values()) { if(typeof settings[`cmd-${command.name}`] !== 'undefined') { command.setEnabledIn(guild, settings[`cmd-${command.name}`]); } } // Load all group statuses for(const group of this.client.registry.groups.values()) { if(typeof settings[`grp-${group.name}`] !== 'undefined') { group.setEnabledIn(guild, settings[`grp-${group.name}`]); } } } } module.exports = SQLiteProvider;
Optimised and cleaned up SQLiteProvider startup loading
src/providers/sqlite.js
Optimised and cleaned up SQLiteProvider startup loading
<ide><path>rc/providers/sqlite.js <ide> .on('commandPrefixChange', (guild, prefix) => this.set(guild, 'prefix', prefix)) <ide> .on('commandStatusChange', (guild, command, enabled) => this.set(guild, `cmd-${command.name}`, enabled)) <ide> .on('groupStatusChange', (guild, group, enabled) => this.set(guild, `grp-${group.name}`, enabled)) <del> .on('commandRegistered', command => { <del> for(const [guild, settings] of this.settings) { <del> if(!client.guilds.has(guild)) continue; <del> if(typeof settings[`cmd-${command.name}`] !== 'undefined') { <del> command.setEnabledIn(guild, settings[`cmd-${command.name}`]); <del> } <del> } <del> }) <ide> .on('guildCreate', guild => { <ide> const settings = this.settings.get(guild.id); <ide> if(!settings) return; <ide> this.setupGuild(guild.id, settings); <add> }) <add> .on('commandRegistered', command => { <add> for(const [guild, settings] of this.settings) { <add> if(guild !== 'global' && !client.guilds.has(guild)) continue; <add> this.setupGuildCommand(client.guilds.get(guild), command, settings); <add> } <add> }) <add> .on('groupRegistered', group => { <add> for(const [guild, settings] of this.settings) { <add> if(guild !== 'global' && !client.guilds.has(guild)) continue; <add> this.setupGuildGroup(client.guilds.get(guild), group, settings); <add> } <ide> }); <ide> } <ide> <ide> <ide> // Load the command prefix <ide> if(settings.prefix) { <del> if(!guild) this.client.commandPrefix = settings.prefix; <del> else guild.commandPrefix = settings.prefix; <add> if(guild) guild._commandPrefix = settings.prefix; <add> else this.client._commandPrefix = settings.prefix; <ide> } <ide> <ide> // Load all command statuses <ide> for(const command of this.client.registry.commands.values()) { <del> if(typeof settings[`cmd-${command.name}`] !== 'undefined') { <del> command.setEnabledIn(guild, settings[`cmd-${command.name}`]); <del> } <add> this.setupGuildCommand(guild, command, settings); <ide> } <ide> <ide> // Load all group statuses <ide> for(const group of this.client.registry.groups.values()) { <del> if(typeof settings[`grp-${group.name}`] !== 'undefined') { <del> group.setEnabledIn(guild, settings[`grp-${group.name}`]); <del> } <add> this.setupGuildGroup(guild, group, settings); <add> } <add> } <add> <add> /** <add> * Sets up a command's status in a guild from the guild's settings <add> * @param {?Guild} guild Guild to set the status in <add> * @param {Command} command Command to set the status of <add> * @param {Object} settings Settings of the guild <add> * @private <add> */ <add> setupGuildCommand(guild, command, settings) { <add> if(typeof settings[`cmd-${command.name}`] === 'undefined') return; <add> if(guild) { <add> if(!guild._commandsEnabled) guild._commandsEnabled = {}; <add> guild._commandsEnabled[command.name] = settings[`cmd-${command.name}`]; <add> } else { <add> command._globalEnabled = settings[`cmd-${command.name}`]; <add> } <add> } <add> <add> /** <add> * Sets up a group's status in a guild from the guild's settings <add> * @param {?Guild} guild Guild to set the status in <add> * @param {CommandGroup} group Group to set the status of <add> * @param {Object} settings Settings of the guild <add> * @private <add> */ <add> setupGuildGroup(guild, group, settings) { <add> if(typeof settings[`grp-${group.name}`] === 'undefined') return; <add> if(guild) { <add> if(!guild._groupsEnabled) guild._groupsEnabled = {}; <add> guild._groupsEnabled[group.name] = settings[`grp-${group.name}`]; <add> } else { <add> group._globalEnabled = settings[`grp-${group.name}`]; <ide> } <ide> } <ide> }
JavaScript
agpl-3.0
8853f0ed5b2988ff1db5c387fb97b5cfd7595aae
0
shakaran/Big-Big-RSS,shakaran/Big-Big-RSS,shakaran/Big-Big-RSS,shakaran/Big-Big-RSS,shakaran/Big-Big-RSS
var global_unread = -1; var _active_feed_id = undefined; var _active_feed_is_cat = false; var hotkey_prefix = false; var hotkey_prefix_pressed = false; var _widescreen_mode = false; var _rpc_seq = 0; function next_seq() { _rpc_seq += 1; return _rpc_seq; } function get_seq() { return _rpc_seq; } function activeFeedIsCat() { return _active_feed_is_cat; } function getActiveFeedId() { try { //console.log("gAFID: " + _active_feed_id); return _active_feed_id; } catch (e) { exception_error("getActiveFeedId", e); } } function setActiveFeedId(id, is_cat) { try { _active_feed_id = id; if (is_cat != undefined) { _active_feed_is_cat = is_cat; } selectFeed(id, is_cat); } catch (e) { exception_error("setActiveFeedId", e); } } function updateFeedList() { try { // $("feeds-holder").innerHTML = "<div id=\"feedlistLoading\">" + // __("Loading, please wait...") + "</div>"; Element.show("feedlistLoading"); if (dijit.byId("feedTree")) { dijit.byId("feedTree").destroyRecursive(); } var store = new dojo.data.ItemFileWriteStore({ url: "backend.php?op=pref_feeds&method=getfeedtree&mode=2"}); var treeModel = new fox.FeedStoreModel({ store: store, query: { "type": getInitParam('enable_feed_cats') == 1 ? "category" : "feed" }, rootId: "root", rootLabel: "Feeds", childrenAttrs: ["items"] }); var tree = new fox.FeedTree({ persist: false, model: treeModel, onOpen: function (item, node) { var id = String(item.id); var cat_id = id.substr(id.indexOf(":")+1); new Ajax.Request("backend.php", { parameters: "backend.php?op=feeds&method=collapse&cid=" + param_escape(cat_id) + "&mode=0" } ); }, onClose: function (item, node) { var id = String(item.id); var cat_id = id.substr(id.indexOf(":")+1); new Ajax.Request("backend.php", { parameters: "backend.php?op=feeds&method=collapse&cid=" + param_escape(cat_id) + "&mode=1" } ); }, onClick: function (item, node) { var id = String(item.id); var is_cat = id.match("^CAT:"); var feed = id.substr(id.indexOf(":")+1); viewfeed(feed, '', is_cat); return false; }, openOnClick: false, showRoot: false, id: "feedTree", }, "feedTree"); /* var menu = new dijit.Menu({id: 'feedMenu'}); menu.addChild(new dijit.MenuItem({ label: "Simple menu item" })); // menu.bindDomNode(tree.domNode); */ var tmph = dojo.connect(dijit.byId('feedMenu'), '_openMyself', function (event) { console.log(dijit.getEnclosingWidget(event.target)); dojo.disconnect(tmph); }); $("feeds-holder").appendChild(tree.domNode); var tmph = dojo.connect(tree, 'onLoad', function() { dojo.disconnect(tmph); Element.hide("feedlistLoading"); tree.collapseHiddenCats(); feedlist_init(); // var node = dijit.byId("feedTree")._itemNodesMap['FEED:-2'][0].domNode // menu.bindDomNode(node); loading_set_progress(25); }); tree.startup(); } catch (e) { exception_error("updateFeedList", e); } } function catchupAllFeeds() { var str = __("Mark all articles as read?"); if (getInitParam("confirm_feed_catchup") != 1 || confirm(str)) { var query_str = "backend.php?op=feeds&method=catchupAll"; notify_progress("Marking all feeds as read..."); //console.log("catchupAllFeeds Q=" + query_str); new Ajax.Request("backend.php", { parameters: query_str, onComplete: function(transport) { feedlist_callback2(transport); } }); global_unread = 0; updateTitle(""); } } function viewCurrentFeed(method) { console.log("viewCurrentFeed"); if (getActiveFeedId() != undefined) { viewfeed(getActiveFeedId(), method, activeFeedIsCat()); } return false; // block unneeded form submits } function timeout() { if (getInitParam("bw_limit") != "1") { request_counters(); setTimeout("timeout()", 60*1000); } } function search() { var query = "backend.php?op=dlg&method=search&param=" + param_escape(getActiveFeedId() + ":" + activeFeedIsCat()); if (dijit.byId("searchDlg")) dijit.byId("searchDlg").destroyRecursive(); dialog = new dijit.Dialog({ id: "searchDlg", title: __("Search"), style: "width: 600px", execute: function() { if (this.validate()) { _search_query = dojo.objectToQuery(this.attr('value')); this.hide(); viewCurrentFeed(); } }, href: query}); dialog.show(); } function updateTitle() { var tmp = "Tiny Tiny RSS"; if (global_unread > 0) { tmp = tmp + " (" + global_unread + ")"; } if (window.fluid) { if (global_unread > 0) { window.fluid.dockBadge = global_unread; } else { window.fluid.dockBadge = ""; } } document.title = tmp; } function genericSanityCheck() { setCookie("ttrss_test", "TEST"); if (getCookie("ttrss_test") != "TEST") { return fatalError(2); } return true; } function init() { try { //dojo.registerModulePath("fox", "../../js/"); dojo.require("fox.FeedTree"); dojo.require("dijit.ColorPalette"); dojo.require("dijit.Dialog"); dojo.require("dijit.form.Button"); dojo.require("dijit.form.CheckBox"); dojo.require("dijit.form.DropDownButton"); dojo.require("dijit.form.FilteringSelect"); dojo.require("dijit.form.Form"); dojo.require("dijit.form.RadioButton"); dojo.require("dijit.form.Select"); dojo.require("dijit.form.SimpleTextarea"); dojo.require("dijit.form.TextBox"); dojo.require("dijit.form.ValidationTextBox"); dojo.require("dijit.InlineEditBox"); dojo.require("dijit.layout.AccordionContainer"); dojo.require("dijit.layout.BorderContainer"); dojo.require("dijit.layout.ContentPane"); dojo.require("dijit.layout.TabContainer"); dojo.require("dijit.Menu"); dojo.require("dijit.ProgressBar"); dojo.require("dijit.ProgressBar"); dojo.require("dijit.Toolbar"); dojo.require("dijit.Tree"); dojo.require("dijit.tree.dndSource"); dojo.require("dojo.data.ItemFileWriteStore"); dojo.parser.parse(); if (!genericSanityCheck()) return false; loading_set_progress(20); var hasAudio = !!((myAudioTag = document.createElement('audio')).canPlayType); new Ajax.Request("backend.php", { parameters: {op: "rpc", method: "sanityCheck", hasAudio: hasAudio}, onComplete: function(transport) { backend_sanity_check_callback(transport); } }); } catch (e) { exception_error("init", e); } } function init_second_stage() { try { dojo.addOnLoad(function() { updateFeedList(); closeArticlePanel(); _widescreen_mode = getInitParam("widescreen"); if (_widescreen_mode) { switchPanelMode(_widescreen_mode); } }); delCookie("ttrss_test"); var toolbar = document.forms["main_toolbar_form"]; dijit.getEnclosingWidget(toolbar.view_mode).attr('value', getInitParam("default_view_mode")); dijit.getEnclosingWidget(toolbar.order_by).attr('value', getInitParam("default_view_order_by")); feeds_sort_by_unread = getInitParam("feeds_sort_by_unread") == 1; loading_set_progress(30); // can't use cache_clear() here because viewfeed might not have initialized yet if ('sessionStorage' in window && window['sessionStorage'] !== null) sessionStorage.clear(); var hotkeys = getInitParam("hotkeys"); var tmp = []; for (sequence in hotkeys[1]) { filtered = sequence.replace(/\|.*$/, ""); tmp[filtered] = hotkeys[1][sequence]; } hotkeys[1] = tmp; setInitParam("hotkeys", hotkeys); console.log("second stage ok"); if (getInitParam("simple_update")) { console.log("scheduling simple feed updater..."); window.setTimeout("update_random_feed()", 30*1000); } } catch (e) { exception_error("init_second_stage", e); } } function quickMenuGo(opid) { try { switch (opid) { case "qmcPrefs": gotoPreferences(); break; case "qmcLogout": gotoLogout(); break; case "qmcTagCloud": displayDlg("printTagCloud"); break; case "qmcTagSelect": displayDlg("printTagSelect"); break; case "qmcSearch": search(); break; case "qmcAddFeed": quickAddFeed(); break; case "qmcDigest": window.location.href = "backend.php?op=digest"; break; case "qmcEditFeed": if (activeFeedIsCat()) alert(__("You can't edit this kind of feed.")); else editFeed(getActiveFeedId()); break; case "qmcRemoveFeed": var actid = getActiveFeedId(); if (activeFeedIsCat()) { alert(__("You can't unsubscribe from the category.")); return; } if (!actid) { alert(__("Please select some feed first.")); return; } var fn = getFeedName(actid); var pr = __("Unsubscribe from %s?").replace("%s", fn); if (confirm(pr)) { unsubscribeFeed(actid); } break; case "qmcCatchupAll": catchupAllFeeds(); break; case "qmcShowOnlyUnread": toggleDispRead(); break; case "qmcAddFilter": quickAddFilter(); break; case "qmcAddLabel": addLabel(); break; case "qmcRescoreFeed": rescoreCurrentFeed(); break; case "qmcToggleWidescreen": if (!isCdmMode()) { _widescreen_mode = !_widescreen_mode; switchPanelMode(_widescreen_mode); } break; case "qmcHKhelp": helpDialog("main"); break; default: console.log("quickMenuGo: unknown action: " + opid); } } catch (e) { exception_error("quickMenuGo", e); } } function toggleDispRead() { try { var hide = !(getInitParam("hide_read_feeds") == "1"); hideOrShowFeeds(hide); var query = "?op=rpc&method=setpref&key=HIDE_READ_FEEDS&value=" + param_escape(hide); setInitParam("hide_read_feeds", hide); new Ajax.Request("backend.php", { parameters: query, onComplete: function(transport) { } }); } catch (e) { exception_error("toggleDispRead", e); } } function parse_runtime_info(data) { //console.log("parsing runtime info..."); for (k in data) { var v = data[k]; // console.log("RI: " + k + " => " + v); if (k == "new_version_available") { if (v == "1") { Element.show(dijit.byId("newVersionIcon").domNode); } else { Element.hide(dijit.byId("newVersionIcon").domNode); } return; } if (k == "daemon_is_running" && v != 1) { notify_error("<span onclick=\"javascript:explainError(1)\">Update daemon is not running.</span>", true); return; } if (k == "daemon_stamp_ok" && v != 1) { notify_error("<span onclick=\"javascript:explainError(3)\">Update daemon is not updating feeds.</span>", true); return; } if (k == "max_feed_id" || k == "num_feeds") { if (init_params[k] != v) { console.log("feed count changed, need to reload feedlist."); updateFeedList(); } } init_params[k] = v; notify(''); } } function collapse_feedlist() { try { if (!Element.visible('feeds-holder')) { Element.show('feeds-holder'); Element.show('feeds-holder_splitter'); $("collapse_feeds_btn").innerHTML = "&lt;&lt;"; } else { Element.hide('feeds-holder'); Element.hide('feeds-holder_splitter'); $("collapse_feeds_btn").innerHTML = "&gt;&gt;"; } dijit.byId("main").resize(); query = "?op=rpc&method=setpref&key=_COLLAPSED_FEEDLIST&value=true"; new Ajax.Request("backend.php", { parameters: query }); } catch (e) { exception_error("collapse_feedlist", e); } } function viewModeChanged() { cache_clear(); return viewCurrentFeed(''); } function viewLimitChanged() { return viewCurrentFeed(''); } function rescoreCurrentFeed() { var actid = getActiveFeedId(); if (activeFeedIsCat() || actid < 0) { alert(__("You can't rescore this kind of feed.")); return; } if (!actid) { alert(__("Please select some feed first.")); return; } var fn = getFeedName(actid); var pr = __("Rescore articles in %s?").replace("%s", fn); if (confirm(pr)) { notify_progress("Rescoring articles..."); var query = "?op=pref-feeds&method=rescore&quiet=1&ids=" + actid; new Ajax.Request("backend.php", { parameters: query, onComplete: function(transport) { viewCurrentFeed(); } }); } } function hotkey_handler(e) { try { if (e.target.nodeName == "INPUT" || e.target.nodeName == "TEXTAREA") return; var keycode = false; var shift_key = false; var cmdline = $('cmdline'); shift_key = e.shiftKey; ctrl_key = e.ctrlKey; if (window.event) { keycode = window.event.keyCode; } else if (e) { keycode = e.which; } var keychar = String.fromCharCode(keycode); if (keycode == 27) { // escape hotkey_prefix = false; } if (keycode == 16) return; // ignore lone shift if (keycode == 17) return; // ignore lone ctrl if (!shift_key) keychar = keychar.toLowerCase(); var hotkeys = getInitParam("hotkeys"); if (!hotkey_prefix && hotkeys[0].indexOf(keychar) != -1) { var date = new Date(); var ts = Math.round(date.getTime() / 1000); hotkey_prefix = keychar; hotkey_prefix_pressed = ts; cmdline.innerHTML = keychar; Element.show(cmdline); return true; } Element.hide(cmdline); var hotkey = keychar.search(/[a-zA-Z0-9]/) != -1 ? keychar : "(" + keycode + ")"; if (ctrl_key) hotkey = "^" + hotkey; hotkey = hotkey_prefix ? hotkey_prefix + " " + hotkey : hotkey; hotkey_prefix = false; var hotkey_action = false; var hotkeys = getInitParam("hotkeys"); for (sequence in hotkeys[1]) { if (sequence == hotkey) { hotkey_action = hotkeys[1][sequence]; break; } } switch (hotkey_action) { case "next_feed": var rv = dijit.byId("feedTree").getNextFeed( getActiveFeedId(), activeFeedIsCat()); if (rv) viewfeed(rv[0], '', rv[1]); return false; case "prev_feed": var rv = dijit.byId("feedTree").getPreviousFeed( getActiveFeedId(), activeFeedIsCat()); if (rv) viewfeed(rv[0], '', rv[1]); return false; case "next_article": moveToPost('next'); return false; case "prev_article": moveToPost('prev'); return false; case "search_dialog": search(); return ; case "toggle_mark": selectionToggleMarked(undefined, false, true); return false; case "toggle_publ": selectionTogglePublished(undefined, false, true); return false; case "toggle_unread": selectionToggleUnread(undefined, false, true); return false; case "edit_tags": var id = getActiveArticleId(); if (id) { editArticleTags(id, getActiveFeedId(), isCdmMode()); return; } return false; case "dismiss_selected": dismissSelectedArticles(); return false; case "dismiss_read": return false; case "open_in_new_window": if (getActiveArticleId()) { openArticleInNewWindow(getActiveArticleId()); return; } return false; case "catchup_below": catchupRelativeToArticle(1); return false; case "catchup_above": catchupRelativeToArticle(0); return false; case "article_scroll_down": scrollArticle(50); return false; case "article_scroll_up": scrollArticle(-50); return false; case "close_article": closeArticlePanel(); return false; case "email_article": if (typeof emailArticle != "undefined") { emailArticle(); } else { alert(__("Please enable mail plugin first.")); } return false; case "select_all": selectArticles('all'); return false; case "select_unread": selectArticles('unread'); return false; case "select_marked": selectArticles('marked'); return false; case "select_published": selectArticles('published'); return false; case "select_invert": selectArticles('invert'); return false; case "select_none": selectArticles('none'); return false; case "feed_refresh": if (getActiveFeedId() != undefined) { viewfeed(getActiveFeedId(), '', activeFeedIsCat()); return; } return false; case "feed_unhide_read": toggleDispRead(); return false; case "feed_subscribe": quickAddFeed(); return false; case "feed_debug_update": window.open("backend.php?op=feeds&method=view&feed=" + getActiveFeedId() + "&view_mode=adaptive&order_by=default&update=&m=ForceUpdate&cat=" + activeFeedIsCat() + "&DevForceUpdate=1&debug=1&xdebug=1&csrf_token=" + getInitParam("csrf_token")); return false; case "feed_edit": if (activeFeedIsCat()) alert(__("You can't edit this kind of feed.")); else editFeed(getActiveFeedId()); return false; case "feed_catchup": if (getActiveFeedId() != undefined) { catchupCurrentFeed(); return; } return false; case "feed_reverse": reverseHeadlineOrder(); return false; case "catchup_all": catchupAllFeeds(); return false; case "cat_toggle_collapse": if (activeFeedIsCat()) { dijit.byId("feedTree").collapseCat(getActiveFeedId()); return; } return false; case "goto_all": viewfeed(-4); return false; case "goto_fresh": viewfeed(-3); return false; case "goto_marked": viewfeed(-1); return false; case "goto_published": viewfeed(-2); return false; case "goto_tagcloud": displayDlg("printTagCloud"); return false; case "goto_prefs": gotoPreferences(); return false; case "select_article_cursor": var id = getArticleUnderPointer(); if (id) { var cb = dijit.byId("RCHK-" + id); if (cb) { cb.attr("checked", !cb.attr("checked")); toggleSelectRowById(cb, "RROW-" + id); return false; } } return false; case "create_label": addLabel(); return false; case "create_filter": quickAddFilter(); return false; case "collapse_sidebar": collapse_feedlist(); return false; case "toggle_widescreen": if (!isCdmMode()) { _widescreen_mode = !_widescreen_mode; switchPanelMode(_widescreen_mode); } return false; case "help_dialog": helpDialog("main"); return false; default: console.log("unhandled action: " + hotkey_action + "; hotkey: " + hotkey); } } catch (e) { exception_error("hotkey_handler", e); } } function inPreferences() { return false; } function reverseHeadlineOrder() { try { var query_str = "?op=rpc&method=togglepref&key=REVERSE_HEADLINES"; new Ajax.Request("backend.php", { parameters: query_str, onComplete: function(transport) { viewCurrentFeed(); } }); } catch (e) { exception_error("reverseHeadlineOrder", e); } } function newVersionDlg() { try { var query = "backend.php?op=dlg&method=newVersion"; if (dijit.byId("newVersionDlg")) dijit.byId("newVersionDlg").destroyRecursive(); dialog = new dijit.Dialog({ id: "newVersionDlg", title: __("New version available!"), style: "width: 600px", href: query, }); dialog.show(); } catch (e) { exception_error("newVersionDlg", e); } } function handle_rpc_json(transport, scheduled_call) { try { var reply = JSON.parse(transport.responseText); if (reply) { var error = reply['error']; if (error) { var code = error['code']; var msg = error['msg']; console.warn("[handle_rpc_json] received fatal error " + code + "/" + msg); if (code != 0) { fatalError(code, msg); return false; } } var seq = reply['seq']; if (seq) { if (get_seq() != seq) { console.log("[handle_rpc_json] sequence mismatch: " + seq + " (want: " + get_seq() + ")"); return true; } } var message = reply['message']; if (message) { if (message == "UPDATE_COUNTERS") { console.log("need to refresh counters..."); setInitParam("last_article_id", -1); request_counters(true); } } var counters = reply['counters']; if (counters) parse_counters(counters, scheduled_call); var runtime_info = reply['runtime-info'];; if (runtime_info) parse_runtime_info(runtime_info); hideOrShowFeeds(getInitParam("hide_read_feeds") == 1); Element.hide(dijit.byId("net-alert").domNode); } else { //notify_error("Error communicating with server."); Element.show(dijit.byId("net-alert").domNode); } } catch (e) { Element.show(dijit.byId("net-alert").domNode); //notify_error("Error communicating with server."); console.log(e); //exception_error("handle_rpc_json", e, transport); } return true; } function switchPanelMode(wide) { try { article_id = getActiveArticleId(); if (wide) { dijit.byId("headlines-wrap-inner").attr("design", 'sidebar'); dijit.byId("content-insert").attr("region", "trailing"); dijit.byId("content-insert").domNode.setStyle({width: '50%', height: 'auto', borderLeftWidth: '1px', borderLeftColor: '#c0c0c0', borderTopWidth: '0px' }); $("headlines-toolbar").setStyle({ borderBottomWidth: '0px' }); } else { dijit.byId("content-insert").attr("region", "bottom"); dijit.byId("content-insert").domNode.setStyle({width: 'auto', height: '50%', borderLeftWidth: '0px', borderTopWidth: '1px'}); $("headlines-toolbar").setStyle({ borderBottomWidth: '1px' }); } closeArticlePanel(); if (article_id) view(article_id); new Ajax.Request("backend.php", { parameters: "op=rpc&method=setpanelmode&wide=" + (wide ? 1 : 0), onComplete: function(transport) { console.log(transport.responseText); } }); } catch (e) { exception_error("switchPanelMode", e); } } function update_random_feed() { try { console.log("in update_random_feed"); new Ajax.Request("backend.php", { parameters: "op=rpc&method=updateRandomFeed", onComplete: function(transport) { handle_rpc_json(transport, true); window.setTimeout("update_random_feed()", 30*1000); } }); } catch (e) { exception_error("update_random_feed", e); } }
js/tt-rss.js
var global_unread = -1; var _active_feed_id = undefined; var _active_feed_is_cat = false; var hotkey_prefix = false; var hotkey_prefix_pressed = false; var _widescreen_mode = false; var _rpc_seq = 0; function next_seq() { _rpc_seq += 1; return _rpc_seq; } function get_seq() { return _rpc_seq; } function activeFeedIsCat() { return _active_feed_is_cat; } function getActiveFeedId() { try { //console.log("gAFID: " + _active_feed_id); return _active_feed_id; } catch (e) { exception_error("getActiveFeedId", e); } } function setActiveFeedId(id, is_cat) { try { _active_feed_id = id; if (is_cat != undefined) { _active_feed_is_cat = is_cat; } selectFeed(id, is_cat); } catch (e) { exception_error("setActiveFeedId", e); } } function updateFeedList() { try { // $("feeds-holder").innerHTML = "<div id=\"feedlistLoading\">" + // __("Loading, please wait...") + "</div>"; Element.show("feedlistLoading"); if (dijit.byId("feedTree")) { dijit.byId("feedTree").destroyRecursive(); } var store = new dojo.data.ItemFileWriteStore({ url: "backend.php?op=pref_feeds&method=getfeedtree&mode=2"}); var treeModel = new fox.FeedStoreModel({ store: store, query: { "type": getInitParam('enable_feed_cats') == 1 ? "category" : "feed" }, rootId: "root", rootLabel: "Feeds", childrenAttrs: ["items"] }); var tree = new fox.FeedTree({ persist: false, model: treeModel, onOpen: function (item, node) { var id = String(item.id); var cat_id = id.substr(id.indexOf(":")+1); new Ajax.Request("backend.php", { parameters: "backend.php?op=feeds&method=collapse&cid=" + param_escape(cat_id) + "&mode=0" } ); }, onClose: function (item, node) { var id = String(item.id); var cat_id = id.substr(id.indexOf(":")+1); new Ajax.Request("backend.php", { parameters: "backend.php?op=feeds&method=collapse&cid=" + param_escape(cat_id) + "&mode=1" } ); }, onClick: function (item, node) { var id = String(item.id); var is_cat = id.match("^CAT:"); var feed = id.substr(id.indexOf(":")+1); viewfeed(feed, '', is_cat); return false; }, openOnClick: false, showRoot: false, id: "feedTree", }, "feedTree"); /* var menu = new dijit.Menu({id: 'feedMenu'}); menu.addChild(new dijit.MenuItem({ label: "Simple menu item" })); // menu.bindDomNode(tree.domNode); */ var tmph = dojo.connect(dijit.byId('feedMenu'), '_openMyself', function (event) { console.log(dijit.getEnclosingWidget(event.target)); dojo.disconnect(tmph); }); $("feeds-holder").appendChild(tree.domNode); var tmph = dojo.connect(tree, 'onLoad', function() { dojo.disconnect(tmph); Element.hide("feedlistLoading"); tree.collapseHiddenCats(); feedlist_init(); // var node = dijit.byId("feedTree")._itemNodesMap['FEED:-2'][0].domNode // menu.bindDomNode(node); loading_set_progress(25); }); tree.startup(); } catch (e) { exception_error("updateFeedList", e); } } function catchupAllFeeds() { var str = __("Mark all articles as read?"); if (getInitParam("confirm_feed_catchup") != 1 || confirm(str)) { var query_str = "backend.php?op=feeds&method=catchupAll"; notify_progress("Marking all feeds as read..."); //console.log("catchupAllFeeds Q=" + query_str); new Ajax.Request("backend.php", { parameters: query_str, onComplete: function(transport) { feedlist_callback2(transport); } }); global_unread = 0; updateTitle(""); } } function viewCurrentFeed(method) { console.log("viewCurrentFeed"); if (getActiveFeedId() != undefined) { viewfeed(getActiveFeedId(), method, activeFeedIsCat()); } return false; // block unneeded form submits } function timeout() { if (getInitParam("bw_limit") != "1") { request_counters(); setTimeout("timeout()", 60*1000); } } function search() { var query = "backend.php?op=dlg&method=search&param=" + param_escape(getActiveFeedId() + ":" + activeFeedIsCat()); if (dijit.byId("searchDlg")) dijit.byId("searchDlg").destroyRecursive(); dialog = new dijit.Dialog({ id: "searchDlg", title: __("Search"), style: "width: 600px", execute: function() { if (this.validate()) { _search_query = dojo.objectToQuery(this.attr('value')); this.hide(); viewCurrentFeed(); } }, href: query}); dialog.show(); } function updateTitle() { var tmp = "Tiny Tiny RSS"; if (global_unread > 0) { tmp = tmp + " (" + global_unread + ")"; } if (window.fluid) { if (global_unread > 0) { window.fluid.dockBadge = global_unread; } else { window.fluid.dockBadge = ""; } } document.title = tmp; } function genericSanityCheck() { setCookie("ttrss_test", "TEST"); if (getCookie("ttrss_test") != "TEST") { return fatalError(2); } return true; } function init() { try { //dojo.registerModulePath("fox", "../../js/"); dojo.require("fox.FeedTree"); dojo.require("dijit.ColorPalette"); dojo.require("dijit.Dialog"); dojo.require("dijit.form.Button"); dojo.require("dijit.form.CheckBox"); dojo.require("dijit.form.DropDownButton"); dojo.require("dijit.form.FilteringSelect"); dojo.require("dijit.form.Form"); dojo.require("dijit.form.RadioButton"); dojo.require("dijit.form.Select"); dojo.require("dijit.form.SimpleTextarea"); dojo.require("dijit.form.TextBox"); dojo.require("dijit.form.ValidationTextBox"); dojo.require("dijit.InlineEditBox"); dojo.require("dijit.layout.AccordionContainer"); dojo.require("dijit.layout.BorderContainer"); dojo.require("dijit.layout.ContentPane"); dojo.require("dijit.layout.TabContainer"); dojo.require("dijit.Menu"); dojo.require("dijit.ProgressBar"); dojo.require("dijit.ProgressBar"); dojo.require("dijit.Toolbar"); dojo.require("dijit.Tree"); dojo.require("dijit.tree.dndSource"); dojo.require("dojo.data.ItemFileWriteStore"); dojo.parser.parse(); if (!genericSanityCheck()) return false; loading_set_progress(20); var hasAudio = !!((myAudioTag = document.createElement('audio')).canPlayType); new Ajax.Request("backend.php", { parameters: {op: "rpc", method: "sanityCheck", hasAudio: hasAudio}, onComplete: function(transport) { backend_sanity_check_callback(transport); } }); } catch (e) { exception_error("init", e); } } function init_second_stage() { try { dojo.addOnLoad(function() { updateFeedList(); closeArticlePanel(); _widescreen_mode = getInitParam("widescreen"); if (_widescreen_mode) { switchPanelMode(_widescreen_mode); } }); delCookie("ttrss_test"); var toolbar = document.forms["main_toolbar_form"]; dijit.getEnclosingWidget(toolbar.view_mode).attr('value', getInitParam("default_view_mode")); dijit.getEnclosingWidget(toolbar.order_by).attr('value', getInitParam("default_view_order_by")); feeds_sort_by_unread = getInitParam("feeds_sort_by_unread") == 1; loading_set_progress(30); // can't use cache_clear() here because viewfeed might not have initialized yet if ('sessionStorage' in window && window['sessionStorage'] !== null) sessionStorage.clear(); var hotkeys = getInitParam("hotkeys"); var tmp = []; for (sequence in hotkeys[1]) { filtered = sequence.replace(/\|.*$/, ""); tmp[filtered] = hotkeys[1][sequence]; } hotkeys[1] = tmp; setInitParam("hotkeys", hotkeys); console.log("second stage ok"); if (getInitParam("simple_update")) { console.log("scheduling simple feed updater..."); window.setTimeout("update_random_feed()", 30*1000); } } catch (e) { exception_error("init_second_stage", e); } } function quickMenuGo(opid) { try { switch (opid) { case "qmcPrefs": gotoPreferences(); break; case "qmcLogout": gotoLogout(); break; case "qmcTagCloud": displayDlg("printTagCloud"); break; case "qmcTagSelect": displayDlg("printTagSelect"); break; case "qmcSearch": search(); break; case "qmcAddFeed": quickAddFeed(); break; case "qmcDigest": window.location.href = "backend.php?op=digest"; break; case "qmcEditFeed": if (activeFeedIsCat()) alert(__("You can't edit this kind of feed.")); else editFeed(getActiveFeedId()); break; case "qmcRemoveFeed": var actid = getActiveFeedId(); if (activeFeedIsCat()) { alert(__("You can't unsubscribe from the category.")); return; } if (!actid) { alert(__("Please select some feed first.")); return; } var fn = getFeedName(actid); var pr = __("Unsubscribe from %s?").replace("%s", fn); if (confirm(pr)) { unsubscribeFeed(actid); } break; case "qmcCatchupAll": catchupAllFeeds(); break; case "qmcShowOnlyUnread": toggleDispRead(); break; case "qmcAddFilter": quickAddFilter(); break; case "qmcAddLabel": addLabel(); break; case "qmcRescoreFeed": rescoreCurrentFeed(); break; case "qmcToggleWidescreen": if (!isCdmMode()) { _widescreen_mode = !_widescreen_mode; switchPanelMode(_widescreen_mode); } break; case "qmcHKhelp": helpDialog("main"); break; default: console.log("quickMenuGo: unknown action: " + opid); } } catch (e) { exception_error("quickMenuGo", e); } } function toggleDispRead() { try { var hide = !(getInitParam("hide_read_feeds") == "1"); hideOrShowFeeds(hide); var query = "?op=rpc&method=setpref&key=HIDE_READ_FEEDS&value=" + param_escape(hide); setInitParam("hide_read_feeds", hide); new Ajax.Request("backend.php", { parameters: query, onComplete: function(transport) { } }); } catch (e) { exception_error("toggleDispRead", e); } } function parse_runtime_info(data) { //console.log("parsing runtime info..."); for (k in data) { var v = data[k]; // console.log("RI: " + k + " => " + v); if (k == "new_version_available") { if (v == "1") { Element.show(dijit.byId("newVersionIcon").domNode); } else { Element.hide(dijit.byId("newVersionIcon").domNode); } return; } if (k == "daemon_is_running" && v != 1) { notify_error("<span onclick=\"javascript:explainError(1)\">Update daemon is not running.</span>", true); return; } if (k == "daemon_stamp_ok" && v != 1) { notify_error("<span onclick=\"javascript:explainError(3)\">Update daemon is not updating feeds.</span>", true); return; } if (k == "max_feed_id" || k == "num_feeds") { if (init_params[k] != v) { console.log("feed count changed, need to reload feedlist."); updateFeedList(); } } init_params[k] = v; notify(''); } } function collapse_feedlist() { try { if (!Element.visible('feeds-holder')) { Element.show('feeds-holder'); Element.show('feeds-holder_splitter'); $("collapse_feeds_btn").innerHTML = "&lt;&lt;"; } else { Element.hide('feeds-holder'); Element.hide('feeds-holder_splitter'); $("collapse_feeds_btn").innerHTML = "&gt;&gt;"; } dijit.byId("main").resize(); query = "?op=rpc&method=setpref&key=_COLLAPSED_FEEDLIST&value=true"; new Ajax.Request("backend.php", { parameters: query }); } catch (e) { exception_error("collapse_feedlist", e); } } function viewModeChanged() { cache_clear(); return viewCurrentFeed(''); } function viewLimitChanged() { return viewCurrentFeed(''); } function rescoreCurrentFeed() { var actid = getActiveFeedId(); if (activeFeedIsCat() || actid < 0) { alert(__("You can't rescore this kind of feed.")); return; } if (!actid) { alert(__("Please select some feed first.")); return; } var fn = getFeedName(actid); var pr = __("Rescore articles in %s?").replace("%s", fn); if (confirm(pr)) { notify_progress("Rescoring articles..."); var query = "?op=pref-feeds&method=rescore&quiet=1&ids=" + actid; new Ajax.Request("backend.php", { parameters: query, onComplete: function(transport) { viewCurrentFeed(); } }); } } function hotkey_handler(e) { try { if (e.target.nodeName == "INPUT" || e.target.nodeName == "TEXTAREA") return; var keycode = false; var shift_key = false; var cmdline = $('cmdline'); shift_key = e.shiftKey; ctrl_key = e.ctrlKey; if (window.event) { keycode = window.event.keyCode; } else if (e) { keycode = e.which; } var keychar = String.fromCharCode(keycode); if (keycode == 27) { // escape hotkey_prefix = false; } if (keycode == 16) return; // ignore lone shift if (keycode == 17) return; // ignore lone ctrl if (!shift_key) keychar = keychar.toLowerCase(); var hotkeys = getInitParam("hotkeys"); if (!hotkey_prefix && hotkeys[0].indexOf(keychar) != -1) { var date = new Date(); var ts = Math.round(date.getTime() / 1000); hotkey_prefix = keychar; hotkey_prefix_pressed = ts; cmdline.innerHTML = keychar; Element.show(cmdline); return true; } Element.hide(cmdline); var hotkey = keychar.search(/[a-zA-Z0-9]/) != -1 ? keychar : "(" + keycode + ")"; if (ctrl_key) hotkey = "^" + hotkey; hotkey = hotkey_prefix ? hotkey_prefix + " " + hotkey : hotkey; hotkey_prefix = false; var hotkey_action = false; var hotkeys = getInitParam("hotkeys"); for (sequence in hotkeys[1]) { if (sequence == hotkey) { hotkey_action = hotkeys[1][sequence]; break; } } switch (hotkey_action) { case "next_feed": var rv = dijit.byId("feedTree").getNextFeed( getActiveFeedId(), activeFeedIsCat()); if (rv) viewfeed(rv[0], '', rv[1]); return false; case "prev_feed": var rv = dijit.byId("feedTree").getPreviousFeed( getActiveFeedId(), activeFeedIsCat()); if (rv) viewfeed(rv[0], '', rv[1]); return false; case "next_article": moveToPost('next'); return false; case "prev_article": moveToPost('prev'); return false; case "search_dialog": search(); return ; case "toggle_mark": selectionToggleMarked(undefined, false, true); return false; case "toggle_publ": selectionTogglePublished(undefined, false, true); return false; case "toggle_unread": selectionToggleUnread(undefined, false, true); return false; case "edit_tags": var id = getActiveArticleId(); if (id) { editArticleTags(id, getActiveFeedId(), isCdmMode()); return; } return false; case "dismiss_selected": dismissSelectedArticles(); return false; case "dismiss_read": return false; case "open_in_new_window": if (getActiveArticleId()) { openArticleInNewWindow(getActiveArticleId()); return; } return false; case "catchup_below": catchupRelativeToArticle(1); return false; case "catchup_above": catchupRelativeToArticle(0); return false; case "article_scroll_down": scrollArticle(50); return false; case "article_scroll_up": scrollArticle(-50); return false; case "close_article": closeArticlePanel(); return false; case "email_article": if (typeof emailArticle != "undefined") { emailArticle(); } else { alert(__("Please enable mail plugin first.")); } return false; case "select_all": selectArticles('all'); return false; case "select_unread": selectArticles('unread'); return false; case "select_marked": selectArticles('marked'); return false; case "select_published": selectArticles('published'); return false; case "select_invert": selectArticles('invert'); return false; case "select_none": selectArticles('none'); return false; case "feed_refresh": if (getActiveFeedId() != undefined) { viewfeed(getActiveFeedId(), '', activeFeedIsCat()); return; } return false; case "feed_unhide_read": toggleDispRead(); return false; case "feed_subscribe": quickAddFeed(); return false; case "feed_debug_update": window.open("backend.php?op=feeds&method=view&feed=" + getActiveFeedId() + "&view_mode=adaptive&order_by=default&update=&m=ForceUpdate&cat=" + activeFeedIsCat() + "&DevForceUpdate=1&debug=1&xdebug=1&csrf_token=" + getInitParam("csrf_token")); return false; case "feed_edit": if (activeFeedIsCat()) alert(__("You can't edit this kind of feed.")); else editFeed(getActiveFeedId()); return false; case "feed_catchup": if (getActiveFeedId() != undefined) { catchupCurrentFeed(); return; } return false; case "feed_reverse": reverseHeadlineOrder(); return false; case "catchup_all": catchupAllFeeds(); return false; case "cat_toggle_collapse": if (activeFeedIsCat()) { dijit.byId("feedTree").collapseCat(getActiveFeedId()); return; } return false; case "goto_all": viewfeed(-4); return false; case "goto_fresh": viewfeed(-3); return false; case "goto_marked": viewfeed(-1); return false; case "goto_published": viewfeed(-2); return false; case "goto_tagcloud": displayDlg("printTagCloud"); return false; case "goto_prefs": gotoPreferences(); return false; case "select_article_cursor": var id = getArticleUnderPointer(); if (id) { var cb = dijit.byId("RCHK-" + id); if (cb) { cb.attr("checked", !cb.attr("checked")); toggleSelectRowById(cb, "RROW-" + id); return false; } } return false; case "create_label": addLabel(); return false; case "create_filter": quickAddFilter(); return false; case "collapse_sidebar": collapse_feedlist(); return false; case "toggle_widescreen": if (!isCdmMode()) { _widescreen_mode = !_widescreen_mode; switchPanelMode(_widescreen_mode); } return false; case "help_dialog": helpDialog("main"); return false; default: console.log("unhandled action: " + hotkey_action + "; hotkey: " + hotkey); } } catch (e) { exception_error("hotkey_handler", e); } } function inPreferences() { return false; } function reverseHeadlineOrder() { try { var query_str = "?op=rpc&method=togglepref&key=REVERSE_HEADLINES"; new Ajax.Request("backend.php", { parameters: query_str, onComplete: function(transport) { viewCurrentFeed(); } }); } catch (e) { exception_error("reverseHeadlineOrder", e); } } function newVersionDlg() { try { var query = "backend.php?op=dlg&method=newVersion"; if (dijit.byId("newVersionDlg")) dijit.byId("newVersionDlg").destroyRecursive(); dialog = new dijit.Dialog({ id: "newVersionDlg", title: __("New version available!"), style: "width: 600px", href: query, }); dialog.show(); } catch (e) { exception_error("newVersionDlg", e); } } function handle_rpc_json(transport, scheduled_call) { try { var reply = JSON.parse(transport.responseText); if (reply) { var error = reply['error']; if (error) { var code = error['code']; var msg = error['msg']; console.warn("[handle_rpc_json] received fatal error " + code + "/" + msg); if (code != 0) { fatalError(code, msg); return false; } } var seq = reply['seq']; if (seq) { if (get_seq() != seq) { console.log("[handle_rpc_json] sequence mismatch: " + seq + " (want: " + get_seq() + ")"); return true; } } var message = reply['message']; if (message) { if (message == "UPDATE_COUNTERS") { console.log("need to refresh counters..."); setInitParam("last_article_id", -1); request_counters(true); } } var counters = reply['counters']; if (counters) parse_counters(counters, scheduled_call); var runtime_info = reply['runtime-info'];; if (runtime_info) parse_runtime_info(runtime_info); hideOrShowFeeds(getInitParam("hide_read_feeds") == 1); Element.hide(dijit.byId("net-alert").domNode); } else { //notify_error("Error communicating with server."); Element.show(dijit.byId("net-alert").domNode); } } catch (e) { Element.show(dijit.byId("net-alert").domNode); //notify_error("Error communicating with server."); console.log(e); //exception_error("handle_rpc_json", e, transport); } return true; } function switchPanelMode(wide) { try { article_id = getActiveArticleId(); if (wide) { dijit.byId("headlines-wrap-inner").attr("design", 'sidebar'); dijit.byId("content-insert").attr("region", "trailing"); dijit.byId("content-insert").domNode.setStyle({width: '50%', height: 'auto', borderLeftWidth: '1px', borderLeftColor: '#c0c0c0', borderTopWidth: '0px' }); $("headlines-toolbar").setStyle({ borderBottomWidth: '0px' }); } else { dijit.byId("content-insert").attr("region", "bottom"); dijit.byId("content-insert").domNode.setStyle({width: 'auto', height: '50%', borderLeftWidth: '0px', borderTopWidthidth: '1px'}); $("headlines-toolbar").setStyle({ borderBottomWidth: '1px' }); } closeArticlePanel(); if (article_id) view(article_id); new Ajax.Request("backend.php", { parameters: "op=rpc&method=setpanelmode&wide=" + (wide ? 1 : 0), onComplete: function(transport) { console.log(transport.responseText); } }); } catch (e) { exception_error("switchPanelMode", e); } } function update_random_feed() { try { console.log("in update_random_feed"); new Ajax.Request("backend.php", { parameters: "op=rpc&method=updateRandomFeed", onComplete: function(transport) { handle_rpc_json(transport, true); window.setTimeout("update_random_feed()", 30*1000); } }); } catch (e) { exception_error("update_random_feed", e); } }
switchPanelMode: fix typo
js/tt-rss.js
switchPanelMode: fix typo
<ide><path>s/tt-rss.js <ide> dijit.byId("content-insert").domNode.setStyle({width: 'auto', <ide> height: '50%', <ide> borderLeftWidth: '0px', <del> borderTopWidthidth: '1px'}); <add> borderTopWidth: '1px'}); <ide> <ide> $("headlines-toolbar").setStyle({ borderBottomWidth: '1px' }); <ide> }
Java
apache-2.0
f22f3b6ece8c725b259be97e49a1f8196ed2b386
0
datanucleus/tests,datanucleus/tests,datanucleus/tests,datanucleus/tests,datanucleus/tests
/********************************************************************** Copyright (c) 2006 Andy Jefferson and others. 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. Contributors: ... **********************************************************************/ package org.datanucleus.tests.metadata; import java.util.List; import javax.persistence.PostLoad; import javax.persistence.PostPersist; import javax.persistence.PrePersist; import javax.persistence.PreRemove; import org.datanucleus.ClassLoaderResolver; import org.datanucleus.ClassLoaderResolverImpl; import org.datanucleus.NucleusContext; import org.datanucleus.PersistenceNucleusContextImpl; import org.datanucleus.api.jpa.metadata.JPAMetaDataManager; import org.datanucleus.metadata.AbstractMemberMetaData; import org.datanucleus.metadata.ClassMetaData; import org.datanucleus.metadata.ColumnMetaData; import org.datanucleus.metadata.ElementMetaData; import org.datanucleus.metadata.EventListenerMetaData; import org.datanucleus.metadata.FieldPersistenceModifier; import org.datanucleus.metadata.ValueGenerationStrategy; import org.datanucleus.metadata.IdentityType; import org.datanucleus.metadata.InheritanceMetaData; import org.datanucleus.metadata.InheritanceStrategy; import org.datanucleus.metadata.JdbcType; import org.datanucleus.metadata.JoinMetaData; import org.datanucleus.metadata.KeyMetaData; import org.datanucleus.metadata.MapMetaData; import org.datanucleus.metadata.MetaDataManager; import org.datanucleus.metadata.OrderMetaData; import org.datanucleus.metadata.PackageMetaData; import org.datanucleus.metadata.PersistenceUnitMetaData; import org.datanucleus.metadata.QueryLanguage; import org.datanucleus.metadata.QueryMetaData; import org.datanucleus.metadata.QueryResultMetaData; import org.datanucleus.metadata.RelationType; import org.datanucleus.metadata.SequenceMetaData; import org.datanucleus.metadata.TableGeneratorMetaData; import org.datanucleus.metadata.OrderMetaData.FieldOrder; import org.datanucleus.metadata.QueryResultMetaData.PersistentTypeMapping; import org.datanucleus.samples.annotations.abstractclasses.AbstractSimpleBase; import org.datanucleus.samples.annotations.abstractclasses.ConcreteSimpleSub1; import org.datanucleus.samples.annotations.abstractclasses.ConcreteSimpleSub2; import org.datanucleus.samples.annotations.array.ByteArray; import org.datanucleus.samples.annotations.idclass.IdClassAccessors; import org.datanucleus.samples.annotations.many_many.PetroleumCustomer; import org.datanucleus.samples.annotations.many_many.PetroleumSupplier; import org.datanucleus.samples.annotations.models.company.Account; import org.datanucleus.samples.annotations.models.company.Department; import org.datanucleus.samples.annotations.models.company.DepartmentPK; import org.datanucleus.samples.annotations.models.company.Employee; import org.datanucleus.samples.annotations.models.company.Manager; import org.datanucleus.samples.annotations.models.company.MyListener; import org.datanucleus.samples.annotations.models.company.Person; import org.datanucleus.samples.annotations.models.company.Project; import org.datanucleus.samples.annotations.models.company.WebSite; import org.datanucleus.samples.annotations.one_many.unidir_2.UserGroup; import org.datanucleus.samples.annotations.one_one.bidir.Boiler; import org.datanucleus.samples.annotations.one_one.bidir.Timer; import org.datanucleus.samples.annotations.one_one.unidir.Login; import org.datanucleus.samples.annotations.one_one.unidir.LoginAccount; import org.datanucleus.samples.annotations.secondarytable.Printer; import org.datanucleus.samples.annotations.types.basic.TypeHolder; import org.datanucleus.samples.annotations.types.enums.EnumHolder; import org.datanucleus.tests.JPAPersistenceTestCase; /** * Tests for the use of JPA annotations and the generation of internal JPOX metadata. */ public class AnnotationTest extends JPAPersistenceTestCase { public AnnotationTest(String name) { super(name); } /** * Test of basic JPA annotations reading capability */ public void testBasic() { NucleusContext nucleusCtx = new PersistenceNucleusContextImpl("JPA", null); MetaDataManager metaDataMgr = new JPAMetaDataManager(nucleusCtx); ClassLoaderResolver clr = new ClassLoaderResolverImpl(); // Checks for Department ClassMetaData cmd1 = (ClassMetaData)metaDataMgr.getMetaDataForClass(Department.class.getName(), clr); String prefix = cmd1.getFullClassName() + " : "; assertEquals(prefix + "detachable is wrong", cmd1.isDetachable(), true); assertEquals(prefix + "identity-type is wrong", cmd1.getIdentityType(), IdentityType.APPLICATION); assertEquals(prefix + "embedded-only is wrong", cmd1.isEmbeddedOnly(), false); assertEquals(prefix + "requires-extent is wrong", cmd1.isRequiresExtent(), true); assertEquals(prefix + "catalog is wrong", cmd1.getCatalog(), null); assertEquals(prefix + "schema is wrong", cmd1.getSchema(), null); assertEquals(prefix + "table is wrong", cmd1.getTable(), "JPA_AN_DEPARTMENT"); assertEquals(prefix + "has incorrect number of persistent fields", cmd1.getNoOfManagedMembers(), 4); InheritanceMetaData inhmd1 = cmd1.getInheritanceMetaData(); assertEquals("Inheritance strategy is incorrect", InheritanceStrategy.NEW_TABLE, inhmd1.getStrategy()); // "projects" AbstractMemberMetaData fmd = cmd1.getMetaDataForMember("projects"); assertNotNull(prefix + "doesnt have required field", fmd); assertEquals(prefix + "should be persistent", fmd.getPersistenceModifier(), FieldPersistenceModifier.PERSISTENT); assertFalse(prefix + "pk is wrong", fmd.isPrimaryKey()); assertFalse(prefix + "dfg is wrong", fmd.isDefaultFetchGroup()); assertTrue(prefix + "has no container specified!", fmd.getCollection() != null); assertEquals(prefix + "should have collection of Project elements but hasnt", fmd.getCollection().getElementType(), Project.class.getName()); assertEquals(prefix + "shouldnt have collection of serialised elements but has", fmd.getCollection().isSerializedElement(), false); assertEquals(prefix + "shouldnt have collection of dependent elements but has", fmd.getCollection().isDependentElement(), false); // Checks for Project ClassMetaData cmd2 = (ClassMetaData)metaDataMgr.getMetaDataForClass(Project.class.getName(), clr); prefix = cmd2.getFullClassName() + " : "; assertEquals(prefix + "detachable is wrong", true, cmd2.isDetachable()); assertEquals(prefix + "identity-type is wrong", cmd2.getIdentityType(), IdentityType.APPLICATION); assertEquals(prefix + "objectid-class is wrong", "org.datanucleus.identity.StringId", cmd2.getObjectidClass()); assertEquals(prefix + "embedded-only is wrong", cmd2.isEmbeddedOnly(), false); assertEquals(prefix + "requires-extent is wrong", cmd2.isRequiresExtent(), true); assertEquals(prefix + "catalog is wrong", cmd2.getCatalog(), null); assertEquals(prefix + "schema is wrong", cmd2.getSchema(), null); assertEquals(prefix + "table is wrong", "JPA_AN_PROJECT", cmd2.getTable()); assertEquals(prefix + "has incorrect number of persistent fields", cmd2.getNoOfManagedMembers(), 2); InheritanceMetaData inhmd2 = cmd2.getInheritanceMetaData(); assertEquals("Inheritance strategy is incorrect", InheritanceStrategy.NEW_TABLE, inhmd2.getStrategy()); // "name" fmd = cmd2.getMetaDataForMember("name"); assertNotNull(prefix + "doesnt have required field", fmd); assertTrue(prefix + "pk is wrong", fmd.isPrimaryKey()); assertTrue(prefix + "dfg is wrong", fmd.isDefaultFetchGroup()); assertEquals(prefix + "should be persistent", fmd.getPersistenceModifier(), FieldPersistenceModifier.PERSISTENT); // "budget" fmd = cmd2.getMetaDataForMember("budget"); assertNotNull(prefix + "doesnt have required field", fmd); assertEquals(prefix + "has incorrect persistent field", fmd.getName(), "budget"); assertFalse(prefix + "pk is wrong", fmd.isPrimaryKey()); assertTrue(prefix + "dfg is wrong", fmd.isDefaultFetchGroup()); assertEquals(prefix + "should be persistent", fmd.getPersistenceModifier(), FieldPersistenceModifier.PERSISTENT); } /** * Test of JPA 1-1 unidir relation */ public void testOneToOneUni() { NucleusContext nucleusCtx = new PersistenceNucleusContextImpl("JPA", null); ClassLoaderResolver clr = nucleusCtx.getClassLoaderResolver(null); MetaDataManager metaDataMgr = new JPAMetaDataManager(nucleusCtx); PersistenceUnitMetaData pumd = getMetaDataForPersistenceUnit(nucleusCtx, "JPATest"); metaDataMgr.loadPersistenceUnit(pumd, null); ClassMetaData cmd1 = (ClassMetaData)metaDataMgr.getMetaDataForClass(LoginAccount.class.getName(), clr); assertEquals("LoginAccount has incorrect table name", cmd1.getTable(), "JPA_AN_LOGINACCOUNT"); AbstractMemberMetaData fmd1 = cmd1.getMetaDataForMember("login"); assertNotNull("LoginAccount.login is null!", fmd1); assertEquals("LoginAccount.login mapped-by is incorrect", fmd1.getMappedBy(), null); assertEquals("LoginAccount.login relationType is incorrect", fmd1.getRelationType(clr), RelationType.ONE_TO_ONE_UNI); assertNotNull("LoginAccount.login has no column info", fmd1.getColumnMetaData()); assertEquals("LoginAccount.login has incorrect number of columns", fmd1.getColumnMetaData().length, 1); assertEquals("LoginAccount.login column name is wrong", fmd1.getColumnMetaData()[0].getName(), "LOGIN_ID"); ClassMetaData cmd2 = (ClassMetaData)metaDataMgr.getMetaDataForClass(Login.class.getName(), clr); assertEquals("LoginAccount has incorrect table name", cmd2.getTable(), "JPA_AN_LOGIN"); } /** * Test of JPA 1-1 bidir relation */ public void testOneToOneBi() { NucleusContext nucleusCtx = new PersistenceNucleusContextImpl("JPA", null); ClassLoaderResolver clr = nucleusCtx.getClassLoaderResolver(null); MetaDataManager metaDataMgr = new JPAMetaDataManager(nucleusCtx); PersistenceUnitMetaData pumd = getMetaDataForPersistenceUnit(nucleusCtx, "JPATest"); metaDataMgr.loadPersistenceUnit(pumd, null); // non-owner side ClassMetaData cmd1 = (ClassMetaData)metaDataMgr.getMetaDataForClass(Boiler.class.getName(), clr); assertEquals("Boiler has incorrect table name", "JPA_AN_BOILER", cmd1.getTable()); AbstractMemberMetaData fmd1 = cmd1.getMetaDataForMember("timer"); assertNotNull("Boiler.timer is null!", fmd1); assertEquals("Boiler.timer mapped-by is incorrect", "boiler", fmd1.getMappedBy()); assertEquals("Boiler.timer relationType is incorrect", RelationType.ONE_TO_ONE_BI, fmd1.getRelationType(clr)); // owner side ClassMetaData cmd2 = (ClassMetaData)metaDataMgr.getMetaDataForClass(Timer.class.getName(), clr); assertEquals("Timer has incorrect table name", "JPA_AN_TIMER", cmd2.getTable()); AbstractMemberMetaData fmd2 = cmd2.getMetaDataForMember("boiler"); assertNotNull("Timer.boiler is null!", fmd2); assertEquals("Timer.boiler mapped-by is incorrect", null, fmd2.getMappedBy()); assertEquals("Timer.boiler relationType is incorrect", RelationType.ONE_TO_ONE_BI, fmd2.getRelationType(clr)); assertNotNull("Timer.boiler has no column info", fmd2.getColumnMetaData()); assertEquals("Timer.boiler has incorrect number of columns", 1, fmd2.getColumnMetaData().length); assertEquals("Timer.boiler column name is wrong", "BOILER_ID", fmd2.getColumnMetaData()[0].getName()); } /** * Test of JPA 1-N bidir FK relation */ public void testOneToManyBiFK() { NucleusContext nucleusCtx = new PersistenceNucleusContextImpl("JPA", null); ClassLoaderResolver clr = nucleusCtx.getClassLoaderResolver(null); MetaDataManager metaDataMgr = new JPAMetaDataManager(nucleusCtx); PersistenceUnitMetaData pumd = getMetaDataForPersistenceUnit(nucleusCtx, "JPATest"); metaDataMgr.loadPersistenceUnit(pumd, null); // owner side ClassMetaData cmd1 = (ClassMetaData)metaDataMgr.getMetaDataForClass(Manager.class.getName(), clr); AbstractMemberMetaData fmd1 = cmd1.getMetaDataForMember("departments"); assertNotNull("Manager.departments is null!", fmd1); assertEquals("Manager.departments mapped-by is incorrect", fmd1.getMappedBy(), "manager"); assertEquals("Manager.departments relationType is incorrect", fmd1.getRelationType(clr), RelationType.ONE_TO_MANY_BI); ElementMetaData elemmd = fmd1.getElementMetaData(); assertNull("Manager.departments has join column info but shouldnt (specified on N side)", elemmd); // non-owner side ClassMetaData cmd2 = (ClassMetaData)metaDataMgr.getMetaDataForClass(Department.class.getName(), clr); AbstractMemberMetaData fmd2 = cmd2.getMetaDataForMember("manager"); assertNotNull("Department.manager is null!", fmd2); assertEquals("Department.manager mapped-by is incorrect", fmd2.getMappedBy(), null); assertEquals("Department.manager relationType is incorrect", fmd2.getRelationType(clr), RelationType.MANY_TO_ONE_BI); ColumnMetaData[] colmds = fmd2.getColumnMetaData(); assertNotNull("Department.manager has no join column info", colmds); assertEquals("Department.manager has incorrect number of joincolumns", colmds.length, 1); assertEquals("Department.manager joincolumn name is wrong", "MGR_ID", colmds[0].getName()); } /** * Test of JPA 1-N unidir JoinTable relation */ public void testOneToManyUniJoin() { NucleusContext nucleusCtx = new PersistenceNucleusContextImpl("JPA", null); ClassLoaderResolver clr = nucleusCtx.getClassLoaderResolver(null); MetaDataManager metaDataMgr = new JPAMetaDataManager(nucleusCtx); PersistenceUnitMetaData pumd = getMetaDataForPersistenceUnit(nucleusCtx, "JPATest"); metaDataMgr.loadPersistenceUnit(pumd, null); // owner side ClassMetaData cmd1 = (ClassMetaData)metaDataMgr.getMetaDataForClass(Department.class.getName(), clr); AbstractMemberMetaData fmd1 = cmd1.getMetaDataForMember("projects"); assertNotNull("Department.projects is null!", fmd1); assertEquals("Department.projects mapped-by is incorrect", null, fmd1.getMappedBy()); assertEquals("Department.projects relationType is incorrect", RelationType.ONE_TO_MANY_UNI, fmd1.getRelationType(clr)); assertEquals("Department.projects jointable name is incorrect", "JPA_AN_DEPT_PROJECTS", fmd1.getTable()); JoinMetaData joinmd = fmd1.getJoinMetaData(); assertNotNull("Department.projects has no join table!", joinmd); assertNotNull("Department.projects has incorrect join columns", joinmd.getColumnMetaData()); assertEquals("Department.projects has incorrect number of join columns", 2, joinmd.getColumnMetaData().length); assertEquals("Department.projects has incorrect join column name", joinmd.getColumnMetaData()[0].getName(), "DEPT_ID"); assertEquals("Department.projects has incorrect join column name", joinmd.getColumnMetaData()[1].getName(), "DEPT_ID_STRING"); ElementMetaData elemmd = fmd1.getElementMetaData(); assertNotNull("Department.projects has no element column info but should", elemmd); ColumnMetaData[] colmds = elemmd.getColumnMetaData(); assertNotNull("Department.projects has incorrect element columns", colmds); assertEquals("Department.projects has incorrect number of element columns", 1, colmds.length); assertEquals("Department.projects has incorrect element column name", "PROJECT_ID", colmds[0].getName()); } /** * Test of JPA 1-N unidir FK relation. * Really is 1-N uni join since JPA doesnt support 1-N uni FK */ /*public void testOneToManyUniFK() { NucleusContext nucleusCtx = new NucleusContext(new PersistenceConfiguration(){}); nucleusCtx.setApi("JPA"); MetaDataManager metaDataMgr = new JPAMetaDataManager(nucleusCtx); ClassLoaderResolver clr = new ClassLoaderResolverImpl(); // owner side ClassMetaData cmd1 = (ClassMetaData)metaDataMgr.getMetaDataForClass(Site.class.getName(), clr); AbstractMemberMetaData fmd1 = cmd1.getMetaDataForMember("offices"); assertNotNull("Site.offices is null!", fmd1); assertEquals("Site.offices mapped-by is incorrect", fmd1.getMappedBy(), null); assertEquals("Site.offices relationType is incorrect", fmd1.getRelationType(clr), Relation.ONE_TO_MANY_UNI); assertEquals("Site.offices jointable name is incorrect", fmd1.getTable(), null); assertNotNull("Site.offices should have join but doesnt", fmd1.getJoinMetaData()); ElementMetaData elemmd = fmd1.getElementMetaData(); assertNotNull("Site.offices has no element column info but should", elemmd); ColumnMetaData[] colmds = elemmd.getColumnMetaData(); assertNotNull("Site.offices has incorrect element columns", colmds); assertEquals("Site.offices has incorrect number of element columns", colmds.length, 1); assertEquals("Site.offices has incorrect element column name", colmds[0].getName(), "SITE_ID"); }*/ /** * Test of JPA 1-N bidir join relation */ public void testOneToManyBiJoin() { NucleusContext nucleusCtx = new PersistenceNucleusContextImpl("JPA", null); ClassLoaderResolver clr = nucleusCtx.getClassLoaderResolver(null); MetaDataManager metaDataMgr = new JPAMetaDataManager(nucleusCtx); PersistenceUnitMetaData pumd = getMetaDataForPersistenceUnit(nucleusCtx, "JPATest"); metaDataMgr.loadPersistenceUnit(pumd, null); // owner side ClassMetaData cmd1 = (ClassMetaData)metaDataMgr.getMetaDataForClass(Manager.class.getName(), clr); assertEquals("Manager has incorrect table name", cmd1.getTable(), "JPA_AN_MANAGER"); AbstractMemberMetaData fmd1 = cmd1.getMetaDataForMember("subordinates"); assertNotNull("Manager.subordinates is null!", fmd1); assertEquals("Manager.subordinates mapped-by is incorrect", fmd1.getMappedBy(), "manager"); assertEquals("Manager.subordinates relationType is incorrect", fmd1.getRelationType(clr), RelationType.ONE_TO_MANY_BI); assertEquals("Manager.subordinates jointable name is incorrect", fmd1.getTable(), "JPA_AN_MGR_EMPLOYEES"); // non-owner side ClassMetaData cmd2 = (ClassMetaData)metaDataMgr.getMetaDataForClass(Employee.class.getName(), clr); assertEquals("Employee has incorrect table name", cmd2.getTable(), "JPA_AN_EMPLOYEE"); AbstractMemberMetaData fmd2 = cmd2.getMetaDataForMember("manager"); assertNotNull("Employee.manager is null!", fmd2); assertEquals("Employee.manager mapped-by is incorrect", fmd2.getMappedBy(), null); assertEquals("Employee.manager relationType is incorrect", fmd2.getRelationType(clr), RelationType.MANY_TO_ONE_BI); assertEquals("Employee.manager jointable name is incorrect", fmd2.getTable(), null); // join-table JoinMetaData joinmd = fmd1.getJoinMetaData(); assertNotNull("Manager.subordinates has no join table!", joinmd); assertNotNull("Manager.subordinates has incorrect join columns", joinmd.getColumnMetaData()); assertEquals("Manager.subordinates has incorrect number of join columns", 1, joinmd.getColumnMetaData().length); assertEquals("Manager.subordinates has incorrect owner join column name", "MGR_ID", joinmd.getColumnMetaData()[0].getName()); ElementMetaData elemmd = fmd1.getElementMetaData(); assertNotNull("Manager.subordinates has no element column info but should", elemmd); assertNotNull("Manager.subordinates has incorrect element columns", elemmd.getColumnMetaData()); assertEquals("Manager.subordinates has incorrect number of element columns", 1, elemmd.getColumnMetaData().length); assertEquals("Manager.subordinates has incorrect element join column name", "EMP_ID", elemmd.getColumnMetaData()[0].getName()); } /** * Test of JPA M-N relation */ public void testManyToMany() { NucleusContext nucleusCtx = new PersistenceNucleusContextImpl("JPA", null); ClassLoaderResolver clr = nucleusCtx.getClassLoaderResolver(null); MetaDataManager metaDataMgr = new JPAMetaDataManager(nucleusCtx); PersistenceUnitMetaData pumd = getMetaDataForPersistenceUnit(nucleusCtx, "JPATest"); metaDataMgr.loadPersistenceUnit(pumd, null); // owner side ClassMetaData cmd1 = (ClassMetaData)metaDataMgr.getMetaDataForClass(PetroleumCustomer.class.getName(), clr); assertEquals("Customer has incorrect table name", cmd1.getTable(), "JPA_AN_PETROL_CUSTOMER"); AbstractMemberMetaData fmd1 = cmd1.getMetaDataForMember("suppliers"); assertNotNull("Customer.suppliers is null!", fmd1); assertEquals("Customer.suppliers mapped-by is incorrect", fmd1.getMappedBy(), "customers"); assertEquals("Customer.suppliers relationType is incorrect", fmd1.getRelationType(clr), RelationType.MANY_TO_MANY_BI); assertEquals("Customer.suppliers jointable name is incorrect", fmd1.getTable(), "JPA_AN_PETROL_CUST_SUPP"); // non-owner side ClassMetaData cmd2 = (ClassMetaData)metaDataMgr.getMetaDataForClass(PetroleumSupplier.class.getName(), clr); assertEquals("Supplier has incorrect table name", cmd2.getTable(), "JPA_AN_PETROL_SUPPLIER"); AbstractMemberMetaData fmd2 = cmd2.getMetaDataForMember("customers"); assertNotNull("Supplier.customers is null!", fmd2); assertEquals("Supplier.customers mapped-by is incorrect", fmd2.getMappedBy(), null); assertEquals("Supplier.customers relationType is incorrect", fmd2.getRelationType(clr), RelationType.MANY_TO_MANY_BI); assertEquals("Supplier.customers jointable name is incorrect", fmd2.getTable(), null); // join table info JoinMetaData joinmd = fmd1.getJoinMetaData(); assertNotNull("Customer.suppliers has no join table!", joinmd); assertNotNull("Customer.suppliers has incorrect join columns", joinmd.getColumnMetaData()); assertEquals("Customer.suppliers has incorrect number of join columns", joinmd.getColumnMetaData().length, 1); assertEquals("Customer.suppliers has incorrect owner join column name", joinmd.getColumnMetaData()[0].getName(), "CUSTOMER_ID"); ElementMetaData elemmd = fmd1.getElementMetaData(); assertNotNull("Customer.suppliers has no element column info but should", elemmd); assertNotNull("Customer.suppliers has incorrect element columns", elemmd.getColumnMetaData()); assertEquals("Customer.suppliers has incorrect number of element columns", elemmd.getColumnMetaData().length, 1); assertEquals("Customer.suppliers has incorrect element join column name", elemmd.getColumnMetaData()[0].getName(), "SUPPLIER_ID"); } /** * Test of JPA 1-N unidir Map relation */ public void testOneToManyUniMapFK() { NucleusContext nucleusCtx = new PersistenceNucleusContextImpl("JPA", null); ClassLoaderResolver clr = nucleusCtx.getClassLoaderResolver(null); MetaDataManager metaDataMgr = new JPAMetaDataManager(nucleusCtx); PersistenceUnitMetaData pumd = getMetaDataForPersistenceUnit(nucleusCtx, "JPATest"); metaDataMgr.loadPersistenceUnit(pumd, null); // owner side ClassMetaData cmd1 = (ClassMetaData)metaDataMgr.getMetaDataForClass(Person.class.getName(), clr); AbstractMemberMetaData fmd1 = cmd1.getMetaDataForMember("phoneNumbers"); assertNotNull("Department.phoneNumbers is null!", fmd1); assertEquals("Department.phoneNumbers mapped-by is incorrect", fmd1.getMappedBy(), null); assertEquals("Department.phoneNumbers relationType is incorrect", fmd1.getRelationType(clr), RelationType.ONE_TO_MANY_UNI); assertEquals("Department.phoneNumbers jointable name is incorrect", fmd1.getTable(), null); MapMetaData mmd = fmd1.getMap(); assertNotNull("Department.phoneNumbers has no Map metadata!", mmd); KeyMetaData keymd = fmd1.getKeyMetaData(); assertNotNull("Department.phoneNumbers has no Key metadata!", keymd); assertEquals("Department.phoneNumbers has incorrect key mapped-by", keymd.getMappedBy(), "name"); } /** * Test of basic JPA @GeneratedValue. */ public void testGeneratedValue() { NucleusContext nucleusCtx = new PersistenceNucleusContextImpl("JPA", null); ClassLoaderResolver clr = nucleusCtx.getClassLoaderResolver(null); MetaDataManager metaDataMgr = new JPAMetaDataManager(nucleusCtx); // Retrieve the metadata from the MetaDataManager (populates and initialises everything) ClassMetaData cmd1 = (ClassMetaData)metaDataMgr.getMetaDataForClass(Account.class.getName(), clr); AbstractMemberMetaData fmd1 = cmd1.getMetaDataForMember("id"); assertNotNull("Account has no id field!", fmd1); assertEquals("Account has incorrect value strategy", fmd1.getValueStrategy(), ValueGenerationStrategy.INCREMENT); } /** * Test of basic JPA @TableGenerator */ public void testTableGenerator() { NucleusContext nucleusCtx = new PersistenceNucleusContextImpl("JPA", null); ClassLoaderResolver clr = nucleusCtx.getClassLoaderResolver(null); MetaDataManager metaDataMgr = new JPAMetaDataManager(nucleusCtx); PersistenceUnitMetaData pumd = getMetaDataForPersistenceUnit(nucleusCtx, "JPATest"); metaDataMgr.loadPersistenceUnit(pumd, null); ClassMetaData cmd1 = (ClassMetaData)metaDataMgr.getMetaDataForClass(Employee.class.getName(), clr); PackageMetaData pmd = cmd1.getPackageMetaData(); assertEquals("Number of TableGenerators registered for Employee class is wrong", pmd.getNoOfTableGenerators(), 1); TableGeneratorMetaData tgmd = pmd.getTableGenerators()[0]; assertEquals("TableGenerator has incorrect name", tgmd.getName(), "EmployeeGenerator"); assertEquals("TableGenerator has incorrect table", tgmd.getTableName(), "ID_TABLE"); assertEquals("TableGenerator has incorrect pk column name", tgmd.getPKColumnName(), "TYPE"); assertEquals("TableGenerator has incorrect value column name", tgmd.getValueColumnName(), "LATEST_VALUE"); assertEquals("TableGenerator has incorrect pk column value", tgmd.getPKColumnValue(), "EMPLOYEE"); assertEquals("TableGenerator has incorrect initial value", tgmd.getInitialValue(), 0); assertEquals("TableGenerator has incorrect allocation size", tgmd.getAllocationSize(), 50); } /** * Test of basic JPA @SequenceGenerator */ public void testSequenceGenerator() { NucleusContext nucleusCtx = new PersistenceNucleusContextImpl("JPA", null); ClassLoaderResolver clr = nucleusCtx.getClassLoaderResolver(null); MetaDataManager metaDataMgr = new JPAMetaDataManager(nucleusCtx); PersistenceUnitMetaData pumd = getMetaDataForPersistenceUnit(nucleusCtx, "JPATest"); metaDataMgr.loadPersistenceUnit(pumd, null); ClassMetaData cmd1 = (ClassMetaData)metaDataMgr.getMetaDataForClass(Department.class.getName(), clr); PackageMetaData pmd = cmd1.getPackageMetaData(); assertEquals("Number of Sequences registered for Department class is wrong", pmd.getNoOfSequences(), 1); SequenceMetaData seqmd = pmd.getSequences()[0]; assertEquals("SequenceGenerator has incorrect name", seqmd.getName(), "DepartmentGenerator"); assertEquals("SequenceGenerator has incorrect sequence name", seqmd.getDatastoreSequence(), "DEPT_SEQ"); assertEquals("SequenceGenerator has incorrect initial value", seqmd.getInitialValue(), 1); assertEquals("SequenceGenerator has incorrect allocation size", seqmd.getAllocationSize(), 50); } /** * Test of basic JPA @EmbeddedId. */ public void testEmbeddedId() { NucleusContext nucleusCtx = new PersistenceNucleusContextImpl("JPA", null); MetaDataManager metaDataMgr = new JPAMetaDataManager(nucleusCtx); // Retrieve the metadata from the MetaDataManager (populates and initialises everything) ClassLoaderResolver clr = new ClassLoaderResolverImpl(); ClassMetaData cmd1 = (ClassMetaData)metaDataMgr.getMetaDataForClass(Department.class.getName(), clr); assertEquals(1, cmd1.getNoOfPrimaryKeyMembers()); } /** * Test of JPA @Embeddable. */ public void testEmbeddable() { NucleusContext nucleusCtx = new PersistenceNucleusContextImpl("JPA", null); MetaDataManager metaDataMgr = new JPAMetaDataManager(nucleusCtx); // Retrieve the metadata from the MetaDataManager (populates and initialises everything) ClassLoaderResolver clr = new ClassLoaderResolverImpl(); ClassMetaData cmd1 = (ClassMetaData)metaDataMgr.getMetaDataForClass(DepartmentPK.class.getName(), clr); assertNotNull(cmd1); } /** * Test of JPA Byte[] is embedded by default */ public void testByteArrayEmbeddedByDefault() { NucleusContext nucleusCtx = new PersistenceNucleusContextImpl("JPA", null); MetaDataManager metaDataMgr = new JPAMetaDataManager(nucleusCtx); // Retrieve the metadata from the MetaDataManager (populates and initialises everything) ClassLoaderResolver clr = new ClassLoaderResolverImpl(); ClassMetaData cmd1 = (ClassMetaData)metaDataMgr.getMetaDataForClass(ByteArray.class.getName(), clr); assertTrue(cmd1.getMetaDataForMember("array1").isEmbedded()); } /** * Test of JPA column length */ public void testColumnLength() { NucleusContext nucleusCtx = new PersistenceNucleusContextImpl("JPA", null); MetaDataManager metaDataMgr = new JPAMetaDataManager(nucleusCtx); // Retrieve the metadata from the MetaDataManager (populates and initialises everything) ClassLoaderResolver clr = new ClassLoaderResolverImpl(); ClassMetaData cmd1 = (ClassMetaData)metaDataMgr.getMetaDataForClass(Printer.class.getName(), clr); AbstractMemberMetaData fmd = cmd1.getMetaDataForMember("make"); assertEquals(fmd.getColumnMetaData().length, 1); assertEquals(fmd.getColumnMetaData()[0].getName(), "MAKE"); assertEquals(40, fmd.getColumnMetaData()[0].getLength().intValue()); } /** * Test of EventListeners */ public void testEventListeners() { NucleusContext nucleusCtx = new PersistenceNucleusContextImpl("JPA", null); ClassLoaderResolver clr = nucleusCtx.getClassLoaderResolver(null); MetaDataManager metaDataMgr = new JPAMetaDataManager(nucleusCtx); PersistenceUnitMetaData pumd = getMetaDataForPersistenceUnit(nucleusCtx, "JPATest"); metaDataMgr.loadPersistenceUnit(pumd, null); ClassMetaData cmd1 = (ClassMetaData)metaDataMgr.getMetaDataForClass(WebSite.class.getName(), clr); // Example callbacks EventListenerMetaData elmd = cmd1.getListenerForClass(cmd1.getFullClassName()); assertNotNull("Site didnt have its own class registered as an EventListener!", elmd); assertEquals("Site EventListener has incorrect method for prePersist callback", elmd.getClassName() + ".prePersist", elmd.getMethodNameForCallbackClass(PrePersist.class.getName())); assertEquals("Site EventListener has incorrect method for postPersist callback", elmd.getClassName() + ".postPersist", elmd.getMethodNameForCallbackClass(PostPersist.class.getName())); assertEquals("Site EventListener has incorrect method for postPersist callback", elmd.getClassName() + ".load", elmd.getMethodNameForCallbackClass(PostLoad.class.getName())); assertNull(elmd.getMethodNameForCallbackClass(PreRemove.class.getName())); // Example listener elmd = cmd1.getListenerForClass(MyListener.class.getName()); assertNotNull("Site didnt have MyListener registered as an EventListener!", elmd); assertEquals("Site EventListener has incorrect method for prePersist callback", elmd.getClassName() + ".register", elmd.getMethodNameForCallbackClass(PostPersist.class.getName())); assertEquals("Site EventListener has incorrect method for postPersist callback", elmd.getClassName() + ".deregister", elmd.getMethodNameForCallbackClass(PreRemove.class.getName())); assertNull(elmd.getMethodNameForCallbackClass(PrePersist.class.getName())); } /** * Test of MappedSuperclass */ public void testMappedSuperclass() { NucleusContext nucleusCtx = new PersistenceNucleusContextImpl("JPA", null); ClassLoaderResolver clr = nucleusCtx.getClassLoaderResolver(null); MetaDataManager metaDataMgr = new JPAMetaDataManager(nucleusCtx); PersistenceUnitMetaData pumd = getMetaDataForPersistenceUnit(nucleusCtx, "JPATest"); metaDataMgr.loadPersistenceUnit(pumd, null); // AbstractSimpleBase ClassMetaData cmd = (ClassMetaData)metaDataMgr.getMetaDataForClass(AbstractSimpleBase.class.getName(), clr); assertNotNull("No MetaData found for AbstractSimpleBase yet is MappedSuperclass", cmd); assertNotNull("No Inheritance info found for AbstractSimpleBase", cmd.getInheritanceMetaData()); assertEquals("Inheritance for AbstractSimpleBase is incorrect", "subclass-table", cmd.getInheritanceMetaData().getStrategy().toString()); AbstractMemberMetaData fmd = cmd.getMetaDataForMember("id"); assertNotNull("No field info found for AbstractSimpleBase.id", fmd); assertNotNull("No column info found for AbstractSimpleBase.id", fmd.getColumnMetaData()); assertEquals("Column name for AbstractSimpleBase.id is wrong", "ID", fmd.getColumnMetaData()[0].getName()); fmd = cmd.getMetaDataForMember("baseField"); assertNotNull("No field info found for AbstractSimpleBase.baseField", fmd); assertNotNull("No column info found for AbstractSimpleBase.baseField", fmd.getColumnMetaData()); assertEquals("Column name for Product.baseField is wrong", "BASE_FIELD", fmd.getColumnMetaData()[0].getName()); // ConcreteSimpleSub1 cmd = (ClassMetaData)metaDataMgr.getMetaDataForClass(ConcreteSimpleSub1.class.getName(), clr); assertNotNull("No MetaData found for ConcreteSimpleSub1 yet is Entity", cmd); assertNotNull("No Inheritance info found for ConcreteSimpleSub1", cmd.getInheritanceMetaData()); assertEquals("Inheritance for ConcreteSimpleSub1 is incorrect", "new-table", cmd.getInheritanceMetaData().getStrategy().toString()); fmd = cmd.getOverriddenMember("baseField"); assertNotNull("No overridden field info found for ConcreteSimpleSub1.baseField", fmd); assertNotNull("No column info found for ConcreteSimpleSub1.baseField", fmd.getColumnMetaData()); assertEquals("Column name for ConcreteSimpleSub1.baseField is wrong", "BASE_FIELD_OR", fmd.getColumnMetaData()[0].getName()); fmd = cmd.getMetaDataForMember("sub1Field"); assertNotNull("No field info found for ConcreteSimpleSub1.sub1Field", fmd); assertNotNull("No column info found for ConcreteSimpleSub1.sub1Field", fmd.getColumnMetaData()); assertEquals("Column name for ConcreteSimpleSub1.sub1Field is wrong", "SUB1_FIELD", fmd.getColumnMetaData()[0].getName()); // ConcreteSimpleSub2 cmd = (ClassMetaData)metaDataMgr.getMetaDataForClass(ConcreteSimpleSub2.class.getName(), clr); assertNotNull("No MetaData found for ConcreteSimpleSub2 yet is Entity", cmd); assertNotNull("No Inheritance info found for ConcreteSimpleSub2", cmd.getInheritanceMetaData()); assertEquals("Inheritance for ConcreteSimpleSub2 is incorrect", "new-table", cmd.getInheritanceMetaData().getStrategy().toString()); fmd = cmd.getOverriddenMember("baseField"); assertNull("Overridden field info found for ConcreteSimpleSub2.baseField!", fmd); fmd = cmd.getMetaDataForMember("sub2Field"); assertNotNull("No overridden field info found for ConcreteSimpleSub2.sub2Field", fmd); assertNotNull("No column info found for ConcreteSimpleSub2.sub2Field", fmd.getColumnMetaData()); assertEquals("Column name for ConcreteSimpleSub2.sub2Field is wrong", "SUB2_FIELD", fmd.getColumnMetaData()[0].getName()); } /** * Test of JPA @NamedQuery, @NamedNativeQuery. */ public void testNamedQuery() { NucleusContext nucleusCtx = new PersistenceNucleusContextImpl("JPA", null); ClassLoaderResolver clr = nucleusCtx.getClassLoaderResolver(null); MetaDataManager metaDataMgr = new JPAMetaDataManager(nucleusCtx); PersistenceUnitMetaData pumd = getMetaDataForPersistenceUnit(nucleusCtx, "JPATest"); metaDataMgr.loadPersistenceUnit(pumd, null); ClassMetaData cmd = (ClassMetaData)metaDataMgr.getMetaDataForClass(LoginAccount.class.getName(), clr); QueryMetaData[] qmds = cmd.getQueries(); assertNotNull("LoginAccount has no queries!", qmds); assertEquals("LoginAccount has incorrect number of queries", 2, qmds.length); QueryMetaData jpqlQuery = null; QueryMetaData sqlQuery = null; if (qmds[0].getLanguage().equals(QueryLanguage.JPQL.toString())) { jpqlQuery = qmds[0]; } else if (qmds[1].getLanguage().equals(QueryLanguage.JPQL.toString())) { jpqlQuery = qmds[1]; } if (qmds[0].getLanguage().equals(QueryLanguage.SQL.toString())) { sqlQuery = qmds[0]; } else if (qmds[1].getLanguage().equals(QueryLanguage.SQL.toString())) { sqlQuery = qmds[1]; } if (jpqlQuery == null) { fail("No JPQL Query was registered for LoginAccount"); } if (sqlQuery == null) { fail("No SQL Query was registered for LoginAccount"); } assertEquals("LoginAccount JPQL has incorrect query name", "LoginForJohnSmith", jpqlQuery.getName()); assertEquals("LoginAccount JPQL has incorrect query", "SELECT a FROM LoginAccount a WHERE a.firstName='John' AND a.lastName='Smith'", jpqlQuery.getQuery()); assertEquals("LoginAccount SQL has incorrect query name", "LoginForJohn", sqlQuery.getName()); assertEquals("LoginAccount SQL has incorrect query", "SELECT * FROM JPA_AN_LOGIN WHERE FIRSTNAME = 'John'", sqlQuery.getQuery()); } /** * Test of JPA @SqlResultSetMapping */ public void testSqlResultSetMapping() { NucleusContext nucleusCtx = new PersistenceNucleusContextImpl("JPA", null); ClassLoaderResolver clr = nucleusCtx.getClassLoaderResolver(null); MetaDataManager metaDataMgr = new JPAMetaDataManager(nucleusCtx); PersistenceUnitMetaData pumd = getMetaDataForPersistenceUnit(nucleusCtx, "JPATest"); metaDataMgr.loadPersistenceUnit(pumd, null); ClassMetaData cmd = (ClassMetaData)metaDataMgr.getMetaDataForClass(LoginAccount.class.getName(), clr); QueryResultMetaData[] queryResultMappings = cmd.getQueryResultMetaData(); assertNotNull("LoginAccount has no QueryResultMetaData!", queryResultMappings); assertEquals("LoginAccount has incorrect number of query result mappings", 4, queryResultMappings.length); // Example 1 : Returning 2 entities QueryResultMetaData qrmd = null; for (int i=0;i<queryResultMappings.length;i++) { QueryResultMetaData md = queryResultMappings[i]; if (md.getName().equals("AN_LOGIN_PLUS_ACCOUNT")) { qrmd = md; break; } } if (qrmd == null) { fail("SQL ResultSet mapping AN_LOGIN_PLUS_ACCOUNT is not present!"); } String[] scalarCols = qrmd.getScalarColumns(); assertNull("LoginAccount sql mapping has incorrect scalar cols", scalarCols); PersistentTypeMapping[] sqlMappingEntities = qrmd.getPersistentTypeMappings(); assertNotNull("LoginAccount sql mapping has incorrect entities", sqlMappingEntities); assertEquals("LoginAccount sql mapping has incorrect number of entities", 2, sqlMappingEntities.length); // LoginAccount assertEquals("LoginAccount sql mapping entity 0 has incorrect class", LoginAccount.class.getName(), sqlMappingEntities[0].getClassName()); assertNull("LoginAccount sql mapping entity 0 has incorrect discriminator", sqlMappingEntities[0].getDiscriminatorColumn()); // Login assertEquals("LoginAccount sql mapping entity 1 has incorrect class", Login.class.getName(), sqlMappingEntities[1].getClassName()); assertNull("LoginAccount sql mapping entity 1 has incorrect discriminator", sqlMappingEntities[1].getDiscriminatorColumn()); // Example 2 : Returning 2 scalars qrmd = null; for (int i=0;i<queryResultMappings.length;i++) { QueryResultMetaData md = queryResultMappings[i]; if (md.getName().equals("AN_ACCOUNT_NAMES")) { qrmd = md; break; } } if (qrmd == null) { fail("SQL ResultSet mapping AN_ACCOUNT_NAMES is not present!"); } scalarCols = qrmd.getScalarColumns(); assertNotNull("LoginAccount sql mapping has incorrect scalar cols", scalarCols); assertEquals("LoginAccount sql mapping has incorrect column name", "FIRSTNAME", scalarCols[0]); assertEquals("LoginAccount sql mapping has incorrect column name", "LASTNAME", scalarCols[1]); sqlMappingEntities = qrmd.getPersistentTypeMappings(); assertNull("LoginAccount sql mapping has incorrect entities", sqlMappingEntities); } /** * Test for use of annotations for secondary tables, in particular @SecondaryTable. * Uses Printer class, storing some fields in table "PRINTER" and some in "PRINTER_TONER". */ public void testSecondaryTable() { NucleusContext nucleusCtx = new PersistenceNucleusContextImpl("JPA", null); MetaDataManager metaDataMgr = new JPAMetaDataManager(nucleusCtx); ClassLoaderResolver clr = new ClassLoaderResolverImpl(); ClassMetaData cmd = (ClassMetaData)metaDataMgr.getMetaDataForClass(Printer.class.getName(), clr); assertEquals("detachable is wrong", cmd.isDetachable(), true); assertEquals("identity-type is wrong", cmd.getIdentityType(), IdentityType.APPLICATION); assertEquals("embedded-only is wrong", cmd.isEmbeddedOnly(), false); assertEquals("requires-extent is wrong", cmd.isRequiresExtent(), true); assertNull("catalog is wrong", cmd.getCatalog()); assertNull("schema is wrong", cmd.getSchema()); assertEquals("table is wrong", cmd.getTable(), "JPA_AN_PRINTER"); assertEquals("has incorrect number of persistent fields", cmd.getNoOfManagedMembers(), 5); // Check JoinMetaData at class-level List<JoinMetaData> joinmds = cmd.getJoinMetaData(); assertNotNull("JoinMetaData at class-level is null!", joinmds); assertEquals("Number of JoinMetaData at class-level is wrong!", joinmds.size(), 1); assertEquals("Table of JoinMetaData at class-level is wrong", "JPA_AN_PRINTER_TONER", joinmds.get(0).getTable()); ColumnMetaData[] joinColmds = joinmds.get(0).getColumnMetaData(); assertEquals("Number of columns with MetaData in secondary table is incorrect", 1, joinColmds.length); assertEquals("Column of JoinMetaData at class-level is wrong", joinColmds[0].getName(), "PRINTER_ID"); // "model" (stored in primary-table) AbstractMemberMetaData fmd = cmd.getMetaDataForMember("model"); assertNotNull("Doesnt have required field", fmd); assertNull("Field 'model' has non-null table!", fmd.getTable()); // "tonerModel" (stored in secondary-table) fmd = cmd.getMetaDataForMember("tonerModel"); assertNotNull("Doesnt have required field", fmd); assertEquals("Field 'tonerModel' has non-null table!", fmd.getTable(), "JPA_AN_PRINTER_TONER"); } /** * Test of JPA enumerated JDBC type. */ public void testEnumeratedJDBCType() { NucleusContext nucleusCtx = new PersistenceNucleusContextImpl("JPA", null); MetaDataManager metaDataMgr = new JPAMetaDataManager(nucleusCtx); ClassLoaderResolver clr = new ClassLoaderResolverImpl(); ClassMetaData cmd1 = (ClassMetaData)metaDataMgr.getMetaDataForClass(EnumHolder.class.getName(), clr); AbstractMemberMetaData mmd1 = cmd1.getMetaDataForMember("colour1"); assertEquals(JdbcType.INTEGER, mmd1.getColumnMetaData()[0].getJdbcType()); assertEquals(FieldPersistenceModifier.PERSISTENT, mmd1.getPersistenceModifier()); AbstractMemberMetaData mmd2 = cmd1.getMetaDataForMember("colour2"); assertEquals(JdbcType.VARCHAR, mmd2.getColumnMetaData()[0].getJdbcType()); assertEquals(FieldPersistenceModifier.PERSISTENT, mmd2.getPersistenceModifier()); } /** * Test of string length default to JPA default 255. */ public void testStringLength() { NucleusContext nucleusCtx = new PersistenceNucleusContextImpl("JPA", null); MetaDataManager metaDataMgr = new JPAMetaDataManager(nucleusCtx); ClassLoaderResolver clr = new ClassLoaderResolverImpl(); ClassMetaData cmd1 = (ClassMetaData)metaDataMgr.getMetaDataForClass(Account.class.getName(), clr); AbstractMemberMetaData mmd1 = cmd1.getMetaDataForMember("username"); assertNull(mmd1.getColumnMetaData()[0].getLength()); } /** * Test of char length default to 1 with JPA. */ public void testCharDefaultTo1Length() { NucleusContext nucleusCtx = new PersistenceNucleusContextImpl("JPA", null); MetaDataManager metaDataMgr = new JPAMetaDataManager(nucleusCtx); ClassLoaderResolver clr = new ClassLoaderResolverImpl(); ClassMetaData cmd1 = (ClassMetaData)metaDataMgr.getMetaDataForClass(TypeHolder.class.getName(), clr); assertEquals(1, cmd1.getMetaDataForMember("char1").getColumnMetaData()[0].getLength().intValue()); } /** * Test of @OrderBy. */ public void testOrderBy() { NucleusContext nucleusCtx = new PersistenceNucleusContextImpl("JPA", null); MetaDataManager metaDataMgr = new JPAMetaDataManager(nucleusCtx); ClassLoaderResolver clr = new ClassLoaderResolverImpl(); ClassMetaData cmd1 = (ClassMetaData)metaDataMgr.getMetaDataForClass(UserGroup.class.getName(), clr); OrderMetaData omd = cmd1.getMetaDataForMember("members").getOrderMetaData(); assertNotNull("UserGroup.members has no OrderMetaData!", omd); FieldOrder[] orderTerms = omd.getFieldOrders(); assertFalse("UserGroup.members is not marked as using an ordered list", omd.isIndexedList()); assertNotNull("UserGroup.members has null field ordering info", orderTerms); assertEquals("UserGroup.members has incorrect number of field ordering terms", orderTerms.length, 1); assertEquals("UserGroup.members has incorrect field ordering field-name", orderTerms[0].getFieldName(), "name"); assertTrue("UserGroup.members has incorrect field ordering direction", orderTerms[0].isForward()); } /** * Test of JPA @IdClass with pk using acessors. */ public void testIdClassAccessors() { NucleusContext nucleusCtx = new PersistenceNucleusContextImpl("JPA", null); MetaDataManager metaDataMgr = new JPAMetaDataManager(nucleusCtx); ClassLoaderResolver clr = new ClassLoaderResolverImpl(); ClassMetaData cmd1 = (ClassMetaData)metaDataMgr.getMetaDataForClass(IdClassAccessors.class.getName(), clr); assertEquals(1, cmd1.getNoOfPrimaryKeyMembers()); assertTrue(cmd1.getAbsolutePositionOfMember("free")>=0); assertEquals("FFFF",cmd1.getMetaDataForManagedMemberAtAbsolutePosition(cmd1.getRelativePositionOfMember("free")).getColumnMetaData()[0].getName()); } /** * Test of persistent properties using annotations. */ /*public void testPersistentProperties() { NucleusContext nucleusCtx = new NucleusContext("JPA", null); MetaDataManager metaDataMgr = new JPAMetaDataManager(nucleusCtx); // Retrieve the metadata from the MetaDataManager (populates and initialises everything) ClassLoaderResolver clr = new ClassLoaderResolverImpl(); ClassMetaData cmd1 = (ClassMetaData)metaDataMgr.getMetaDataForClass(JPAGetter.class.getName(), clr); assertEquals(1, cmd1.getNoOfPrimaryKeyMembers()); }*/ /** * Test of column name for property instead of field */ /*public void testPropertyColumName() { NucleusContext nucleusCtx = new NucleusContext("JPA", null); MetaDataManager metaDataMgr = new JPAMetaDataManager(nucleusCtx); // Retrieve the metadata from the MetaDataManager (populates and initialises everything) ClassLoaderResolver clr = new ClassLoaderResolverImpl(); ClassMetaData cmd1 = (ClassMetaData)metaDataMgr.getMetaDataForClass(Employee.class.getName(), clr); // it is valid according JPA to have property accessor instead of field accessors. property accessors are persistent while field not. assertNotNull("Employee.lastName has no field information", cmd1.getMetaDataForMember("lastName")); assertNotNull("Employee.lastName has no column information", cmd1.getMetaDataForMember("lastName").getColumnMetaData()); assertEquals("Employee.lastName has incorrect number of columns", 1, cmd1.getMetaDataForMember("lastName").getColumnMetaData().length); assertEquals("Employee.last has incorrect column spec", "LASTNAME", cmd1.getMetaDataForMember("lastName").getColumnMetaData()[0].getName()); ClassMetaData cmd2 = (ClassMetaData)metaDataMgr.getMetaDataForClass(Person.class.getName(), clr); // it is valid according JPA to have property accessor instead of field accessors. property accessors are persistent while field not. assertNotNull(cmd2.getMetaDataForMember("age")); assertNotNull("AGE_COL",cmd2.getMetaDataForMember("age").getColumnMetaData()[0].getName()); assertNotNull(cmd2.getMetaDataForMember("maidenName")); assertEquals(FieldPersistenceModifier.NONE,cmd2.getMetaDataForMember("_maidenName").getPersistenceModifier()); assertEquals(FieldPersistenceModifier.PERSISTENT,cmd2.getMetaDataForMember("maidenName").getPersistenceModifier()); }*/ /** * Test of JPA @MapKeyColumn. */ public void testMapKeyColumn() { NucleusContext nucleusCtx = new PersistenceNucleusContextImpl("JPA", null); MetaDataManager metaDataMgr = new JPAMetaDataManager(nucleusCtx); // Retrieve the metadata from the MetaDataManager (populates and initialises everything) ClassLoaderResolver clr = new ClassLoaderResolverImpl(); ClassMetaData cmd1 = (ClassMetaData)metaDataMgr.getMetaDataForClass(Person.class.getName(), clr); assertEquals("phoneNumbers_key1",cmd1.getMetaDataForMember("phoneNumbers").getKeyMetaData().getColumnMetaData()[0].getName()); } }
jpa/general/src/test/org/datanucleus/tests/metadata/AnnotationTest.java
/********************************************************************** Copyright (c) 2006 Andy Jefferson and others. 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. Contributors: ... **********************************************************************/ package org.datanucleus.tests.metadata; import java.util.List; import javax.persistence.PostLoad; import javax.persistence.PostPersist; import javax.persistence.PrePersist; import javax.persistence.PreRemove; import org.datanucleus.ClassLoaderResolver; import org.datanucleus.ClassLoaderResolverImpl; import org.datanucleus.NucleusContext; import org.datanucleus.PersistenceNucleusContextImpl; import org.datanucleus.api.jpa.metadata.JPAMetaDataManager; import org.datanucleus.metadata.AbstractMemberMetaData; import org.datanucleus.metadata.ClassMetaData; import org.datanucleus.metadata.ColumnMetaData; import org.datanucleus.metadata.ElementMetaData; import org.datanucleus.metadata.EventListenerMetaData; import org.datanucleus.metadata.FieldPersistenceModifier; import org.datanucleus.metadata.ValueGenerationStrategy; import org.datanucleus.metadata.IdentityType; import org.datanucleus.metadata.InheritanceMetaData; import org.datanucleus.metadata.InheritanceStrategy; import org.datanucleus.metadata.JdbcType; import org.datanucleus.metadata.JoinMetaData; import org.datanucleus.metadata.KeyMetaData; import org.datanucleus.metadata.MapMetaData; import org.datanucleus.metadata.MetaDataManager; import org.datanucleus.metadata.OrderMetaData; import org.datanucleus.metadata.PackageMetaData; import org.datanucleus.metadata.PersistenceUnitMetaData; import org.datanucleus.metadata.QueryLanguage; import org.datanucleus.metadata.QueryMetaData; import org.datanucleus.metadata.QueryResultMetaData; import org.datanucleus.metadata.RelationType; import org.datanucleus.metadata.SequenceMetaData; import org.datanucleus.metadata.TableGeneratorMetaData; import org.datanucleus.metadata.OrderMetaData.FieldOrder; import org.datanucleus.metadata.QueryResultMetaData.PersistentTypeMapping; import org.datanucleus.samples.annotations.abstractclasses.AbstractSimpleBase; import org.datanucleus.samples.annotations.abstractclasses.ConcreteSimpleSub1; import org.datanucleus.samples.annotations.abstractclasses.ConcreteSimpleSub2; import org.datanucleus.samples.annotations.array.ByteArray; import org.datanucleus.samples.annotations.idclass.IdClassAccessors; import org.datanucleus.samples.annotations.many_many.PetroleumCustomer; import org.datanucleus.samples.annotations.many_many.PetroleumSupplier; import org.datanucleus.samples.annotations.models.company.Account; import org.datanucleus.samples.annotations.models.company.Department; import org.datanucleus.samples.annotations.models.company.DepartmentPK; import org.datanucleus.samples.annotations.models.company.Employee; import org.datanucleus.samples.annotations.models.company.Manager; import org.datanucleus.samples.annotations.models.company.MyListener; import org.datanucleus.samples.annotations.models.company.Person; import org.datanucleus.samples.annotations.models.company.Project; import org.datanucleus.samples.annotations.models.company.WebSite; import org.datanucleus.samples.annotations.one_many.unidir_2.UserGroup; import org.datanucleus.samples.annotations.one_one.bidir.Boiler; import org.datanucleus.samples.annotations.one_one.bidir.Timer; import org.datanucleus.samples.annotations.one_one.unidir.Login; import org.datanucleus.samples.annotations.one_one.unidir.LoginAccount; import org.datanucleus.samples.annotations.secondarytable.Printer; import org.datanucleus.samples.annotations.types.basic.TypeHolder; import org.datanucleus.samples.annotations.types.enums.EnumHolder; import org.datanucleus.tests.JPAPersistenceTestCase; /** * Tests for the use of JPA annotations and the generation of internal JPOX metadata. */ public class AnnotationTest extends JPAPersistenceTestCase { public AnnotationTest(String name) { super(name); } /** * Test of basic JPA annotations reading capability */ public void testBasic() { NucleusContext nucleusCtx = new PersistenceNucleusContextImpl("JPA", null); MetaDataManager metaDataMgr = new JPAMetaDataManager(nucleusCtx); ClassLoaderResolver clr = new ClassLoaderResolverImpl(); // Checks for Department ClassMetaData cmd1 = (ClassMetaData)metaDataMgr.getMetaDataForClass(Department.class.getName(), clr); String prefix = cmd1.getFullClassName() + " : "; assertEquals(prefix + "detachable is wrong", cmd1.isDetachable(), true); assertEquals(prefix + "identity-type is wrong", cmd1.getIdentityType(), IdentityType.APPLICATION); assertEquals(prefix + "embedded-only is wrong", cmd1.isEmbeddedOnly(), false); assertEquals(prefix + "requires-extent is wrong", cmd1.isRequiresExtent(), true); assertEquals(prefix + "catalog is wrong", cmd1.getCatalog(), null); assertEquals(prefix + "schema is wrong", cmd1.getSchema(), null); assertEquals(prefix + "table is wrong", cmd1.getTable(), "JPA_AN_DEPARTMENT"); assertEquals(prefix + "has incorrect number of persistent fields", cmd1.getNoOfManagedMembers(), 4); InheritanceMetaData inhmd1 = cmd1.getInheritanceMetaData(); assertEquals("Inheritance strategy is incorrect", InheritanceStrategy.NEW_TABLE, inhmd1.getStrategy()); // "projects" AbstractMemberMetaData fmd = cmd1.getMetaDataForMember("projects"); assertNotNull(prefix + "doesnt have required field", fmd); assertEquals(prefix + "should be persistent", fmd.getPersistenceModifier(), FieldPersistenceModifier.PERSISTENT); assertFalse(prefix + "pk is wrong", fmd.isPrimaryKey()); assertFalse(prefix + "dfg is wrong", fmd.isDefaultFetchGroup()); assertTrue(prefix + "has no container specified!", fmd.getCollection() != null); assertEquals(prefix + "should have collection of Project elements but hasnt", fmd.getCollection().getElementType(), Project.class.getName()); assertEquals(prefix + "shouldnt have collection of serialised elements but has", fmd.getCollection().isSerializedElement(), false); assertEquals(prefix + "shouldnt have collection of dependent elements but has", fmd.getCollection().isDependentElement(), false); // Checks for Project ClassMetaData cmd2 = (ClassMetaData)metaDataMgr.getMetaDataForClass(Project.class.getName(), clr); prefix = cmd2.getFullClassName() + " : "; assertEquals(prefix + "detachable is wrong", true, cmd2.isDetachable()); assertEquals(prefix + "identity-type is wrong", cmd2.getIdentityType(), IdentityType.APPLICATION); assertEquals(prefix + "objectid-class is wrong", "org.datanucleus.identity.StringId", cmd2.getObjectidClass()); assertEquals(prefix + "embedded-only is wrong", cmd2.isEmbeddedOnly(), false); assertEquals(prefix + "requires-extent is wrong", cmd2.isRequiresExtent(), true); assertEquals(prefix + "catalog is wrong", cmd2.getCatalog(), null); assertEquals(prefix + "schema is wrong", cmd2.getSchema(), null); assertEquals(prefix + "table is wrong", "JPA_AN_PROJECT", cmd2.getTable()); assertEquals(prefix + "has incorrect number of persistent fields", cmd2.getNoOfManagedMembers(), 2); InheritanceMetaData inhmd2 = cmd2.getInheritanceMetaData(); assertEquals("Inheritance strategy is incorrect", InheritanceStrategy.NEW_TABLE, inhmd2.getStrategy()); // "name" fmd = cmd2.getMetaDataForMember("name"); assertNotNull(prefix + "doesnt have required field", fmd); assertTrue(prefix + "pk is wrong", fmd.isPrimaryKey()); assertTrue(prefix + "dfg is wrong", fmd.isDefaultFetchGroup()); assertEquals(prefix + "should be persistent", fmd.getPersistenceModifier(), FieldPersistenceModifier.PERSISTENT); // "budget" fmd = cmd2.getMetaDataForMember("budget"); assertNotNull(prefix + "doesnt have required field", fmd); assertEquals(prefix + "has incorrect persistent field", fmd.getName(), "budget"); assertFalse(prefix + "pk is wrong", fmd.isPrimaryKey()); assertTrue(prefix + "dfg is wrong", fmd.isDefaultFetchGroup()); assertEquals(prefix + "should be persistent", fmd.getPersistenceModifier(), FieldPersistenceModifier.PERSISTENT); } /** * Test of JPA 1-1 unidir relation */ public void testOneToOneUni() { NucleusContext nucleusCtx = new PersistenceNucleusContextImpl("JPA", null); ClassLoaderResolver clr = nucleusCtx.getClassLoaderResolver(null); MetaDataManager metaDataMgr = new JPAMetaDataManager(nucleusCtx); PersistenceUnitMetaData pumd = getMetaDataForPersistenceUnit(nucleusCtx, "JPATest"); metaDataMgr.loadPersistenceUnit(pumd, null); ClassMetaData cmd1 = (ClassMetaData)metaDataMgr.getMetaDataForClass(LoginAccount.class.getName(), clr); assertEquals("LoginAccount has incorrect table name", cmd1.getTable(), "JPA_AN_LOGINACCOUNT"); AbstractMemberMetaData fmd1 = cmd1.getMetaDataForMember("login"); assertNotNull("LoginAccount.login is null!", fmd1); assertEquals("LoginAccount.login mapped-by is incorrect", fmd1.getMappedBy(), null); assertEquals("LoginAccount.login relationType is incorrect", fmd1.getRelationType(clr), RelationType.ONE_TO_ONE_UNI); assertNotNull("LoginAccount.login has no column info", fmd1.getColumnMetaData()); assertEquals("LoginAccount.login has incorrect number of columns", fmd1.getColumnMetaData().length, 1); assertEquals("LoginAccount.login column name is wrong", fmd1.getColumnMetaData()[0].getName(), "LOGIN_ID"); ClassMetaData cmd2 = (ClassMetaData)metaDataMgr.getMetaDataForClass(Login.class.getName(), clr); assertEquals("LoginAccount has incorrect table name", cmd2.getTable(), "JPA_AN_LOGIN"); } /** * Test of JPA 1-1 bidir relation */ public void testOneToOneBi() { NucleusContext nucleusCtx = new PersistenceNucleusContextImpl("JPA", null); ClassLoaderResolver clr = nucleusCtx.getClassLoaderResolver(null); MetaDataManager metaDataMgr = new JPAMetaDataManager(nucleusCtx); PersistenceUnitMetaData pumd = getMetaDataForPersistenceUnit(nucleusCtx, "JPATest"); metaDataMgr.loadPersistenceUnit(pumd, null); // non-owner side ClassMetaData cmd1 = (ClassMetaData)metaDataMgr.getMetaDataForClass(Boiler.class.getName(), clr); assertEquals("Boiler has incorrect table name", "JPA_AN_BOILER", cmd1.getTable()); AbstractMemberMetaData fmd1 = cmd1.getMetaDataForMember("timer"); assertNotNull("Boiler.timer is null!", fmd1); assertEquals("Boiler.timer mapped-by is incorrect", "boiler", fmd1.getMappedBy()); assertEquals("Boiler.timer relationType is incorrect", RelationType.ONE_TO_ONE_BI, fmd1.getRelationType(clr)); // owner side ClassMetaData cmd2 = (ClassMetaData)metaDataMgr.getMetaDataForClass(Timer.class.getName(), clr); assertEquals("Timer has incorrect table name", "JPA_AN_TIMER", cmd2.getTable()); AbstractMemberMetaData fmd2 = cmd2.getMetaDataForMember("boiler"); assertNotNull("Timer.boiler is null!", fmd2); assertEquals("Timer.boiler mapped-by is incorrect", null, fmd2.getMappedBy()); assertEquals("Timer.boiler relationType is incorrect", RelationType.ONE_TO_ONE_BI, fmd2.getRelationType(clr)); assertNotNull("Timer.boiler has no column info", fmd2.getColumnMetaData()); assertEquals("Timer.boiler has incorrect number of columns", 1, fmd2.getColumnMetaData().length); assertEquals("Timer.boiler column name is wrong", "BOILER_ID", fmd2.getColumnMetaData()[0].getName()); } /** * Test of JPA 1-N bidir FK relation */ public void testOneToManyBiFK() { NucleusContext nucleusCtx = new PersistenceNucleusContextImpl("JPA", null); ClassLoaderResolver clr = nucleusCtx.getClassLoaderResolver(null); MetaDataManager metaDataMgr = new JPAMetaDataManager(nucleusCtx); PersistenceUnitMetaData pumd = getMetaDataForPersistenceUnit(nucleusCtx, "JPATest"); metaDataMgr.loadPersistenceUnit(pumd, null); // owner side ClassMetaData cmd1 = (ClassMetaData)metaDataMgr.getMetaDataForClass(Manager.class.getName(), clr); AbstractMemberMetaData fmd1 = cmd1.getMetaDataForMember("departments"); assertNotNull("Manager.departments is null!", fmd1); assertEquals("Manager.departments mapped-by is incorrect", fmd1.getMappedBy(), "manager"); assertEquals("Manager.departments relationType is incorrect", fmd1.getRelationType(clr), RelationType.ONE_TO_MANY_BI); ElementMetaData elemmd = fmd1.getElementMetaData(); assertNull("Manager.departments has join column info but shouldnt (specified on N side)", elemmd); // non-owner side ClassMetaData cmd2 = (ClassMetaData)metaDataMgr.getMetaDataForClass(Department.class.getName(), clr); AbstractMemberMetaData fmd2 = cmd2.getMetaDataForMember("manager"); assertNotNull("Department.manager is null!", fmd2); assertEquals("Department.manager mapped-by is incorrect", fmd2.getMappedBy(), null); assertEquals("Department.manager relationType is incorrect", fmd2.getRelationType(clr), RelationType.MANY_TO_ONE_BI); ColumnMetaData[] colmds = fmd2.getColumnMetaData(); assertNotNull("Department.manager has no join column info", colmds); assertEquals("Department.manager has incorrect number of joincolumns", colmds.length, 1); assertEquals("Department.manager joincolumn name is wrong", "MGR_ID", colmds[0].getName()); } /** * Test of JPA 1-N unidir JoinTable relation */ public void testOneToManyUniJoin() { NucleusContext nucleusCtx = new PersistenceNucleusContextImpl("JPA", null); ClassLoaderResolver clr = nucleusCtx.getClassLoaderResolver(null); MetaDataManager metaDataMgr = new JPAMetaDataManager(nucleusCtx); PersistenceUnitMetaData pumd = getMetaDataForPersistenceUnit(nucleusCtx, "JPATest"); metaDataMgr.loadPersistenceUnit(pumd, null); // owner side ClassMetaData cmd1 = (ClassMetaData)metaDataMgr.getMetaDataForClass(Department.class.getName(), clr); AbstractMemberMetaData fmd1 = cmd1.getMetaDataForMember("projects"); assertNotNull("Department.projects is null!", fmd1); assertEquals("Department.projects mapped-by is incorrect", null, fmd1.getMappedBy()); assertEquals("Department.projects relationType is incorrect", RelationType.ONE_TO_MANY_UNI, fmd1.getRelationType(clr)); assertEquals("Department.projects jointable name is incorrect", "JPA_AN_DEPT_PROJECTS", fmd1.getTable()); JoinMetaData joinmd = fmd1.getJoinMetaData(); assertNotNull("Department.projects has no join table!", joinmd); assertNotNull("Department.projects has incorrect join columns", joinmd.getColumnMetaData()); assertEquals("Department.projects has incorrect number of join columns", 2, joinmd.getColumnMetaData().length); assertEquals("Department.projects has incorrect join column name", joinmd.getColumnMetaData()[0].getName(), "DEPT_ID"); assertEquals("Department.projects has incorrect join column name", joinmd.getColumnMetaData()[1].getName(), "DEPT_ID_STRING"); ElementMetaData elemmd = fmd1.getElementMetaData(); assertNotNull("Department.projects has no element column info but should", elemmd); ColumnMetaData[] colmds = elemmd.getColumnMetaData(); assertNotNull("Department.projects has incorrect element columns", colmds); assertEquals("Department.projects has incorrect number of element columns", 1, colmds.length); assertEquals("Department.projects has incorrect element column name", "PROJECT_ID", colmds[0].getName()); } /** * Test of JPA 1-N unidir FK relation. * Really is 1-N uni join since JPA doesnt support 1-N uni FK */ /*public void testOneToManyUniFK() { NucleusContext nucleusCtx = new NucleusContext(new PersistenceConfiguration(){}); nucleusCtx.setApi("JPA"); MetaDataManager metaDataMgr = new JPAMetaDataManager(nucleusCtx); ClassLoaderResolver clr = new ClassLoaderResolverImpl(); // owner side ClassMetaData cmd1 = (ClassMetaData)metaDataMgr.getMetaDataForClass(Site.class.getName(), clr); AbstractMemberMetaData fmd1 = cmd1.getMetaDataForMember("offices"); assertNotNull("Site.offices is null!", fmd1); assertEquals("Site.offices mapped-by is incorrect", fmd1.getMappedBy(), null); assertEquals("Site.offices relationType is incorrect", fmd1.getRelationType(clr), Relation.ONE_TO_MANY_UNI); assertEquals("Site.offices jointable name is incorrect", fmd1.getTable(), null); assertNotNull("Site.offices should have join but doesnt", fmd1.getJoinMetaData()); ElementMetaData elemmd = fmd1.getElementMetaData(); assertNotNull("Site.offices has no element column info but should", elemmd); ColumnMetaData[] colmds = elemmd.getColumnMetaData(); assertNotNull("Site.offices has incorrect element columns", colmds); assertEquals("Site.offices has incorrect number of element columns", colmds.length, 1); assertEquals("Site.offices has incorrect element column name", colmds[0].getName(), "SITE_ID"); }*/ /** * Test of JPA 1-N bidir join relation */ public void testOneToManyBiJoin() { NucleusContext nucleusCtx = new PersistenceNucleusContextImpl("JPA", null); ClassLoaderResolver clr = nucleusCtx.getClassLoaderResolver(null); MetaDataManager metaDataMgr = new JPAMetaDataManager(nucleusCtx); PersistenceUnitMetaData pumd = getMetaDataForPersistenceUnit(nucleusCtx, "JPATest"); metaDataMgr.loadPersistenceUnit(pumd, null); // owner side ClassMetaData cmd1 = (ClassMetaData)metaDataMgr.getMetaDataForClass(Manager.class.getName(), clr); assertEquals("Manager has incorrect table name", cmd1.getTable(), "JPA_AN_MANAGER"); AbstractMemberMetaData fmd1 = cmd1.getMetaDataForMember("subordinates"); assertNotNull("Manager.subordinates is null!", fmd1); assertEquals("Manager.subordinates mapped-by is incorrect", fmd1.getMappedBy(), "manager"); assertEquals("Manager.subordinates relationType is incorrect", fmd1.getRelationType(clr), RelationType.ONE_TO_MANY_BI); assertEquals("Manager.subordinates jointable name is incorrect", fmd1.getTable(), "JPA_AN_MGR_EMPLOYEES"); // non-owner side ClassMetaData cmd2 = (ClassMetaData)metaDataMgr.getMetaDataForClass(Employee.class.getName(), clr); assertEquals("Employee has incorrect table name", cmd2.getTable(), "JPA_AN_EMPLOYEE"); AbstractMemberMetaData fmd2 = cmd2.getMetaDataForMember("manager"); assertNotNull("Employee.manager is null!", fmd2); assertEquals("Employee.manager mapped-by is incorrect", fmd2.getMappedBy(), null); assertEquals("Employee.manager relationType is incorrect", fmd2.getRelationType(clr), RelationType.MANY_TO_ONE_BI); assertEquals("Employee.manager jointable name is incorrect", fmd2.getTable(), null); // join-table JoinMetaData joinmd = fmd1.getJoinMetaData(); assertNotNull("Manager.subordinates has no join table!", joinmd); assertNotNull("Manager.subordinates has incorrect join columns", joinmd.getColumnMetaData()); assertEquals("Manager.subordinates has incorrect number of join columns", 1, joinmd.getColumnMetaData().length); assertEquals("Manager.subordinates has incorrect owner join column name", "MGR_ID", joinmd.getColumnMetaData()[0].getName()); ElementMetaData elemmd = fmd1.getElementMetaData(); assertNotNull("Manager.subordinates has no element column info but should", elemmd); assertNotNull("Manager.subordinates has incorrect element columns", elemmd.getColumnMetaData()); assertEquals("Manager.subordinates has incorrect number of element columns", 1, elemmd.getColumnMetaData().length); assertEquals("Manager.subordinates has incorrect element join column name", "EMP_ID", elemmd.getColumnMetaData()[0].getName()); } /** * Test of JPA M-N relation */ public void testManyToMany() { NucleusContext nucleusCtx = new PersistenceNucleusContextImpl("JPA", null); ClassLoaderResolver clr = nucleusCtx.getClassLoaderResolver(null); MetaDataManager metaDataMgr = new JPAMetaDataManager(nucleusCtx); PersistenceUnitMetaData pumd = getMetaDataForPersistenceUnit(nucleusCtx, "JPATest"); metaDataMgr.loadPersistenceUnit(pumd, null); // owner side ClassMetaData cmd1 = (ClassMetaData)metaDataMgr.getMetaDataForClass(PetroleumCustomer.class.getName(), clr); assertEquals("Customer has incorrect table name", cmd1.getTable(), "JPA_AN_PETROL_CUSTOMER"); AbstractMemberMetaData fmd1 = cmd1.getMetaDataForMember("suppliers"); assertNotNull("Customer.suppliers is null!", fmd1); assertEquals("Customer.suppliers mapped-by is incorrect", fmd1.getMappedBy(), "customers"); assertEquals("Customer.suppliers relationType is incorrect", fmd1.getRelationType(clr), RelationType.MANY_TO_MANY_BI); assertEquals("Customer.suppliers jointable name is incorrect", fmd1.getTable(), "JPA_AN_PETROL_CUST_SUPP"); // non-owner side ClassMetaData cmd2 = (ClassMetaData)metaDataMgr.getMetaDataForClass(PetroleumSupplier.class.getName(), clr); assertEquals("Supplier has incorrect table name", cmd2.getTable(), "JPA_AN_PETROL_SUPPLIER"); AbstractMemberMetaData fmd2 = cmd2.getMetaDataForMember("customers"); assertNotNull("Supplier.customers is null!", fmd2); assertEquals("Supplier.customers mapped-by is incorrect", fmd2.getMappedBy(), null); assertEquals("Supplier.customers relationType is incorrect", fmd2.getRelationType(clr), RelationType.MANY_TO_MANY_BI); assertEquals("Supplier.customers jointable name is incorrect", fmd2.getTable(), null); // join table info JoinMetaData joinmd = fmd1.getJoinMetaData(); assertNotNull("Customer.suppliers has no join table!", joinmd); assertNotNull("Customer.suppliers has incorrect join columns", joinmd.getColumnMetaData()); assertEquals("Customer.suppliers has incorrect number of join columns", joinmd.getColumnMetaData().length, 1); assertEquals("Customer.suppliers has incorrect owner join column name", joinmd.getColumnMetaData()[0].getName(), "CUSTOMER_ID"); ElementMetaData elemmd = fmd1.getElementMetaData(); assertNotNull("Customer.suppliers has no element column info but should", elemmd); assertNotNull("Customer.suppliers has incorrect element columns", elemmd.getColumnMetaData()); assertEquals("Customer.suppliers has incorrect number of element columns", elemmd.getColumnMetaData().length, 1); assertEquals("Customer.suppliers has incorrect element join column name", elemmd.getColumnMetaData()[0].getName(), "SUPPLIER_ID"); } /** * Test of JPA 1-N unidir Map relation */ public void testOneToManyUniMapFK() { NucleusContext nucleusCtx = new PersistenceNucleusContextImpl("JPA", null); ClassLoaderResolver clr = nucleusCtx.getClassLoaderResolver(null); MetaDataManager metaDataMgr = new JPAMetaDataManager(nucleusCtx); PersistenceUnitMetaData pumd = getMetaDataForPersistenceUnit(nucleusCtx, "JPATest"); metaDataMgr.loadPersistenceUnit(pumd, null); // owner side ClassMetaData cmd1 = (ClassMetaData)metaDataMgr.getMetaDataForClass(Person.class.getName(), clr); AbstractMemberMetaData fmd1 = cmd1.getMetaDataForMember("phoneNumbers"); assertNotNull("Department.phoneNumbers is null!", fmd1); assertEquals("Department.phoneNumbers mapped-by is incorrect", fmd1.getMappedBy(), null); assertEquals("Department.phoneNumbers relationType is incorrect", fmd1.getRelationType(clr), RelationType.ONE_TO_MANY_UNI); assertEquals("Department.phoneNumbers jointable name is incorrect", fmd1.getTable(), null); MapMetaData mmd = fmd1.getMap(); assertNotNull("Department.phoneNumbers has no Map metadata!", mmd); KeyMetaData keymd = fmd1.getKeyMetaData(); assertNotNull("Department.phoneNumbers has no Key metadata!", keymd); assertEquals("Department.phoneNumbers has incorrect key mapped-by", keymd.getMappedBy(), "name"); } /** * Test of basic JPA @GeneratedValue. */ public void testGeneratedValue() { NucleusContext nucleusCtx = new PersistenceNucleusContextImpl("JPA", null); ClassLoaderResolver clr = nucleusCtx.getClassLoaderResolver(null); MetaDataManager metaDataMgr = new JPAMetaDataManager(nucleusCtx); // Retrieve the metadata from the MetaDataManager (populates and initialises everything) ClassMetaData cmd1 = (ClassMetaData)metaDataMgr.getMetaDataForClass(Account.class.getName(), clr); AbstractMemberMetaData fmd1 = cmd1.getMetaDataForMember("id"); assertNotNull("Account has no id field!", fmd1); assertEquals("Account has incorrect value strategy", fmd1.getValueStrategy(), ValueGenerationStrategy.INCREMENT); } /** * Test of basic JPA @TableGenerator */ public void testTableGenerator() { NucleusContext nucleusCtx = new PersistenceNucleusContextImpl("JPA", null); ClassLoaderResolver clr = nucleusCtx.getClassLoaderResolver(null); MetaDataManager metaDataMgr = new JPAMetaDataManager(nucleusCtx); PersistenceUnitMetaData pumd = getMetaDataForPersistenceUnit(nucleusCtx, "JPATest"); metaDataMgr.loadPersistenceUnit(pumd, null); ClassMetaData cmd1 = (ClassMetaData)metaDataMgr.getMetaDataForClass(Employee.class.getName(), clr); PackageMetaData pmd = cmd1.getPackageMetaData(); assertEquals("Number of TableGenerators registered for Employee class is wrong", pmd.getNoOfTableGenerators(), 1); TableGeneratorMetaData tgmd = pmd.getTableGenerators()[0]; assertEquals("TableGenerator has incorrect name", tgmd.getName(), "EmployeeGenerator"); assertEquals("TableGenerator has incorrect table", tgmd.getTableName(), "ID_TABLE"); assertEquals("TableGenerator has incorrect pk column name", tgmd.getPKColumnName(), "TYPE"); assertEquals("TableGenerator has incorrect value column name", tgmd.getValueColumnName(), "LATEST_VALUE"); assertEquals("TableGenerator has incorrect pk column value", tgmd.getPKColumnValue(), "EMPLOYEE"); assertEquals("TableGenerator has incorrect initial value", tgmd.getInitialValue(), 0); assertEquals("TableGenerator has incorrect allocation size", tgmd.getAllocationSize(), 50); } /** * Test of basic JPA @SequenceGenerator */ public void testSequenceGenerator() { NucleusContext nucleusCtx = new PersistenceNucleusContextImpl("JPA", null); ClassLoaderResolver clr = nucleusCtx.getClassLoaderResolver(null); MetaDataManager metaDataMgr = new JPAMetaDataManager(nucleusCtx); PersistenceUnitMetaData pumd = getMetaDataForPersistenceUnit(nucleusCtx, "JPATest"); metaDataMgr.loadPersistenceUnit(pumd, null); ClassMetaData cmd1 = (ClassMetaData)metaDataMgr.getMetaDataForClass(Department.class.getName(), clr); PackageMetaData pmd = cmd1.getPackageMetaData(); assertEquals("Number of Sequences registered for Department class is wrong", pmd.getNoOfSequences(), 1); SequenceMetaData seqmd = pmd.getSequences()[0]; assertEquals("SequenceGenerator has incorrect name", seqmd.getName(), "DepartmentGenerator"); assertEquals("SequenceGenerator has incorrect sequence name", seqmd.getDatastoreSequence(), "DEPT_SEQ"); assertEquals("SequenceGenerator has incorrect initial value", seqmd.getInitialValue(), 1); assertEquals("SequenceGenerator has incorrect allocation size", seqmd.getAllocationSize(), 50); } /** * Test of basic JPA @EmbeddedId. */ public void testEmbeddedId() { NucleusContext nucleusCtx = new PersistenceNucleusContextImpl("JPA", null); MetaDataManager metaDataMgr = new JPAMetaDataManager(nucleusCtx); // Retrieve the metadata from the MetaDataManager (populates and initialises everything) ClassLoaderResolver clr = new ClassLoaderResolverImpl(); ClassMetaData cmd1 = (ClassMetaData)metaDataMgr.getMetaDataForClass(Department.class.getName(), clr); assertEquals(1, cmd1.getNoOfPrimaryKeyMembers()); } /** * Test of JPA @Embeddable. */ public void testEmbeddable() { NucleusContext nucleusCtx = new PersistenceNucleusContextImpl("JPA", null); MetaDataManager metaDataMgr = new JPAMetaDataManager(nucleusCtx); // Retrieve the metadata from the MetaDataManager (populates and initialises everything) ClassLoaderResolver clr = new ClassLoaderResolverImpl(); ClassMetaData cmd1 = (ClassMetaData)metaDataMgr.getMetaDataForClass(DepartmentPK.class.getName(), clr); assertNotNull(cmd1); } /** * Test of JPA Byte[] is embedded by default */ public void testByteArrayEmbeddedByDefault() { NucleusContext nucleusCtx = new PersistenceNucleusContextImpl("JPA", null); MetaDataManager metaDataMgr = new JPAMetaDataManager(nucleusCtx); // Retrieve the metadata from the MetaDataManager (populates and initialises everything) ClassLoaderResolver clr = new ClassLoaderResolverImpl(); ClassMetaData cmd1 = (ClassMetaData)metaDataMgr.getMetaDataForClass(ByteArray.class.getName(), clr); assertTrue(cmd1.getMetaDataForMember("array1").isEmbedded()); } /** * Test of JPA column length */ public void testColumnLength() { NucleusContext nucleusCtx = new PersistenceNucleusContextImpl("JPA", null); MetaDataManager metaDataMgr = new JPAMetaDataManager(nucleusCtx); // Retrieve the metadata from the MetaDataManager (populates and initialises everything) ClassLoaderResolver clr = new ClassLoaderResolverImpl(); ClassMetaData cmd1 = (ClassMetaData)metaDataMgr.getMetaDataForClass(Printer.class.getName(), clr); AbstractMemberMetaData fmd = cmd1.getMetaDataForMember("make"); assertEquals(fmd.getColumnMetaData().length, 1); assertEquals(fmd.getColumnMetaData()[0].getName(), "MAKE"); assertEquals(40, fmd.getColumnMetaData()[0].getLength().intValue()); } /** * Test of EventListeners */ public void testEventListeners() { NucleusContext nucleusCtx = new PersistenceNucleusContextImpl("JPA", null); ClassLoaderResolver clr = nucleusCtx.getClassLoaderResolver(null); MetaDataManager metaDataMgr = new JPAMetaDataManager(nucleusCtx); PersistenceUnitMetaData pumd = getMetaDataForPersistenceUnit(nucleusCtx, "JPATest"); metaDataMgr.loadPersistenceUnit(pumd, null); ClassMetaData cmd1 = (ClassMetaData)metaDataMgr.getMetaDataForClass(WebSite.class.getName(), clr); // Example callbacks EventListenerMetaData elmd = cmd1.getListenerForClass(cmd1.getFullClassName()); assertNotNull("Site didnt have its own class registered as an EventListener!", elmd); assertEquals("Site EventListener has incorrect method for prePersist callback", elmd.getClassName() + ".prePersist", elmd.getMethodNameForCallbackClass(PrePersist.class.getName())); assertEquals("Site EventListener has incorrect method for postPersist callback", elmd.getClassName() + ".postPersist", elmd.getMethodNameForCallbackClass(PostPersist.class.getName())); assertEquals("Site EventListener has incorrect method for postPersist callback", elmd.getClassName() + ".load", elmd.getMethodNameForCallbackClass(PostLoad.class.getName())); assertNull(elmd.getMethodNameForCallbackClass(PreRemove.class.getName())); // Example listener elmd = cmd1.getListenerForClass(MyListener.class.getName()); assertNotNull("Site didnt have MyListener registered as an EventListener!", elmd); assertEquals("Site EventListener has incorrect method for prePersist callback", elmd.getClassName() + ".register", elmd.getMethodNameForCallbackClass(PostPersist.class.getName())); assertEquals("Site EventListener has incorrect method for postPersist callback", elmd.getClassName() + ".deregister", elmd.getMethodNameForCallbackClass(PreRemove.class.getName())); assertNull(elmd.getMethodNameForCallbackClass(PrePersist.class.getName())); } /** * Test of MappedSuperclass */ public void testMappedSuperclass() { NucleusContext nucleusCtx = new PersistenceNucleusContextImpl("JPA", null); ClassLoaderResolver clr = nucleusCtx.getClassLoaderResolver(null); MetaDataManager metaDataMgr = new JPAMetaDataManager(nucleusCtx); PersistenceUnitMetaData pumd = getMetaDataForPersistenceUnit(nucleusCtx, "JPATest"); metaDataMgr.loadPersistenceUnit(pumd, null); // AbstractSimpleBase ClassMetaData cmd = (ClassMetaData)metaDataMgr.getMetaDataForClass(AbstractSimpleBase.class.getName(), clr); assertNotNull("No MetaData found for AbstractSimpleBase yet is MappedSuperclass", cmd); assertNotNull("No Inheritance info found for AbstractSimpleBase", cmd.getInheritanceMetaData()); assertEquals("Inheritance for AbstractSimpleBase is incorrect", "subclass-table", cmd.getInheritanceMetaData().getStrategy().toString()); AbstractMemberMetaData fmd = cmd.getMetaDataForMember("id"); assertNotNull("No field info found for AbstractSimpleBase.id", fmd); assertNotNull("No column info found for AbstractSimpleBase.id", fmd.getColumnMetaData()); assertEquals("Column name for AbstractSimpleBase.id is wrong", "ID", fmd.getColumnMetaData()[0].getName()); fmd = cmd.getMetaDataForMember("baseField"); assertNotNull("No field info found for AbstractSimpleBase.baseField", fmd); assertNotNull("No column info found for AbstractSimpleBase.baseField", fmd.getColumnMetaData()); assertEquals("Column name for Product.baseField is wrong", "BASE_FIELD", fmd.getColumnMetaData()[0].getName()); // ConcreteSimpleSub1 cmd = (ClassMetaData)metaDataMgr.getMetaDataForClass(ConcreteSimpleSub1.class.getName(), clr); assertNotNull("No MetaData found for ConcreteSimpleSub1 yet is Entity", cmd); assertNotNull("No Inheritance info found for ConcreteSimpleSub1", cmd.getInheritanceMetaData()); assertEquals("Inheritance for ConcreteSimpleSub1 is incorrect", "new-table", cmd.getInheritanceMetaData().getStrategy().toString()); fmd = cmd.getOverriddenMember("baseField"); assertNotNull("No overridden field info found for ConcreteSimpleSub1.baseField", fmd); assertNotNull("No column info found for ConcreteSimpleSub1.baseField", fmd.getColumnMetaData()); assertEquals("Column name for ConcreteSimpleSub1.baseField is wrong", "BASE_FIELD_OR", fmd.getColumnMetaData()[0].getName()); fmd = cmd.getMetaDataForMember("sub1Field"); assertNotNull("No field info found for ConcreteSimpleSub1.sub1Field", fmd); assertNotNull("No column info found for ConcreteSimpleSub1.sub1Field", fmd.getColumnMetaData()); assertEquals("Column name for ConcreteSimpleSub1.sub1Field is wrong", "SUB1_FIELD", fmd.getColumnMetaData()[0].getName()); // ConcreteSimpleSub2 cmd = (ClassMetaData)metaDataMgr.getMetaDataForClass(ConcreteSimpleSub2.class.getName(), clr); assertNotNull("No MetaData found for ConcreteSimpleSub2 yet is Entity", cmd); assertNotNull("No Inheritance info found for ConcreteSimpleSub2", cmd.getInheritanceMetaData()); assertEquals("Inheritance for ConcreteSimpleSub2 is incorrect", "new-table", cmd.getInheritanceMetaData().getStrategy().toString()); fmd = cmd.getOverriddenMember("baseField"); assertNull("Overridden field info found for ConcreteSimpleSub2.baseField!", fmd); fmd = cmd.getMetaDataForMember("sub2Field"); assertNotNull("No overridden field info found for ConcreteSimpleSub2.sub2Field", fmd); assertNotNull("No column info found for ConcreteSimpleSub2.sub2Field", fmd.getColumnMetaData()); assertEquals("Column name for ConcreteSimpleSub2.sub2Field is wrong", "SUB2_FIELD", fmd.getColumnMetaData()[0].getName()); } /** * Test of JPA @NamedQuery, @NamedNativeQuery. */ public void testNamedQuery() { NucleusContext nucleusCtx = new PersistenceNucleusContextImpl("JPA", null); ClassLoaderResolver clr = nucleusCtx.getClassLoaderResolver(null); MetaDataManager metaDataMgr = new JPAMetaDataManager(nucleusCtx); PersistenceUnitMetaData pumd = getMetaDataForPersistenceUnit(nucleusCtx, "JPATest"); metaDataMgr.loadPersistenceUnit(pumd, null); ClassMetaData cmd = (ClassMetaData)metaDataMgr.getMetaDataForClass(LoginAccount.class.getName(), clr); QueryMetaData[] qmds = cmd.getQueries(); assertNotNull("LoginAccount has no queries!", qmds); assertEquals("LoginAccount has incorrect number of queries", 2, qmds.length); QueryMetaData jpqlQuery = null; QueryMetaData sqlQuery = null; if (qmds[0].getLanguage().equals(QueryLanguage.JPQL.toString())) { jpqlQuery = qmds[0]; } else if (qmds[1].getLanguage().equals(QueryLanguage.JPQL.toString())) { jpqlQuery = qmds[1]; } if (qmds[0].getLanguage().equals(QueryLanguage.SQL.toString())) { sqlQuery = qmds[0]; } else if (qmds[1].getLanguage().equals(QueryLanguage.SQL.toString())) { sqlQuery = qmds[1]; } if (jpqlQuery == null) { fail("No JPQL Query was registered for LoginAccount"); } if (sqlQuery == null) { fail("No SQL Query was registered for LoginAccount"); } assertEquals("LoginAccount JPQL has incorrect query name", "LoginForJohnSmith", jpqlQuery.getName()); assertEquals("LoginAccount JPQL has incorrect query", "SELECT a FROM LoginAccount a WHERE a.firstName='John' AND a.lastName='Smith'", jpqlQuery.getQuery()); assertEquals("LoginAccount SQL has incorrect query name", "LoginForJohn", sqlQuery.getName()); assertEquals("LoginAccount SQL has incorrect query", "SELECT * FROM JPA_AN_LOGIN WHERE FIRSTNAME = 'John'", sqlQuery.getQuery()); } /** * Test of JPA @SqlResultSetMapping */ public void testSqlResultSetMapping() { NucleusContext nucleusCtx = new PersistenceNucleusContextImpl("JPA", null); ClassLoaderResolver clr = nucleusCtx.getClassLoaderResolver(null); MetaDataManager metaDataMgr = new JPAMetaDataManager(nucleusCtx); PersistenceUnitMetaData pumd = getMetaDataForPersistenceUnit(nucleusCtx, "JPATest"); metaDataMgr.loadPersistenceUnit(pumd, null); ClassMetaData cmd = (ClassMetaData)metaDataMgr.getMetaDataForClass(LoginAccount.class.getName(), clr); QueryResultMetaData[] queryResultMappings = cmd.getQueryResultMetaData(); assertNotNull("LoginAccount has no QueryResultMetaData!", queryResultMappings); assertEquals("LoginAccount has incorrect number of query result mappings", 4, queryResultMappings.length); // Example 1 : Returning 2 entities QueryResultMetaData qrmd = null; for (int i=0;i<queryResultMappings.length;i++) { QueryResultMetaData md = queryResultMappings[i]; if (md.getName().equals("AN_LOGIN_PLUS_ACCOUNT")) { qrmd = md; break; } } if (qrmd == null) { fail("SQL ResultSet mapping AN_LOGIN_PLUS_ACCOUNT is not present!"); } String[] scalarCols = qrmd.getScalarColumns(); assertNull("LoginAccount sql mapping has incorrect scalar cols", scalarCols); PersistentTypeMapping[] sqlMappingEntities = qrmd.getPersistentTypeMappings(); assertNotNull("LoginAccount sql mapping has incorrect entities", sqlMappingEntities); assertEquals("LoginAccount sql mapping has incorrect number of entities", 2, sqlMappingEntities.length); // LoginAccount assertEquals("LoginAccount sql mapping entity 0 has incorrect class", LoginAccount.class.getName(), sqlMappingEntities[0].getClassName()); assertNull("LoginAccount sql mapping entity 0 has incorrect discriminator", sqlMappingEntities[0].getDiscriminatorColumn()); // Login assertEquals("LoginAccount sql mapping entity 1 has incorrect class", Login.class.getName(), sqlMappingEntities[1].getClassName()); assertNull("LoginAccount sql mapping entity 1 has incorrect discriminator", sqlMappingEntities[1].getDiscriminatorColumn()); // Example 2 : Returning 2 scalars qrmd = null; for (int i=0;i<queryResultMappings.length;i++) { QueryResultMetaData md = queryResultMappings[i]; if (md.getName().equals("AN_ACCOUNT_NAMES")) { qrmd = md; break; } } if (qrmd == null) { fail("SQL ResultSet mapping AN_ACCOUNT_NAMES is not present!"); } scalarCols = qrmd.getScalarColumns(); assertNotNull("LoginAccount sql mapping has incorrect scalar cols", scalarCols); assertEquals("LoginAccount sql mapping has incorrect column name", "FIRSTNAME", scalarCols[0]); assertEquals("LoginAccount sql mapping has incorrect column name", "LASTNAME", scalarCols[1]); sqlMappingEntities = qrmd.getPersistentTypeMappings(); assertNull("LoginAccount sql mapping has incorrect entities", sqlMappingEntities); } /** * Test for use of annotations for secondary tables, in particular @SecondaryTable. * Uses Printer class, storing some fields in table "PRINTER" and some in "PRINTER_TONER". */ public void testSecondaryTable() { NucleusContext nucleusCtx = new PersistenceNucleusContextImpl("JPA", null); MetaDataManager metaDataMgr = new JPAMetaDataManager(nucleusCtx); ClassLoaderResolver clr = new ClassLoaderResolverImpl(); ClassMetaData cmd = (ClassMetaData)metaDataMgr.getMetaDataForClass(Printer.class.getName(), clr); assertEquals("detachable is wrong", cmd.isDetachable(), true); assertEquals("identity-type is wrong", cmd.getIdentityType(), IdentityType.APPLICATION); assertEquals("embedded-only is wrong", cmd.isEmbeddedOnly(), false); assertEquals("requires-extent is wrong", cmd.isRequiresExtent(), true); assertNull("catalog is wrong", cmd.getCatalog()); assertNull("schema is wrong", cmd.getSchema()); assertEquals("table is wrong", cmd.getTable(), "JPA_AN_PRINTER"); assertEquals("has incorrect number of persistent fields", cmd.getNoOfManagedMembers(), 5); // Check JoinMetaData at class-level List<JoinMetaData> joinmds = cmd.getJoinMetaData(); assertNotNull("JoinMetaData at class-level is null!", joinmds); assertEquals("Number of JoinMetaData at class-level is wrong!", joinmds.size(), 1); assertEquals("Table of JoinMetaData at class-level is wrong", "JPA_AN_PRINTER_TONER", joinmds.get(0).getTable()); ColumnMetaData[] joinColmds = joinmds.get(0).getColumnMetaData(); assertEquals("Number of columns with MetaData in secondary table is incorrect", 1, joinColmds.length); assertEquals("Column of JoinMetaData at class-level is wrong", joinColmds[0].getName(), "PRINTER_ID"); // "model" (stored in primary-table) AbstractMemberMetaData fmd = cmd.getMetaDataForMember("model"); assertNotNull("Doesnt have required field", fmd); assertNull("Field 'model' has non-null table!", fmd.getTable()); // "tonerModel" (stored in secondary-table) fmd = cmd.getMetaDataForMember("tonerModel"); assertNotNull("Doesnt have required field", fmd); assertEquals("Field 'tonerModel' has non-null table!", fmd.getTable(), "JPA_AN_PRINTER_TONER"); } /** * Test of JPA enumerated JDBC type. */ public void testEnumeratedJDBCType() { NucleusContext nucleusCtx = new PersistenceNucleusContextImpl("JPA", null); MetaDataManager metaDataMgr = new JPAMetaDataManager(nucleusCtx); ClassLoaderResolver clr = new ClassLoaderResolverImpl(); ClassMetaData cmd1 = (ClassMetaData)metaDataMgr.getMetaDataForClass(EnumHolder.class.getName(), clr); AbstractMemberMetaData mmd1 = cmd1.getMetaDataForMember("colour1"); assertEquals(JdbcType.INTEGER, mmd1.getColumnMetaData()[0].getJdbcType()); assertEquals(FieldPersistenceModifier.PERSISTENT, mmd1.getPersistenceModifier()); AbstractMemberMetaData mmd2 = cmd1.getMetaDataForMember("colour2"); assertEquals(JdbcType.VARCHAR, mmd2.getColumnMetaData()[0].getJdbcType()); assertEquals(FieldPersistenceModifier.PERSISTENT, mmd2.getPersistenceModifier()); } /** * Test of string length default to JPA default 255. */ public void testStringLength() { NucleusContext nucleusCtx = new PersistenceNucleusContextImpl("JPA", null); MetaDataManager metaDataMgr = new JPAMetaDataManager(nucleusCtx); ClassLoaderResolver clr = new ClassLoaderResolverImpl(); ClassMetaData cmd1 = (ClassMetaData)metaDataMgr.getMetaDataForClass(Account.class.getName(), clr); AbstractMemberMetaData mmd1 = cmd1.getMetaDataForMember("username"); assertEquals(255, mmd1.getColumnMetaData()[0].getLength().intValue()); } /** * Test of char length default to 1 with JPA. */ public void testCharDefaultTo1Length() { NucleusContext nucleusCtx = new PersistenceNucleusContextImpl("JPA", null); MetaDataManager metaDataMgr = new JPAMetaDataManager(nucleusCtx); ClassLoaderResolver clr = new ClassLoaderResolverImpl(); ClassMetaData cmd1 = (ClassMetaData)metaDataMgr.getMetaDataForClass(TypeHolder.class.getName(), clr); assertEquals(1, cmd1.getMetaDataForMember("char1").getColumnMetaData()[0].getLength().intValue()); } /** * Test of @OrderBy. */ public void testOrderBy() { NucleusContext nucleusCtx = new PersistenceNucleusContextImpl("JPA", null); MetaDataManager metaDataMgr = new JPAMetaDataManager(nucleusCtx); ClassLoaderResolver clr = new ClassLoaderResolverImpl(); ClassMetaData cmd1 = (ClassMetaData)metaDataMgr.getMetaDataForClass(UserGroup.class.getName(), clr); OrderMetaData omd = cmd1.getMetaDataForMember("members").getOrderMetaData(); assertNotNull("UserGroup.members has no OrderMetaData!", omd); FieldOrder[] orderTerms = omd.getFieldOrders(); assertFalse("UserGroup.members is not marked as using an ordered list", omd.isIndexedList()); assertNotNull("UserGroup.members has null field ordering info", orderTerms); assertEquals("UserGroup.members has incorrect number of field ordering terms", orderTerms.length, 1); assertEquals("UserGroup.members has incorrect field ordering field-name", orderTerms[0].getFieldName(), "name"); assertTrue("UserGroup.members has incorrect field ordering direction", orderTerms[0].isForward()); } /** * Test of JPA @IdClass with pk using acessors. */ public void testIdClassAccessors() { NucleusContext nucleusCtx = new PersistenceNucleusContextImpl("JPA", null); MetaDataManager metaDataMgr = new JPAMetaDataManager(nucleusCtx); ClassLoaderResolver clr = new ClassLoaderResolverImpl(); ClassMetaData cmd1 = (ClassMetaData)metaDataMgr.getMetaDataForClass(IdClassAccessors.class.getName(), clr); assertEquals(1, cmd1.getNoOfPrimaryKeyMembers()); assertTrue(cmd1.getAbsolutePositionOfMember("free")>=0); assertEquals("FFFF",cmd1.getMetaDataForManagedMemberAtAbsolutePosition(cmd1.getRelativePositionOfMember("free")).getColumnMetaData()[0].getName()); } /** * Test of persistent properties using annotations. */ /*public void testPersistentProperties() { NucleusContext nucleusCtx = new NucleusContext("JPA", null); MetaDataManager metaDataMgr = new JPAMetaDataManager(nucleusCtx); // Retrieve the metadata from the MetaDataManager (populates and initialises everything) ClassLoaderResolver clr = new ClassLoaderResolverImpl(); ClassMetaData cmd1 = (ClassMetaData)metaDataMgr.getMetaDataForClass(JPAGetter.class.getName(), clr); assertEquals(1, cmd1.getNoOfPrimaryKeyMembers()); }*/ /** * Test of column name for property instead of field */ /*public void testPropertyColumName() { NucleusContext nucleusCtx = new NucleusContext("JPA", null); MetaDataManager metaDataMgr = new JPAMetaDataManager(nucleusCtx); // Retrieve the metadata from the MetaDataManager (populates and initialises everything) ClassLoaderResolver clr = new ClassLoaderResolverImpl(); ClassMetaData cmd1 = (ClassMetaData)metaDataMgr.getMetaDataForClass(Employee.class.getName(), clr); // it is valid according JPA to have property accessor instead of field accessors. property accessors are persistent while field not. assertNotNull("Employee.lastName has no field information", cmd1.getMetaDataForMember("lastName")); assertNotNull("Employee.lastName has no column information", cmd1.getMetaDataForMember("lastName").getColumnMetaData()); assertEquals("Employee.lastName has incorrect number of columns", 1, cmd1.getMetaDataForMember("lastName").getColumnMetaData().length); assertEquals("Employee.last has incorrect column spec", "LASTNAME", cmd1.getMetaDataForMember("lastName").getColumnMetaData()[0].getName()); ClassMetaData cmd2 = (ClassMetaData)metaDataMgr.getMetaDataForClass(Person.class.getName(), clr); // it is valid according JPA to have property accessor instead of field accessors. property accessors are persistent while field not. assertNotNull(cmd2.getMetaDataForMember("age")); assertNotNull("AGE_COL",cmd2.getMetaDataForMember("age").getColumnMetaData()[0].getName()); assertNotNull(cmd2.getMetaDataForMember("maidenName")); assertEquals(FieldPersistenceModifier.NONE,cmd2.getMetaDataForMember("_maidenName").getPersistenceModifier()); assertEquals(FieldPersistenceModifier.PERSISTENT,cmd2.getMetaDataForMember("maidenName").getPersistenceModifier()); }*/ /** * Test of JPA @MapKeyColumn. */ public void testMapKeyColumn() { NucleusContext nucleusCtx = new PersistenceNucleusContextImpl("JPA", null); MetaDataManager metaDataMgr = new JPAMetaDataManager(nucleusCtx); // Retrieve the metadata from the MetaDataManager (populates and initialises everything) ClassLoaderResolver clr = new ClassLoaderResolverImpl(); ClassMetaData cmd1 = (ClassMetaData)metaDataMgr.getMetaDataForClass(Person.class.getName(), clr); assertEquals("phoneNumbers_key1",cmd1.getMetaDataForMember("phoneNumbers").getKeyMetaData().getColumnMetaData()[0].getName()); } }
fix expectation
jpa/general/src/test/org/datanucleus/tests/metadata/AnnotationTest.java
fix expectation
<ide><path>pa/general/src/test/org/datanucleus/tests/metadata/AnnotationTest.java <ide> ClassLoaderResolver clr = new ClassLoaderResolverImpl(); <ide> ClassMetaData cmd1 = (ClassMetaData)metaDataMgr.getMetaDataForClass(Account.class.getName(), clr); <ide> AbstractMemberMetaData mmd1 = cmd1.getMetaDataForMember("username"); <del> assertEquals(255, mmd1.getColumnMetaData()[0].getLength().intValue()); <add> assertNull(mmd1.getColumnMetaData()[0].getLength()); <ide> } <ide> <ide> /**
Java
bsd-2-clause
72fa5c2734bf89c52b730bf39b379970d45711bd
0
TehSAUCE/imagej,biovoxxel/imagej,TehSAUCE/imagej,biovoxxel/imagej,biovoxxel/imagej,TehSAUCE/imagej
/* * #%L * ImageJ software for multidimensional image processing and analysis. * %% * Copyright (C) 2009 - 2012 Board of Regents of the University of * Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck * Institute of Molecular Cell Biology and Genetics. * %% * 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. * * 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 HOLDERS 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. * * The views and conclusions contained in the software and documentation are * those of the authors and should not be interpreted as representing official * policies, either expressed or implied, of any organization. * #L% */ package imagej.ext.plugin; import imagej.ext.display.Display; import imagej.ext.module.Module; import imagej.ext.module.ModulePostprocessor; import imagej.ext.module.ModulePreprocessor; import imagej.ext.tool.Tool; import imagej.platform.Platform; import imagej.service.Service; /** * Top-level interface for plugins. Plugins discoverable at runtime must * implement this interface and be annotated with @{@link Plugin}. * <p> * The core types of plugins are as follows: * </p> * <ul> * <li>{@link RunnablePlugin} - plugins that are executable as {@link Module}s. * These plugins typically perform a discrete operation, and are accessible via * the ImageJ menus.</li> * <li>{@link Service} - plugins that define new API in a particular area.</li> * <li>{@link Tool} - plugins that map user input (e.g., keyboard and mouse * actions) to behavior. They are usually rendered as icons in the ImageJ * toolbar.</li> * <li>{@link Display} - plugins that visualize objects, often used to display * module outputs.</li> * <li>{@link PreprocessorPlugin} - plugins that perform preprocessing on * modules. A {@link PreprocessorPlugin} is a discoverable * {@link ModulePreprocessor}.</li> * <li>{@link PostprocessorPlugin} - plugins that perform postprocessing on * modules. A {@link PostprocessorPlugin} is a discoverable * {@link ModulePostprocessor}.</li> * <li>{@link Platform} - plugins for defining platform-specific behavior.</li> * </ul> * <p> * What all plugins have in common is that they are declared using an annotation * (@{@link Plugin}), and discovered if present on the classpath at runtime. * </p> * * @author Curtis Rueden * @see Plugin * @see PluginService */ public interface IPlugin { // top-level marker interface for discovery via SezPoz }
core/core/src/main/java/imagej/ext/plugin/IPlugin.java
/* * #%L * ImageJ software for multidimensional image processing and analysis. * %% * Copyright (C) 2009 - 2012 Board of Regents of the University of * Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck * Institute of Molecular Cell Biology and Genetics. * %% * 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. * * 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 HOLDERS 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. * * The views and conclusions contained in the software and documentation are * those of the authors and should not be interpreted as representing official * policies, either expressed or implied, of any organization. * #L% */ package imagej.ext.plugin; import imagej.ext.display.Display; import imagej.ext.module.ModulePostprocessor; import imagej.ext.module.ModulePreprocessor; import imagej.ext.tool.Tool; /** * Top-level interface for plugins. Plugins discoverable at runtime must * implement this interface and be annotated with @{@link Plugin}. * <p> * There are several different kinds of plugins: * </p> * <ul> * <li>{@link RunnablePlugin} - plugins that are executable as modules.</li> * <li>{@link ImageJPlugin} - executable plugins that perform a discrete * operation, accessible via the ImageJ menus.</li> * <li>{@link Tool} - plugins that map user input (e.g., keyboard and mouse * actions) to behavior. They are usually rendered as icons in the ImageJ * toolbar.</li> * <li>{@link Display} - plugins that visualize objects, often used to display * module outputs.</li> * <li>{@link PreprocessorPlugin} - plugins that perform pre-processing on * modules. A {@link PreprocessorPlugin} is a discoverable * {@link ModulePreprocessor}.</li> * <li>{@link PostprocessorPlugin} - plugins that perform post-processing on * modules. A {@link PostprocessorPlugin} is a discoverable * {@link ModulePostprocessor}.</li> * </ul> * <p> * What all plugins have in common is that they are declared using an annotation * (@{@link Plugin}), and discovered if present on the classpath at runtime. * </p> * * @author Curtis Rueden * @see Plugin * @see PluginService */ public interface IPlugin { // top-level marker interface for discovery via SezPoz }
Improve javadoc for the IPlugin interface
core/core/src/main/java/imagej/ext/plugin/IPlugin.java
Improve javadoc for the IPlugin interface
<ide><path>ore/core/src/main/java/imagej/ext/plugin/IPlugin.java <ide> package imagej.ext.plugin; <ide> <ide> import imagej.ext.display.Display; <add>import imagej.ext.module.Module; <ide> import imagej.ext.module.ModulePostprocessor; <ide> import imagej.ext.module.ModulePreprocessor; <ide> import imagej.ext.tool.Tool; <add>import imagej.platform.Platform; <add>import imagej.service.Service; <ide> <ide> /** <ide> * Top-level interface for plugins. Plugins discoverable at runtime must <ide> * implement this interface and be annotated with @{@link Plugin}. <ide> * <p> <del> * There are several different kinds of plugins: <add> * The core types of plugins are as follows: <ide> * </p> <ide> * <ul> <del> * <li>{@link RunnablePlugin} - plugins that are executable as modules.</li> <del> * <li>{@link ImageJPlugin} - executable plugins that perform a discrete <del> * operation, accessible via the ImageJ menus.</li> <add> * <li>{@link RunnablePlugin} - plugins that are executable as {@link Module}s. <add> * These plugins typically perform a discrete operation, and are accessible via <add> * the ImageJ menus.</li> <add> * <li>{@link Service} - plugins that define new API in a particular area.</li> <ide> * <li>{@link Tool} - plugins that map user input (e.g., keyboard and mouse <ide> * actions) to behavior. They are usually rendered as icons in the ImageJ <ide> * toolbar.</li> <ide> * <li>{@link Display} - plugins that visualize objects, often used to display <ide> * module outputs.</li> <del> * <li>{@link PreprocessorPlugin} - plugins that perform pre-processing on <add> * <li>{@link PreprocessorPlugin} - plugins that perform preprocessing on <ide> * modules. A {@link PreprocessorPlugin} is a discoverable <ide> * {@link ModulePreprocessor}.</li> <del> * <li>{@link PostprocessorPlugin} - plugins that perform post-processing on <add> * <li>{@link PostprocessorPlugin} - plugins that perform postprocessing on <ide> * modules. A {@link PostprocessorPlugin} is a discoverable <ide> * {@link ModulePostprocessor}.</li> <add> * <li>{@link Platform} - plugins for defining platform-specific behavior.</li> <ide> * </ul> <ide> * <p> <ide> * What all plugins have in common is that they are declared using an annotation
JavaScript
mit
acbf881b1f7cede2a903f226bdaa7f636ce688d3
0
ghacksuserjs/ghacks-user.js,ghacksuserjs/ghacks-user.js
/****** * name: ghacks user.js * date: 13 November 2018 * version 63-beta: Pants Romance * "Rah rah ah-ah-ah! Ro mah ro-mah-mah. Gaga oh-la-la! Want your pants romance" * authors: v52+ github | v51- www.ghacks.net * url: https://github.com/ghacksuserjs/ghacks-user.js * license: MIT: https://github.com/ghacksuserjs/ghacks-user.js/blob/master/LICENSE.txt * releases: These are end-of-stable-life-cycle legacy archives. *Always* use the master branch user.js for a current up-to-date version. url: https://github.com/ghacksuserjs/ghacks-user.js/releases * README: 1. READ the full README * https://github.com/ghacksuserjs/ghacks-user.js/blob/master/README.md 2. READ this * https://github.com/ghacksuserjs/ghacks-user.js/wiki/1.3-Implementation 3. If you skipped steps 1 and 2 above (shame on you), then here is the absolute minimum * Auto-installing updates for Firefox and extensions are disabled (section 0302's) * Some user data is erased on close (section 2800). Change this to suit your needs * EACH RELEASE check: - 4600s: reset prefs made redundant due to privacy.resistFingerprinting (RPF) or enable them as an alternative to RFP or for ESR users - 9999s: reset deprecated prefs in about:config or enable relevant section(s) for ESR * Site breakage WILL happen - There are often trade-offs and conflicts between Security vs Privacy vs Anti-Fingerprinting and these need to be balanced against Functionality & Convenience & Breakage * You will need to make a few changes to suit your own needs - Search this file for the "[SETUP]" tag to find SOME common items you could check before using to avoid unexpected surprises - Search this file for the "[WARNING]" tag to troubleshoot or prevent SOME common issues 4. BACKUP your profile folder before implementing (and/or test in a new/cloned profile) 5. KEEP UP TO DATE: https://github.com/ghacksuserjs/ghacks-user.js/wiki#small_orange_diamond-maintenance ******/ /* START: internal custom pref to test for syntax errors * [NOTE] In FF60+, not all syntax errors cause parsing to abort i.e. reaching the last debug * pref no longer necessarily means that all prefs have been applied. Check the console right * after startup for any warnings/error messages related to non-applied prefs * [1] https://blog.mozilla.org/nnethercote/2018/03/09/a-new-preferences-parser-for-firefox/ ***/ user_pref("_user.js.parrot", "START: Oh yes, the Norwegian Blue... what's wrong with it?"); /* 0000: disable about:config warning ***/ user_pref("general.warnOnAboutConfig", false); /* 0001: start Firefox in PB (Private Browsing) mode * [SETTING] Privacy & Security>History>Custom Settings>Always use private browsing mode * [NOTE] In this mode *all* windows are "private windows" and the PB mode icon is not displayed * [NOTE] The P in PB mode is misleading: it means no "persistent" local storage of history, * caches, searches or cookies (which you can achieve in normal mode). In fact, it limits or * removes the ability to control these, and you need to quit Firefox to clear them. PB is best * used as a one off window (File>New Private Window) to provide a temporary self-contained * new instance. Closing all Private Windows clears all traces. Repeat as required. * [WARNING] PB does not allow indexedDB which breaks many Extensions that use it * including uBlock Origin, uMatrix, Violentmonkey and Stylus * [1] https://wiki.mozilla.org/Private_Browsing ***/ // user_pref("browser.privatebrowsing.autostart", true); /*** 0100: STARTUP ***/ user_pref("_user.js.parrot", "0100 syntax error: the parrot's dead!"); /* 0101: disable default browser check * [SETTING] General>Startup>Always check if Firefox is your default browser ***/ user_pref("browser.shell.checkDefaultBrowser", false); /* 0102: set START page (0=blank, 1=home, 2=last visited page, 3=resume previous session) * [SETTING] General>Startup>When Firefox starts ***/ user_pref("browser.startup.page", 0); /* 0103: set HOME+NEWWINDOW page * about:home=Activity Stream (default, see 0514), custom URL, about:blank * [SETTING] Home>New Windows and Tabs>Homepage and new windows ***/ user_pref("browser.startup.homepage", "about:blank"); /* 0104: set NEWTAB page * true=Activity Stream (default, see 0514), false=blank page * [SETTING] Home>New Windows and Tabs>New tabs ***/ user_pref("browser.newtabpage.enabled", false); user_pref("browser.newtab.preload", false); /*** 0200: GEOLOCATION ***/ user_pref("_user.js.parrot", "0200 syntax error: the parrot's definitely deceased!"); /* 0201: disable Location-Aware Browsing * [1] https://www.mozilla.org/firefox/geolocation/ ***/ // user_pref("geo.enabled", false); /* 0201b: set a default permission for Location (FF58+) * [SETTING] to add site exceptions: Page Info>Permissions>Access Your Location * [SETTING] to manage site exceptions: Options>Privacy & Security>Permissions>Location>Settings ***/ // user_pref("permissions.default.geo", 2); // 0=always ask (default), 1=allow, 2=block /* 0202: disable GeoIP-based search results * [NOTE] May not be hidden if Firefox has changed your settings due to your locale * [1] https://trac.torproject.org/projects/tor/ticket/16254 * [2] https://support.mozilla.org/en-US/kb/how-stop-firefox-making-automatic-connections#w_geolocation-for-default-search-engine ***/ user_pref("browser.search.region", "US"); // (hidden pref) user_pref("browser.search.geoip.url", ""); /* 0205: set OS & APP locale (FF59+) * If set to empty, the OS locales are used. If not set at all, default locale is used ***/ user_pref("intl.locale.requested", "en-US"); // (hidden pref) /* 0206: disable geographically specific results/search engines e.g. "browser.search.*.US" * i.e. ignore all of Mozilla's various search engines in multiple locales ***/ user_pref("browser.search.geoSpecificDefaults", false); user_pref("browser.search.geoSpecificDefaults.url", ""); /* 0207: set language to match ***/ user_pref("intl.accept_languages", "en-US, en"); /* 0208: enforce US English locale regardless of the system locale * [1] https://bugzilla.mozilla.org/867501 ***/ user_pref("javascript.use_us_english_locale", true); // (hidden pref) /* 0209: use APP locale over OS locale in regional preferences (FF56+) * [1] https://bugzilla.mozilla.org/buglist.cgi?bug_id=1379420,1364789 ***/ user_pref("intl.regional_prefs.use_os_locales", false); /* 0210: use Mozilla geolocation service instead of Google when geolocation is enabled * Optionally enable logging to the console (defaults to false) ***/ user_pref("geo.wifi.uri", "https://location.services.mozilla.com/v1/geolocate?key=%MOZILLA_API_KEY%"); // user_pref("geo.wifi.logging.enabled", true); // (hidden pref) /*** 0300: QUIET FOX We choose to not disable auto-CHECKs (0301's) but to disable auto-INSTALLs (0302's). There are many legitimate reasons to turn off auto-INSTALLS, including hijacked or monetized extensions, time constraints, legacy issues, and fear of breakage/bugs. It is still important to do updates for security reasons, please do so manually. ***/ user_pref("_user.js.parrot", "0300 syntax error: the parrot's not pinin' for the fjords!"); /* 0301b: disable auto-update checks for extensions * [SETTING] about:addons>Extensions>[cog-wheel-icon]>Update Add-ons Automatically (toggle) ***/ // user_pref("extensions.update.enabled", false); /* 0302a: disable auto update installing for Firefox * [SETTING] General>Firefox Updates>Check for updates but let you choose... ***/ user_pref("app.update.auto", false); /* 0302b: disable auto update installing for extensions (after the check in 0301b) * [SETTING] about:addons>Extensions>[cog-wheel-icon]>Update Add-ons Automatically (toggle) ***/ user_pref("extensions.update.autoUpdateDefault", false); /* 0303: disable background update service [WINDOWS] * [SETTING] General>Firefox Updates>Use a background service to install updates ***/ user_pref("app.update.service.enabled", false); /* 0304: disable background update staging ***/ user_pref("app.update.staging.enabled", false); /* 0305: enforce update information is displayed * This is the update available, downloaded, error and success information ***/ user_pref("app.update.silent", false); /* 0306: disable extension metadata updating * sends daily pings to Mozilla about extensions and recent startups ***/ user_pref("extensions.getAddons.cache.enabled", false); /* 0307: disable auto updating of personas (themes) ***/ user_pref("lightweightThemes.update.enabled", false); /* 0308: disable search update * [SETTING] General>Firefox Update>Automatically update search engines ***/ user_pref("browser.search.update", false); /* 0309: disable sending Flash crash reports ***/ user_pref("dom.ipc.plugins.flash.subprocess.crashreporter.enabled", false); /* 0310: disable sending the URL of the website where a plugin crashed ***/ user_pref("dom.ipc.plugins.reportCrashURL", false); /* 0320: disable about:addons' Get Add-ons panel (uses Google-Analytics) ***/ user_pref("extensions.getAddons.showPane", false); // hidden pref user_pref("extensions.webservice.discoverURL", ""); /* 0330: disable telemetry * the pref (.unified) affects the behaviour of the pref (.enabled) * IF unified=false then .enabled controls the telemetry module * IF unified=true then .enabled ONLY controls whether to record extended data * so make sure to have both set as false * [NOTE] FF58+ `toolkit.telemetry.enabled` is now LOCKED to reflect prerelease * or release builds (true and false respectively), see [2] * [1] https://firefox-source-docs.mozilla.org/toolkit/components/telemetry/telemetry/internals/preferences.html * [2] https://medium.com/georg-fritzsche/data-preference-changes-in-firefox-58-2d5df9c428b5 ***/ user_pref("toolkit.telemetry.unified", false); user_pref("toolkit.telemetry.enabled", false); // see [NOTE] above FF58+ user_pref("toolkit.telemetry.server", "data:,"); user_pref("toolkit.telemetry.archive.enabled", false); user_pref("toolkit.telemetry.cachedClientID", ""); user_pref("toolkit.telemetry.newProfilePing.enabled", false); // (FF55+) user_pref("toolkit.telemetry.shutdownPingSender.enabled", false); // (FF55+) user_pref("toolkit.telemetry.updatePing.enabled", false); // (FF56+) user_pref("toolkit.telemetry.bhrPing.enabled", false); // (FF57+) Background Hang Reporter user_pref("toolkit.telemetry.firstShutdownPing.enabled", false); // (FF57+) user_pref("toolkit.telemetry.hybridContent.enabled", false); // (FF59+) /* 0333: disable health report * [SETTING] Privacy & Security>Firefox Data Collection & Use>Allow Firefox to send technical... data ***/ user_pref("datareporting.healthreport.uploadEnabled", false); /* 0334: disable new data submission, master kill switch (FF41+) * If disabled, no policy is shown or upload takes place, ever * [1] https://bugzilla.mozilla.org/1195552 ***/ user_pref("datareporting.policy.dataSubmissionEnabled", false); /* 0350: disable crash reports ***/ user_pref("breakpad.reportURL", ""); /* 0351: disable sending of crash reports (FF44+) * [SETTING] Privacy & Security>Firefox Data Collection & Use>Allow Firefox to send crash reports ***/ user_pref("browser.tabs.crashReporting.sendReport", false); user_pref("browser.crashReports.unsubmittedCheck.enabled", false); // (FF51+) user_pref("browser.crashReports.unsubmittedCheck.autoSubmit", false); // (FF51-57) user_pref("browser.crashReports.unsubmittedCheck.autoSubmit2", false); // (FF58+) /* 0370: disable "Snippets" (Mozilla content shown on about:home screen) * [1] https://wiki.mozilla.org/Firefox/Projects/Firefox_Start/Snippet_Service ***/ user_pref("browser.aboutHomeSnippets.updateUrl", "data:,"); /* 0380: disable Browser Error Reporter (FF60+) * [1] https://support.mozilla.org/en-US/kb/firefox-nightly-error-collection * [2] https://firefox-source-docs.mozilla.org/browser/browser/BrowserErrorReporter.html ***/ user_pref("browser.chrome.errorReporter.enabled", false); user_pref("browser.chrome.errorReporter.submitUrl", ""); /*** 0400: BLOCKLISTS / SAFE BROWSING / TRACKING PROTECTION This section has security & tracking protection implications vs privacy concerns vs effectiveness vs 3rd party 'censorship'. We DO NOT advocate no protection. If you disable Tracking Protection (TP) and/or Safe Browsing (SB), then SECTION 0400 REQUIRES YOU HAVE uBLOCK ORIGIN INSTALLED. Safe Browsing is designed to protect users from malicious sites. Tracking Protection is designed to lessen the impact of third parties on websites to reduce tracking and to speed up your browsing. These do rely on 3rd parties (Google for SB and Disconnect for TP), but many steps, which are continually being improved, have been taken to preserve privacy. Disable at your own risk. ***/ user_pref("_user.js.parrot", "0400 syntax error: the parrot's passed on!"); /** BLOCKLISTS ***/ /* 0401: enable Firefox blocklist, but sanitize blocklist url * [NOTE] It includes updates for "revoked certificates" * [1] https://blog.mozilla.org/security/2015/03/03/revoking-intermediate-certificates-introducing-onecrl/ * [2] https://trac.torproject.org/projects/tor/ticket/16931 ***/ user_pref("extensions.blocklist.enabled", true); // default: true user_pref("extensions.blocklist.url", "https://blocklists.settings.services.mozilla.com/v1/blocklist/3/%APP_ID%/%APP_VERSION%/"); /* 0403: disable individual unwanted/unneeded parts of the Kinto blocklists * What is Kinto?: https://wiki.mozilla.org/Firefox/Kinto#Specifications * As Firefox transitions to Kinto, the blocklists have been broken down into entries for certs to be * revoked, extensions and plugins to be disabled, and gfx environments that cause problems or crashes ***/ // user_pref("services.blocklist.onecrl.collection", ""); // revoked certificates // user_pref("services.blocklist.addons.collection", ""); // user_pref("services.blocklist.plugins.collection", ""); // user_pref("services.blocklist.gfx.collection", ""); /** SAFE BROWSING (SB) This sub-section has been redesigned to differentiate between "real-time"/"user initiated" data being sent to Google from all other settings such as using local blocklists/whitelists and updating those lists. There are NO privacy issues here. *IF* required, a full url is never sent to Google, only a PART-hash of the prefix, and this is hidden with noise of other real PART-hashes. Google also swear it is anonymized and only used to flag malicious sites/activity. Firefox also takes measures such as striping out identifying parameters and storing safe browsing cookies in a separate jar. SB v4 (FF57+) doesn't even use cookies. (#Turn on browser.safebrowsing.debug to monitor this activity) #Required reading [#] https://feeding.cloud.geek.nz/posts/how-safe-browsing-works-in-firefox/ [1] https://wiki.mozilla.org/Security/Safe_Browsing ***/ /* 0410: disable "Block dangerous and deceptive content" (under Options>Privacy & Security) * This covers deceptive sites such as phishing and social engineering ***/ // user_pref("browser.safebrowsing.malware.enabled", false); // user_pref("browser.safebrowsing.phishing.enabled", false); // (FF50+) /* 0411: disable "Block dangerous downloads" (under Options>Privacy & Security) * This covers malware and PUPs (potentially unwanted programs) ***/ // user_pref("browser.safebrowsing.downloads.enabled", false); /* 0412: disable "Warn me about unwanted and uncommon software" (under Options>Privacy & Security) (FF48+) ***/ // user_pref("browser.safebrowsing.downloads.remote.block_potentially_unwanted", false); // user_pref("browser.safebrowsing.downloads.remote.block_uncommon", false); // user_pref("browser.safebrowsing.downloads.remote.block_dangerous", false); // (FF49+) // user_pref("browser.safebrowsing.downloads.remote.block_dangerous_host", false); // (FF49+) /* 0413: disable Google safebrowsing updates ***/ // user_pref("browser.safebrowsing.provider.google.updateURL", ""); // user_pref("browser.safebrowsing.provider.google.gethashURL", ""); // user_pref("browser.safebrowsing.provider.google4.updateURL", ""); // (FF50+) // user_pref("browser.safebrowsing.provider.google4.gethashURL", ""); // (FF50+) /* 0414: disable binaries NOT in local lists being checked by Google (real-time checking) ***/ user_pref("browser.safebrowsing.downloads.remote.enabled", false); user_pref("browser.safebrowsing.downloads.remote.url", ""); /* 0415: disable reporting URLs ***/ user_pref("browser.safebrowsing.provider.google.reportURL", ""); user_pref("browser.safebrowsing.reportPhishURL", ""); user_pref("browser.safebrowsing.provider.google4.reportURL", ""); // (FF50+) user_pref("browser.safebrowsing.provider.google.reportMalwareMistakeURL", ""); // (FF54+) user_pref("browser.safebrowsing.provider.google.reportPhishMistakeURL", ""); // (FF54+) user_pref("browser.safebrowsing.provider.google4.reportMalwareMistakeURL", ""); // (FF54+) user_pref("browser.safebrowsing.provider.google4.reportPhishMistakeURL", ""); // (FF54+) /* 0416: disable 'ignore this warning' on Safe Browsing warnings which when clicked * bypasses the block for that session. This is a means for admins to enforce SB * [TEST] see github wiki APPENDIX A: Test Sites: Section 5 * [1] https://bugzilla.mozilla.org/1226490 ***/ // user_pref("browser.safebrowsing.allowOverride", false); /* 0417: disable data sharing (FF58+) ***/ user_pref("browser.safebrowsing.provider.google4.dataSharing.enabled", false); user_pref("browser.safebrowsing.provider.google4.dataSharingURL", ""); /** TRACKING PROTECTION (TP) There are NO privacy concerns here, but we strongly recommend to use uBlock Origin as well, as it offers more comprehensive and specialized lists. It also allows per domain control. ***/ /* 0420: enable Tracking Protection in all windows * [NOTE] TP sends DNT headers regardless of the DNT pref (see 1610) * [1] https://wiki.mozilla.org/Security/Tracking_protection * [2] https://support.mozilla.org/kb/tracking-protection-firefox ***/ // user_pref("privacy.trackingprotection.pbmode.enabled", true); // default: true // user_pref("privacy.trackingprotection.enabled", true); /* 0422: set which Tracking Protection block list to use * [WARNING] We don't recommend enforcing this from here, as available block lists can change * [SETTING] Privacy & Security>Tracking Protection>Change Block List ***/ // user_pref("urlclassifier.trackingTable", "test-track-simple,base-track-digest256"); // basic /* 0423: disable Mozilla's blocklist for known Flash tracking/fingerprinting (FF48+) * [1] https://www.ghacks.net/2016/07/18/firefox-48-blocklist-against-plugin-fingerprinting/ * [2] https://bugzilla.mozilla.org/1237198 ***/ // user_pref("browser.safebrowsing.blockedURIs.enabled", false); /* 0424: disable Mozilla's tracking protection and Flash blocklist updates ***/ // user_pref("browser.safebrowsing.provider.mozilla.gethashURL", ""); // user_pref("browser.safebrowsing.provider.mozilla.updateURL", ""); /* 0425: disable passive Tracking Protection (FF53+) * Passive TP annotates channels to lower the priority of network loads for resources on the tracking protection list * [NOTE] It has no effect if TP is enabled, but keep in mind that by default TP is only enabled in Private Windows * This is included for people who want to completely disable Tracking Protection. * [1] https://bugzilla.mozilla.org/buglist.cgi?bug_id=1170190,1141814 ***/ // user_pref("privacy.trackingprotection.annotate_channels", false); // user_pref("privacy.trackingprotection.lower_network_priority", false); /* 0426: enforce Content Blocking (required to block cookies) (FF63+) ***/ user_pref("browser.contentblocking.enabled", true); // default: true /*** 0500: SYSTEM ADD-ONS / EXPERIMENTS System Add-ons are a method for shipping extensions, considered to be built-in features to Firefox, that are hidden from the about:addons UI. To view your System Add-ons go to about:support, they are listed under "Firefox Features" Some System Add-ons have no on-off prefs. Instead you can manually remove them. Note that app updates will restore them. They may also be updated and possibly restored automatically (see 0505) * Portable: "...\App\Firefox64\browser\features\" (or "App\Firefox\etc" for 32bit) * Windows: "...\Program Files\Mozilla\browser\features" (or "Program Files (X86)\etc" for 32bit) * Mac: "...\Applications\Firefox\Contents\Resources\browser\features\" [NOTE] On Mac you can right-click on the application and select "Show Package Contents" * Linux: "/usr/lib/firefox/browser/features" (or similar) [1] https://firefox-source-docs.mozilla.org/toolkit/mozapps/extensions/addon-manager/SystemAddons.html [2] https://dxr.mozilla.org/mozilla-central/source/browser/extensions ***/ user_pref("_user.js.parrot", "0500 syntax error: the parrot's cashed in 'is chips!"); /* 0502: disable Mozilla permission to silently opt you into tests ***/ user_pref("network.allow-experiments", false); /* 0503: disable Normandy/Shield (FF60+) * Shield is an telemetry system (including Heartbeat) that can also push and test "recipes" * [1] https://wiki.mozilla.org/Firefox/Shield * [2] https://github.com/mozilla/normandy ***/ user_pref("app.normandy.enabled", false); user_pref("app.normandy.api_url", ""); user_pref("app.shield.optoutstudies.enabled", false); /* 0505: disable System Add-on updates * [NOTE] In FF61 and lower, you will not get any System Add-on updates except when you update Firefox ***/ // user_pref("extensions.systemAddon.update.enabled", false); // (FF62+) // user_pref("extensions.systemAddon.update.url", ""); /* 0506: disable PingCentre telemetry (used in several System Add-ons) (FF57+) * Currently blocked by 'datareporting.healthreport.uploadEnabled' (see 0333) ***/ user_pref("browser.ping-centre.telemetry", false); /* 0510: disable Pocket (FF39+) * Pocket is a third party (now owned by Mozilla) "save for later" cloud service * [1] https://en.wikipedia.org/wiki/Pocket_(application) * [2] https://www.gnu.gl/blog/Posts/multiple-vulnerabilities-in-pocket/ ***/ user_pref("extensions.pocket.enabled", false); /* 0514: disable Activity Stream (FF54+) * Activity Stream is the default homepage/newtab in FF57+. It is based on metadata and browsing behavior, * and includes telemetry and web content such as snippets, top stories (pocket), top sites, etc. * - ONE: make sure to set your "home" and "newtab" to about:blank (or use an extension to control them) * - TWO: DELETE the XPI file in your System Add-ons directory (note this get reinstalled on app updates) * And/or you can try to control the ever-growing, ever-changing "browser.newtabpage.activity-stream.*" prefs * [FF63+] Activity Stream (AS) is now builtin and no longer an easily deletable system addon! * We'll clean this up and move to a new number when ESR67 is released. * [1] https://wiki.mozilla.org/Firefox/Activity_Stream * [2] https://www.ghacks.net/2016/02/15/firefox-mockups-show-activity-stream-new-tab-page-and-share-updates/ ***/ user_pref("browser.library.activity-stream.enabled", false); // (FF57+) /* 0514a: disable AS Snippets ***/ user_pref("browser.newtabpage.activity-stream.disableSnippets", true); user_pref("browser.newtabpage.activity-stream.feeds.snippets", false); // [SETTING] Home>Firefox Home Content>Snippets /* 0514b: disable AS Top Stories and other Pocket-based and/or sponsored content ***/ user_pref("browser.newtabpage.activity-stream.feeds.section.topstories", false); user_pref("browser.newtabpage.activity-stream.section.highlights.includePocket", false); // [SETTING] Home>Firefox Home Content>Highlights>Pages Saved to Pocket user_pref("browser.newtabpage.activity-stream.showSponsored", false); /* 0514c: disable AS telemetry ***/ user_pref("browser.newtabpage.activity-stream.feeds.telemetry", false); user_pref("browser.newtabpage.activity-stream.telemetry", false); user_pref("browser.newtabpage.activity-stream.telemetry.ping.endpoint", ""); /* 0515: disable Screenshots (FF55+) * alternatively in FF60+, disable uploading to the Screenshots server * [1] https://github.com/mozilla-services/screenshots * [2] https://www.ghacks.net/2017/05/28/firefox-screenshots-integrated-in-firefox-nightly/ ***/ // user_pref("extensions.screenshots.disabled", true); // user_pref("extensions.screenshots.upload-disabled", true); // (FF60+) /* 0516: disable Onboarding (FF55+) * Onboarding is an interactive tour/setup for new installs/profiles and features. Every time * about:home or about:newtab is opened, the onboarding overlay is injected into that page * [NOTE] Onboarding uses Google Analytics [2], and leaks resource://URIs [3] * [1] https://wiki.mozilla.org/Firefox/Onboarding * [2] https://github.com/mozilla/onboard/commit/db4d6c8726c89a5d6a241c1b1065827b525c5baf * [3] https://bugzilla.mozilla.org/863246#c154 ***/ user_pref("browser.onboarding.enabled", false); /* 0517: disable Form Autofill (FF55+) * [SETTING] Privacy & Security>Forms & Passwords>Enable Profile Autofill * [NOTE] Stored data is NOT secure (uses a JSON file) * [NOTE] Heuristics controls Form Autofill on forms without @autocomplete attributes * [1] https://wiki.mozilla.org/Firefox/Features/Form_Autofill * [2] https://www.ghacks.net/2017/05/24/firefoxs-new-form-autofill-is-awesome/ ***/ user_pref("extensions.formautofill.addresses.enabled", false); user_pref("extensions.formautofill.available", "off"); // (FF56+) user_pref("extensions.formautofill.creditCards.enabled", false); // (FF56+) user_pref("extensions.formautofill.heuristics.enabled", false); /* 0518: disable Web Compatibility Reporter (FF56+) * Web Compatibility Reporter adds a "Report Site Issue" button to send data to Mozilla ***/ user_pref("extensions.webcompat-reporter.enabled", false); /*** 0600: BLOCK IMPLICIT OUTBOUND [not explicitly asked for - e.g. clicked on] ***/ user_pref("_user.js.parrot", "0600 syntax error: the parrot's no more!"); /* 0601: disable link prefetching * [1] https://developer.mozilla.org/docs/Web/HTTP/Link_prefetching_FAQ ***/ user_pref("network.prefetch-next", false); /* 0602: disable DNS prefetching * [1] https://www.ghacks.net/2013/04/27/firefox-prefetching-what-you-need-to-know/ * [2] https://developer.mozilla.org/docs/Web/HTTP/Headers/X-DNS-Prefetch-Control ***/ user_pref("network.dns.disablePrefetch", true); user_pref("network.dns.disablePrefetchFromHTTPS", true); // (hidden pref) /* 0603a: disable Seer/Necko * [1] https://developer.mozilla.org/docs/Mozilla/Projects/Necko ***/ user_pref("network.predictor.enabled", false); /* 0603b: disable more Necko/Captive Portal * [1] https://en.wikipedia.org/wiki/Captive_portal * [2] https://wiki.mozilla.org/Necko/CaptivePortal * [3] https://trac.torproject.org/projects/tor/ticket/21790 ***/ user_pref("captivedetect.canonicalURL", ""); user_pref("network.captive-portal-service.enabled", false); // (FF52+) /* 0605: disable link-mouseover opening connection to linked server * [1] https://news.slashdot.org/story/15/08/14/2321202/how-to-quash-firefoxs-silent-requests * [2] https://www.ghacks.net/2015/08/16/block-firefox-from-connecting-to-sites-when-you-hover-over-links/ ***/ user_pref("network.http.speculative-parallel-limit", 0); /* 0606: disable pings (but enforce same host in case) * [1] http://kb.mozillazine.org/Browser.send_pings * [2] http://kb.mozillazine.org/Browser.send_pings.require_same_host ***/ user_pref("browser.send_pings", false); user_pref("browser.send_pings.require_same_host", true); /* 0607: disable links launching Windows Store on Windows 8/8.1/10 [WINDOWS] * [1] https://www.ghacks.net/2016/03/25/block-firefox-chrome-windows-store/ ***/ user_pref("network.protocol-handler.external.ms-windows-store", false); /* 0608: disable predictor / prefetching (FF48+) ***/ user_pref("network.predictor.enable-prefetch", false); /*** 0700: HTTP* / TCP/IP / DNS / PROXY / SOCKS etc ***/ user_pref("_user.js.parrot", "0700 syntax error: the parrot's given up the ghost!"); /* 0701: disable IPv6 * IPv6 can be abused, especially regarding MAC addresses. They also do not play nice * with VPNs. That's even assuming your ISP and/or router and/or website can handle it * [WARNING] This is just an application level fallback. Disabling IPv6 is best done * at an OS/network level, and/or configured properly in VPN setups * [TEST] http://ipv6leak.com/ * [1] https://github.com/ghacksuserjs/ghacks-user.js/issues/437#issuecomment-403740626 * [2] https://www.internetsociety.org/tag/ipv6-security/ (see Myths 2,4,5,6) ***/ user_pref("network.dns.disableIPv6", true); /* 0702: disable HTTP2 (which was based on SPDY which is now deprecated) * HTTP2 raises concerns with "multiplexing" and "server push", does nothing to enhance * privacy, and in fact opens up a number of server-side fingerprinting opportunities * [1] https://http2.github.io/faq/ * [2] https://blog.scottlogic.com/2014/11/07/http-2-a-quick-look.html * [3] https://queue.acm.org/detail.cfm?id=2716278 * [4] https://github.com/ghacksuserjs/ghacks-user.js/issues/107 ***/ user_pref("network.http.spdy.enabled", false); user_pref("network.http.spdy.enabled.deps", false); user_pref("network.http.spdy.enabled.http2", false); /* 0703: disable HTTP Alternative Services (FF37+) * [1] https://www.ghacks.net/2015/08/18/a-comprehensive-list-of-firefox-privacy-and-security-settings/#comment-3970881 * [2] https://www.mnot.net/blog/2016/03/09/alt-svc ***/ user_pref("network.http.altsvc.enabled", false); user_pref("network.http.altsvc.oe", false); /* 0704: enforce the proxy server to do any DNS lookups when using SOCKS * e.g. in TOR, this stops your local DNS server from knowing your Tor destination * as a remote Tor node will handle the DNS request * [1] http://kb.mozillazine.org/Network.proxy.socks_remote_dns * [2] https://trac.torproject.org/projects/tor/wiki/doc/TorifyHOWTO/WebBrowsers ***/ user_pref("network.proxy.socks_remote_dns", true); /* 0706: remove paths when sending URLs to PAC scripts (FF51+) * CVE-2017-5384: Information disclosure via Proxy Auto-Config (PAC) * [1] https://bugzilla.mozilla.org/1255474 ***/ user_pref("network.proxy.autoconfig_url.include_path", false); // default: false /* 0707: disable (or setup) DNS-over-HTTPS (DoH) (FF60+) * TRR = Trusted Recursive Resolver * .mode: 0=off, 1=race, 2=TRR first, 3=TRR only, 4=race for stats, but always use native result * [WARNING] DoH bypasses hosts and gives info to yet another party (e.g. Cloudflare) * [1] https://www.ghacks.net/2018/04/02/configure-dns-over-https-in-firefox/ * [2] https://hacks.mozilla.org/2018/05/a-cartoon-intro-to-dns-over-https/ ***/ // user_pref("network.trr.mode", 0); // user_pref("network.trr.bootstrapAddress", ""); // user_pref("network.trr.uri", ""); /* 0708: disable FTP (FF60+) * [1] https://www.ghacks.net/2018/02/20/firefox-60-with-new-preference-to-disable-ftp/ ***/ // user_pref("network.ftp.enabled", false); /* 0709: disable using UNC (Uniform Naming Convention) paths (FF61+) * [1] https://trac.torproject.org/projects/tor/ticket/26424 ***/ user_pref("network.file.disable_unc_paths", true); // (hidden pref) /* 0710: disable GIO as a potential proxy bypass vector * Gvfs/GIO has a set of supported protocols like obex, network, archive, computer, dav, cdda, * gphoto2, trash, etc. By default only smb and sftp protocols are accepted so far (as of FF64) * [1] https://bugzilla.mozilla.org/1433507 * [2] https://trac.torproject.org/23044 * [3] https://en.wikipedia.org/wiki/GVfs * [4] https://en.wikipedia.org/wiki/GIO_(software) ***/ user_pref("network.gio.supported-protocols", ""); // (hidden pref) /*** 0800: LOCATION BAR / SEARCH BAR / SUGGESTIONS / HISTORY / FORMS [SETUP] If you are in a private environment (no unwanted eyeballs) and your device is private (restricted access), and the device is secure when unattended (locked, encrypted, forensic hardened), then items 0850 and above can be relaxed in return for more convenience and functionality. Likewise, you may want to check the items cleared on shutdown in section 2800. [NOTE] The urlbar is also commonly referred to as the location bar and address bar #Required reading [#] https://xkcd.com/538/ ***/ user_pref("_user.js.parrot", "0800 syntax error: the parrot's ceased to be!"); /* 0801: disable location bar using search - PRIVACY * don't leak typos to a search engine, give an error message instead ***/ user_pref("keyword.enabled", false); /* 0802: disable location bar domain guessing - PRIVACY/SECURITY * domain guessing intercepts DNS "hostname not found errors" and resends a * request (e.g. by adding www or .com). This is inconsistent use (e.g. FQDNs), does not work * via Proxy Servers (different error), is a flawed use of DNS (TLDs: why treat .com * as the 411 for DNS errors?), privacy issues (why connect to sites you didn't * intend to), can leak sensitive data (e.g. query strings: e.g. Princeton attack), * and is a security risk (e.g. common typos & malicious sites set up to exploit this) ***/ user_pref("browser.fixup.alternate.enabled", false); /* 0803: display all parts of the url in the location bar - helps SECURITY ***/ user_pref("browser.urlbar.trimURLs", false); /* 0804: limit history leaks via enumeration (PER TAB: back/forward) - PRIVACY * This is a PER TAB session history. You still have a full history stored under all history * default=50, minimum=1=currentpage, 2 is the recommended minimum as some pages * use it as a means of referral (e.g. hotlinking), 4 or 6 or 10 may be more practical ***/ user_pref("browser.sessionhistory.max_entries", 10); /* 0805: disable CSS querying page history - CSS history leak - PRIVACY * [NOTE] This has NEVER been fully "resolved": in Mozilla/docs it is stated it's * only in 'certain circumstances', also see latest comments in [2] * [TEST] http://lcamtuf.coredump.cx/yahh/ (see github wiki APPENDIX C on how to use) * [1] https://dbaron.org/mozilla/visited-privacy * [2] https://bugzilla.mozilla.org/147777 * [3] https://developer.mozilla.org/docs/Web/CSS/Privacy_and_the_:visited_selector ***/ user_pref("layout.css.visited_links_enabled", false); /* 0806: disable displaying javascript in history URLs - SECURITY ***/ user_pref("browser.urlbar.filter.javascript", true); /* 0807: disable search bar LIVE search suggestions - PRIVACY * [SETTING] Search>Provide search suggestions ***/ user_pref("browser.search.suggest.enabled", false); /* 0808: disable location bar LIVE search suggestions (requires 0807 = true) - PRIVACY * Also disable the location bar prompt to enable/disable or learn more about it. * [SETTING] Search>Show search suggestions in address bar results ***/ user_pref("browser.urlbar.suggest.searches", false); user_pref("browser.urlbar.userMadeSearchSuggestionsChoice", true); // (FF41+) /* 0809: disable location bar suggesting "preloaded" top websites (FF54+) * [1] https://bugzilla.mozilla.org/1211726 ***/ user_pref("browser.urlbar.usepreloadedtopurls.enabled", false); /* 0810: disable location bar making speculative connections (FF56+) * [1] https://bugzilla.mozilla.org/1348275 ***/ user_pref("browser.urlbar.speculativeConnect.enabled", false); /* 0850a: disable location bar autocomplete and suggestion types * If you enforce any of the suggestion types, you MUST enforce 'autocomplete' * - If *ALL* of the suggestion types are false, 'autocomplete' must also be false * - If *ANY* of the suggestion types are true, 'autocomplete' must also be true * [SETTING] Privacy & Security>Address Bar>When using the address bar, suggest * [WARNING] If all three suggestion types are false, search engine keywords are disabled ***/ user_pref("browser.urlbar.autocomplete.enabled", false); user_pref("browser.urlbar.suggest.history", false); user_pref("browser.urlbar.suggest.bookmark", false); user_pref("browser.urlbar.suggest.openpage", false); /* 0850c: disable location bar dropdown * This value controls the total number of entries to appear in the location bar dropdown * [NOTE] Items (bookmarks/history/openpages) with a high "frecency"/"bonus" will always * be displayed (no we do not know how these are calculated or what the threshold is), * and this does not affect the search by search engine suggestion (see 0808) * [USAGE] This setting is only useful if you want to enable search engine keywords * (i.e. at least one of 0850a suggestion types must be true) but you want to *limit* suggestions shown ***/ // user_pref("browser.urlbar.maxRichResults", 0); /* 0850d: disable location bar autofill * [1] http://kb.mozillazine.org/Inline_autocomplete ***/ user_pref("browser.urlbar.autoFill", false); /* 0850e: disable location bar one-off searches (FF51+) * [1] https://www.ghacks.net/2016/08/09/firefox-one-off-searches-address-bar/ ***/ user_pref("browser.urlbar.oneOffSearches", false); /* 0850f: disable location bar suggesting local search history (FF57+) * [1] https://bugzilla.mozilla.org/1181644 ***/ user_pref("browser.urlbar.maxHistoricalSearchSuggestions", 0); // max. number of search suggestions /* 0860: disable search and form history * [SETTING] Privacy & Security>History>Custom Settings>Remember search and form history * [NOTE] You can clear formdata on exiting Firefox (see 2803) ***/ user_pref("browser.formfill.enable", false); /* 0862: disable browsing and download history * [SETTING] Privacy & Security>History>Custom Settings>Remember my browsing and download history * [NOTE] You can clear history and downloads on exiting Firefox (see 2803) ***/ // user_pref("places.history.enabled", false); /* 0864: disable date/time picker (FF57+ default true) * This can leak your locale if not en-US * [1] https://trac.torproject.org/projects/tor/ticket/21787 ***/ user_pref("dom.forms.datetime", false); /* 0870: disable Windows jumplist [WINDOWS] ***/ user_pref("browser.taskbar.lists.enabled", false); user_pref("browser.taskbar.lists.frequent.enabled", false); user_pref("browser.taskbar.lists.recent.enabled", false); user_pref("browser.taskbar.lists.tasks.enabled", false); /* 0871: disable Windows taskbar preview [WINDOWS] ***/ user_pref("browser.taskbar.previews.enable", false); /*** 0900: PASSWORDS ***/ user_pref("_user.js.parrot", "0900 syntax error: the parrot's expired!"); /* 0901: disable saving passwords * [SETTING] Privacy & Security>Forms & Passwords>Remember logins and passwords for sites * [NOTE] This does not clear any passwords already saved ***/ // user_pref("signon.rememberSignons", false); /* 0902: use a master password (recommended if you save passwords) * There are no preferences for this. It is all handled internally. * [SETTING] Privacy & Security>Forms & Passwords>Use a master password * [1] https://support.mozilla.org/kb/use-master-password-protect-stored-logins ***/ /* 0903: set how often Firefox should ask for the master password * 0=the first time (default), 1=every time it's needed, 2=every n minutes (as per the next pref) ***/ user_pref("security.ask_for_password", 2); /* 0904: set how often in minutes Firefox should ask for the master password (see pref above) * in minutes, default is 30 ***/ user_pref("security.password_lifetime", 5); /* 0905: disable auto-filling username & password form fields - SECURITY * can leak in cross-site forms AND be spoofed * [NOTE] Password will still be auto-filled after a user name is manually entered * [1] http://kb.mozillazine.org/Signon.autofillForms ***/ user_pref("signon.autofillForms", false); /* 0906: disable websites' autocomplete="off" (FF30+) * Don't let sites dictate use of saved logins and passwords. Increase security through * stronger password use. The trade-off is the convenience. Some sites should never be * saved (such as banking sites). Set at true, informed users can make their own choice. ***/ user_pref("signon.storeWhenAutocompleteOff", true); // default: true /* 0907: display warnings for logins on non-secure (non HTTPS) pages * [1] https://bugzilla.mozilla.org/1217156 ***/ user_pref("security.insecure_password.ui.enabled", true); /* 0908: remove user & password info when attempting to fix an entered URL (i.e. 0802 is true) * e.g. //user:password@foo -> //user@(prefix)foo(suffix) NOT //user:password@(prefix)foo(suffix) ***/ user_pref("browser.fixup.hide_user_pass", true); /* 0909: disable formless login capture for Password Manager (FF51+) ***/ user_pref("signon.formlessCapture.enabled", false); /* 0910: disable autofilling saved passwords on HTTP pages and show warning (FF52+) * [1] https://www.fxsitecompat.com/en-CA/docs/2017/insecure-login-forms-now-disable-autofill-show-warning-beneath-input-control/ * [2] https://bugzilla.mozilla.org/buglist.cgi?bug_id=1217152,1319119 ***/ user_pref("signon.autofillForms.http", false); user_pref("security.insecure_field_warning.contextual.enabled", true); /* 0911: prevent cross-origin images from triggering an HTTP-Authentication prompt (FF55+) * [1] https://bugzilla.mozilla.org/1357835 ***/ user_pref("network.auth.subresource-img-cross-origin-http-auth-allow", false); /*** 1000: CACHE [SETUP] ETAG [1] and other [2][3] cache tracking/fingerprinting techniques can be averted by disabling *BOTH* disk (1001) and memory (1003) cache. ETAGs can also be neutralized by modifying response headers [4]. Another solution is to use a hardened configuration with Temporary Containers [5]. Alternatively, you can *LIMIT* exposure by clearing cache on close (2803). or on a regular basis manually or with an extension. [1] https://en.wikipedia.org/wiki/HTTP_ETag#Tracking_using_ETags [2] https://robertheaton.com/2014/01/20/cookieless-user-tracking-for-douchebags/ [3] https://www.grepular.com/Preventing_Web_Tracking_via_the_Browser_Cache [4] https://github.com/ghacksuserjs/ghacks-user.js/wiki/4.2.4-Header-Editor [5] https://medium.com/@stoically/enhance-your-privacy-in-firefox-with-temporary-containers-33925cd6cd21 ***/ user_pref("_user.js.parrot", "1000 syntax error: the parrot's gone to meet 'is maker!"); /** CACHE ***/ /* 1001: disable disk cache ***/ user_pref("browser.cache.disk.enable", false); user_pref("browser.cache.disk.capacity", 0); user_pref("browser.cache.disk.smart_size.enabled", false); user_pref("browser.cache.disk.smart_size.first_run", false); /* 1002: disable disk cache for SSL pages * [1] http://kb.mozillazine.org/Browser.cache.disk_cache_ssl ***/ user_pref("browser.cache.disk_cache_ssl", false); /* 1003: disable memory cache * [NOTE] Not recommended due to performance issues ***/ // user_pref("browser.cache.memory.enable", false); // user_pref("browser.cache.memory.capacity", 0); // (hidden pref) /* 1005: disable fastback cache * To improve performance when pressing back/forward Firefox stores visited pages * so they don't have to be re-parsed. This is not the same as memory cache. * 0=none, -1=auto (that's minus 1), or for other values see [1] * [NOTE] Not recommended unless you know what you're doing * [1] http://kb.mozillazine.org/Browser.sessionhistory.max_total_viewers ***/ // user_pref("browser.sessionhistory.max_total_viewers", 0); /* 1006: disable permissions manager from writing to disk [RESTART] * [NOTE] This means any permission changes are session only * [1] https://bugzilla.mozilla.org/967812 ***/ // user_pref("permissions.memory_only", true); // (hidden pref) /* 1008: set DNS cache and expiration time (default 400 and 60, same as TBB) ***/ // user_pref("network.dnsCacheEntries", 400); // user_pref("network.dnsCacheExpiration", 60); /** SESSIONS & SESSION RESTORE ***/ /* 1020: disable the Session Restore service completely * [WARNING] [SETUP] This also disables the "Recently Closed Tabs" feature * It does not affect "Recently Closed Windows" or any history. ***/ user_pref("browser.sessionstore.max_tabs_undo", 0); user_pref("browser.sessionstore.max_windows_undo", 0); /* 1021: disable storing extra session data * extra session data contains contents of forms, scrollbar positions, cookies and POST data * define on which sites to save extra session data: * 0=everywhere, 1=unencrypted sites, 2=nowhere ***/ user_pref("browser.sessionstore.privacy_level", 2); /* 1022: disable resuming session from crash [SETUP] ***/ user_pref("browser.sessionstore.resume_from_crash", false); /* 1023: set the minimum interval between session save operations - increasing it * can help on older machines and some websites, as well as reducing writes, see [1] * Default is 15000 (15 secs). Try 30000 (30sec), 60000 (1min) etc * [WARNING] This can also affect entries in the "Recently Closed Tabs" feature: * i.e. the longer the interval the more chance a quick tab open/close won't be captured. * This longer interval *may* affect history but we cannot replicate any history not recorded * [1] https://bugzilla.mozilla.org/1304389 ***/ user_pref("browser.sessionstore.interval", 30000); /* 1024: disable automatic Firefox start and session restore after reboot [WINDOWS] (FF62+) * [1] https://bugzilla.mozilla.org/603903 ***/ user_pref("toolkit.winRegisterApplicationRestart", false); /** FAVICONS ***/ /* 1030: disable favicons in shortcuts * URL shortcuts use a cached randomly named .ico file which is stored in your * profile/shortcutCache directory. The .ico remains after the shortcut is deleted. * If set to false then the shortcuts use a generic Firefox icon ***/ user_pref("browser.shell.shortcutFavicons", false); /* 1031: disable favicons in tabs and new bookmarks * bookmark favicons are stored as data blobs in favicons.sqlite ***/ // user_pref("browser.chrome.site_icons", false); /* 1032: disable favicons in web notifications ***/ user_pref("alerts.showFavicons", false); // default: false /*** 1200: HTTPS ( SSL/TLS / OCSP / CERTS / HSTS / HPKP / CIPHERS ) Note that your cipher and other settings can be used server side as a fingerprint attack vector, see [1] (It's quite technical but the first part is easy to understand and you can stop reading when you reach the second section titled "Enter Bro") Option 1: Use Firefox defaults for the 1260's items (item 1260 default for SHA-1, is local only anyway). There is nothing *weak* about Firefox's defaults, but Mozilla (and other browsers) will always lag for fear of breakage and upset end-users Option 2: Disable the ciphers in 1261, 1262 and 1263. These shouldn't break anything. Optionally, disable the ciphers in 1264. [1] https://www.securityartwork.es/2017/02/02/tls-client-fingerprinting-with-bro/ ***/ user_pref("_user.js.parrot", "1200 syntax error: the parrot's a stiff!"); /** SSL (Secure Sockets Layer) / TLS (Transport Layer Security) ***/ /* 1201: disable old SSL/TLS "insecure" renegotiation (vulnerable to a MiTM attack) * [WARNING] <2% of secure sites do NOT support the newer "secure" renegotiation, see [2] * [1] https://wiki.mozilla.org/Security:Renegotiation * [2] https://www.ssllabs.com/ssl-pulse/ ***/ user_pref("security.ssl.require_safe_negotiation", true); /* 1202: control TLS versions with min and max * 1=min version of TLS 1.0, 2=min version of TLS 1.1, 3=min version of TLS 1.2 etc * [NOTE] Jul-2017: Telemetry indicates approx 2% of TLS web traffic uses 1.0 or 1.1 * [WARNING] If you get an "SSL_ERROR_NO_CYPHER_OVERLAP" error, temporarily * set a lower value for 'security.tls.version.min' in about:config * [1] http://kb.mozillazine.org/Security.tls.version.* * [2] https://www.ssl.com/how-to/turn-off-ssl-3-0-and-tls-1-0-in-your-browser/ * [2] archived: https://archive.is/hY2Mm ***/ // user_pref("security.tls.version.min", 3); user_pref("security.tls.version.max", 4); // 4 = allow up to and including TLS 1.3 /* 1203: disable SSL session tracking (FF36+) * SSL Session IDs speed up HTTPS connections (no need to renegotiate) and last for 48hrs. * Since the ID is unique, web servers can (and do) use it for tracking. If set to true, * this disables sending SSL Session IDs and TLS Session Tickets to prevent session tracking * [1] https://tools.ietf.org/html/rfc5077 * [2] https://bugzilla.mozilla.org/967977 ***/ user_pref("security.ssl.disable_session_identifiers", true); // (hidden pref) /* 1204: disable SSL Error Reporting * [1] https://firefox-source-docs.mozilla.org/browser/base/sslerrorreport/preferences.html ***/ user_pref("security.ssl.errorReporting.automatic", false); user_pref("security.ssl.errorReporting.enabled", false); user_pref("security.ssl.errorReporting.url", ""); /* 1205: disable TLS1.3 0-RTT (round-trip time) (FF51+) * [1] https://github.com/tlswg/tls13-spec/issues/1001 * [2] https://blog.cloudflare.com/tls-1-3-overview-and-q-and-a/ ***/ user_pref("security.tls.enable_0rtt_data", false); // (FF55+ default true) /** OCSP (Online Certificate Status Protocol) #Required reading [#] https://scotthelme.co.uk/revocation-is-broken/ ***/ /* 1210: enable OCSP Stapling * [1] https://blog.mozilla.org/security/2013/07/29/ocsp-stapling-in-firefox/ ***/ user_pref("security.ssl.enable_ocsp_stapling", true); /* 1211: control when to use OCSP fetching (to confirm current validity of certificates) * 0=disabled, 1=enabled (default), 2=enabled for EV certificates only * OCSP (non-stapled) leaks information about the sites you visit to the CA (cert authority) * It's a trade-off between security (checking) and privacy (leaking info to the CA) * [NOTE] This pref only controls OCSP fetching and does not affect OCSP stapling * [1] https://en.wikipedia.org/wiki/Ocsp ***/ user_pref("security.OCSP.enabled", 1); /* 1212: set OCSP fetch failures (non-stapled, see 1211) to hard-fail * When a CA cannot be reached to validate a cert, Firefox just continues the connection (=soft-fail) * Setting this pref to true tells Firefox to instead terminate the connection (=hard-fail) * It is pointless to soft-fail when an OCSP fetch fails: you cannot confirm a cert is still valid (it * could have been revoked) and/or you could be under attack (e.g. malicious blocking of OCSP servers) * [1] https://blog.mozilla.org/security/2013/07/29/ocsp-stapling-in-firefox/ * [2] https://www.imperialviolet.org/2014/04/19/revchecking.html ***/ user_pref("security.OCSP.require", true); /** CERTS / HSTS (HTTP Strict Transport Security) / HPKP (HTTP Public Key Pinning) ***/ /* 1220: disable Windows 8.1's Microsoft Family Safety cert [WINDOWS] (FF50+) * 0=disable detecting Family Safety mode and importing the root * 1=only attempt to detect Family Safety mode (don't import the root) * 2=detect Family Safety mode and import the root * [1] https://trac.torproject.org/projects/tor/ticket/21686 ***/ user_pref("security.family_safety.mode", 0); /* 1221: disable intermediate certificate caching (fingerprinting attack vector) [RESTART] * [NOTE] This may be better handled under FPI (ticket 1323644, part of Tor Uplift) * [WARNING] This affects login/cert/key dbs. The effect is all credentials are session-only. * Saved logins and passwords are not available. Reset the pref and restart to return them. * [TEST] https://fiprinca.0x90.eu/poc/ * [1] https://bugzilla.mozilla.org/1334485 - related bug * [2] https://bugzilla.mozilla.org/1216882 - related bug (see comment 9) ***/ // user_pref("security.nocertdb", true); // (hidden pref) /* 1222: enforce strict pinning * PKP (Public Key Pinning) 0=disabled 1=allow user MiTM (such as your antivirus), 2=strict * [WARNING] If you rely on an AV (antivirus) to protect your web browsing * by inspecting ALL your web traffic, then leave at current default=1 * [1] https://trac.torproject.org/projects/tor/ticket/16206 ***/ user_pref("security.cert_pinning.enforcement_level", 2); /** MIXED CONTENT ***/ /* 1240: disable insecure active content on https pages - mixed content * [1] https://trac.torproject.org/projects/tor/ticket/21323 ***/ user_pref("security.mixed_content.block_active_content", true); // default: true /* 1241: disable insecure passive content (such as images) on https pages - mixed context ***/ user_pref("security.mixed_content.block_display_content", true); /* 1243: block unencrypted requests from Flash on encrypted pages to mitigate MitM attacks (FF59+) * [1] https://bugzilla.mozilla.org/1190623 ***/ user_pref("security.mixed_content.block_object_subrequest", true); /** CIPHERS [see the section 1200 intro] ***/ /* 1260: disable or limit SHA-1 * 0=all SHA1 certs are allowed * 1=all SHA1 certs are blocked (including perfectly valid ones from 2015 and earlier) * 2=deprecated option that now maps to 1 * 3=only allowed for locally-added roots (e.g. anti-virus) * 4=only allowed for locally-added roots or for certs in 2015 and earlier * [WARNING] When disabled, some man-in-the-middle devices (e.g. security scanners and * antivirus products, may fail to connect to HTTPS sites. SHA-1 is *almost* obsolete. * [1] https://blog.mozilla.org/security/2016/10/18/phasing-out-sha-1-on-the-public-web/ ***/ user_pref("security.pki.sha1_enforcement_level", 1); /* 1261: disable 3DES (effective key size < 128) * [1] https://en.wikipedia.org/wiki/3des#Security * [2] http://en.citizendium.org/wiki/Meet-in-the-middle_attack * [3] https://www-archive.mozilla.org/projects/security/pki/nss/ssl/fips-ssl-ciphersuites.html ***/ // user_pref("security.ssl3.rsa_des_ede3_sha", false); /* 1262: disable 128 bits ***/ // user_pref("security.ssl3.ecdhe_ecdsa_aes_128_sha", false); // user_pref("security.ssl3.ecdhe_rsa_aes_128_sha", false); /* 1263: disable DHE (Diffie-Hellman Key Exchange) * [WARNING] May break obscure sites, but not major sites, which should support ECDH over DHE * [1] https://www.eff.org/deeplinks/2015/10/how-to-protect-yourself-from-nsa-attacks-1024-bit-DH ***/ // user_pref("security.ssl3.dhe_rsa_aes_128_sha", false); // user_pref("security.ssl3.dhe_rsa_aes_256_sha", false); /* 1264: disable the remaining non-modern cipher suites as of FF52 * [NOTE] Commented out because it still breaks too many sites ***/ // user_pref("security.ssl3.rsa_aes_128_sha", false); // user_pref("security.ssl3.rsa_aes_256_sha", false); /** UI (User Interface) ***/ /* 1270: display warning (red padlock) for "broken security" (see 1201) * [1] https://wiki.mozilla.org/Security:Renegotiation ***/ user_pref("security.ssl.treat_unsafe_negotiation_as_broken", true); /* 1271: control "Add Security Exception" dialog on SSL warnings * 0=do neither 1=pre-populate url 2=pre-populate url + pre-fetch cert (default) * [1] https://github.com/pyllyukko/user.js/issues/210 ***/ user_pref("browser.ssl_override_behavior", 1); /* 1272: display advanced information on Insecure Connection warning pages * only works when it's possible to add an exception * i.e. it doesn't work for HSTS discrepancies (https://subdomain.preloaded-hsts.badssl.com/) * [TEST] https://expired.badssl.com/ ***/ user_pref("browser.xul.error_pages.expert_bad_cert", true); /* 1273: display "insecure" icon (FF59+) and "Not Secure" text (FF60+) on HTTP sites ***/ user_pref("security.insecure_connection_icon.enabled", true); // all windows user_pref("security.insecure_connection_text.enabled", true); // user_pref("security.insecure_connection_icon.pbmode.enabled", true); // private windows only // user_pref("security.insecure_connection_text.pbmode.enabled", true); /*** 1400: FONTS ***/ user_pref("_user.js.parrot", "1400 syntax error: the parrot's bereft of life!"); /* 1401: disable websites choosing fonts (0=block, 1=allow) * If you disallow fonts, this drastically limits/reduces font * enumeration (by JS) which is a high entropy fingerprinting vector. * [SETTING] General>Language and Appearance>Advanced>Allow pages to choose... * [SETUP] Disabling fonts can uglify the web a fair bit. ***/ user_pref("browser.display.use_document_fonts", 0); /* 1402: set more legible default fonts [SETUP] * [SETTING] General>Language and Appearance>Fonts & Colors>Advanced>Serif|Sans-serif|Monospace * [NOTE] Example below for Windows/Western only ***/ // user_pref("font.name.serif.x-unicode", "Georgia"); // user_pref("font.name.serif.x-western", "Georgia"); // default: Times New Roman // user_pref("font.name.sans-serif.x-unicode", "Arial"); // user_pref("font.name.sans-serif.x-western", "Arial"); // default: Arial // user_pref("font.name.monospace.x-unicode", "Lucida Console"); // user_pref("font.name.monospace.x-western", "Lucida Console"); // default: Courier New /* 1403: disable icon fonts (glyphs) (FF41) and local fallback rendering * [1] https://bugzilla.mozilla.org/789788 * [2] https://trac.torproject.org/projects/tor/ticket/8455 ***/ // user_pref("gfx.downloadable_fonts.enabled", false); // user_pref("gfx.downloadable_fonts.fallback_delay", -1); /* 1404: disable rendering of SVG OpenType fonts * [1] https://wiki.mozilla.org/SVGOpenTypeFonts - iSECPartnersReport recommends to disable this ***/ user_pref("gfx.font_rendering.opentype_svg.enabled", false); /* 1405: disable WOFF2 (Web Open Font Format) (FF35+) ***/ user_pref("gfx.downloadable_fonts.woff2.enabled", false); /* 1406: disable CSS Font Loading API * [SETUP] Disabling fonts can uglify the web a fair bit. ***/ user_pref("layout.css.font-loading-api.enabled", false); /* 1407: disable special underline handling for a few fonts which you will probably never use [RESTART] * Any of these fonts on your system can be enumerated for fingerprinting. * [1] http://kb.mozillazine.org/Font.blacklist.underline_offset ***/ user_pref("font.blacklist.underline_offset", ""); /* 1408: disable graphite which FF49 turned back on by default * In the past it had security issues. Update: This continues to be the case, see [1] * [1] https://www.mozilla.org/security/advisories/mfsa2017-15/#CVE-2017-7778 ***/ user_pref("gfx.font_rendering.graphite.enabled", false); /* 1409: limit system font exposure to a whitelist (FF52+) [SETUP] [RESTART] * If the whitelist is empty, then whitelisting is considered disabled and all fonts are allowed. * [NOTE] Creating your own probably highly-unique whitelist will raise your entropy. If * you block sites choosing fonts in 1401, this preference is irrelevant. In future, * privacy.resistFingerprinting (see 4500) may cover this, and 1401 can be relaxed. * [1] https://bugzilla.mozilla.org/1121643 ***/ // user_pref("font.system.whitelist", ""); // (hidden pref) /*** 1600: HEADERS / REFERERS Only *cross domain* referers need controlling and XOriginPolicy (1603) is perfect for that. Thus we enforce the default values for 1601, 1602, 1605 and 1606 to minimize breakage, and only tweak 1603 and 1604. Our default settings provide the best balance between protection and amount of breakage. To harden it a bit more you can set XOriginPolicy (1603) to 2 (+ optionally 1604 to 1 or 2). To fix broken sites (including your modem/router), temporarily set XOriginPolicy=0 and XOriginTrimmingPolicy=2 in about:config, use the site and then change the values back. If you visit those sites regularly (e.g. Vimeo), use an extension. full URI: https://example.com:8888/foo/bar.html?id=1234 scheme+host+port+path: https://example.com:8888/foo/bar.html scheme+host+port: https://example.com:8888 #Required reading [#] https://feeding.cloud.geek.nz/posts/tweaking-referrer-for-privacy-in-firefox/ ***/ user_pref("_user.js.parrot", "1600 syntax error: the parrot rests in peace!"); /* 1601: ALL: control when images/links send a referer * 0=never, 1=send only when links are clicked, 2=for links and images (default) ***/ user_pref("network.http.sendRefererHeader", 2); /* 1602: ALL: control the amount of information to send * 0=send full URI (default), 1=scheme+host+port+path, 2=scheme+host+port ***/ user_pref("network.http.referer.trimmingPolicy", 0); /* 1603: CROSS ORIGIN: control when to send a referer [SETUP] * 0=always (default), 1=only if base domains match, 2=only if hosts match ***/ user_pref("network.http.referer.XOriginPolicy", 1); /* 1604: CROSS ORIGIN: control the amount of information to send (FF52+) * 0=send full URI (default), 1=scheme+host+port+path, 2=scheme+host+port ***/ user_pref("network.http.referer.XOriginTrimmingPolicy", 0); /* 1605: ALL: disable spoofing a referer * [WARNING] Spoofing effectively disables the anti-CSRF (Cross-Site Request Forgery) protections that some sites may rely on ***/ user_pref("network.http.referer.spoofSource", false); /* 1606: ALL: set the default Referrer Policy * 0=no-referer, 1=same-origin, 2=strict-origin-when-cross-origin, 3=no-referrer-when-downgrade * [NOTE] This is only a default, it can be overridden by a site-controlled Referrer Policy * [1] https://www.w3.org/TR/referrer-policy/ * [2] https://developer.mozilla.org/docs/Web/HTTP/Headers/Referrer-Policy * [3] https://blog.mozilla.org/security/2018/01/31/preventing-data-leaks-by-stripping-path-information-in-http-referrers/ ***/ user_pref("network.http.referer.defaultPolicy", 3); // (FF59+) default: 3 user_pref("network.http.referer.defaultPolicy.pbmode", 2); // (FF59+) default: 2 /* 1607: TOR: hide (not spoof) referrer when leaving a .onion domain (FF54+) * [NOTE] Firefox cannot access .onion sites by default. We recommend you use * TBB (Tor Browser Bundle) which is specifically designed for the dark web * [1] https://bugzilla.mozilla.org/1305144 ***/ user_pref("network.http.referer.hideOnionSource", true); /* 1610: ALL: enable the DNT (Do Not Track) HTTP header * [SETTING] Privacy & Security>Tracking Protecting>Send websites a "Do Not Track"... * [NOTE] DNT is enforced with TP (see 0420) regardless of this pref ***/ user_pref("privacy.donottrackheader.enabled", true); /*** 1700: CONTAINERS [SETUP] [1] https://support.mozilla.org/kb/containers-experiment [2] https://wiki.mozilla.org/Security/Contextual_Identity_Project/Containers [3] https://github.com/mozilla/testpilot-containers ***/ user_pref("_user.js.parrot", "1700 syntax error: the parrot's bit the dust!"); /* 1701: enable Container Tabs setting in preferences (see 1702) (FF50+) * [1] https://bugzilla.mozilla.org/1279029 ***/ // user_pref("privacy.userContext.ui.enabled", true); /* 1702: enable Container Tabs (FF50+) * [SETTING] Privacy & Security>Tabs>Enable Container Tabs ***/ // user_pref("privacy.userContext.enabled", true); /* 1703: enable a private container for thumbnail loads (FF51+) ***/ // user_pref("privacy.usercontext.about_newtab_segregation.enabled", true); // default: true in FF61+ /* 1704: set long press behaviour on "+ Tab" button to display container menu (FF53+) * 0=disables long press, 1=when clicked, the menu is shown * 2=the menu is shown after X milliseconds * [NOTE] The menu does not contain a non-container tab option * [1] https://bugzilla.mozilla.org/1328756 ***/ // user_pref("privacy.userContext.longPressBehavior", 2); /*** 1800: PLUGINS ***/ user_pref("_user.js.parrot", "1800 syntax error: the parrot's pushing up daisies!"); /* 1801: set default plugin state (i.e. new plugins on discovery) to never activate * 0=disabled, 1=ask to activate, 2=active - you can override individual plugins ***/ user_pref("plugin.default.state", 0); user_pref("plugin.defaultXpi.state", 0); /* 1802: enable click to play and set to 0 minutes ***/ user_pref("plugins.click_to_play", true); user_pref("plugin.sessionPermissionNow.intervalInMinutes", 0); /* 1803: disable Flash plugin (Add-ons>Plugins) * 0=deactivated, 1=ask, 2=enabled * ESR52.x is the last branch to *fully* support NPAPI, FF52+ stable only supports Flash * [NOTE] You can still override individual sites via site permissions * [1] https://www.ghacks.net/2013/07/09/how-to-make-sure-that-a-firefox-plugin-never-activates-again/ ***/ user_pref("plugin.state.flash", 0); /* 1805: disable scanning for plugins [WINDOWS] * [1] http://kb.mozillazine.org/Plugin_scanning * plid.all = whether to scan the directories specified in the Windows registry for PLIDs. * Used to detect RealPlayer, Java, Antivirus etc, but since FF52 only covers Flash ***/ user_pref("plugin.scan.plid.all", false); /* 1820: disable all GMP (Gecko Media Plugins) [SETUP] * [1] https://wiki.mozilla.org/GeckoMediaPlugins ***/ user_pref("media.gmp-provider.enabled", false); user_pref("media.gmp.trial-create.enabled", false); user_pref("media.gmp-manager.url", "data:text/plain,"); user_pref("media.gmp-manager.url.override", "data:text/plain,"); // (hidden pref) user_pref("media.gmp-manager.updateEnabled", false); // disable local fallback (hidden pref) /* 1825: disable widevine CDM (Content Decryption Module) [SETUP] ***/ user_pref("media.gmp-widevinecdm.visible", false); user_pref("media.gmp-widevinecdm.enabled", false); user_pref("media.gmp-widevinecdm.autoupdate", false); /* 1830: disable all DRM content (EME: Encryption Media Extension) [SETUP] * [1] https://www.eff.org/deeplinks/2017/10/drms-dead-canary-how-we-just-lost-web-what-we-learned-it-and-what-we-need-do-next ***/ user_pref("media.eme.enabled", false); // [SETTING] General>DRM Content>Play DRM-controlled content user_pref("browser.eme.ui.enabled", false); // hides "Play DRM-controlled content" checkbox [RESTART] /* 1840: disable the OpenH264 Video Codec by Cisco to "Never Activate" * This is the bundled codec used for video chat in WebRTC ***/ user_pref("media.gmp-gmpopenh264.enabled", false); // (hidden pref) user_pref("media.gmp-gmpopenh264.autoupdate", false); /*** 2000: MEDIA / CAMERA / MIC ***/ user_pref("_user.js.parrot", "2000 syntax error: the parrot's snuffed it!"); /* 2001: disable WebRTC (Web Real-Time Communication) * [1] https://www.privacytools.io/#webrtc ***/ user_pref("media.peerconnection.enabled", false); user_pref("media.peerconnection.use_document_iceservers", false); user_pref("media.peerconnection.video.enabled", false); user_pref("media.peerconnection.identity.enabled", false); user_pref("media.peerconnection.identity.timeout", 1); user_pref("media.peerconnection.turn.disable", true); user_pref("media.peerconnection.ice.tcp", false); user_pref("media.navigator.video.enabled", false); // video capability for WebRTC /* 2002: limit WebRTC IP leaks if using WebRTC * [1] https://bugzilla.mozilla.org/buglist.cgi?bug_id=1189041,1297416 * [2] https://wiki.mozilla.org/Media/WebRTC/Privacy ***/ user_pref("media.peerconnection.ice.default_address_only", true); // (FF42-FF50) user_pref("media.peerconnection.ice.no_host", true); // (FF51+) /* 2010: disable WebGL (Web Graphics Library), force bare minimum feature set if used & disable WebGL extensions * [1] https://www.contextis.com/resources/blog/webgl-new-dimension-browser-exploitation/ * [2] https://security.stackexchange.com/questions/13799/is-webgl-a-security-concern ***/ user_pref("webgl.disabled", true); user_pref("pdfjs.enableWebGL", false); user_pref("webgl.min_capability_mode", true); user_pref("webgl.disable-extensions", true); user_pref("webgl.disable-fail-if-major-performance-caveat", true); /* 2012: disable two more webgl preferences (FF51+) ***/ user_pref("webgl.dxgl.enabled", false); // [WINDOWS] user_pref("webgl.enable-webgl2", false); /* 2022: disable screensharing ***/ user_pref("media.getusermedia.screensharing.enabled", false); user_pref("media.getusermedia.browser.enabled", false); user_pref("media.getusermedia.audiocapture.enabled", false); /* 2024: set a default permission for Camera/Microphone (FF58+) * 0=always ask (default), 1=allow, 2=block * [SETTING] to add site exceptions: Page Info>Permissions>Use the Camera/Microphone * [SETTING] to manage site exceptions: Options>Privacy & Security>Permissions>Camera/Microphone>Settings ***/ // user_pref("permissions.default.camera", 2); // user_pref("permissions.default.microphone", 2); /* 2026: disable canvas capture stream (FF41+) * [1] https://developer.mozilla.org/docs/Web/API/HTMLCanvasElement/captureStream ***/ user_pref("canvas.capturestream.enabled", false); /* 2027: disable camera image capture (FF35+) * [1] https://trac.torproject.org/projects/tor/ticket/16339 ***/ user_pref("dom.imagecapture.enabled", false); // default: false /* 2028: disable offscreen canvas (FF44+) * [1] https://developer.mozilla.org/docs/Web/API/OffscreenCanvas ***/ user_pref("gfx.offscreencanvas.enabled", false); // default: false /* 2030: disable auto-play of HTML5 media (FF63+) * 0=Allowed (default), 1=Blocked, 2=Prompt * [WARNING] This may break video playback on various sites ***/ user_pref("media.autoplay.default", 1); /* 2031: disable audio auto-play in non-active tabs (FF51+) * [1] https://www.ghacks.net/2016/11/14/firefox-51-blocks-automatic-audio-playback-in-non-active-tabs/ ***/ user_pref("media.block-autoplay-until-in-foreground", true); /*** 2200: WINDOW MEDDLING & LEAKS / POPUPS ***/ user_pref("_user.js.parrot", "2200 syntax error: the parrot's 'istory!"); /* 2201: prevent websites from disabling new window features * [1] http://kb.mozillazine.org/Prevent_websites_from_disabling_new_window_features ***/ user_pref("dom.disable_window_open_feature.close", true); user_pref("dom.disable_window_open_feature.location", true); // default: true user_pref("dom.disable_window_open_feature.menubar", true); user_pref("dom.disable_window_open_feature.minimizable", true); user_pref("dom.disable_window_open_feature.personalbar", true); // bookmarks toolbar user_pref("dom.disable_window_open_feature.resizable", true); // default: true user_pref("dom.disable_window_open_feature.status", true); // status bar - default: true user_pref("dom.disable_window_open_feature.titlebar", true); user_pref("dom.disable_window_open_feature.toolbar", true); /* 2202: prevent scripts moving and resizing open windows ***/ user_pref("dom.disable_window_move_resize", true); /* 2203: open links targeting new windows in a new tab instead * This stops malicious window sizes and some screen resolution leaks. * You can still right-click a link and open in a new window. * [TEST] https://people.torproject.org/~gk/misc/entire_desktop.html * [1] https://trac.torproject.org/projects/tor/ticket/9881 ***/ user_pref("browser.link.open_newwindow", 3); user_pref("browser.link.open_newwindow.restriction", 0); /* 2204: disable Fullscreen API (requires user interaction) to prevent screen-resolution leaks * [NOTE] You can still manually toggle the browser's fullscreen state (F11), * but this pref will disable embedded video/game fullscreen controls, e.g. youtube * [TEST] https://developer.mozilla.org/samples/domref/fullscreen.html ***/ // user_pref("full-screen-api.enabled", false); /* 2210: block popup windows * [SETTING] Privacy & Security>Permissions>Block pop-up windows ***/ user_pref("dom.disable_open_during_load", true); /* 2211: set max popups from a single non-click event - default is 20! ***/ user_pref("dom.popup_maximum", 3); /* 2212: limit events that can cause a popup * default is "change click dblclick mouseup pointerup notificationclick reset submit touchend" * [1] http://kb.mozillazine.org/Dom.popup_allowed_events ***/ user_pref("dom.popup_allowed_events", "click dblclick"); /*** 2300: WEB WORKERS [SETUP] A worker is a JS "background task" running in a global context, i.e. it is different from the current window. Workers can spawn new workers (must be the same origin & scheme), including service and shared workers. Shared workers can be utilized by multiple scripts and communicate between browsing contexts (windows/tabs/iframes) and can even control your cache. [WARNING] Disabling "web workers" might break sites [UPDATE] uMatrix 1.2.0+ allows a per-scope control for workers (2301-deprecated) and service workers (2302) #Required reading [#] https://github.com/gorhill/uMatrix/releases/tag/1.2.0 [1] Web Workers: https://developer.mozilla.org/docs/Web/API/Web_Workers_API [2] Worker: https://developer.mozilla.org/docs/Web/API/Worker [3] Service Worker: https://developer.mozilla.org/docs/Web/API/Service_Worker_API [4] SharedWorker: https://developer.mozilla.org/docs/Web/API/SharedWorker [5] ChromeWorker: https://developer.mozilla.org/docs/Web/API/ChromeWorker [6] Notifications: https://support.mozilla.org/questions/1165867#answer-981820 ***/ user_pref("_user.js.parrot", "2300 syntax error: the parrot's off the twig!"); /* 2302: disable service workers * Service workers essentially act as proxy servers that sit between web apps, and the browser * and network, are event driven, and can control the web page/site it is associated with, * intercepting and modifying navigation and resource requests, and caching resources. * [NOTE] Service worker APIs are hidden (in Firefox) and cannot be used when in PB mode. * [NOTE] Service workers only run over HTTPS. Service Workers have no DOM access. ***/ user_pref("dom.serviceWorkers.enabled", false); /* 2304: disable web notifications * [1] https://developer.mozilla.org/docs/Web/API/Notifications_API ***/ user_pref("dom.webnotifications.enabled", false); // (FF22+) user_pref("dom.webnotifications.serviceworker.enabled", false); // (FF44+) /* 2305: set a default permission for Notifications (see 2304) (FF58+) * [SETTING] to add site exceptions: Page Info>Permissions>Receive Notifications * [SETTING] to manage site exceptions: Options>Privacy & Security>Permissions>Notifications>Settings ***/ // user_pref("permissions.default.desktop-notification", 2); // 0=always ask (default), 1=allow, 2=block /* 2306: disable push notifications (FF44+) * web apps can receive messages pushed to them from a server, whether or * not the web app is in the foreground, or even currently loaded * [1] https://developer.mozilla.org/docs/Web/API/Push_API ***/ user_pref("dom.push.enabled", false); user_pref("dom.push.connection.enabled", false); user_pref("dom.push.serverURL", ""); user_pref("dom.push.userAgentID", ""); /*** 2400: DOM (DOCUMENT OBJECT MODEL) & JAVASCRIPT ***/ user_pref("_user.js.parrot", "2400 syntax error: the parrot's kicked the bucket!"); /* 2401: disable website control over browser right-click context menu * [NOTE] Shift-Right-Click will always bring up the browser right-click context menu ***/ // user_pref("dom.event.contextmenu.enabled", false); /* 2402: disable website access to clipboard events/content * [WARNING] This will break some sites functionality such as pasting into facebook, wordpress * this applies to onCut, onCopy, onPaste events - i.e. you have to interact with * the website for it to look at the clipboard * [1] https://www.ghacks.net/2014/01/08/block-websites-reading-modifying-clipboard-contents-firefox/ ***/ user_pref("dom.event.clipboardevents.enabled", false); /* 2403: disable clipboard commands (cut/copy) from "non-privileged" content (FF41+) * this disables document.execCommand("cut"/"copy") to protect your clipboard * [1] https://bugzilla.mozilla.org/1170911 ***/ user_pref("dom.allow_cut_copy", false); // (hidden pref) /* 2404: disable "Confirm you want to leave" dialog on page close * Does not prevent JS leaks of the page close event. * [1] https://developer.mozilla.org/docs/Web/Events/beforeunload * [2] https://support.mozilla.org/questions/1043508 ***/ user_pref("dom.disable_beforeunload", true); /* 2414: disable shaking the screen ***/ user_pref("dom.vibrator.enabled", false); /* 2420: disable asm.js (FF22+) * [1] http://asmjs.org/ * [2] https://www.mozilla.org/security/advisories/mfsa2015-29/ * [3] https://www.mozilla.org/security/advisories/mfsa2015-50/ * [4] https://www.mozilla.org/security/advisories/mfsa2017-01/#CVE-2017-5375 * [5] https://www.mozilla.org/security/advisories/mfsa2017-05/#CVE-2017-5400 * [6] https://rh0dev.github.io/blog/2017/the-return-of-the-jit/ ***/ user_pref("javascript.options.asmjs", false); /* 2421: disable Ion and baseline JIT to help harden JS against exploits * [WARNING] Causes the odd site issue and there is also a performance loss * [1] https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2015-0817 ***/ // user_pref("javascript.options.ion", false); // user_pref("javascript.options.baselinejit", false); /* 2422: disable WebAssembly for now (FF52+) * [1] https://developer.mozilla.org/docs/WebAssembly ***/ user_pref("javascript.options.wasm", false); /* 2426: disable Intersection Observer API (FF53+) * Almost a year to complete, three versions late to stable (as default false), * number #1 cause of crashes in nightly numerous times, and is (primarily) an * ad network API for "ad viewability checks" down to a pixel level * [1] https://developer.mozilla.org/docs/Web/API/Intersection_Observer_API * [2] https://w3c.github.io/IntersectionObserver/ * [3] https://bugzilla.mozilla.org/1243846 ***/ user_pref("dom.IntersectionObserver.enabled", false); /* 2427: disable Shared Memory (Spectre mitigation) * [1] https://github.com/tc39/ecmascript_sharedmem/blob/master/TUTORIAL.md * [2] https://blog.mozilla.org/security/2018/01/03/mitigations-landing-new-class-timing-attack/ ***/ user_pref("javascript.options.shared_memory", false); /*** 2500: HARDWARE FINGERPRINTING ***/ user_pref("_user.js.parrot", "2500 syntax error: the parrot's shuffled off 'is mortal coil!"); /* 2502: disable Battery Status API * Initially a Linux issue (high precision readout) that was fixed. * However, it is still another metric for fingerprinting, used to raise entropy. * e.g. do you have a battery or not, current charging status, charge level, times remaining etc * [NOTE] From FF52+ Battery Status API is only available in chrome/privileged code. see [1] * [1] https://bugzilla.mozilla.org/1313580 ***/ // user_pref("dom.battery.enabled", false); /* 2504: disable virtual reality devices * [WARNING] [SETUP] Optional protection depending on your connected devices * [1] https://developer.mozilla.org/docs/Web/API/WebVR_API ***/ // user_pref("dom.vr.enabled", false); /* 2505: disable media device enumeration (FF29+) * [NOTE] media.peerconnection.enabled should also be set to false (see 2001) * [1] https://wiki.mozilla.org/Media/getUserMedia * [2] https://developer.mozilla.org/docs/Web/API/MediaDevices/enumerateDevices ***/ user_pref("media.navigator.enabled", false); /* 2508: disable hardware acceleration to reduce graphics fingerprinting * [SETTING] General>Performance>Custom>Use hardware acceleration when available * [WARNING] [SETUP] Affects text rendering (fonts will look different), impacts video performance, * and parts of Quantum that utilize the GPU will also be affected as they are rolled out * [1] https://wiki.mozilla.org/Platform/GFX/HardwareAcceleration ***/ // user_pref("gfx.direct2d.disabled", true); // [WINDOWS] user_pref("layers.acceleration.disabled", true); /* 2510: disable Web Audio API (FF51+) * [1] https://bugzilla.mozilla.org/1288359 ***/ user_pref("dom.webaudio.enabled", false); /* 2516: disable PointerEvents * [1] https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent ***/ user_pref("dom.w3c_pointer_events.enabled", false); /* 2517: disable Media Capabilities API (FF63+) * [WARNING] This *may* affect media performance if disabled, no one is sure * [1] https://github.com/WICG/media-capabilities * [2] https://wicg.github.io/media-capabilities/#security-privacy-considerations ***/ // user_pref("media.media-capabilities.enabled", false); /*** 2600: MISCELLANEOUS ***/ user_pref("_user.js.parrot", "2600 syntax error: the parrot's run down the curtain!"); /* 2601: prevent accessibility services from accessing your browser [RESTART] * [SETTING] Privacy & Security>Permissions>Prevent accessibility services from accessing your browser * [1] https://support.mozilla.org/kb/accessibility-services ***/ user_pref("accessibility.force_disabled", 1); /* 2602: disable sending additional analytics to web servers * [1] https://developer.mozilla.org/docs/Web/API/Navigator/sendBeacon ***/ user_pref("beacon.enabled", false); /* 2603: remove temp files opened with an external application * [1] https://bugzilla.mozilla.org/302433 ***/ user_pref("browser.helperApps.deleteTempFileOnExit", true); /* 2604: disable page thumbnail collection * look in profile/thumbnails directory - you may want to clean that out ***/ user_pref("browser.pagethumbnails.capturing_disabled", true); // (hidden pref) /* 2605: block web content in file processes (FF55+) * [WARNING] [SETUP] You may want to disable this for corporate or developer environments * [1] https://bugzilla.mozilla.org/1343184 ***/ user_pref("browser.tabs.remote.allowLinkedWebInFileUriProcess", false); /* 2606: disable UITour backend so there is no chance that a remote page can use it ***/ user_pref("browser.uitour.enabled", false); user_pref("browser.uitour.url", ""); /* 2607: disable various developer tools in browser context * [SETTING] Devtools>Advanced Settings>Enable browser chrome and add-on debugging toolboxes * [1] https://github.com/pyllyukko/user.js/issues/179#issuecomment-246468676 ***/ user_pref("devtools.chrome.enabled", false); /* 2608: disable WebIDE to prevent remote debugging and extension downloads * [1] https://trac.torproject.org/projects/tor/ticket/16222 ***/ user_pref("devtools.webide.autoinstallADBHelper", false); user_pref("devtools.debugger.remote-enabled", false); user_pref("devtools.webide.enabled", false); /* 2609: disable MathML (Mathematical Markup Language) (FF51+) * [TEST] http://browserspy.dk/mathml.php * [1] https://bugzilla.mozilla.org/1173199 ***/ user_pref("mathml.disabled", true); /* 2610: disable in-content SVG (Scalable Vector Graphics) (FF53+) * [WARNING] Expect breakage incl. youtube player controls. Best left for a "hardened" profile. * [1] https://bugzilla.mozilla.org/1216893 ***/ // user_pref("svg.disabled", true); /* 2611: disable middle mouse click opening links from clipboard * [1] https://trac.torproject.org/projects/tor/ticket/10089 * [2] http://kb.mozillazine.org/Middlemouse.contentLoadURL ***/ user_pref("middlemouse.contentLoadURL", false); /* 2614: limit HTTP redirects (this does not control redirects with HTML meta tags or JS) * [WARNING] A low setting of 5 or under will probably break some sites (e.g. gmail logins) * To control HTML Meta tag and JS redirects, use an extension. Default is 20 ***/ user_pref("network.http.redirection-limit", 10); /* 2615: disable websites overriding Firefox's keyboard shortcuts (FF58+) * [SETTING] to add site exceptions: Page Info>Permissions>Override Keyboard Shortcuts * [NOTE] At the time of writing, causes issues with delete and backspace keys ***/ // user_pref("permissions.default.shortcuts", 2); // 0 (default) or 1=allow, 2=block /* 2616: remove special permissions for certain mozilla domains (FF35+) * [1] resource://app/defaults/permissions ***/ user_pref("permissions.manager.defaultsUrl", ""); /* 2617: remove webchannel whitelist ***/ user_pref("webchannel.allowObject.urlWhitelist", ""); /* 2618: disable exposure of system colors to CSS or canvas (FF44+) * [NOTE] see second listed bug: may cause black on black for elements with undefined colors * [1] https://bugzilla.mozilla.org/buglist.cgi?bug_id=232227,1330876 ***/ user_pref("ui.use_standins_for_native_colors", true); // (hidden pref) /* 2619: enforce Punycode for Internationalized Domain Names to eliminate possible spoofing * Firefox has *some* protections, but it is better to be safe than sorry. The downside: it will also * display legitimate IDN's punycoded, which might be undesirable for users of non-latin alphabets * [TEST] https://www.xn--80ak6aa92e.com/ (www.apple.com) * [1] https://wiki.mozilla.org/IDN_Display_Algorithm * [2] https://en.wikipedia.org/wiki/IDN_homograph_attack * [3] CVE-2017-5383: https://www.mozilla.org/security/advisories/mfsa2017-02/ * [4] https://www.xudongz.com/blog/2017/idn-phishing/ ***/ user_pref("network.IDN_show_punycode", true); /* 2620: enable Firefox's built-in PDF reader [SETUP] * [SETTING] General>Applications>Portable Document Format (PDF) * This setting controls if the option "Display in Firefox" in the above setting is available * and by effect controls whether PDFs are handled in-browser or externally ("Ask" or "Open With") * PROS: pdfjs is lightweight, open source, and as secure/vetted as any pdf reader out there (more than most) * Exploits are rare (1 serious case in 4 yrs), treated seriously and patched quickly. * It doesn't break "state separation" of browser content (by not sharing with OS, independent apps). * It maintains disk avoidance and application data isolation. It's convenient. You can still save to disk. * CONS: You may prefer a different pdf reader for security reasons * CAVEAT: JS can still force a pdf to open in-browser by bundling its own code (rare) ***/ user_pref("pdfjs.disabled", false); /** DOWNLOADS ***/ /* 2650: discourage downloading to desktop (0=desktop 1=downloads 2=last used) * [SETTING] To set your default "downloads": General>Downloads>Save files to ***/ user_pref("browser.download.folderList", 2); /* 2651: enforce user interaction for security by always asking the user where to download * [SETTING] General>Downloads>Always ask you where to save files ***/ user_pref("browser.download.useDownloadDir", false); /* 2652: disable adding downloads to the system's "recent documents" list ***/ user_pref("browser.download.manager.addToRecentDocs", false); /* 2653: disable hiding mime types (Options>General>Applications) not associated with a plugin ***/ user_pref("browser.download.hide_plugins_without_extensions", false); /* 2654: disable "open with" in download dialog (FF50+) * This is very useful to enable when the browser is sandboxed (e.g. via AppArmor) * in such a way that it is forbidden to run external applications. * [SETUP] This may interfere with some users' workflow or methods * [1] https://bugzilla.mozilla.org/1281959 ***/ user_pref("browser.download.forbid_open_with", true); /** EXTENSIONS ***/ /* 2660: lock down allowed extension directories * [WARNING] This will break extensions that do not use the default XPI directories * [1] https://mike.kaply.com/2012/02/21/understanding-add-on-scopes/ * [1] archived: https://archive.is/DYjAM ***/ user_pref("extensions.enabledScopes", 1); // (hidden pref) user_pref("extensions.autoDisableScopes", 15); /* 2662: disable webextension restrictions on certain mozilla domains (also see 4503) (FF60+) * [1] https://bugzilla.mozilla.org/buglist.cgi?bug_id=1384330,1406795,1415644,1453988 ***/ // user_pref("extensions.webextensions.restrictedDomains", ""); /* 2663: enable warning when websites try to install add-ons * [SETTING] Privacy & Security>Permissions>Warn you when websites try to install add-ons ***/ user_pref("xpinstall.whitelist.required", true); // default: true /** SECURITY ***/ /* 2680: enable CSP (Content Security Policy) * [1] https://developer.mozilla.org/docs/Web/HTTP/CSP ***/ user_pref("security.csp.enable", true); // default: true /* 2681: disable CSP violation events (FF59+) * [1] https://developer.mozilla.org/docs/Web/API/SecurityPolicyViolationEvent ***/ user_pref("security.csp.enable_violation_events", false); /* 2682: enable CSP 1.1 experimental hash-source directive (FF29+) * [1] https://bugzilla.mozilla.org/buglist.cgi?bug_id=855326,883975 ***/ user_pref("security.csp.experimentalEnabled", true); /* 2683: block top level window data: URIs (FF56+) * [1] https://bugzilla.mozilla.org/1331351 * [2] https://www.wordfence.com/blog/2017/01/gmail-phishing-data-uri/ * [3] https://www.fxsitecompat.com/en-CA/docs/2017/data-url-navigations-on-top-level-window-will-be-blocked/ ***/ user_pref("security.data_uri.block_toplevel_data_uri_navigations", true); // default: true in FF59+ /* 2684: enforce a security delay on some confirmation dialogs such as install, open/save * [1] http://kb.mozillazine.org/Disable_extension_install_delay_-_Firefox * [2] https://www.squarefree.com/2004/07/01/race-conditions-in-security-dialogs/ ***/ user_pref("security.dialog_enable_delay", 700); // default: 1000 (milliseconds) /*** 2700: PERSISTENT STORAGE Data SET by websites including cookies : profile\cookies.sqlite localStorage : profile\webappsstore.sqlite indexedDB : profile\storage\default appCache : profile\OfflineCache serviceWorkers : ***/ user_pref("_user.js.parrot", "2700 syntax error: the parrot's joined the bleedin' choir invisible!"); /* 2701: disable 3rd-party cookies and site-data [SETUP] * You can set exceptions under site permissions or use an extension * 0=Accept cookies and site data, 1=Block third-party cookies, 2=Block all cookies, * 3=Block cookies from unvisited sites, 4=Block third-party trackers (FF63+) * [NOTE] value 4 is tied to the Tracking Protection lists so make sure you have 0424 + 0425 on default values! * [SETTING] Privacy & Security>History>Custom Settings>Accept cookies from sites * [NOTE] Blocking 3rd party controls 3rd party access to localStorage, IndexedDB, Cache API and Service Worker Cache. * Blocking 1st party controls access to localStorage and IndexedDB (note: Service Workers can still use IndexedDB). * [1] https://www.fxsitecompat.com/en-CA/docs/2015/web-storage-indexeddb-cache-api-now-obey-third-party-cookies-preference/ ***/ user_pref("network.cookie.cookieBehavior", 1); /* 2702: set third-party cookies (i.e ALL) (if enabled, see above pref) to session-only and (FF58+) set third-party non-secure (i.e HTTP) cookies to session-only [NOTE] .sessionOnly overrides .nonsecureSessionOnly except when .sessionOnly=false and .nonsecureSessionOnly=true. This allows you to keep HTTPS cookies, but session-only HTTP ones * [1] https://feeding.cloud.geek.nz/posts/tweaking-cookies-for-privacy-in-firefox/ * [2] http://kb.mozillazine.org/Network.cookie.thirdparty.sessionOnly ***/ user_pref("network.cookie.thirdparty.sessionOnly", true); user_pref("network.cookie.thirdparty.nonsecureSessionOnly", true); // (FF58+) /* 2703: set cookie lifetime policy * 0=until they expire (default), 2=until you close Firefox * [NOTE] 3=for n days : no longer supported in FF63+ (see 2704-deprecated) * [SETTING] Privacy & Security>History>Custom Settings>Accept cookies from sites>Keep until ***/ // user_pref("network.cookie.lifetimePolicy", 0); /* 2705: disable HTTP sites setting cookies with the "secure" directive (FF52+) * [1] https://developer.mozilla.org/Firefox/Releases/52#HTTP ***/ user_pref("network.cookie.leave-secure-alone", true); // default: true /* 2706: enable support for same-site cookies (FF60+) * [1] https://bugzilla.mozilla.org/795346 * [2] https://blog.mozilla.org/security/2018/04/24/same-site-cookies-in-firefox-60/ * [3] https://www.sjoerdlangkemper.nl/2016/04/14/preventing-csrf-with-samesite-cookie-attribute/ ***/ // user_pref("network.cookie.same-site.enabled", true); // default: true /* 2710: disable DOM (Document Object Model) Storage * [WARNING] This will break a LOT of sites' functionality AND extensions! * You are better off using an extension for more granular control ***/ // user_pref("dom.storage.enabled", false); /* 2720: enforce IndexedDB (IDB) as enabled * IDB is required for extensions and Firefox internals (even before FF63 in [1]) * To control *website* IDB data, control allowing cookies and service workers, or use * Temporary Containers. To mitigate *website* IDB, FPI helps (4001), and/or sanitize * on close (Offline Website Data, see 2800) or on-demand (Ctrl-Shift-Del), or automatically * via an extenion. Note that IDB currently cannot be sanitized by host. * [1] https://blog.mozilla.org/addons/2018/08/03/new-backend-for-storage-local-api/ ***/ user_pref("dom.indexedDB.enabled", true); // default: true /* 2730: disable offline cache ***/ user_pref("browser.cache.offline.enable", false); /* 2730b: disable offline cache on insecure sites (FF60+) * [1] https://blog.mozilla.org/security/2018/02/12/restricting-appcache-secure-contexts/ ***/ user_pref("browser.cache.offline.insecure.enable", false); // default: false in FF62+ /* 2731: enforce websites to ask to store data for offline use * [1] https://support.mozilla.org/questions/1098540 * [2] https://bugzilla.mozilla.org/959985 ***/ user_pref("offline-apps.allow_by_default", false); /* 2740: disable service workers cache and cache storage * [1] https://w3c.github.io/ServiceWorker/#privacy ***/ user_pref("dom.caches.enabled", false); /* 2750: disable Storage API (FF51+) * The API gives sites the ability to find out how much space they can use, how much * they are already using, and even control whether or not they need to be alerted * before the user agent disposes of site data in order to make room for other things. * [1] https://developer.mozilla.org/docs/Web/API/StorageManager * [2] https://developer.mozilla.org/docs/Web/API/Storage_API * [3] https://blog.mozilla.org/l10n/2017/03/07/firefox-l10n-report-aurora-54/ ***/ // user_pref("dom.storageManager.enabled", false); /*** 2800: SHUTDOWN [SETUP] You should set the values to what suits you best. - "Offline Website Data" includes appCache (2730), localStorage (2710), Service Worker cache (2740), and QuotaManager (IndexedDB (2720), asm-cache) - In both 2803 + 2804, the 'download' and 'history' prefs are combined in the Firefox interface as "Browsing & Download History" and their values will be synced ***/ user_pref("_user.js.parrot", "2800 syntax error: the parrot's bleedin' demised!"); /* 2802: enable Firefox to clear history items on shutdown * [SETTING] Privacy & Security>History>Clear history when Firefox closes ***/ user_pref("privacy.sanitize.sanitizeOnShutdown", true); /* 2803: set what history items to clear on shutdown * [SETTING] Privacy & Security>History>Clear history when Firefox closes>Settings * [NOTE] If 'history' is true, downloads will also be cleared regardless of the value * but if 'history' is false, downloads can still be cleared independently * However, this may not always be the case. The interface combines and syncs these * prefs when set from there, and the sanitize code may change at any time ***/ user_pref("privacy.clearOnShutdown.cache", true); user_pref("privacy.clearOnShutdown.cookies", true); user_pref("privacy.clearOnShutdown.downloads", true); // see note above user_pref("privacy.clearOnShutdown.formdata", true); // Form & Search History user_pref("privacy.clearOnShutdown.history", true); // Browsing & Download History user_pref("privacy.clearOnShutdown.offlineApps", true); // Offline Website Data user_pref("privacy.clearOnShutdown.sessions", true); // Active Logins user_pref("privacy.clearOnShutdown.siteSettings", false); // Site Preferences /* 2804: reset default history items to clear with Ctrl-Shift-Del (to match above) * This dialog can also be accessed from the menu History>Clear Recent History * Firefox remembers your last choices. This will reset them when you start Firefox. * [NOTE] Regardless of what you set privacy.cpd.downloads to, as soon as the dialog * for "Clear Recent History" is opened, it is synced to the same as 'history' ***/ user_pref("privacy.cpd.cache", true); user_pref("privacy.cpd.cookies", true); // user_pref("privacy.cpd.downloads", true); // not used, see note above user_pref("privacy.cpd.formdata", true); // Form & Search History user_pref("privacy.cpd.history", true); // Browsing & Download History user_pref("privacy.cpd.offlineApps", true); // Offline Website Data user_pref("privacy.cpd.passwords", false); // this is not listed user_pref("privacy.cpd.sessions", true); // Active Logins user_pref("privacy.cpd.siteSettings", false); // Site Preferences /* 2805: privacy.*.openWindows (clear session restore data) (FF34+) * [NOTE] There is a years-old bug that these cause two windows when Firefox restarts. * You do not need these anyway if session restore is disabled (see 1020) ***/ // user_pref("privacy.clearOnShutdown.openWindows", true); // user_pref("privacy.cpd.openWindows", true); /* 2806: reset default 'Time range to clear' for 'Clear Recent History' (see 2804) * Firefox remembers your last choice. This will reset the value when you start Firefox. * 0=everything, 1=last hour, 2=last two hours, 3=last four hours, * 4=today, 5=last five minutes, 6=last twenty-four hours * [NOTE] The values 5 + 6 are not listed in the dropdown, which will display a * blank value if they are used, but they do work as advertised ***/ user_pref("privacy.sanitize.timeSpan", 0); /*** 4000: FIRST PARTY ISOLATION (FPI) ** 1278037 - isolate indexedDB (FF51+) ** 1277803 - isolate favicons (FF52+) ** 1264562 - isolate OCSP cache (FF52+) ** 1268726 - isolate Shared Workers (FF52+) ** 1316283 - isolate SSL session cache (FF52+) ** 1317927 - isolate media cache (FF53+) ** 1323644 - isolate HSTS and HPKP (FF54+) ** 1334690 - isolate HTTP Alternative Services (FF54+) ** 1334693 - isolate SPDY/HTTP2 (FF55+) ** 1337893 - isolate DNS cache (FF55+) ** 1344170 - isolate blob: URI (FF55+) ** 1300671 - isolate data:, about: URLs (FF55+) ** 1473247 - isolate IP addresses (FF63+) ** 1492607 - isolate postMessage with targetOrigin "*" (requires 4002) (FF65+) NOTE: FPI has some issues depending on your Firefox release ** 1418931 - [fixed in FF58+] IndexedDB (Offline Website Data) with FPI Origin Attributes are not removed with "Clear All/Recent History" or "On Close" ** 1381197 - [fixed in FF59+] extensions cannot control cookies with FPI Origin Attributes ***/ user_pref("_user.js.parrot", "4000 syntax error: the parrot's pegged out"); /* 4001: enable First Party Isolation (FF51+) * [WARNING] May break cross-domain logins and site functionality until perfected * [1] https://bugzilla.mozilla.org/1260931 ***/ user_pref("privacy.firstparty.isolate", true); /* 4002: enforce FPI restriction for window.opener (FF54+) * [NOTE] Setting this to false may reduce the breakage in 4001 * [FF65+] blocks postMessage with targetOrigin "*" if originAttributes don't match. But * to reduce breakage it ignores the 1st-party domain (FPD) originAttribute. (see [2],[3]) * The 2nd pref removes that limitation and will only allow communication if FPDs also match. * [1] https://bugzilla.mozilla.org/1319773#c22 * [2] https://bugzilla.mozilla.org/1492607 * [3] https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage ***/ user_pref("privacy.firstparty.isolate.restrict_opener_access", true); // default: true // user_pref("privacy.firstparty.isolate.block_post_message", true); // (hidden pref) /*** 4500: privacy.resistFingerprinting (RFP) This master switch will be used for a wide range of items, many of which will **override** existing prefs from FF55+, often providing a **better** solution IMPORTANT: As existing prefs become redundant, and some of them WILL interfere with how RFP works, they will be moved to section 4600 and made inactive ** 418986 - limit window.screen & CSS media queries leaking identifiable info (FF41+) [POC] http://ip-check.info/?lang=en (screen, usable screen, and browser window will match) [NOTE] Does not cover everything yet - https://bugzilla.mozilla.org/1216800 [NOTE] This will probably make your values pretty unique until you resize or snap the inner window width + height into standard/common resolutions (such as 1366x768) To set a size, open a XUL (chrome) page (such as about:config) which is at 100% zoom, hit Shift+F4 to open the scratchpad, type window.resizeTo(1366,768), hit Ctrl+R to run. Test your window size, do some math, resize to allow for all the non inner window elements [TEST] http://browserspy.dk/screen.php ** 1281949 - spoof screen orientation (FF50+) ** 1281963 - hide the contents of navigator.plugins and navigator.mimeTypes (FF50+) FF53: Fixes GetSupportedNames in nsMimeTypeArray and nsPluginArray (1324044) ** 1330890 - spoof timezone as UTC 0 (FF55+) FF58: Date.toLocaleFormat deprecated (818634) FF60: Date.toLocaleDateString and Intl.DateTimeFormat fixed (1409973) ** 1360039 - spoof navigator.hardwareConcurrency as 2 (see 4601) (FF55+) This spoof *shouldn't* affect core chrome/Firefox performance ** 1217238 - reduce precision of time exposed by javascript (FF55+) ** 1369303 - spoof/disable performance API (see 2410-deprecated, 4602, 4603) (FF56+) ** 1333651 & 1383495 & 1396468 - spoof Navigator API (see section 4700) (FF56+) FF56: The version number will be rounded down to the nearest multiple of 10 FF57: The version number will match current ESR (1393283, 1418672, 1418162) FF59: The OS will be reported as Windows, OSX, Android, or Linux (to reduce breakage) (1404608) ** 1369319 - disable device sensor API (see 4604) (FF56+) ** 1369357 - disable site specific zoom (see 4605) (FF56+) ** 1337161 - hide gamepads from content (see 4606) (FF56+) ** 1372072 - spoof network information API as "unknown" (see 4607) (FF56+) ** 1333641 - reduce fingerprinting in WebSpeech API (see 4608) (FF56+) ** 1372069 & 1403813 & 1441295 - block geolocation requests (same as denying a site permission) (see 0201, 0211) (FF56-62) ** 1369309 - spoof media statistics (see 4610) (FF57+) ** 1382499 - reduce screen co-ordinate fingerprinting in Touch API (see 4611) (FF57+) ** 1217290 & 1409677 - enable fingerprinting resistance for WebGL (see 2010-12) (FF57+) ** 1382545 - reduce fingerprinting in Animation API (FF57+) ** 1354633 - limit MediaError.message to a whitelist (FF57+) ** 1382533 - enable fingerprinting resistance for Presentation API (FF57+) This blocks exposure of local IP Addresses via mDNS (Multicast DNS) ** 967895 - enable site permission prompt before allowing canvas data extraction (FF58+) FF59: Added to site permissions panel (1413780) Only prompt when triggered by user input (1376865) ** 1372073 - spoof/block fingerprinting in MediaDevices API (see 4612) (FF59+) ** 1039069 - warn when language prefs are set to non en-US (see 0207, 0208) (FF59+) ** 1222285 & 1433592 - spoof keyboard events and suppress keyboard modifier events (FF59+) Spoofing mimics the content language of the document. Currently it only supports en-US. Modifier events suppressed are SHIFT and both ALT keys. Chrome is not affected. FF60: Fix keydown/keyup events (1438795) ** 1337157 - disable WebGL debug renderer info (see 4613) (FF60+) ** 1459089 - disable OS locale in HTTP Accept-Language headers [ANDROID] (FF62+) ** 1363508 - spoof/suppress Pointer Events (FF64+) ***/ user_pref("_user.js.parrot", "4500 syntax error: the parrot's popped 'is clogs"); /* 4501: enable privacy.resistFingerprinting (FF41+) * [1] https://bugzilla.mozilla.org/418986 ***/ user_pref("privacy.resistFingerprinting", true); // (hidden pref) (not hidden FF55+) /* 4502: set new window sizes to round to hundreds (FF55+) [SETUP] * [NOTE] Width will round down to multiples of 200s and height to 100s, to fit your screen. * The override values are a starting point to round from if you want some control * [1] https://bugzilla.mozilla.org/1330882 * [2] https://hardware.metrics.mozilla.com/ ***/ // user_pref("privacy.window.maxInnerWidth", 1600); // (hidden pref) // user_pref("privacy.window.maxInnerHeight", 900); // (hidden pref) /* 4503: disable mozAddonManager Web API (FF57+) * [NOTE] As a side-effect in FF57-59 this allowed extensions to work on AMO. In FF60+ you also need * to sanitize or clear extensions.webextensions.restrictedDomains (see 2662) to keep that side-effect * [1] https://bugzilla.mozilla.org/buglist.cgi?bug_id=1384330,1406795,1415644,1453988 ***/ user_pref("privacy.resistFingerprinting.block_mozAddonManager", true); // (hidden pref) /* 4504: disable showing about:blank as soon as possible during startup (FF60+) * When default true (FF62+) this no longer masks the RFP resizing activity * [1] https://bugzilla.mozilla.org/1448423 ***/ user_pref("browser.startup.blankWindow", false); /*** 4600: RFP (4500) ALTERNATIVES [SETUP] * IF you DO use RFP (see 4500) then you DO NOT need these redundant prefs. In fact, some even cause RFP to not behave as you would expect and alter your fingerprint. Make sure they are RESET in about:config as per your Firefox version * IF you DO NOT use RFP or are on ESR... then turn on each ESR section below ***/ user_pref("_user.js.parrot", "4600 syntax error: the parrot's crossed the Jordan"); /* [NOTE] ESR52.x and non-RFP users replace the * with a slash on this line to enable these // FF55+ // 4601: [2514] spoof (or limit?) number of CPU cores (FF48+) // [WARNING] *may* affect core chrome/Firefox performance, will affect content. // [1] https://bugzilla.mozilla.org/1008453 // [2] https://trac.torproject.org/projects/tor/ticket/21675 // [3] https://trac.torproject.org/projects/tor/ticket/22127 // [4] https://html.spec.whatwg.org/multipage/workers.html#navigator.hardwareconcurrency // user_pref("dom.maxHardwareConcurrency", 2); // * * * / // FF56+ // 4602: [2411] disable resource/navigation timing user_pref("dom.enable_resource_timing", false); // 4603: [2412] disable timing attacks // [1] https://wiki.mozilla.org/Security/Reviews/Firefox/NavigationTimingAPI user_pref("dom.enable_performance", false); // 4604: [2512] disable device sensor API // [WARNING] [SETUP] Optional protection depending on your device // [1] https://trac.torproject.org/projects/tor/ticket/15758 // [2] https://blog.lukaszolejnik.com/stealing-sensitive-browser-data-with-the-w3c-ambient-light-sensor-api/ // [3] https://bugzilla.mozilla.org/buglist.cgi?bug_id=1357733,1292751 // user_pref("device.sensors.enabled", false); // 4605: [2515] disable site specific zoom // Zoom levels affect screen res and are highly fingerprintable. This does not stop you using // zoom, it will just not use/remember any site specific settings. Zoom levels on new tabs // and new windows are reset to default and only the current tab retains the current zoom user_pref("browser.zoom.siteSpecific", false); // 4606: [2501] disable gamepad API - USB device ID enumeration // [WARNING] [SETUP] Optional protection depending on your connected devices // [1] https://trac.torproject.org/projects/tor/ticket/13023 // user_pref("dom.gamepad.enabled", false); // 4607: [2503] disable giving away network info (FF31+) // e.g. bluetooth, cellular, ethernet, wifi, wimax, other, mixed, unknown, none // [1] https://developer.mozilla.org/docs/Web/API/Network_Information_API // [2] https://wicg.github.io/netinfo/ // [3] https://bugzilla.mozilla.org/960426 user_pref("dom.netinfo.enabled", false); // 4608: [2021] disable the SpeechSynthesis (Text-to-Speech) part of the Web Speech API // [1] https://developer.mozilla.org/docs/Web/API/Web_Speech_API // [2] https://developer.mozilla.org/docs/Web/API/SpeechSynthesis // [3] https://wiki.mozilla.org/HTML5_Speech_API user_pref("media.webspeech.synth.enabled", false); // * * * / // FF57+ // 4610: [2506] disable video statistics - JS performance fingerprinting (FF25+) // [1] https://trac.torproject.org/projects/tor/ticket/15757 // [2] https://bugzilla.mozilla.org/654550 user_pref("media.video_stats.enabled", false); // 4611: [2509] disable touch events // fingerprinting attack vector - leaks screen res & actual screen coordinates // 0=disabled, 1=enabled, 2=autodetect // [WARNING] [SETUP] Optional protection depending on your device // [1] https://developer.mozilla.org/docs/Web/API/Touch_events // [2] https://trac.torproject.org/projects/tor/ticket/10286 // user_pref("dom.w3c_touch_events.enabled", 0); // * * * / // FF59+ // 4612: [2511] disable MediaDevices change detection (FF51+) // [1] https://developer.mozilla.org/docs/Web/Events/devicechange // [2] https://developer.mozilla.org/docs/Web/API/MediaDevices/ondevicechange user_pref("media.ondevicechange.enabled", false); // * * * / // FF60+ // 4613: [2011] disable WebGL debug info being available to websites // [1] https://bugzilla.mozilla.org/1171228 // [2] https://developer.mozilla.org/docs/Web/API/WEBGL_debug_renderer_info user_pref("webgl.enable-debug-renderer-info", false); // * * * / // ***/ /*** 4700: RFP (4500) ALTERNATIVES - NAVIGATOR / USER AGENT (UA) SPOOFING This is FYI ONLY. These prefs are INSUFFICIENT(a) on their own, you need to use RFP (4500) or an extension, in which case they become POINTLESS. (a) Many of the components that make up your UA can be derived by other means. And when those values differ, you provide more bits and raise entropy. Examples of leaks include navigator objects, date locale/formats, iframes, headers, tcp/ip attributes, feature detection, and **many** more. ALL values below intentionally left blank - use RFP, or get a vetted, tested extension and mimic RFP values to *lower* entropy, or randomize to *raise* it ***/ user_pref("_user.js.parrot", "4700 syntax error: the parrot's taken 'is last bow"); /* 4701: navigator.userAgent ***/ // user_pref("general.useragent.override", ""); // (hidden pref) /* 4702: navigator.buildID * Revealed build time down to the second. In FF64+ it now returns a fixed timestamp * [1] https://bugzilla.mozilla.org/583181 * [2] https://www.fxsitecompat.com/en-CA/docs/2018/navigator-buildid-now-returns-a-fixed-timestamp/ ***/ // user_pref("general.buildID.override", ""); // (hidden pref) /* 4703: navigator.appName ***/ // user_pref("general.appname.override", ""); // (hidden pref) /* 4704: navigator.appVersion ***/ // user_pref("general.appversion.override", ""); // (hidden pref) /* 4705: navigator.platform ***/ // user_pref("general.platform.override", ""); // (hidden pref) /* 4706: navigator.oscpu ***/ // user_pref("general.oscpu.override", ""); // (hidden pref) /*** 5000: PERSONAL [SETUP] Non-project related but useful. If any of these interest you, add them to your overrides ***/ user_pref("_user.js.parrot", "5000 syntax error: this is an ex-parrot!"); /* WELCOME & WHAT's NEW NOTICES ***/ // user_pref("browser.startup.homepage_override.mstone", "ignore"); // master switch // user_pref("startup.homepage_welcome_url", ""); // user_pref("startup.homepage_welcome_url.additional", ""); // user_pref("startup.homepage_override_url", ""); // What's New page after updates /* WARNINGS ***/ // user_pref("browser.tabs.warnOnClose", false); // user_pref("browser.tabs.warnOnCloseOtherTabs", false); // user_pref("browser.tabs.warnOnOpen", false); // user_pref("full-screen-api.warning.delay", 0); // user_pref("full-screen-api.warning.timeout", 0); /* APPEARANCE ***/ // user_pref("browser.download.autohideButton", false); // (FF57+) // user_pref("toolkit.cosmeticAnimations.enabled", false); // (FF55+) /* CONTENT BEHAVIOR ***/ // user_pref("accessibility.typeaheadfind", true); // enable "Find As You Type" // user_pref("clipboard.autocopy", false); // disable autocopy default [LINUX] // user_pref("layout.spellcheckDefault", 2); // 0=none, 1-multi-line, 2=multi-line & single-line /* UX BEHAVIOR ***/ // user_pref("browser.backspace_action", 2); // 0=previous page, 1=scroll up, 2=do nothing // user_pref("browser.tabs.closeWindowWithLastTab", false); // user_pref("browser.tabs.loadBookmarksInTabs", true); // open bookmarks in a new tab (FF57+) // user_pref("browser.urlbar.decodeURLsOnCopy", true); // see Bugzilla 1320061 (FF53+) // user_pref("general.autoScroll", false); // middle-click enabling auto-scrolling [WINDOWS] [MAC] // user_pref("ui.key.menuAccessKey", 0); // disable alt key toggling the menu bar [RESTART] /* OTHER ***/ // user_pref("browser.bookmarks.max_backups", 2); // user_pref("identity.fxaccounts.enabled", false); // disable and hide Firefox Accounts and Sync (FF60+) [RESTART] // user_pref("network.manage-offline-status", false); // see Bugzilla 620472 // user_pref("reader.parse-on-load.enabled", false); // "Reader View" // user_pref("xpinstall.signatures.required", false); // enforced extension signing (Nightly/ESR) /*** 9999: DEPRECATED / REMOVED / LEGACY / RENAMED Documentation denoted as [-]. Numbers may be re-used. See [1] for a link-clickable, viewer-friendly version of the deprecated bugzilla tickets. The original state of each pref has been preserved, or changed to match the current setup, but you are advised to review them. [NOTE] Up to FF53, to enable a section change /* FFxx to // FFxx For FF53 on, we have bundled releases to cater for ESR. Change /* to // on the first line [1] https://github.com/ghacksuserjs/ghacks-user.js/issues/123 ***/ user_pref("_user.js.parrot", "9999 syntax error: the parrot's deprecated!"); /* FF42 and older // 2604: (25+) disable page thumbnails - replaced by browser.pagethumbnails.capturing_disabled // [-] https://bugzilla.mozilla.org/897811 user_pref("pageThumbs.enabled", false); // 2503: (31+) disable network API - replaced by dom.netinfo.enabled // [-] https://bugzilla.mozilla.org/960426 user_pref("dom.network.enabled", false); // 2600's: (35+) disable WebSockets // [-] https://bugzilla.mozilla.org/1091016 user_pref("network.websocket.enabled", false); // 1610: (36+) set DNT "value" to "not be tracked" (FF21+) // [1] http://kb.mozillazine.org/Privacy.donottrackheader.value // [-] https://bugzilla.mozilla.org/1042135#c101 // user_pref("privacy.donottrackheader.value", 1); // 2023: (37+) disable camera autofocus callback // The API will be superseded by the WebRTC Capture and Stream API // [1] https://developer.mozilla.org/docs/Archive/B2G_OS/API/CameraControl // [-] https://bugzilla.mozilla.org/1107683 user_pref("camera.control.autofocus_moving_callback.enabled", false); // 0415: (41+) disable reporting URLs (safe browsing) - removed or replaced by various // [-] https://bugzilla.mozilla.org/1109475 user_pref("browser.safebrowsing.reportErrorURL", ""); // browser.safebrowsing.reportPhishMistakeURL user_pref("browser.safebrowsing.reportGenericURL", ""); // removed user_pref("browser.safebrowsing.reportMalwareErrorURL", ""); // browser.safebrowsing.reportMalwareMistakeURL user_pref("browser.safebrowsing.reportMalwareURL", ""); // removed user_pref("browser.safebrowsing.reportURL", ""); // removed // 0702: (41+) disable HTTP2 (draft) // [-] https://bugzilla.mozilla.org/1132357 user_pref("network.http.spdy.enabled.http2draft", false); // 1804: (41+) disable plugin enumeration // [-] https://bugzilla.mozilla.org/1169945 user_pref("plugins.enumerable_names", ""); // 2803: (42+) clear passwords on shutdown // [-] https://bugzilla.mozilla.org/1102184 // user_pref("privacy.clearOnShutdown.passwords", false); // 5002: (42+) disable warning when a domain requests full screen // replaced by setting full-screen-api.warning.timeout to zero // [-] https://bugzilla.mozilla.org/1160017 // user_pref("full-screen-api.approval-required", false); // ***/ /* FF43 // 0410's: disable safebrowsing urls & updates - replaced by various // [-] https://bugzilla.mozilla.org/1107372 // user_pref("browser.safebrowsing.gethashURL", ""); // browser.safebrowsing.provider.google.gethashURL // user_pref("browser.safebrowsing.updateURL", ""); // browser.safebrowsing.provider.google.updateURL user_pref("browser.safebrowsing.malware.reportURL", ""); // browser.safebrowsing.provider.google.reportURL // 0420's: disable tracking protection - replaced by various // [-] https://bugzilla.mozilla.org/1107372 // user_pref("browser.trackingprotection.gethashURL", ""); // browser.safebrowsing.provider.mozilla.gethashURL // user_pref("browser.trackingprotection.updateURL", ""); // browser.safebrowsing.provider.mozilla.updateURL // 1803: remove plugin finder service // [1] http://kb.mozillazine.org/Pfs.datasource.url // [-] https://bugzilla.mozilla.org/1202193 user_pref("pfs.datasource.url", ""); // 5003: disable new search panel UI // [-] https://bugzilla.mozilla.org/1119250 // user_pref("browser.search.showOneOffButtons", false); // ***/ /* FF44 // 0414: disable safebrowsing's real-time binary checking (google) (FF43+) // [-] https://bugzilla.mozilla.org/1237103 user_pref("browser.safebrowsing.provider.google.appRepURL", ""); // browser.safebrowsing.appRepURL // 1200's: block rc4 whitelist // [-] https://bugzilla.mozilla.org/1215796 user_pref("security.tls.insecure_fallback_hosts.use_static_list", false); // 2300's: disable SharedWorkers // [1] https://trac.torproject.org/projects/tor/ticket/15562 // [-] https://bugzilla.mozilla.org/1207635 user_pref("dom.workers.sharedWorkers.enabled", false); // 2403: disable scripts changing images // [TEST] https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_img_src2 // [WARNING] Will break some sites such as Google Maps and a lot of web apps // [-] https://bugzilla.mozilla.org/773429 // user_pref("dom.disable_image_src_set", true); // ***/ /* FF45 // 1021b: disable deferred level of storing extra session data 0=all 1=http-only 2=none // extra session data contains contents of forms, scrollbar positions, cookies and POST data // [-] https://bugzilla.mozilla.org/1235379 user_pref("browser.sessionstore.privacy_level_deferred", 2); // ***/ /* FF46 // 0333: disable health report // [-] https://bugzilla.mozilla.org/1234526 user_pref("datareporting.healthreport.service.enabled", false); // (hidden pref) user_pref("datareporting.healthreport.documentServerURI", ""); // (hidden pref) // 0334b: disable FHR (Firefox Health Report) v2 data being sent to Mozilla servers // [-] https://bugzilla.mozilla.org/1234522 user_pref("datareporting.policy.dataSubmissionEnabled.v2", false); // 0414: disable safebrowsing pref - replaced by browser.safebrowsing.downloads.remote.url // [-] https://bugzilla.mozilla.org/1239587 user_pref("browser.safebrowsing.appRepURL", ""); // Google application reputation check // 0420: disable polaris (part of Tracking Protection, never used in stable) // [-] https://bugzilla.mozilla.org/1235565 // user_pref("browser.polaris.enabled", false); // 0510: disable "Pocket" - replaced by extensions.pocket.* // [-] https://bugzilla.mozilla.org/1215694 user_pref("browser.pocket.enabled", false); user_pref("browser.pocket.api", ""); user_pref("browser.pocket.site", ""); user_pref("browser.pocket.oAuthConsumerKey", ""); // ***/ /* FF47 // 0330b: set unifiedIsOptIn to make sure telemetry respects OptIn choice and that telemetry // is enabled ONLY for people that opted into it, even if unified Telemetry is enabled // [-] https://bugzilla.mozilla.org/1236580 user_pref("toolkit.telemetry.unifiedIsOptIn", true); // (hidden pref) // 0333b: disable about:healthreport page UNIFIED // [-] https://bugzilla.mozilla.org/1236580 user_pref("datareporting.healthreport.about.reportUrlUnified", "data:text/plain,"); // 0807: disable history manipulation // [1] https://developer.mozilla.org/docs/Web/API/History_API // [-] https://bugzilla.mozilla.org/1249542 user_pref("browser.history.allowPopState", false); user_pref("browser.history.allowPushState", false); user_pref("browser.history.allowReplaceState", false); // ***/ /* FF48 // 0806: disable 'unified complete': 'Search with [default search engine]' // [-] http://techdows.com/2016/05/firefox-unified-complete-aboutconfig-preference-removed.html // [-] https://bugzilla.mozilla.org/1181078 user_pref("browser.urlbar.unifiedcomplete", false); // ***/ /* FF49 // 0372: disable "Hello" // [1] https://www.mozilla.org/privacy/archive/hello/2016-03/ // [2] https://security.stackexchange.com/questions/94284/how-secure-is-firefox-hello // [-] https://bugzilla.mozilla.org/1287827 user_pref("loop.enabled", false); user_pref("loop.server", ""); user_pref("loop.feedback.formURL", ""); user_pref("loop.feedback.manualFormURL", ""); user_pref("loop.facebook.appId", ""); user_pref("loop.facebook.enabled", false); user_pref("loop.facebook.fallbackUrl", ""); user_pref("loop.facebook.shareUrl", ""); user_pref("loop.logDomains", false); // 2201: disable new window scrollbars being hidden // [-] https://bugzilla.mozilla.org/1257887 user_pref("dom.disable_window_open_feature.scrollbars", true); // 2303: disable push notification (UDP wake-up) // [-] https://bugzilla.mozilla.org/1265914 user_pref("dom.push.udp.wakeupEnabled", false); // ***/ /* FF50 // 0101: disable Windows10 intro on startup [WINDOWS] // [-] https://bugzilla.mozilla.org/1274633 user_pref("browser.usedOnWindows10.introURL", ""); // 0308: disable plugin update notifications // [-] https://bugzilla.mozilla.org/1277905 user_pref("plugins.update.notifyUser", false); // 0410: disable "Block dangerous and deceptive content" - replaced by browser.safebrowsing.phishing.enabled // [-] https://bugzilla.mozilla.org/1025965 // user_pref("browser.safebrowsing.enabled", false); // 1266: disable rc4 ciphers // [1] https://trac.torproject.org/projects/tor/ticket/17369 // [-] https://bugzilla.mozilla.org/1268728 // [-] https://www.fxsitecompat.com/en-CA/docs/2016/rc4-support-has-been-completely-removed/ user_pref("security.ssl3.ecdhe_ecdsa_rc4_128_sha", false); user_pref("security.ssl3.ecdhe_rsa_rc4_128_sha", false); user_pref("security.ssl3.rsa_rc4_128_md5", false); user_pref("security.ssl3.rsa_rc4_128_sha", false); // 1809: remove Mozilla's plugin update URL // [-] https://bugzilla.mozilla.org/1277905 user_pref("plugins.update.url", ""); // ***/ /* FF51 // 0702: disable SPDY // [-] https://bugzilla.mozilla.org/1248197 user_pref("network.http.spdy.enabled.v3-1", false); // 1851: delay play of videos until they're visible // [1] https://bugzilla.mozilla.org/1180563 // [-] https://bugzilla.mozilla.org/1262053 user_pref("media.block-play-until-visible", true); // 2504: disable virtual reality devices // [-] https://bugzilla.mozilla.org/1250244 user_pref("dom.vr.oculus050.enabled", false); // ***/ /* FF52 // 1601: disable referer from an SSL Website // [-] https://bugzilla.mozilla.org/1308725 user_pref("network.http.sendSecureXSiteReferrer", false); // 1850: disable Adobe EME "Primetime CDM" (Content Decryption Module) // [1] https://trac.torproject.org/projects/tor/ticket/16285 // [-] https://bugzilla.mozilla.org/buglist.cgi?bug_id=1329538,1337121 // FF52 // [-] https://bugzilla.mozilla.org/1329543 // FF53 user_pref("media.gmp-eme-adobe.enabled", false); user_pref("media.gmp-eme-adobe.visible", false); user_pref("media.gmp-eme-adobe.autoupdate", false); // 2405: disable WebTelephony API // [1] https://wiki.mozilla.org/WebAPI/Security/WebTelephony // [-] https://bugzilla.mozilla.org/1309719 user_pref("dom.telephony.enabled", false); // ***/ /* FF53 // 1265: block rc4 fallback // [-] https://bugzilla.mozilla.org/1130670 user_pref("security.tls.unrestricted_rc4_fallback", false); // 1806: disable Acrobat, Quicktime, WMP (the string = min version number allowed) // [-] https://bugzilla.mozilla.org/buglist.cgi?bug_id=1317108,1317109,1317110 user_pref("plugin.scan.Acrobat", "99999"); user_pref("plugin.scan.Quicktime", "99999"); user_pref("plugin.scan.WindowsMediaPlayer", "99999"); // 2022: disable screensharing // [-] https://bugzilla.mozilla.org/1329562 user_pref("media.getusermedia.screensharing.allow_on_old_platforms", false); // 2507: disable keyboard fingerprinting // [-] https://bugzilla.mozilla.org/1322736 user_pref("dom.beforeAfterKeyboardEvent.enabled", false); // ***/ /* FF54 // 0415: disable reporting URLs (safe browsing) // [-] https://bugzilla.mozilla.org/1288633 user_pref("browser.safebrowsing.reportMalwareMistakeURL", ""); user_pref("browser.safebrowsing.reportPhishMistakeURL", ""); // 1830: block websites detecting DRM is disabled // [-] https://bugzilla.mozilla.org/1242321 user_pref("media.eme.apiVisible", false); // 2425: disable Archive Reader API // i.e. reading archive contents directly in the browser, through DOM file objects // [-] https://bugzilla.mozilla.org/1342361 user_pref("dom.archivereader.enabled", false); // ***/ /* FF55 // 0209: disable geolocation on non-secure origins (FF54+) // [1] https://bugzilla.mozilla.org/1269531 // [-] https://bugzilla.mozilla.org/1072859 user_pref("geo.security.allowinsecure", false); // 0336: disable "Heartbeat" (Mozilla user rating telemetry) (FF37+) // [1] https://trac.torproject.org/projects/tor/ticket/18738 // [-] https://bugzilla.mozilla.org/1361578 user_pref("browser.selfsupport.enabled", false); // (hidden pref) user_pref("browser.selfsupport.url", ""); // 0360: disable new tab "pings" // [-] https://bugzilla.mozilla.org/1241390 user_pref("browser.newtabpage.directory.ping", "data:text/plain,"); // 0861: disable saving form history on secure websites // [-] https://bugzilla.mozilla.org/1361220 user_pref("browser.formfill.saveHttpsForms", false); // 0863: disable Form Autofill (FF54+) - replaced by extensions.formautofill.* // [-] https://bugzilla.mozilla.org/1364334 user_pref("browser.formautofill.enabled", false); // 2410: disable User Timing API // [1] https://trac.torproject.org/projects/tor/ticket/16336 // [-] https://bugzilla.mozilla.org/1344669 user_pref("dom.enable_user_timing", false); // 2507: disable keyboard fingerprinting (FF38+) (physical keyboards) // The Keyboard API allows tracking the "read parameter" of pressed keys in forms on // web pages. These parameters vary between types of keyboard layouts such as QWERTY, // AZERTY, Dvorak, and between various languages, e.g. German vs English. // [WARNING] Don't use if Android + physical keyboard // [1] https://developer.mozilla.org/docs/Web/API/KeyboardEvent/code // [2] https://www.privacy-handbuch.de/handbuch_21v.htm // [-] https://bugzilla.mozilla.org/1352949 user_pref("dom.keyboardevent.code.enabled", false); // 5015: disable tab animation - replaced by toolkit.cosmeticAnimations.enabled // [-] https://bugzilla.mozilla.org/1352069 user_pref("browser.tabs.animate", false); // 5016: disable fullscreeen animation - replaced by toolkit.cosmeticAnimations.enabled // [-] https://bugzilla.mozilla.org/1352069 user_pref("browser.fullscreen.animate", false); // ***/ /* FF56 // 0515: disable Screenshots (rollout pref only) (FF54+) // [-] https://bugzilla.mozilla.org/1386333 // user_pref("extensions.screenshots.system-disabled", true); // 0517: disable Form Autofill (FF55+) - replaced by extensions.formautofill.available // [-] https://bugzilla.mozilla.org/1385201 user_pref("extensions.formautofill.experimental", false); // ***/ /* FF57 // 0374: disable "social" integration // [1] https://developer.mozilla.org/docs/Mozilla/Projects/Social_API // [-] https://bugzilla.mozilla.org/buglist.cgi?bug_id=1388902,1406193 (some leftovers were removed in FF58) user_pref("social.whitelist", ""); user_pref("social.toast-notifications.enabled", false); user_pref("social.shareDirectory", ""); user_pref("social.remote-install.enabled", false); user_pref("social.directories", ""); user_pref("social.share.activationPanelEnabled", false); user_pref("social.enabled", false); // (hidden pref) // 1830: disable DRM's EME WideVineAdapter // [-] https://bugzilla.mozilla.org/1395468 user_pref("media.eme.chromium-api.enabled", false); // (FF55+) // 2608: disable WebIDE extension downloads (Valence) // [1] https://trac.torproject.org/projects/tor/ticket/16222 // [-] https://bugzilla.mozilla.org/1393497 user_pref("devtools.webide.autoinstallFxdtAdapters", false); // 2600's: disable SimpleServiceDiscovery - which can bypass proxy settings - e.g. Roku // [1] https://trac.torproject.org/projects/tor/ticket/16222 // [-] https://bugzilla.mozilla.org/1393582 user_pref("browser.casting.enabled", false); // 5022: hide recently bookmarked items (you still have the original bookmarks) (FF49+) // [-] https://bugzilla.mozilla.org/1401238 user_pref("browser.bookmarks.showRecentlyBookmarked", false); // ***/ /* FF59 // 0203: disable using OS locale, force APP locale - replaced by intl.locale.requested // [-] https://bugzilla.mozilla.org/1414390 user_pref("intl.locale.matchOS", false); // 0204: set APP locale - replaced by intl.locale.requested // [-] https://bugzilla.mozilla.org/1414390 user_pref("general.useragent.locale", "en-US"); // 0333b: disable about:healthreport page (which connects to Mozilla for locale/css+js+json) // If you have disabled health reports, then this about page is useless - disable it // If you want to see what health data is present, then this must be set at default // [-] https://bugzilla.mozilla.org/1352497 user_pref("datareporting.healthreport.about.reportUrl", "data:text/plain,"); // 0511: disable FlyWeb (FF49+) // Flyweb is a set of APIs for advertising and discovering local-area web servers // [1] https://flyweb.github.io/ // [2] https://wiki.mozilla.org/FlyWeb/Security_scenarios // [3] https://www.ghacks.net/2016/07/26/firefox-flyweb/ // [-] https://bugzilla.mozilla.org/1374574 user_pref("dom.flyweb.enabled", false); // 1007: disable randomized FF HTTP cache decay experiments // [1] https://trac.torproject.org/projects/tor/ticket/13575 // [-] https://bugzilla.mozilla.org/1430197 user_pref("browser.cache.frecency_experiment", -1); // 1242: enable Mixed-Content-Blocker to use the HSTS cache but disable the HSTS Priming requests (FF51+) // Allow resources from domains with an existing HSTS cache record or in the HSTS preload list // to be upgraded to HTTPS internally but disable sending out HSTS Priming requests, because // those may cause noticeable delays e.g. requests time out or are not handled well by servers // [NOTE] If you want to use the priming requests make sure 'use_hsts' is also true // [1] https://bugzilla.mozilla.org/1246540#c145 // [-] https://bugzilla.mozilla.org/1424917 user_pref("security.mixed_content.use_hsts", true); user_pref("security.mixed_content.send_hsts_priming", false); // 1606: set the default Referrer Policy - replaced by network.http.referer.defaultPolicy // [-] https://bugzilla.mozilla.org/587523 user_pref("network.http.referer.userControlPolicy", 3); // (FF53-FF58) default: 3 // 1804: disable plugins using external/untrusted scripts with XPCOM or XPConnect // [-] (part8) https://bugzilla.mozilla.org/1416703#c21 user_pref("security.xpconnect.plugin.unrestricted", false); // 2022: disable screensharing domain whitelist // [-] https://bugzilla.mozilla.org/1411742 user_pref("media.getusermedia.screensharing.allowed_domains", ""); // 2023: disable camera stuff // [-] (part7) https://bugzilla.mozilla.org/1416703#c21 user_pref("camera.control.face_detection.enabled", false); // 2202: prevent scripts from changing the status text // [-] https://bugzilla.mozilla.org/1425999 user_pref("dom.disable_window_status_change", true); // 2416: disable idle observation // [-] (part7) https://bugzilla.mozilla.org/1416703#c21 user_pref("dom.idle-observers-api.enabled", false); // ***/ /* FF60 // 0360: disable new tab tile ads & preload & marketing junk // [-] https://bugzilla.mozilla.org/buglist.cgi?bug_id=1370930,1433133 user_pref("browser.newtabpage.directory.source", "data:text/plain,"); user_pref("browser.newtabpage.enhanced", false); user_pref("browser.newtabpage.introShown", true); // 0512: disable Shield (FF53+) - replaced internally by Normandy (see 0503) // Shield is an telemetry system (including Heartbeat) that can also push and test "recipes" // [1] https://wiki.mozilla.org/Firefox/Shield // [2] https://github.com/mozilla/normandy // [-] https://bugzilla.mozilla.org/1436113 user_pref("extensions.shield-recipe-client.enabled", false); user_pref("extensions.shield-recipe-client.api_url", ""); // 0514: disable Activity Stream (FF54+) // [-] https://bugzilla.mozilla.org/1433324 user_pref("browser.newtabpage.activity-stream.enabled", false); // 2301: disable workers // [WARNING] Disabling workers *will* break sites (e.g. Google Street View, Twitter) // [NOTE] CVE-2016-5259, CVE-2016-2812, CVE-2016-1949, CVE-2016-5287 (fixed) // [-] https://bugzilla.mozilla.org/1434934 user_pref("dom.workers.enabled", false); // 5000's: open "page/selection source" in a new window // [-] https://bugzilla.mozilla.org/1418403 // user_pref("view_source.tab", false); // ***/ /* ESR60.x still uses all the following prefs // [NOTE] replace the * with a slash in the line above to re-enable them // FF61 // 0501: disable experiments // [1] https://wiki.mozilla.org/Telemetry/Experiments // [-] https://bugzilla.mozilla.org/buglist.cgi?bug_id=1420908,1450801 user_pref("experiments.enabled", false); user_pref("experiments.manifest.uri", ""); user_pref("experiments.supported", false); user_pref("experiments.activeExperiment", false); // 2612: disable remote JAR files being opened, regardless of content type (FF42+) // [1] https://bugzilla.mozilla.org/1173171 // [2] https://www.fxsitecompat.com/en-CA/docs/2015/jar-protocol-support-has-been-disabled-by-default/ // [-] https://bugzilla.mozilla.org/1427726 user_pref("network.jar.block-remote-files", true); // 2613: disable JAR from opening Unsafe File Types // [-] https://bugzilla.mozilla.org/1427726 user_pref("network.jar.open-unsafe-types", false); // * * * / // FF62 // 1803: disable Java plugin // [-] (part5) https://bugzilla.mozilla.org/1461243 user_pref("plugin.state.java", 0); // * * * / // FF63 // 0202: disable GeoIP-based search results // [NOTE] May not be hidden if Firefox has changed your settings due to your locale // [-] https://bugzilla.mozilla.org/1462015 user_pref("browser.search.countryCode", "US"); // (hidden pref) // 0301a: disable auto-update checks for Firefox // [SETTING] General>Firefox Updates>Never check for updates // [-] https://bugzilla.mozilla.org/1420514 // user_pref("app.update.enabled", false); // 0402: enable Kinto blocklist updates (FF50+) // What is Kinto?: https://wiki.mozilla.org/Firefox/Kinto#Specifications // As Firefox transitions to Kinto, the blocklists have been broken down into entries for certs to be // revoked, extensions and plugins to be disabled, and gfx environments that cause problems or crashes // [-] https://bugzilla.mozilla.org/1458917 user_pref("services.blocklist.update_enabled", true); // 0503: disable "Savant" Shield study (FF61+) // [-] https://bugzilla.mozilla.org/1457226 user_pref("shield.savant.enabled", false); // 1031: disable favicons in tabs and new bookmarks - merged into browser.chrome.site_icons // [-] https://bugzilla.mozilla.org/1453751 // user_pref("browser.chrome.favicons", false); // 2030: disable auto-play of HTML5 media - replaced by media.autoplay.default // [WARNING] This may break video playback on various sites // [-] https://bugzilla.mozilla.org/1470082 user_pref("media.autoplay.enabled", false); // 2704: set cookie lifetime in days (see 2703) // [-] https://bugzilla.mozilla.org/1457170 // user_pref("network.cookie.lifetime.days", 90); // default: 90 // 5000's: enable "Ctrl+Tab cycles through tabs in recently used order" - replaced by browser.ctrlTab.recentlyUsedOrder // [-] https://bugzilla.mozilla.org/1473595 // user_pref("browser.ctrlTab.previews", true); // * * * / // ***/ /* END: internal custom pref to test for syntax errors ***/ user_pref("_user.js.parrot", "SUCCESS: No no he's not dead, he's, he's restin'!");
user.js
/****** * name: ghacks user.js * date: 13 November 2018 * version 63-beta: Pants Romance * "Rah rah ah-ah-ah! Ro mah ro-mah-mah. Gaga oh-la-la! Want your pants romance" * authors: v52+ github | v51- www.ghacks.net * url: https://github.com/ghacksuserjs/ghacks-user.js * license: MIT: https://github.com/ghacksuserjs/ghacks-user.js/blob/master/LICENSE.txt * releases: These are end-of-stable-life-cycle legacy archives. *Always* use the master branch user.js for a current up-to-date version. url: https://github.com/ghacksuserjs/ghacks-user.js/releases * README: 1. READ the full README * https://github.com/ghacksuserjs/ghacks-user.js/blob/master/README.md 2. READ this * https://github.com/ghacksuserjs/ghacks-user.js/wiki/1.3-Implementation 3. If you skipped steps 1 and 2 above (shame on you), then here is the absolute minimum * Auto-installing updates for Firefox and extensions are disabled (section 0302's) * Some user data is erased on close (section 2800). Change this to suit your needs * EACH RELEASE check: - 4600s: reset prefs made redundant due to privacy.resistFingerprinting (RPF) or enable them as an alternative to RFP or for ESR users - 9999s: reset deprecated prefs in about:config or enable relevant section(s) for ESR * Site breakage WILL happen - There are often trade-offs and conflicts between Security vs Privacy vs Anti-Fingerprinting and these need to be balanced against Functionality & Convenience & Breakage * You will need to make a few changes to suit your own needs - Search this file for the "[SETUP]" tag to find SOME common items you could check before using to avoid unexpected surprises - Search this file for the "[WARNING]" tag to troubleshoot or prevent SOME common issues 4. BACKUP your profile folder before implementing (and/or test in a new/cloned profile) 5. KEEP UP TO DATE: https://github.com/ghacksuserjs/ghacks-user.js/wiki#small_orange_diamond-maintenance ******/ /* START: internal custom pref to test for syntax errors * [NOTE] In FF60+, not all syntax errors cause parsing to abort i.e. reaching the last debug * pref no longer necessarily means that all prefs have been applied. Check the console right * after startup for any warnings/error messages related to non-applied prefs * [1] https://blog.mozilla.org/nnethercote/2018/03/09/a-new-preferences-parser-for-firefox/ ***/ user_pref("_user.js.parrot", "START: Oh yes, the Norwegian Blue... what's wrong with it?"); /* 0000: disable about:config warning ***/ user_pref("general.warnOnAboutConfig", false); /* 0001: start Firefox in PB (Private Browsing) mode * [SETTING] Privacy & Security>History>Custom Settings>Always use private browsing mode * [NOTE] In this mode *all* windows are "private windows" and the PB mode icon is not displayed * [NOTE] The P in PB mode is misleading: it means no "persistent" local storage of history, * caches, searches or cookies (which you can achieve in normal mode). In fact, it limits or * removes the ability to control these, and you need to quit Firefox to clear them. PB is best * used as a one off window (File>New Private Window) to provide a temporary self-contained * new instance. Closing all Private Windows clears all traces. Repeat as required. * [WARNING] PB does not allow indexedDB which breaks many Extensions that use it * including uBlock Origin, uMatrix, Violentmonkey and Stylus * [1] https://wiki.mozilla.org/Private_Browsing ***/ // user_pref("browser.privatebrowsing.autostart", true); /*** 0100: STARTUP ***/ user_pref("_user.js.parrot", "0100 syntax error: the parrot's dead!"); /* 0101: disable default browser check * [SETTING] General>Startup>Always check if Firefox is your default browser ***/ user_pref("browser.shell.checkDefaultBrowser", false); /* 0102: set START page (0=blank, 1=home, 2=last visited page, 3=resume previous session) * [SETTING] General>Startup>When Firefox starts ***/ user_pref("browser.startup.page", 0); /* 0103: set HOME+NEWWINDOW page * about:home=Activity Stream (default, see 0514), custom URL, about:blank * [SETTING] Home>New Windows and Tabs>Homepage and new windows ***/ user_pref("browser.startup.homepage", "about:blank"); /* 0104: set NEWTAB page * true=Activity Stream (default, see 0514), false=blank page * [SETTING] Home>New Windows and Tabs>New tabs ***/ user_pref("browser.newtabpage.enabled", false); user_pref("browser.newtab.preload", false); /*** 0200: GEOLOCATION ***/ user_pref("_user.js.parrot", "0200 syntax error: the parrot's definitely deceased!"); /* 0201: disable Location-Aware Browsing * [1] https://www.mozilla.org/firefox/geolocation/ ***/ // user_pref("geo.enabled", false); /* 0201b: set a default permission for Location (FF58+) * [SETTING] to add site exceptions: Page Info>Permissions>Access Your Location * [SETTING] to manage site exceptions: Options>Privacy & Security>Permissions>Location>Settings ***/ // user_pref("permissions.default.geo", 2); // 0=always ask (default), 1=allow, 2=block /* 0202: disable GeoIP-based search results * [NOTE] May not be hidden if Firefox has changed your settings due to your locale * [1] https://trac.torproject.org/projects/tor/ticket/16254 * [2] https://support.mozilla.org/en-US/kb/how-stop-firefox-making-automatic-connections#w_geolocation-for-default-search-engine ***/ user_pref("browser.search.region", "US"); // (hidden pref) user_pref("browser.search.geoip.url", ""); /* 0205: set OS & APP locale (FF59+) * If set to empty, the OS locales are used. If not set at all, default locale is used ***/ user_pref("intl.locale.requested", "en-US"); // (hidden pref) /* 0206: disable geographically specific results/search engines e.g. "browser.search.*.US" * i.e. ignore all of Mozilla's various search engines in multiple locales ***/ user_pref("browser.search.geoSpecificDefaults", false); user_pref("browser.search.geoSpecificDefaults.url", ""); /* 0207: set language to match ***/ user_pref("intl.accept_languages", "en-US, en"); /* 0208: enforce US English locale regardless of the system locale * [1] https://bugzilla.mozilla.org/867501 ***/ user_pref("javascript.use_us_english_locale", true); // (hidden pref) /* 0209: use APP locale over OS locale in regional preferences (FF56+) * [1] https://bugzilla.mozilla.org/buglist.cgi?bug_id=1379420,1364789 ***/ user_pref("intl.regional_prefs.use_os_locales", false); /* 0210: use Mozilla geolocation service instead of Google when geolocation is enabled * Optionally enable logging to the console (defaults to false) ***/ user_pref("geo.wifi.uri", "https://location.services.mozilla.com/v1/geolocate?key=%MOZILLA_API_KEY%"); // user_pref("geo.wifi.logging.enabled", true); // (hidden pref) /*** 0300: QUIET FOX We choose to not disable auto-CHECKs (0301's) but to disable auto-INSTALLs (0302's). There are many legitimate reasons to turn off auto-INSTALLS, including hijacked or monetized extensions, time constraints, legacy issues, and fear of breakage/bugs. It is still important to do updates for security reasons, please do so manually. ***/ user_pref("_user.js.parrot", "0300 syntax error: the parrot's not pinin' for the fjords!"); /* 0301b: disable auto-update checks for extensions * [SETTING] about:addons>Extensions>[cog-wheel-icon]>Update Add-ons Automatically (toggle) ***/ // user_pref("extensions.update.enabled", false); /* 0302a: disable auto update installing for Firefox * [SETTING] General>Firefox Updates>Check for updates but let you choose... ***/ user_pref("app.update.auto", false); /* 0302b: disable auto update installing for extensions (after the check in 0301b) * [SETTING] about:addons>Extensions>[cog-wheel-icon]>Update Add-ons Automatically (toggle) ***/ user_pref("extensions.update.autoUpdateDefault", false); /* 0303: disable background update service [WINDOWS] * [SETTING] General>Firefox Updates>Use a background service to install updates ***/ user_pref("app.update.service.enabled", false); /* 0304: disable background update staging ***/ user_pref("app.update.staging.enabled", false); /* 0305: enforce update information is displayed * This is the update available, downloaded, error and success information ***/ user_pref("app.update.silent", false); /* 0306: disable extension metadata updating * sends daily pings to Mozilla about extensions and recent startups ***/ user_pref("extensions.getAddons.cache.enabled", false); /* 0307: disable auto updating of personas (themes) ***/ user_pref("lightweightThemes.update.enabled", false); /* 0308: disable search update * [SETTING] General>Firefox Update>Automatically update search engines ***/ user_pref("browser.search.update", false); /* 0309: disable sending Flash crash reports ***/ user_pref("dom.ipc.plugins.flash.subprocess.crashreporter.enabled", false); /* 0310: disable sending the URL of the website where a plugin crashed ***/ user_pref("dom.ipc.plugins.reportCrashURL", false); /* 0320: disable about:addons' Get Add-ons panel (uses Google-Analytics) ***/ user_pref("extensions.getAddons.showPane", false); // hidden pref user_pref("extensions.webservice.discoverURL", ""); /* 0330: disable telemetry * the pref (.unified) affects the behaviour of the pref (.enabled) * IF unified=false then .enabled controls the telemetry module * IF unified=true then .enabled ONLY controls whether to record extended data * so make sure to have both set as false * [NOTE] FF58+ `toolkit.telemetry.enabled` is now LOCKED to reflect prerelease * or release builds (true and false respectively), see [2] * [1] https://firefox-source-docs.mozilla.org/toolkit/components/telemetry/telemetry/internals/preferences.html * [2] https://medium.com/georg-fritzsche/data-preference-changes-in-firefox-58-2d5df9c428b5 ***/ user_pref("toolkit.telemetry.unified", false); user_pref("toolkit.telemetry.enabled", false); // see [NOTE] above FF58+ user_pref("toolkit.telemetry.server", "data:,"); user_pref("toolkit.telemetry.archive.enabled", false); user_pref("toolkit.telemetry.cachedClientID", ""); user_pref("toolkit.telemetry.newProfilePing.enabled", false); // (FF55+) user_pref("toolkit.telemetry.shutdownPingSender.enabled", false); // (FF55+) user_pref("toolkit.telemetry.updatePing.enabled", false); // (FF56+) user_pref("toolkit.telemetry.bhrPing.enabled", false); // (FF57+) Background Hang Reporter user_pref("toolkit.telemetry.firstShutdownPing.enabled", false); // (FF57+) user_pref("toolkit.telemetry.hybridContent.enabled", false); // (FF59+) /* 0333: disable health report * [SETTING] Privacy & Security>Firefox Data Collection & Use>Allow Firefox to send technical... data ***/ user_pref("datareporting.healthreport.uploadEnabled", false); /* 0334: disable new data submission, master kill switch (FF41+) * If disabled, no policy is shown or upload takes place, ever * [1] https://bugzilla.mozilla.org/1195552 ***/ user_pref("datareporting.policy.dataSubmissionEnabled", false); /* 0350: disable crash reports ***/ user_pref("breakpad.reportURL", ""); /* 0351: disable sending of crash reports (FF44+) * [SETTING] Privacy & Security>Firefox Data Collection & Use>Allow Firefox to send crash reports ***/ user_pref("browser.tabs.crashReporting.sendReport", false); user_pref("browser.crashReports.unsubmittedCheck.enabled", false); // (FF51+) user_pref("browser.crashReports.unsubmittedCheck.autoSubmit", false); // (FF51-57) user_pref("browser.crashReports.unsubmittedCheck.autoSubmit2", false); // (FF58+) /* 0370: disable "Snippets" (Mozilla content shown on about:home screen) * [1] https://wiki.mozilla.org/Firefox/Projects/Firefox_Start/Snippet_Service ***/ user_pref("browser.aboutHomeSnippets.updateUrl", "data:,"); /* 0380: disable Browser Error Reporter (FF60+) * [1] https://support.mozilla.org/en-US/kb/firefox-nightly-error-collection * [2] https://firefox-source-docs.mozilla.org/browser/browser/BrowserErrorReporter.html ***/ user_pref("browser.chrome.errorReporter.enabled", false); user_pref("browser.chrome.errorReporter.submitUrl", ""); /*** 0400: BLOCKLISTS / SAFE BROWSING / TRACKING PROTECTION This section has security & tracking protection implications vs privacy concerns vs effectiveness vs 3rd party 'censorship'. We DO NOT advocate no protection. If you disable Tracking Protection (TP) and/or Safe Browsing (SB), then SECTION 0400 REQUIRES YOU HAVE uBLOCK ORIGIN INSTALLED. Safe Browsing is designed to protect users from malicious sites. Tracking Protection is designed to lessen the impact of third parties on websites to reduce tracking and to speed up your browsing. These do rely on 3rd parties (Google for SB and Disconnect for TP), but many steps, which are continually being improved, have been taken to preserve privacy. Disable at your own risk. ***/ user_pref("_user.js.parrot", "0400 syntax error: the parrot's passed on!"); /** BLOCKLISTS ***/ /* 0401: enable Firefox blocklist, but sanitize blocklist url * [NOTE] It includes updates for "revoked certificates" * [1] https://blog.mozilla.org/security/2015/03/03/revoking-intermediate-certificates-introducing-onecrl/ * [2] https://trac.torproject.org/projects/tor/ticket/16931 ***/ user_pref("extensions.blocklist.enabled", true); // default: true user_pref("extensions.blocklist.url", "https://blocklists.settings.services.mozilla.com/v1/blocklist/3/%APP_ID%/%APP_VERSION%/"); /* 0403: disable individual unwanted/unneeded parts of the Kinto blocklists * What is Kinto?: https://wiki.mozilla.org/Firefox/Kinto#Specifications * As Firefox transitions to Kinto, the blocklists have been broken down into entries for certs to be * revoked, extensions and plugins to be disabled, and gfx environments that cause problems or crashes ***/ // user_pref("services.blocklist.onecrl.collection", ""); // revoked certificates // user_pref("services.blocklist.addons.collection", ""); // user_pref("services.blocklist.plugins.collection", ""); // user_pref("services.blocklist.gfx.collection", ""); /** SAFE BROWSING (SB) This sub-section has been redesigned to differentiate between "real-time"/"user initiated" data being sent to Google from all other settings such as using local blocklists/whitelists and updating those lists. There are NO privacy issues here. *IF* required, a full url is never sent to Google, only a PART-hash of the prefix, and this is hidden with noise of other real PART-hashes. Google also swear it is anonymized and only used to flag malicious sites/activity. Firefox also takes measures such as striping out identifying parameters and storing safe browsing cookies in a separate jar. SB v4 (FF57+) doesn't even use cookies. (#Turn on browser.safebrowsing.debug to monitor this activity) #Required reading [#] https://feeding.cloud.geek.nz/posts/how-safe-browsing-works-in-firefox/ [1] https://wiki.mozilla.org/Security/Safe_Browsing ***/ /* 0410: disable "Block dangerous and deceptive content" (under Options>Privacy & Security) * This covers deceptive sites such as phishing and social engineering ***/ // user_pref("browser.safebrowsing.malware.enabled", false); // user_pref("browser.safebrowsing.phishing.enabled", false); // (FF50+) /* 0411: disable "Block dangerous downloads" (under Options>Privacy & Security) * This covers malware and PUPs (potentially unwanted programs) ***/ // user_pref("browser.safebrowsing.downloads.enabled", false); /* 0412: disable "Warn me about unwanted and uncommon software" (under Options>Privacy & Security) (FF48+) ***/ // user_pref("browser.safebrowsing.downloads.remote.block_potentially_unwanted", false); // user_pref("browser.safebrowsing.downloads.remote.block_uncommon", false); // user_pref("browser.safebrowsing.downloads.remote.block_dangerous", false); // (FF49+) // user_pref("browser.safebrowsing.downloads.remote.block_dangerous_host", false); // (FF49+) /* 0413: disable Google safebrowsing updates ***/ // user_pref("browser.safebrowsing.provider.google.updateURL", ""); // user_pref("browser.safebrowsing.provider.google.gethashURL", ""); // user_pref("browser.safebrowsing.provider.google4.updateURL", ""); // (FF50+) // user_pref("browser.safebrowsing.provider.google4.gethashURL", ""); // (FF50+) /* 0414: disable binaries NOT in local lists being checked by Google (real-time checking) ***/ user_pref("browser.safebrowsing.downloads.remote.enabled", false); user_pref("browser.safebrowsing.downloads.remote.url", ""); /* 0415: disable reporting URLs ***/ user_pref("browser.safebrowsing.provider.google.reportURL", ""); user_pref("browser.safebrowsing.reportPhishURL", ""); user_pref("browser.safebrowsing.provider.google4.reportURL", ""); // (FF50+) user_pref("browser.safebrowsing.provider.google.reportMalwareMistakeURL", ""); // (FF54+) user_pref("browser.safebrowsing.provider.google.reportPhishMistakeURL", ""); // (FF54+) user_pref("browser.safebrowsing.provider.google4.reportMalwareMistakeURL", ""); // (FF54+) user_pref("browser.safebrowsing.provider.google4.reportPhishMistakeURL", ""); // (FF54+) /* 0416: disable 'ignore this warning' on Safe Browsing warnings which when clicked * bypasses the block for that session. This is a means for admins to enforce SB * [TEST] see github wiki APPENDIX A: Test Sites: Section 5 * [1] https://bugzilla.mozilla.org/1226490 ***/ // user_pref("browser.safebrowsing.allowOverride", false); /* 0417: disable data sharing (FF58+) ***/ user_pref("browser.safebrowsing.provider.google4.dataSharing.enabled", false); user_pref("browser.safebrowsing.provider.google4.dataSharingURL", ""); /** TRACKING PROTECTION (TP) There are NO privacy concerns here, but we strongly recommend to use uBlock Origin as well, as it offers more comprehensive and specialized lists. It also allows per domain control. ***/ /* 0420: enable Tracking Protection in all windows * [NOTE] TP sends DNT headers regardless of the DNT pref (see 1610) * [1] https://wiki.mozilla.org/Security/Tracking_protection * [2] https://support.mozilla.org/kb/tracking-protection-firefox ***/ // user_pref("privacy.trackingprotection.pbmode.enabled", true); // default: true // user_pref("privacy.trackingprotection.enabled", true); /* 0422: set which Tracking Protection block list to use * [WARNING] We don't recommend enforcing this from here, as available block lists can change * [SETTING] Privacy & Security>Tracking Protection>Change Block List ***/ // user_pref("urlclassifier.trackingTable", "test-track-simple,base-track-digest256"); // basic /* 0423: disable Mozilla's blocklist for known Flash tracking/fingerprinting (FF48+) * [1] https://www.ghacks.net/2016/07/18/firefox-48-blocklist-against-plugin-fingerprinting/ * [2] https://bugzilla.mozilla.org/1237198 ***/ // user_pref("browser.safebrowsing.blockedURIs.enabled", false); /* 0424: disable Mozilla's tracking protection and Flash blocklist updates ***/ // user_pref("browser.safebrowsing.provider.mozilla.gethashURL", ""); // user_pref("browser.safebrowsing.provider.mozilla.updateURL", ""); /* 0425: disable passive Tracking Protection (FF53+) * Passive TP annotates channels to lower the priority of network loads for resources on the tracking protection list * [NOTE] It has no effect if TP is enabled, but keep in mind that by default TP is only enabled in Private Windows * This is included for people who want to completely disable Tracking Protection. * [1] https://bugzilla.mozilla.org/buglist.cgi?bug_id=1170190,1141814 ***/ // user_pref("privacy.trackingprotection.annotate_channels", false); // user_pref("privacy.trackingprotection.lower_network_priority", false); /* 0426: enforce Content Blocking (required to block cookies) (FF63+) ***/ user_pref("browser.contentblocking.enabled", true); // default: true /*** 0500: SYSTEM ADD-ONS / EXPERIMENTS System Add-ons are a method for shipping extensions, considered to be built-in features to Firefox, that are hidden from the about:addons UI. To view your System Add-ons go to about:support, they are listed under "Firefox Features" Some System Add-ons have no on-off prefs. Instead you can manually remove them. Note that app updates will restore them. They may also be updated and possibly restored automatically (see 0505) * Portable: "...\App\Firefox64\browser\features\" (or "App\Firefox\etc" for 32bit) * Windows: "...\Program Files\Mozilla\browser\features" (or "Program Files (X86)\etc" for 32bit) * Mac: "...\Applications\Firefox\Contents\Resources\browser\features\" [NOTE] On Mac you can right-click on the application and select "Show Package Contents" * Linux: "/usr/lib/firefox/browser/features" (or similar) [1] https://firefox-source-docs.mozilla.org/toolkit/mozapps/extensions/addon-manager/SystemAddons.html [2] https://dxr.mozilla.org/mozilla-central/source/browser/extensions ***/ user_pref("_user.js.parrot", "0500 syntax error: the parrot's cashed in 'is chips!"); /* 0502: disable Mozilla permission to silently opt you into tests ***/ user_pref("network.allow-experiments", false); /* 0503: disable Normandy/Shield (FF60+) * Shield is an telemetry system (including Heartbeat) that can also push and test "recipes" * [1] https://wiki.mozilla.org/Firefox/Shield * [2] https://github.com/mozilla/normandy ***/ user_pref("app.normandy.enabled", false); user_pref("app.normandy.api_url", ""); user_pref("app.shield.optoutstudies.enabled", false); /* 0505: disable System Add-on updates * [NOTE] In FF61 and lower, you will not get any System Add-on updates except when you update Firefox ***/ // user_pref("extensions.systemAddon.update.enabled", false); // (FF62+) // user_pref("extensions.systemAddon.update.url", ""); /* 0506: disable PingCentre telemetry (used in several System Add-ons) (FF57+) * Currently blocked by 'datareporting.healthreport.uploadEnabled' (see 0333) ***/ user_pref("browser.ping-centre.telemetry", false); /* 0510: disable Pocket (FF39+) * Pocket is a third party (now owned by Mozilla) "save for later" cloud service * [1] https://en.wikipedia.org/wiki/Pocket_(application) * [2] https://www.gnu.gl/blog/Posts/multiple-vulnerabilities-in-pocket/ ***/ user_pref("extensions.pocket.enabled", false); /* 0514: disable Activity Stream (FF54+) * Activity Stream is the default homepage/newtab in FF57+. It is based on metadata and browsing behavior, * and includes telemetry and web content such as snippets, top stories (pocket), top sites, etc. * - ONE: make sure to set your "home" and "newtab" to about:blank (or use an extension to control them) * - TWO: DELETE the XPI file in your System Add-ons directory (note this get reinstalled on app updates) * And/or you can try to control the ever-growing, ever-changing "browser.newtabpage.activity-stream.*" prefs * [FF63+] Activity Stream (AS) is now builtin and no longer an easily deletable system addon! * We'll clean this up and move to a new number when ESR67 is released. * [1] https://wiki.mozilla.org/Firefox/Activity_Stream * [2] https://www.ghacks.net/2016/02/15/firefox-mockups-show-activity-stream-new-tab-page-and-share-updates/ ***/ user_pref("browser.library.activity-stream.enabled", false); // (FF57+) /* 0514a: disable AS Snippets ***/ user_pref("browser.newtabpage.activity-stream.disableSnippets", true); user_pref("browser.newtabpage.activity-stream.feeds.snippets", false); // [SETTING] Home>Firefox Home Content>Snippets /* 0514b: disable AS Top Stories and other Pocket-based and/or sponsored content ***/ user_pref("browser.newtabpage.activity-stream.feeds.section.topstories", false); user_pref("browser.newtabpage.activity-stream.section.highlights.includePocket", false); // [SETTING] Home>Firefox Home Content>Highlights>Pages Saved to Pocket user_pref("browser.newtabpage.activity-stream.showSponsored", false); /* 0514c: disable AS telemetry ***/ user_pref("browser.newtabpage.activity-stream.feeds.telemetry", false); user_pref("browser.newtabpage.activity-stream.telemetry", false); user_pref("browser.newtabpage.activity-stream.telemetry.ping.endpoint", ""); /* 0515: disable Screenshots (FF55+) * alternatively in FF60+, disable uploading to the Screenshots server * [1] https://github.com/mozilla-services/screenshots * [2] https://www.ghacks.net/2017/05/28/firefox-screenshots-integrated-in-firefox-nightly/ ***/ // user_pref("extensions.screenshots.disabled", true); // user_pref("extensions.screenshots.upload-disabled", true); // (FF60+) /* 0516: disable Onboarding (FF55+) * Onboarding is an interactive tour/setup for new installs/profiles and features. Every time * about:home or about:newtab is opened, the onboarding overlay is injected into that page * [NOTE] Onboarding uses Google Analytics [2], and leaks resource://URIs [3] * [1] https://wiki.mozilla.org/Firefox/Onboarding * [2] https://github.com/mozilla/onboard/commit/db4d6c8726c89a5d6a241c1b1065827b525c5baf * [3] https://bugzilla.mozilla.org/863246#c154 ***/ user_pref("browser.onboarding.enabled", false); /* 0517: disable Form Autofill (FF55+) * [SETTING] Privacy & Security>Forms & Passwords>Enable Profile Autofill * [NOTE] Stored data is NOT secure (uses a JSON file) * [NOTE] Heuristics controls Form Autofill on forms without @autocomplete attributes * [1] https://wiki.mozilla.org/Firefox/Features/Form_Autofill * [2] https://www.ghacks.net/2017/05/24/firefoxs-new-form-autofill-is-awesome/ ***/ user_pref("extensions.formautofill.addresses.enabled", false); user_pref("extensions.formautofill.available", "off"); // (FF56+) user_pref("extensions.formautofill.creditCards.enabled", false); // (FF56+) user_pref("extensions.formautofill.heuristics.enabled", false); /* 0518: disable Web Compatibility Reporter (FF56+) * Web Compatibility Reporter adds a "Report Site Issue" button to send data to Mozilla ***/ user_pref("extensions.webcompat-reporter.enabled", false); /*** 0600: BLOCK IMPLICIT OUTBOUND [not explicitly asked for - e.g. clicked on] ***/ user_pref("_user.js.parrot", "0600 syntax error: the parrot's no more!"); /* 0601: disable link prefetching * [1] https://developer.mozilla.org/docs/Web/HTTP/Link_prefetching_FAQ ***/ user_pref("network.prefetch-next", false); /* 0602: disable DNS prefetching * [1] https://www.ghacks.net/2013/04/27/firefox-prefetching-what-you-need-to-know/ * [2] https://developer.mozilla.org/docs/Web/HTTP/Headers/X-DNS-Prefetch-Control ***/ user_pref("network.dns.disablePrefetch", true); user_pref("network.dns.disablePrefetchFromHTTPS", true); // (hidden pref) /* 0603a: disable Seer/Necko * [1] https://developer.mozilla.org/docs/Mozilla/Projects/Necko ***/ user_pref("network.predictor.enabled", false); /* 0603b: disable more Necko/Captive Portal * [1] https://en.wikipedia.org/wiki/Captive_portal * [2] https://wiki.mozilla.org/Necko/CaptivePortal * [3] https://trac.torproject.org/projects/tor/ticket/21790 ***/ user_pref("captivedetect.canonicalURL", ""); user_pref("network.captive-portal-service.enabled", false); // (FF52+) /* 0605: disable link-mouseover opening connection to linked server * [1] https://news.slashdot.org/story/15/08/14/2321202/how-to-quash-firefoxs-silent-requests * [2] https://www.ghacks.net/2015/08/16/block-firefox-from-connecting-to-sites-when-you-hover-over-links/ ***/ user_pref("network.http.speculative-parallel-limit", 0); /* 0606: disable pings (but enforce same host in case) * [1] http://kb.mozillazine.org/Browser.send_pings * [2] http://kb.mozillazine.org/Browser.send_pings.require_same_host ***/ user_pref("browser.send_pings", false); user_pref("browser.send_pings.require_same_host", true); /* 0607: disable links launching Windows Store on Windows 8/8.1/10 [WINDOWS] * [1] https://www.ghacks.net/2016/03/25/block-firefox-chrome-windows-store/ ***/ user_pref("network.protocol-handler.external.ms-windows-store", false); /* 0608: disable predictor / prefetching (FF48+) ***/ user_pref("network.predictor.enable-prefetch", false); /*** 0700: HTTP* / TCP/IP / DNS / PROXY / SOCKS etc ***/ user_pref("_user.js.parrot", "0700 syntax error: the parrot's given up the ghost!"); /* 0701: disable IPv6 * IPv6 can be abused, especially regarding MAC addresses. They also do not play nice * with VPNs. That's even assuming your ISP and/or router and/or website can handle it * [WARNING] This is just an application level fallback. Disabling IPv6 is best done * at an OS/network level, and/or configured properly in VPN setups * [TEST] http://ipv6leak.com/ * [1] https://github.com/ghacksuserjs/ghacks-user.js/issues/437#issuecomment-403740626 * [2] https://www.internetsociety.org/tag/ipv6-security/ (see Myths 2,4,5,6) ***/ user_pref("network.dns.disableIPv6", true); /* 0702: disable HTTP2 (which was based on SPDY which is now deprecated) * HTTP2 raises concerns with "multiplexing" and "server push", does nothing to enhance * privacy, and in fact opens up a number of server-side fingerprinting opportunities * [1] https://http2.github.io/faq/ * [2] https://blog.scottlogic.com/2014/11/07/http-2-a-quick-look.html * [3] https://queue.acm.org/detail.cfm?id=2716278 * [4] https://github.com/ghacksuserjs/ghacks-user.js/issues/107 ***/ user_pref("network.http.spdy.enabled", false); user_pref("network.http.spdy.enabled.deps", false); user_pref("network.http.spdy.enabled.http2", false); /* 0703: disable HTTP Alternative Services (FF37+) * [1] https://www.ghacks.net/2015/08/18/a-comprehensive-list-of-firefox-privacy-and-security-settings/#comment-3970881 * [2] https://www.mnot.net/blog/2016/03/09/alt-svc ***/ user_pref("network.http.altsvc.enabled", false); user_pref("network.http.altsvc.oe", false); /* 0704: enforce the proxy server to do any DNS lookups when using SOCKS * e.g. in TOR, this stops your local DNS server from knowing your Tor destination * as a remote Tor node will handle the DNS request * [1] http://kb.mozillazine.org/Network.proxy.socks_remote_dns * [2] https://trac.torproject.org/projects/tor/wiki/doc/TorifyHOWTO/WebBrowsers ***/ user_pref("network.proxy.socks_remote_dns", true); /* 0706: remove paths when sending URLs to PAC scripts (FF51+) * CVE-2017-5384: Information disclosure via Proxy Auto-Config (PAC) * [1] https://bugzilla.mozilla.org/1255474 ***/ user_pref("network.proxy.autoconfig_url.include_path", false); // default: false /* 0707: disable (or setup) DNS-over-HTTPS (DoH) (FF60+) * TRR = Trusted Recursive Resolver * .mode: 0=off, 1=race, 2=TRR first, 3=TRR only, 4=race for stats, but always use native result * [WARNING] DoH bypasses hosts and gives info to yet another party (e.g. Cloudflare) * [1] https://www.ghacks.net/2018/04/02/configure-dns-over-https-in-firefox/ * [2] https://hacks.mozilla.org/2018/05/a-cartoon-intro-to-dns-over-https/ ***/ // user_pref("network.trr.mode", 0); // user_pref("network.trr.bootstrapAddress", ""); // user_pref("network.trr.uri", ""); /* 0708: disable FTP (FF60+) * [1] https://www.ghacks.net/2018/02/20/firefox-60-with-new-preference-to-disable-ftp/ ***/ // user_pref("network.ftp.enabled", false); /* 0709: disable using UNC (Uniform Naming Convention) paths (FF61+) * [1] https://trac.torproject.org/projects/tor/ticket/26424 ***/ user_pref("network.file.disable_unc_paths", true); // (hidden pref) /* 0710: disable GIO as a potential proxy bypass vector * Gvfs/GIO has a set of supported protocols like obex, network, archive, computer, dav, cdda, * gphoto2, trash, etc. By default only smb and sftp protocols are accepted so far (as of FF64) * [1] https://bugzilla.mozilla.org/1433507 * [2] https://trac.torproject.org/23044 * [3] https://en.wikipedia.org/wiki/GVfs * [4] https://en.wikipedia.org/wiki/GIO_(software) ***/ user_pref("network.gio.supported-protocols", ""); // (hidden pref) /*** 0800: LOCATION BAR / SEARCH BAR / SUGGESTIONS / HISTORY / FORMS [SETUP] If you are in a private environment (no unwanted eyeballs) and your device is private (restricted access), and the device is secure when unattended (locked, encrypted, forensic hardened), then items 0850 and above can be relaxed in return for more convenience and functionality. Likewise, you may want to check the items cleared on shutdown in section 2800. [NOTE] The urlbar is also commonly referred to as the location bar and address bar #Required reading [#] https://xkcd.com/538/ ***/ user_pref("_user.js.parrot", "0800 syntax error: the parrot's ceased to be!"); /* 0801: disable location bar using search - PRIVACY * don't leak typos to a search engine, give an error message instead ***/ user_pref("keyword.enabled", false); /* 0802: disable location bar domain guessing - PRIVACY/SECURITY * domain guessing intercepts DNS "hostname not found errors" and resends a * request (e.g. by adding www or .com). This is inconsistent use (e.g. FQDNs), does not work * via Proxy Servers (different error), is a flawed use of DNS (TLDs: why treat .com * as the 411 for DNS errors?), privacy issues (why connect to sites you didn't * intend to), can leak sensitive data (e.g. query strings: e.g. Princeton attack), * and is a security risk (e.g. common typos & malicious sites set up to exploit this) ***/ user_pref("browser.fixup.alternate.enabled", false); /* 0803: display all parts of the url in the location bar - helps SECURITY ***/ user_pref("browser.urlbar.trimURLs", false); /* 0804: limit history leaks via enumeration (PER TAB: back/forward) - PRIVACY * This is a PER TAB session history. You still have a full history stored under all history * default=50, minimum=1=currentpage, 2 is the recommended minimum as some pages * use it as a means of referral (e.g. hotlinking), 4 or 6 or 10 may be more practical ***/ user_pref("browser.sessionhistory.max_entries", 10); /* 0805: disable CSS querying page history - CSS history leak - PRIVACY * [NOTE] This has NEVER been fully "resolved": in Mozilla/docs it is stated it's * only in 'certain circumstances', also see latest comments in [2] * [TEST] http://lcamtuf.coredump.cx/yahh/ (see github wiki APPENDIX C on how to use) * [1] https://dbaron.org/mozilla/visited-privacy * [2] https://bugzilla.mozilla.org/147777 * [3] https://developer.mozilla.org/docs/Web/CSS/Privacy_and_the_:visited_selector ***/ user_pref("layout.css.visited_links_enabled", false); /* 0806: disable displaying javascript in history URLs - SECURITY ***/ user_pref("browser.urlbar.filter.javascript", true); /* 0807: disable search bar LIVE search suggestions - PRIVACY * [SETTING] Search>Provide search suggestions ***/ user_pref("browser.search.suggest.enabled", false); /* 0808: disable location bar LIVE search suggestions (requires 0807 = true) - PRIVACY * Also disable the location bar prompt to enable/disable or learn more about it. * [SETTING] Search>Show search suggestions in address bar results ***/ user_pref("browser.urlbar.suggest.searches", false); user_pref("browser.urlbar.userMadeSearchSuggestionsChoice", true); // (FF41+) /* 0809: disable location bar suggesting "preloaded" top websites (FF54+) * [1] https://bugzilla.mozilla.org/1211726 ***/ user_pref("browser.urlbar.usepreloadedtopurls.enabled", false); /* 0810: disable location bar making speculative connections (FF56+) * [1] https://bugzilla.mozilla.org/1348275 ***/ user_pref("browser.urlbar.speculativeConnect.enabled", false); /* 0850a: disable location bar autocomplete and suggestion types * If you enforce any of the suggestion types, you MUST enforce 'autocomplete' * - If *ALL* of the suggestion types are false, 'autocomplete' must also be false * - If *ANY* of the suggestion types are true, 'autocomplete' must also be true * [SETTING] Privacy & Security>Address Bar>When using the address bar, suggest * [WARNING] If all three suggestion types are false, search engine keywords are disabled ***/ user_pref("browser.urlbar.autocomplete.enabled", false); user_pref("browser.urlbar.suggest.history", false); user_pref("browser.urlbar.suggest.bookmark", false); user_pref("browser.urlbar.suggest.openpage", false); /* 0850c: disable location bar dropdown * This value controls the total number of entries to appear in the location bar dropdown * [NOTE] Items (bookmarks/history/openpages) with a high "frecency"/"bonus" will always * be displayed (no we do not know how these are calculated or what the threshold is), * and this does not affect the search by search engine suggestion (see 0808) * [USAGE] This setting is only useful if you want to enable search engine keywords * (i.e. at least one of 0850a suggestion types must be true) but you want to *limit* suggestions shown ***/ // user_pref("browser.urlbar.maxRichResults", 0); /* 0850d: disable location bar autofill * [1] http://kb.mozillazine.org/Inline_autocomplete ***/ user_pref("browser.urlbar.autoFill", false); /* 0850e: disable location bar one-off searches (FF51+) * [1] https://www.ghacks.net/2016/08/09/firefox-one-off-searches-address-bar/ ***/ user_pref("browser.urlbar.oneOffSearches", false); /* 0850f: disable location bar suggesting local search history (FF57+) * [1] https://bugzilla.mozilla.org/1181644 ***/ user_pref("browser.urlbar.maxHistoricalSearchSuggestions", 0); // max. number of search suggestions /* 0860: disable search and form history * [SETTING] Privacy & Security>History>Custom Settings>Remember search and form history * [NOTE] You can clear formdata on exiting Firefox (see 2803) ***/ user_pref("browser.formfill.enable", false); /* 0862: disable browsing and download history * [SETTING] Privacy & Security>History>Custom Settings>Remember my browsing and download history * [NOTE] You can clear history and downloads on exiting Firefox (see 2803) ***/ // user_pref("places.history.enabled", false); /* 0864: disable date/time picker (FF57+ default true) * This can leak your locale if not en-US * [1] https://trac.torproject.org/projects/tor/ticket/21787 ***/ user_pref("dom.forms.datetime", false); /* 0870: disable Windows jumplist [WINDOWS] ***/ user_pref("browser.taskbar.lists.enabled", false); user_pref("browser.taskbar.lists.frequent.enabled", false); user_pref("browser.taskbar.lists.recent.enabled", false); user_pref("browser.taskbar.lists.tasks.enabled", false); /* 0871: disable Windows taskbar preview [WINDOWS] ***/ user_pref("browser.taskbar.previews.enable", false); /*** 0900: PASSWORDS ***/ user_pref("_user.js.parrot", "0900 syntax error: the parrot's expired!"); /* 0901: disable saving passwords * [SETTING] Privacy & Security>Forms & Passwords>Remember logins and passwords for sites * [NOTE] This does not clear any passwords already saved ***/ // user_pref("signon.rememberSignons", false); /* 0902: use a master password (recommended if you save passwords) * There are no preferences for this. It is all handled internally. * [SETTING] Privacy & Security>Forms & Passwords>Use a master password * [1] https://support.mozilla.org/kb/use-master-password-protect-stored-logins ***/ /* 0903: set how often Firefox should ask for the master password * 0=the first time (default), 1=every time it's needed, 2=every n minutes (as per the next pref) ***/ user_pref("security.ask_for_password", 2); /* 0904: set how often in minutes Firefox should ask for the master password (see pref above) * in minutes, default is 30 ***/ user_pref("security.password_lifetime", 5); /* 0905: disable auto-filling username & password form fields - SECURITY * can leak in cross-site forms AND be spoofed * [NOTE] Password will still be auto-filled after a user name is manually entered * [1] http://kb.mozillazine.org/Signon.autofillForms ***/ user_pref("signon.autofillForms", false); /* 0906: disable websites' autocomplete="off" (FF30+) * Don't let sites dictate use of saved logins and passwords. Increase security through * stronger password use. The trade-off is the convenience. Some sites should never be * saved (such as banking sites). Set at true, informed users can make their own choice. ***/ user_pref("signon.storeWhenAutocompleteOff", true); // default: true /* 0907: display warnings for logins on non-secure (non HTTPS) pages * [1] https://bugzilla.mozilla.org/1217156 ***/ user_pref("security.insecure_password.ui.enabled", true); /* 0908: remove user & password info when attempting to fix an entered URL (i.e. 0802 is true) * e.g. //user:password@foo -> //user@(prefix)foo(suffix) NOT //user:password@(prefix)foo(suffix) ***/ user_pref("browser.fixup.hide_user_pass", true); /* 0909: disable formless login capture for Password Manager (FF51+) ***/ user_pref("signon.formlessCapture.enabled", false); /* 0910: disable autofilling saved passwords on HTTP pages and show warning (FF52+) * [1] https://www.fxsitecompat.com/en-CA/docs/2017/insecure-login-forms-now-disable-autofill-show-warning-beneath-input-control/ * [2] https://bugzilla.mozilla.org/buglist.cgi?bug_id=1217152,1319119 ***/ user_pref("signon.autofillForms.http", false); user_pref("security.insecure_field_warning.contextual.enabled", true); /* 0911: prevent cross-origin images from triggering an HTTP-Authentication prompt (FF55+) * [1] https://bugzilla.mozilla.org/1357835 ***/ user_pref("network.auth.subresource-img-cross-origin-http-auth-allow", false); /*** 1000: CACHE [SETUP] ETAG [1] and other [2][3] cache tracking/fingerprinting techniques can be averted by disabling *BOTH* disk (1001) and memory (1003) cache. ETAGs can also be neutralized by modifying response headers [4]. Another solution is to use a hardened configuration with Temporary Containers [5]. Alternatively, you can *LIMIT* exposure by clearing cache on close (2803). or on a regular basis manually or with an extension. [1] https://en.wikipedia.org/wiki/HTTP_ETag#Tracking_using_ETags [2] https://robertheaton.com/2014/01/20/cookieless-user-tracking-for-douchebags/ [3] https://www.grepular.com/Preventing_Web_Tracking_via_the_Browser_Cache [4] https://github.com/ghacksuserjs/ghacks-user.js/wiki/4.2.4-Header-Editor [5] https://medium.com/@stoically/enhance-your-privacy-in-firefox-with-temporary-containers-33925cd6cd21 ***/ user_pref("_user.js.parrot", "1000 syntax error: the parrot's gone to meet 'is maker!"); /** CACHE ***/ /* 1001: disable disk cache ***/ user_pref("browser.cache.disk.enable", false); user_pref("browser.cache.disk.capacity", 0); user_pref("browser.cache.disk.smart_size.enabled", false); user_pref("browser.cache.disk.smart_size.first_run", false); /* 1002: disable disk cache for SSL pages * [1] http://kb.mozillazine.org/Browser.cache.disk_cache_ssl ***/ user_pref("browser.cache.disk_cache_ssl", false); /* 1003: disable memory cache * [NOTE] Not recommended due to performance issues ***/ // user_pref("browser.cache.memory.enable", false); // user_pref("browser.cache.memory.capacity", 0); // (hidden pref) /* 1005: disable fastback cache * To improve performance when pressing back/forward Firefox stores visited pages * so they don't have to be re-parsed. This is not the same as memory cache. * 0=none, -1=auto (that's minus 1), or for other values see [1] * [NOTE] Not recommended unless you know what you're doing * [1] http://kb.mozillazine.org/Browser.sessionhistory.max_total_viewers ***/ // user_pref("browser.sessionhistory.max_total_viewers", 0); /* 1006: disable permissions manager from writing to disk [RESTART] * [NOTE] This means any permission changes are session only * [1] https://bugzilla.mozilla.org/967812 ***/ // user_pref("permissions.memory_only", true); // (hidden pref) /* 1008: set DNS cache and expiration time (default 400 and 60, same as TBB) ***/ // user_pref("network.dnsCacheEntries", 400); // user_pref("network.dnsCacheExpiration", 60); /** SESSIONS & SESSION RESTORE ***/ /* 1020: disable the Session Restore service completely * [WARNING] [SETUP] This also disables the "Recently Closed Tabs" feature * It does not affect "Recently Closed Windows" or any history. ***/ user_pref("browser.sessionstore.max_tabs_undo", 0); user_pref("browser.sessionstore.max_windows_undo", 0); /* 1021: disable storing extra session data * extra session data contains contents of forms, scrollbar positions, cookies and POST data * define on which sites to save extra session data: * 0=everywhere, 1=unencrypted sites, 2=nowhere ***/ user_pref("browser.sessionstore.privacy_level", 2); /* 1022: disable resuming session from crash [SETUP] ***/ user_pref("browser.sessionstore.resume_from_crash", false); /* 1023: set the minimum interval between session save operations - increasing it * can help on older machines and some websites, as well as reducing writes, see [1] * Default is 15000 (15 secs). Try 30000 (30sec), 60000 (1min) etc * [WARNING] This can also affect entries in the "Recently Closed Tabs" feature: * i.e. the longer the interval the more chance a quick tab open/close won't be captured. * This longer interval *may* affect history but we cannot replicate any history not recorded * [1] https://bugzilla.mozilla.org/1304389 ***/ user_pref("browser.sessionstore.interval", 30000); /* 1024: disable automatic Firefox start and session restore after reboot [WINDOWS] (FF62+) * [1] https://bugzilla.mozilla.org/603903 ***/ user_pref("toolkit.winRegisterApplicationRestart", false); /** FAVICONS ***/ /* 1030: disable favicons in shortcuts * URL shortcuts use a cached randomly named .ico file which is stored in your * profile/shortcutCache directory. The .ico remains after the shortcut is deleted. * If set to false then the shortcuts use a generic Firefox icon ***/ user_pref("browser.shell.shortcutFavicons", false); /* 1031: disable favicons in tabs and new bookmarks * bookmark favicons are stored as data blobs in favicons.sqlite ***/ // user_pref("browser.chrome.site_icons", false); /* 1032: disable favicons in web notifications ***/ user_pref("alerts.showFavicons", false); // default: false /*** 1200: HTTPS ( SSL/TLS / OCSP / CERTS / HSTS / HPKP / CIPHERS ) Note that your cipher and other settings can be used server side as a fingerprint attack vector, see [1] (It's quite technical but the first part is easy to understand and you can stop reading when you reach the second section titled "Enter Bro") Option 1: Use Firefox defaults for the 1260's items (item 1260 default for SHA-1, is local only anyway). There is nothing *weak* about Firefox's defaults, but Mozilla (and other browsers) will always lag for fear of breakage and upset end-users Option 2: Disable the ciphers in 1261, 1262 and 1263. These shouldn't break anything. Optionally, disable the ciphers in 1264. [1] https://www.securityartwork.es/2017/02/02/tls-client-fingerprinting-with-bro/ ***/ user_pref("_user.js.parrot", "1200 syntax error: the parrot's a stiff!"); /** SSL (Secure Sockets Layer) / TLS (Transport Layer Security) ***/ /* 1201: disable old SSL/TLS "insecure" renegotiation (vulnerable to a MiTM attack) * [WARNING] <2% of secure sites do NOT support the newer "secure" renegotiation, see [2] * [1] https://wiki.mozilla.org/Security:Renegotiation * [2] https://www.ssllabs.com/ssl-pulse/ ***/ user_pref("security.ssl.require_safe_negotiation", true); /* 1202: control TLS versions with min and max * 1=min version of TLS 1.0, 2=min version of TLS 1.1, 3=min version of TLS 1.2 etc * [NOTE] Jul-2017: Telemetry indicates approx 2% of TLS web traffic uses 1.0 or 1.1 * [WARNING] If you get an "SSL_ERROR_NO_CYPHER_OVERLAP" error, temporarily * set a lower value for 'security.tls.version.min' in about:config * [1] http://kb.mozillazine.org/Security.tls.version.* * [2] https://www.ssl.com/how-to/turn-off-ssl-3-0-and-tls-1-0-in-your-browser/ * [2] archived: https://archive.is/hY2Mm ***/ // user_pref("security.tls.version.min", 3); user_pref("security.tls.version.max", 4); // 4 = allow up to and including TLS 1.3 /* 1203: disable SSL session tracking (FF36+) * SSL Session IDs speed up HTTPS connections (no need to renegotiate) and last for 48hrs. * Since the ID is unique, web servers can (and do) use it for tracking. If set to true, * this disables sending SSL Session IDs and TLS Session Tickets to prevent session tracking * [1] https://tools.ietf.org/html/rfc5077 * [2] https://bugzilla.mozilla.org/967977 ***/ user_pref("security.ssl.disable_session_identifiers", true); // (hidden pref) /* 1204: disable SSL Error Reporting * [1] https://firefox-source-docs.mozilla.org/browser/base/sslerrorreport/preferences.html ***/ user_pref("security.ssl.errorReporting.automatic", false); user_pref("security.ssl.errorReporting.enabled", false); user_pref("security.ssl.errorReporting.url", ""); /* 1205: disable TLS1.3 0-RTT (round-trip time) (FF51+) * [1] https://github.com/tlswg/tls13-spec/issues/1001 * [2] https://blog.cloudflare.com/tls-1-3-overview-and-q-and-a/ ***/ user_pref("security.tls.enable_0rtt_data", false); // (FF55+ default true) /** OCSP (Online Certificate Status Protocol) #Required reading [#] https://scotthelme.co.uk/revocation-is-broken/ ***/ /* 1210: enable OCSP Stapling * [1] https://blog.mozilla.org/security/2013/07/29/ocsp-stapling-in-firefox/ ***/ user_pref("security.ssl.enable_ocsp_stapling", true); /* 1211: control when to use OCSP fetching (to confirm current validity of certificates) * 0=disabled, 1=enabled (default), 2=enabled for EV certificates only * OCSP (non-stapled) leaks information about the sites you visit to the CA (cert authority) * It's a trade-off between security (checking) and privacy (leaking info to the CA) * [NOTE] This pref only controls OCSP fetching and does not affect OCSP stapling * [1] https://en.wikipedia.org/wiki/Ocsp ***/ user_pref("security.OCSP.enabled", 1); /* 1212: set OCSP fetch failures (non-stapled, see 1211) to hard-fail * When a CA cannot be reached to validate a cert, Firefox just continues the connection (=soft-fail) * Setting this pref to true tells Firefox to instead terminate the connection (=hard-fail) * It is pointless to soft-fail when an OCSP fetch fails: you cannot confirm a cert is still valid (it * could have been revoked) and/or you could be under attack (e.g. malicious blocking of OCSP servers) * [1] https://blog.mozilla.org/security/2013/07/29/ocsp-stapling-in-firefox/ * [2] https://www.imperialviolet.org/2014/04/19/revchecking.html ***/ user_pref("security.OCSP.require", true); /** CERTS / HSTS (HTTP Strict Transport Security) / HPKP (HTTP Public Key Pinning) ***/ /* 1220: disable Windows 8.1's Microsoft Family Safety cert [WINDOWS] (FF50+) * 0=disable detecting Family Safety mode and importing the root * 1=only attempt to detect Family Safety mode (don't import the root) * 2=detect Family Safety mode and import the root * [1] https://trac.torproject.org/projects/tor/ticket/21686 ***/ user_pref("security.family_safety.mode", 0); /* 1221: disable intermediate certificate caching (fingerprinting attack vector) [RESTART] * [NOTE] This may be better handled under FPI (ticket 1323644, part of Tor Uplift) * [WARNING] This affects login/cert/key dbs. The effect is all credentials are session-only. * Saved logins and passwords are not available. Reset the pref and restart to return them. * [TEST] https://fiprinca.0x90.eu/poc/ * [1] https://bugzilla.mozilla.org/1334485 - related bug * [2] https://bugzilla.mozilla.org/1216882 - related bug (see comment 9) ***/ // user_pref("security.nocertdb", true); // (hidden pref) /* 1222: enforce strict pinning * PKP (Public Key Pinning) 0=disabled 1=allow user MiTM (such as your antivirus), 2=strict * [WARNING] If you rely on an AV (antivirus) to protect your web browsing * by inspecting ALL your web traffic, then leave at current default=1 * [1] https://trac.torproject.org/projects/tor/ticket/16206 ***/ user_pref("security.cert_pinning.enforcement_level", 2); /** MIXED CONTENT ***/ /* 1240: disable insecure active content on https pages - mixed content * [1] https://trac.torproject.org/projects/tor/ticket/21323 ***/ user_pref("security.mixed_content.block_active_content", true); // default: true /* 1241: disable insecure passive content (such as images) on https pages - mixed context ***/ user_pref("security.mixed_content.block_display_content", true); /* 1243: block unencrypted requests from Flash on encrypted pages to mitigate MitM attacks (FF59+) * [1] https://bugzilla.mozilla.org/show_bug.cgi?id=1190623 ***/ user_pref("security.mixed_content.block_object_subrequest", true); /** CIPHERS [see the section 1200 intro] ***/ /* 1260: disable or limit SHA-1 * 0=all SHA1 certs are allowed * 1=all SHA1 certs are blocked (including perfectly valid ones from 2015 and earlier) * 2=deprecated option that now maps to 1 * 3=only allowed for locally-added roots (e.g. anti-virus) * 4=only allowed for locally-added roots or for certs in 2015 and earlier * [WARNING] When disabled, some man-in-the-middle devices (e.g. security scanners and * antivirus products, may fail to connect to HTTPS sites. SHA-1 is *almost* obsolete. * [1] https://blog.mozilla.org/security/2016/10/18/phasing-out-sha-1-on-the-public-web/ ***/ user_pref("security.pki.sha1_enforcement_level", 1); /* 1261: disable 3DES (effective key size < 128) * [1] https://en.wikipedia.org/wiki/3des#Security * [2] http://en.citizendium.org/wiki/Meet-in-the-middle_attack * [3] https://www-archive.mozilla.org/projects/security/pki/nss/ssl/fips-ssl-ciphersuites.html ***/ // user_pref("security.ssl3.rsa_des_ede3_sha", false); /* 1262: disable 128 bits ***/ // user_pref("security.ssl3.ecdhe_ecdsa_aes_128_sha", false); // user_pref("security.ssl3.ecdhe_rsa_aes_128_sha", false); /* 1263: disable DHE (Diffie-Hellman Key Exchange) * [WARNING] May break obscure sites, but not major sites, which should support ECDH over DHE * [1] https://www.eff.org/deeplinks/2015/10/how-to-protect-yourself-from-nsa-attacks-1024-bit-DH ***/ // user_pref("security.ssl3.dhe_rsa_aes_128_sha", false); // user_pref("security.ssl3.dhe_rsa_aes_256_sha", false); /* 1264: disable the remaining non-modern cipher suites as of FF52 * [NOTE] Commented out because it still breaks too many sites ***/ // user_pref("security.ssl3.rsa_aes_128_sha", false); // user_pref("security.ssl3.rsa_aes_256_sha", false); /** UI (User Interface) ***/ /* 1270: display warning (red padlock) for "broken security" (see 1201) * [1] https://wiki.mozilla.org/Security:Renegotiation ***/ user_pref("security.ssl.treat_unsafe_negotiation_as_broken", true); /* 1271: control "Add Security Exception" dialog on SSL warnings * 0=do neither 1=pre-populate url 2=pre-populate url + pre-fetch cert (default) * [1] https://github.com/pyllyukko/user.js/issues/210 ***/ user_pref("browser.ssl_override_behavior", 1); /* 1272: display advanced information on Insecure Connection warning pages * only works when it's possible to add an exception * i.e. it doesn't work for HSTS discrepancies (https://subdomain.preloaded-hsts.badssl.com/) * [TEST] https://expired.badssl.com/ ***/ user_pref("browser.xul.error_pages.expert_bad_cert", true); /* 1273: display "insecure" icon (FF59+) and "Not Secure" text (FF60+) on HTTP sites ***/ user_pref("security.insecure_connection_icon.enabled", true); // all windows user_pref("security.insecure_connection_text.enabled", true); // user_pref("security.insecure_connection_icon.pbmode.enabled", true); // private windows only // user_pref("security.insecure_connection_text.pbmode.enabled", true); /*** 1400: FONTS ***/ user_pref("_user.js.parrot", "1400 syntax error: the parrot's bereft of life!"); /* 1401: disable websites choosing fonts (0=block, 1=allow) * If you disallow fonts, this drastically limits/reduces font * enumeration (by JS) which is a high entropy fingerprinting vector. * [SETTING] General>Language and Appearance>Advanced>Allow pages to choose... * [SETUP] Disabling fonts can uglify the web a fair bit. ***/ user_pref("browser.display.use_document_fonts", 0); /* 1402: set more legible default fonts [SETUP] * [SETTING] General>Language and Appearance>Fonts & Colors>Advanced>Serif|Sans-serif|Monospace * [NOTE] Example below for Windows/Western only ***/ // user_pref("font.name.serif.x-unicode", "Georgia"); // user_pref("font.name.serif.x-western", "Georgia"); // default: Times New Roman // user_pref("font.name.sans-serif.x-unicode", "Arial"); // user_pref("font.name.sans-serif.x-western", "Arial"); // default: Arial // user_pref("font.name.monospace.x-unicode", "Lucida Console"); // user_pref("font.name.monospace.x-western", "Lucida Console"); // default: Courier New /* 1403: disable icon fonts (glyphs) (FF41) and local fallback rendering * [1] https://bugzilla.mozilla.org/789788 * [2] https://trac.torproject.org/projects/tor/ticket/8455 ***/ // user_pref("gfx.downloadable_fonts.enabled", false); // user_pref("gfx.downloadable_fonts.fallback_delay", -1); /* 1404: disable rendering of SVG OpenType fonts * [1] https://wiki.mozilla.org/SVGOpenTypeFonts - iSECPartnersReport recommends to disable this ***/ user_pref("gfx.font_rendering.opentype_svg.enabled", false); /* 1405: disable WOFF2 (Web Open Font Format) (FF35+) ***/ user_pref("gfx.downloadable_fonts.woff2.enabled", false); /* 1406: disable CSS Font Loading API * [SETUP] Disabling fonts can uglify the web a fair bit. ***/ user_pref("layout.css.font-loading-api.enabled", false); /* 1407: disable special underline handling for a few fonts which you will probably never use [RESTART] * Any of these fonts on your system can be enumerated for fingerprinting. * [1] http://kb.mozillazine.org/Font.blacklist.underline_offset ***/ user_pref("font.blacklist.underline_offset", ""); /* 1408: disable graphite which FF49 turned back on by default * In the past it had security issues. Update: This continues to be the case, see [1] * [1] https://www.mozilla.org/security/advisories/mfsa2017-15/#CVE-2017-7778 ***/ user_pref("gfx.font_rendering.graphite.enabled", false); /* 1409: limit system font exposure to a whitelist (FF52+) [SETUP] [RESTART] * If the whitelist is empty, then whitelisting is considered disabled and all fonts are allowed. * [NOTE] Creating your own probably highly-unique whitelist will raise your entropy. If * you block sites choosing fonts in 1401, this preference is irrelevant. In future, * privacy.resistFingerprinting (see 4500) may cover this, and 1401 can be relaxed. * [1] https://bugzilla.mozilla.org/1121643 ***/ // user_pref("font.system.whitelist", ""); // (hidden pref) /*** 1600: HEADERS / REFERERS Only *cross domain* referers need controlling and XOriginPolicy (1603) is perfect for that. Thus we enforce the default values for 1601, 1602, 1605 and 1606 to minimize breakage, and only tweak 1603 and 1604. Our default settings provide the best balance between protection and amount of breakage. To harden it a bit more you can set XOriginPolicy (1603) to 2 (+ optionally 1604 to 1 or 2). To fix broken sites (including your modem/router), temporarily set XOriginPolicy=0 and XOriginTrimmingPolicy=2 in about:config, use the site and then change the values back. If you visit those sites regularly (e.g. Vimeo), use an extension. full URI: https://example.com:8888/foo/bar.html?id=1234 scheme+host+port+path: https://example.com:8888/foo/bar.html scheme+host+port: https://example.com:8888 #Required reading [#] https://feeding.cloud.geek.nz/posts/tweaking-referrer-for-privacy-in-firefox/ ***/ user_pref("_user.js.parrot", "1600 syntax error: the parrot rests in peace!"); /* 1601: ALL: control when images/links send a referer * 0=never, 1=send only when links are clicked, 2=for links and images (default) ***/ user_pref("network.http.sendRefererHeader", 2); /* 1602: ALL: control the amount of information to send * 0=send full URI (default), 1=scheme+host+port+path, 2=scheme+host+port ***/ user_pref("network.http.referer.trimmingPolicy", 0); /* 1603: CROSS ORIGIN: control when to send a referer [SETUP] * 0=always (default), 1=only if base domains match, 2=only if hosts match ***/ user_pref("network.http.referer.XOriginPolicy", 1); /* 1604: CROSS ORIGIN: control the amount of information to send (FF52+) * 0=send full URI (default), 1=scheme+host+port+path, 2=scheme+host+port ***/ user_pref("network.http.referer.XOriginTrimmingPolicy", 0); /* 1605: ALL: disable spoofing a referer * [WARNING] Spoofing effectively disables the anti-CSRF (Cross-Site Request Forgery) protections that some sites may rely on ***/ user_pref("network.http.referer.spoofSource", false); /* 1606: ALL: set the default Referrer Policy * 0=no-referer, 1=same-origin, 2=strict-origin-when-cross-origin, 3=no-referrer-when-downgrade * [NOTE] This is only a default, it can be overridden by a site-controlled Referrer Policy * [1] https://www.w3.org/TR/referrer-policy/ * [2] https://developer.mozilla.org/docs/Web/HTTP/Headers/Referrer-Policy * [3] https://blog.mozilla.org/security/2018/01/31/preventing-data-leaks-by-stripping-path-information-in-http-referrers/ ***/ user_pref("network.http.referer.defaultPolicy", 3); // (FF59+) default: 3 user_pref("network.http.referer.defaultPolicy.pbmode", 2); // (FF59+) default: 2 /* 1607: TOR: hide (not spoof) referrer when leaving a .onion domain (FF54+) * [NOTE] Firefox cannot access .onion sites by default. We recommend you use * TBB (Tor Browser Bundle) which is specifically designed for the dark web * [1] https://bugzilla.mozilla.org/1305144 ***/ user_pref("network.http.referer.hideOnionSource", true); /* 1610: ALL: enable the DNT (Do Not Track) HTTP header * [SETTING] Privacy & Security>Tracking Protecting>Send websites a "Do Not Track"... * [NOTE] DNT is enforced with TP (see 0420) regardless of this pref ***/ user_pref("privacy.donottrackheader.enabled", true); /*** 1700: CONTAINERS [SETUP] [1] https://support.mozilla.org/kb/containers-experiment [2] https://wiki.mozilla.org/Security/Contextual_Identity_Project/Containers [3] https://github.com/mozilla/testpilot-containers ***/ user_pref("_user.js.parrot", "1700 syntax error: the parrot's bit the dust!"); /* 1701: enable Container Tabs setting in preferences (see 1702) (FF50+) * [1] https://bugzilla.mozilla.org/1279029 ***/ // user_pref("privacy.userContext.ui.enabled", true); /* 1702: enable Container Tabs (FF50+) * [SETTING] Privacy & Security>Tabs>Enable Container Tabs ***/ // user_pref("privacy.userContext.enabled", true); /* 1703: enable a private container for thumbnail loads (FF51+) ***/ // user_pref("privacy.usercontext.about_newtab_segregation.enabled", true); // default: true in FF61+ /* 1704: set long press behaviour on "+ Tab" button to display container menu (FF53+) * 0=disables long press, 1=when clicked, the menu is shown * 2=the menu is shown after X milliseconds * [NOTE] The menu does not contain a non-container tab option * [1] https://bugzilla.mozilla.org/1328756 ***/ // user_pref("privacy.userContext.longPressBehavior", 2); /*** 1800: PLUGINS ***/ user_pref("_user.js.parrot", "1800 syntax error: the parrot's pushing up daisies!"); /* 1801: set default plugin state (i.e. new plugins on discovery) to never activate * 0=disabled, 1=ask to activate, 2=active - you can override individual plugins ***/ user_pref("plugin.default.state", 0); user_pref("plugin.defaultXpi.state", 0); /* 1802: enable click to play and set to 0 minutes ***/ user_pref("plugins.click_to_play", true); user_pref("plugin.sessionPermissionNow.intervalInMinutes", 0); /* 1803: disable Flash plugin (Add-ons>Plugins) * 0=deactivated, 1=ask, 2=enabled * ESR52.x is the last branch to *fully* support NPAPI, FF52+ stable only supports Flash * [NOTE] You can still override individual sites via site permissions * [1] https://www.ghacks.net/2013/07/09/how-to-make-sure-that-a-firefox-plugin-never-activates-again/ ***/ user_pref("plugin.state.flash", 0); /* 1805: disable scanning for plugins [WINDOWS] * [1] http://kb.mozillazine.org/Plugin_scanning * plid.all = whether to scan the directories specified in the Windows registry for PLIDs. * Used to detect RealPlayer, Java, Antivirus etc, but since FF52 only covers Flash ***/ user_pref("plugin.scan.plid.all", false); /* 1820: disable all GMP (Gecko Media Plugins) [SETUP] * [1] https://wiki.mozilla.org/GeckoMediaPlugins ***/ user_pref("media.gmp-provider.enabled", false); user_pref("media.gmp.trial-create.enabled", false); user_pref("media.gmp-manager.url", "data:text/plain,"); user_pref("media.gmp-manager.url.override", "data:text/plain,"); // (hidden pref) user_pref("media.gmp-manager.updateEnabled", false); // disable local fallback (hidden pref) /* 1825: disable widevine CDM (Content Decryption Module) [SETUP] ***/ user_pref("media.gmp-widevinecdm.visible", false); user_pref("media.gmp-widevinecdm.enabled", false); user_pref("media.gmp-widevinecdm.autoupdate", false); /* 1830: disable all DRM content (EME: Encryption Media Extension) [SETUP] * [1] https://www.eff.org/deeplinks/2017/10/drms-dead-canary-how-we-just-lost-web-what-we-learned-it-and-what-we-need-do-next ***/ user_pref("media.eme.enabled", false); // [SETTING] General>DRM Content>Play DRM-controlled content user_pref("browser.eme.ui.enabled", false); // hides "Play DRM-controlled content" checkbox [RESTART] /* 1840: disable the OpenH264 Video Codec by Cisco to "Never Activate" * This is the bundled codec used for video chat in WebRTC ***/ user_pref("media.gmp-gmpopenh264.enabled", false); // (hidden pref) user_pref("media.gmp-gmpopenh264.autoupdate", false); /*** 2000: MEDIA / CAMERA / MIC ***/ user_pref("_user.js.parrot", "2000 syntax error: the parrot's snuffed it!"); /* 2001: disable WebRTC (Web Real-Time Communication) * [1] https://www.privacytools.io/#webrtc ***/ user_pref("media.peerconnection.enabled", false); user_pref("media.peerconnection.use_document_iceservers", false); user_pref("media.peerconnection.video.enabled", false); user_pref("media.peerconnection.identity.enabled", false); user_pref("media.peerconnection.identity.timeout", 1); user_pref("media.peerconnection.turn.disable", true); user_pref("media.peerconnection.ice.tcp", false); user_pref("media.navigator.video.enabled", false); // video capability for WebRTC /* 2002: limit WebRTC IP leaks if using WebRTC * [1] https://bugzilla.mozilla.org/buglist.cgi?bug_id=1189041,1297416 * [2] https://wiki.mozilla.org/Media/WebRTC/Privacy ***/ user_pref("media.peerconnection.ice.default_address_only", true); // (FF42-FF50) user_pref("media.peerconnection.ice.no_host", true); // (FF51+) /* 2010: disable WebGL (Web Graphics Library), force bare minimum feature set if used & disable WebGL extensions * [1] https://www.contextis.com/resources/blog/webgl-new-dimension-browser-exploitation/ * [2] https://security.stackexchange.com/questions/13799/is-webgl-a-security-concern ***/ user_pref("webgl.disabled", true); user_pref("pdfjs.enableWebGL", false); user_pref("webgl.min_capability_mode", true); user_pref("webgl.disable-extensions", true); user_pref("webgl.disable-fail-if-major-performance-caveat", true); /* 2012: disable two more webgl preferences (FF51+) ***/ user_pref("webgl.dxgl.enabled", false); // [WINDOWS] user_pref("webgl.enable-webgl2", false); /* 2022: disable screensharing ***/ user_pref("media.getusermedia.screensharing.enabled", false); user_pref("media.getusermedia.browser.enabled", false); user_pref("media.getusermedia.audiocapture.enabled", false); /* 2024: set a default permission for Camera/Microphone (FF58+) * 0=always ask (default), 1=allow, 2=block * [SETTING] to add site exceptions: Page Info>Permissions>Use the Camera/Microphone * [SETTING] to manage site exceptions: Options>Privacy & Security>Permissions>Camera/Microphone>Settings ***/ // user_pref("permissions.default.camera", 2); // user_pref("permissions.default.microphone", 2); /* 2026: disable canvas capture stream (FF41+) * [1] https://developer.mozilla.org/docs/Web/API/HTMLCanvasElement/captureStream ***/ user_pref("canvas.capturestream.enabled", false); /* 2027: disable camera image capture (FF35+) * [1] https://trac.torproject.org/projects/tor/ticket/16339 ***/ user_pref("dom.imagecapture.enabled", false); // default: false /* 2028: disable offscreen canvas (FF44+) * [1] https://developer.mozilla.org/docs/Web/API/OffscreenCanvas ***/ user_pref("gfx.offscreencanvas.enabled", false); // default: false /* 2030: disable auto-play of HTML5 media (FF63+) * 0=Allowed (default), 1=Blocked, 2=Prompt * [WARNING] This may break video playback on various sites ***/ user_pref("media.autoplay.default", 1); /* 2031: disable audio auto-play in non-active tabs (FF51+) * [1] https://www.ghacks.net/2016/11/14/firefox-51-blocks-automatic-audio-playback-in-non-active-tabs/ ***/ user_pref("media.block-autoplay-until-in-foreground", true); /*** 2200: WINDOW MEDDLING & LEAKS / POPUPS ***/ user_pref("_user.js.parrot", "2200 syntax error: the parrot's 'istory!"); /* 2201: prevent websites from disabling new window features * [1] http://kb.mozillazine.org/Prevent_websites_from_disabling_new_window_features ***/ user_pref("dom.disable_window_open_feature.close", true); user_pref("dom.disable_window_open_feature.location", true); // default: true user_pref("dom.disable_window_open_feature.menubar", true); user_pref("dom.disable_window_open_feature.minimizable", true); user_pref("dom.disable_window_open_feature.personalbar", true); // bookmarks toolbar user_pref("dom.disable_window_open_feature.resizable", true); // default: true user_pref("dom.disable_window_open_feature.status", true); // status bar - default: true user_pref("dom.disable_window_open_feature.titlebar", true); user_pref("dom.disable_window_open_feature.toolbar", true); /* 2202: prevent scripts moving and resizing open windows ***/ user_pref("dom.disable_window_move_resize", true); /* 2203: open links targeting new windows in a new tab instead * This stops malicious window sizes and some screen resolution leaks. * You can still right-click a link and open in a new window. * [TEST] https://people.torproject.org/~gk/misc/entire_desktop.html * [1] https://trac.torproject.org/projects/tor/ticket/9881 ***/ user_pref("browser.link.open_newwindow", 3); user_pref("browser.link.open_newwindow.restriction", 0); /* 2204: disable Fullscreen API (requires user interaction) to prevent screen-resolution leaks * [NOTE] You can still manually toggle the browser's fullscreen state (F11), * but this pref will disable embedded video/game fullscreen controls, e.g. youtube * [TEST] https://developer.mozilla.org/samples/domref/fullscreen.html ***/ // user_pref("full-screen-api.enabled", false); /* 2210: block popup windows * [SETTING] Privacy & Security>Permissions>Block pop-up windows ***/ user_pref("dom.disable_open_during_load", true); /* 2211: set max popups from a single non-click event - default is 20! ***/ user_pref("dom.popup_maximum", 3); /* 2212: limit events that can cause a popup * default is "change click dblclick mouseup pointerup notificationclick reset submit touchend" * [1] http://kb.mozillazine.org/Dom.popup_allowed_events ***/ user_pref("dom.popup_allowed_events", "click dblclick"); /*** 2300: WEB WORKERS [SETUP] A worker is a JS "background task" running in a global context, i.e. it is different from the current window. Workers can spawn new workers (must be the same origin & scheme), including service and shared workers. Shared workers can be utilized by multiple scripts and communicate between browsing contexts (windows/tabs/iframes) and can even control your cache. [WARNING] Disabling "web workers" might break sites [UPDATE] uMatrix 1.2.0+ allows a per-scope control for workers (2301-deprecated) and service workers (2302) #Required reading [#] https://github.com/gorhill/uMatrix/releases/tag/1.2.0 [1] Web Workers: https://developer.mozilla.org/docs/Web/API/Web_Workers_API [2] Worker: https://developer.mozilla.org/docs/Web/API/Worker [3] Service Worker: https://developer.mozilla.org/docs/Web/API/Service_Worker_API [4] SharedWorker: https://developer.mozilla.org/docs/Web/API/SharedWorker [5] ChromeWorker: https://developer.mozilla.org/docs/Web/API/ChromeWorker [6] Notifications: https://support.mozilla.org/questions/1165867#answer-981820 ***/ user_pref("_user.js.parrot", "2300 syntax error: the parrot's off the twig!"); /* 2302: disable service workers * Service workers essentially act as proxy servers that sit between web apps, and the browser * and network, are event driven, and can control the web page/site it is associated with, * intercepting and modifying navigation and resource requests, and caching resources. * [NOTE] Service worker APIs are hidden (in Firefox) and cannot be used when in PB mode. * [NOTE] Service workers only run over HTTPS. Service Workers have no DOM access. ***/ user_pref("dom.serviceWorkers.enabled", false); /* 2304: disable web notifications * [1] https://developer.mozilla.org/docs/Web/API/Notifications_API ***/ user_pref("dom.webnotifications.enabled", false); // (FF22+) user_pref("dom.webnotifications.serviceworker.enabled", false); // (FF44+) /* 2305: set a default permission for Notifications (see 2304) (FF58+) * [SETTING] to add site exceptions: Page Info>Permissions>Receive Notifications * [SETTING] to manage site exceptions: Options>Privacy & Security>Permissions>Notifications>Settings ***/ // user_pref("permissions.default.desktop-notification", 2); // 0=always ask (default), 1=allow, 2=block /* 2306: disable push notifications (FF44+) * web apps can receive messages pushed to them from a server, whether or * not the web app is in the foreground, or even currently loaded * [1] https://developer.mozilla.org/docs/Web/API/Push_API ***/ user_pref("dom.push.enabled", false); user_pref("dom.push.connection.enabled", false); user_pref("dom.push.serverURL", ""); user_pref("dom.push.userAgentID", ""); /*** 2400: DOM (DOCUMENT OBJECT MODEL) & JAVASCRIPT ***/ user_pref("_user.js.parrot", "2400 syntax error: the parrot's kicked the bucket!"); /* 2401: disable website control over browser right-click context menu * [NOTE] Shift-Right-Click will always bring up the browser right-click context menu ***/ // user_pref("dom.event.contextmenu.enabled", false); /* 2402: disable website access to clipboard events/content * [WARNING] This will break some sites functionality such as pasting into facebook, wordpress * this applies to onCut, onCopy, onPaste events - i.e. you have to interact with * the website for it to look at the clipboard * [1] https://www.ghacks.net/2014/01/08/block-websites-reading-modifying-clipboard-contents-firefox/ ***/ user_pref("dom.event.clipboardevents.enabled", false); /* 2403: disable clipboard commands (cut/copy) from "non-privileged" content (FF41+) * this disables document.execCommand("cut"/"copy") to protect your clipboard * [1] https://bugzilla.mozilla.org/1170911 ***/ user_pref("dom.allow_cut_copy", false); // (hidden pref) /* 2404: disable "Confirm you want to leave" dialog on page close * Does not prevent JS leaks of the page close event. * [1] https://developer.mozilla.org/docs/Web/Events/beforeunload * [2] https://support.mozilla.org/questions/1043508 ***/ user_pref("dom.disable_beforeunload", true); /* 2414: disable shaking the screen ***/ user_pref("dom.vibrator.enabled", false); /* 2420: disable asm.js (FF22+) * [1] http://asmjs.org/ * [2] https://www.mozilla.org/security/advisories/mfsa2015-29/ * [3] https://www.mozilla.org/security/advisories/mfsa2015-50/ * [4] https://www.mozilla.org/security/advisories/mfsa2017-01/#CVE-2017-5375 * [5] https://www.mozilla.org/security/advisories/mfsa2017-05/#CVE-2017-5400 * [6] https://rh0dev.github.io/blog/2017/the-return-of-the-jit/ ***/ user_pref("javascript.options.asmjs", false); /* 2421: disable Ion and baseline JIT to help harden JS against exploits * [WARNING] Causes the odd site issue and there is also a performance loss * [1] https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2015-0817 ***/ // user_pref("javascript.options.ion", false); // user_pref("javascript.options.baselinejit", false); /* 2422: disable WebAssembly for now (FF52+) * [1] https://developer.mozilla.org/docs/WebAssembly ***/ user_pref("javascript.options.wasm", false); /* 2426: disable Intersection Observer API (FF53+) * Almost a year to complete, three versions late to stable (as default false), * number #1 cause of crashes in nightly numerous times, and is (primarily) an * ad network API for "ad viewability checks" down to a pixel level * [1] https://developer.mozilla.org/docs/Web/API/Intersection_Observer_API * [2] https://w3c.github.io/IntersectionObserver/ * [3] https://bugzilla.mozilla.org/1243846 ***/ user_pref("dom.IntersectionObserver.enabled", false); /* 2427: disable Shared Memory (Spectre mitigation) * [1] https://github.com/tc39/ecmascript_sharedmem/blob/master/TUTORIAL.md * [2] https://blog.mozilla.org/security/2018/01/03/mitigations-landing-new-class-timing-attack/ ***/ user_pref("javascript.options.shared_memory", false); /*** 2500: HARDWARE FINGERPRINTING ***/ user_pref("_user.js.parrot", "2500 syntax error: the parrot's shuffled off 'is mortal coil!"); /* 2502: disable Battery Status API * Initially a Linux issue (high precision readout) that was fixed. * However, it is still another metric for fingerprinting, used to raise entropy. * e.g. do you have a battery or not, current charging status, charge level, times remaining etc * [NOTE] From FF52+ Battery Status API is only available in chrome/privileged code. see [1] * [1] https://bugzilla.mozilla.org/1313580 ***/ // user_pref("dom.battery.enabled", false); /* 2504: disable virtual reality devices * [WARNING] [SETUP] Optional protection depending on your connected devices * [1] https://developer.mozilla.org/docs/Web/API/WebVR_API ***/ // user_pref("dom.vr.enabled", false); /* 2505: disable media device enumeration (FF29+) * [NOTE] media.peerconnection.enabled should also be set to false (see 2001) * [1] https://wiki.mozilla.org/Media/getUserMedia * [2] https://developer.mozilla.org/docs/Web/API/MediaDevices/enumerateDevices ***/ user_pref("media.navigator.enabled", false); /* 2508: disable hardware acceleration to reduce graphics fingerprinting * [SETTING] General>Performance>Custom>Use hardware acceleration when available * [WARNING] [SETUP] Affects text rendering (fonts will look different), impacts video performance, * and parts of Quantum that utilize the GPU will also be affected as they are rolled out * [1] https://wiki.mozilla.org/Platform/GFX/HardwareAcceleration ***/ // user_pref("gfx.direct2d.disabled", true); // [WINDOWS] user_pref("layers.acceleration.disabled", true); /* 2510: disable Web Audio API (FF51+) * [1] https://bugzilla.mozilla.org/1288359 ***/ user_pref("dom.webaudio.enabled", false); /* 2516: disable PointerEvents * [1] https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent ***/ user_pref("dom.w3c_pointer_events.enabled", false); /* 2517: disable Media Capabilities API (FF63+) * [WARNING] This *may* affect media performance if disabled, no one is sure * [1] https://github.com/WICG/media-capabilities * [2] https://wicg.github.io/media-capabilities/#security-privacy-considerations ***/ // user_pref("media.media-capabilities.enabled", false); /*** 2600: MISCELLANEOUS ***/ user_pref("_user.js.parrot", "2600 syntax error: the parrot's run down the curtain!"); /* 2601: prevent accessibility services from accessing your browser [RESTART] * [SETTING] Privacy & Security>Permissions>Prevent accessibility services from accessing your browser * [1] https://support.mozilla.org/kb/accessibility-services ***/ user_pref("accessibility.force_disabled", 1); /* 2602: disable sending additional analytics to web servers * [1] https://developer.mozilla.org/docs/Web/API/Navigator/sendBeacon ***/ user_pref("beacon.enabled", false); /* 2603: remove temp files opened with an external application * [1] https://bugzilla.mozilla.org/302433 ***/ user_pref("browser.helperApps.deleteTempFileOnExit", true); /* 2604: disable page thumbnail collection * look in profile/thumbnails directory - you may want to clean that out ***/ user_pref("browser.pagethumbnails.capturing_disabled", true); // (hidden pref) /* 2605: block web content in file processes (FF55+) * [WARNING] [SETUP] You may want to disable this for corporate or developer environments * [1] https://bugzilla.mozilla.org/1343184 ***/ user_pref("browser.tabs.remote.allowLinkedWebInFileUriProcess", false); /* 2606: disable UITour backend so there is no chance that a remote page can use it ***/ user_pref("browser.uitour.enabled", false); user_pref("browser.uitour.url", ""); /* 2607: disable various developer tools in browser context * [SETTING] Devtools>Advanced Settings>Enable browser chrome and add-on debugging toolboxes * [1] https://github.com/pyllyukko/user.js/issues/179#issuecomment-246468676 ***/ user_pref("devtools.chrome.enabled", false); /* 2608: disable WebIDE to prevent remote debugging and extension downloads * [1] https://trac.torproject.org/projects/tor/ticket/16222 ***/ user_pref("devtools.webide.autoinstallADBHelper", false); user_pref("devtools.debugger.remote-enabled", false); user_pref("devtools.webide.enabled", false); /* 2609: disable MathML (Mathematical Markup Language) (FF51+) * [TEST] http://browserspy.dk/mathml.php * [1] https://bugzilla.mozilla.org/1173199 ***/ user_pref("mathml.disabled", true); /* 2610: disable in-content SVG (Scalable Vector Graphics) (FF53+) * [WARNING] Expect breakage incl. youtube player controls. Best left for a "hardened" profile. * [1] https://bugzilla.mozilla.org/1216893 ***/ // user_pref("svg.disabled", true); /* 2611: disable middle mouse click opening links from clipboard * [1] https://trac.torproject.org/projects/tor/ticket/10089 * [2] http://kb.mozillazine.org/Middlemouse.contentLoadURL ***/ user_pref("middlemouse.contentLoadURL", false); /* 2614: limit HTTP redirects (this does not control redirects with HTML meta tags or JS) * [WARNING] A low setting of 5 or under will probably break some sites (e.g. gmail logins) * To control HTML Meta tag and JS redirects, use an extension. Default is 20 ***/ user_pref("network.http.redirection-limit", 10); /* 2615: disable websites overriding Firefox's keyboard shortcuts (FF58+) * [SETTING] to add site exceptions: Page Info>Permissions>Override Keyboard Shortcuts * [NOTE] At the time of writing, causes issues with delete and backspace keys ***/ // user_pref("permissions.default.shortcuts", 2); // 0 (default) or 1=allow, 2=block /* 2616: remove special permissions for certain mozilla domains (FF35+) * [1] resource://app/defaults/permissions ***/ user_pref("permissions.manager.defaultsUrl", ""); /* 2617: remove webchannel whitelist ***/ user_pref("webchannel.allowObject.urlWhitelist", ""); /* 2618: disable exposure of system colors to CSS or canvas (FF44+) * [NOTE] see second listed bug: may cause black on black for elements with undefined colors * [1] https://bugzilla.mozilla.org/buglist.cgi?bug_id=232227,1330876 ***/ user_pref("ui.use_standins_for_native_colors", true); // (hidden pref) /* 2619: enforce Punycode for Internationalized Domain Names to eliminate possible spoofing * Firefox has *some* protections, but it is better to be safe than sorry. The downside: it will also * display legitimate IDN's punycoded, which might be undesirable for users of non-latin alphabets * [TEST] https://www.xn--80ak6aa92e.com/ (www.apple.com) * [1] https://wiki.mozilla.org/IDN_Display_Algorithm * [2] https://en.wikipedia.org/wiki/IDN_homograph_attack * [3] CVE-2017-5383: https://www.mozilla.org/security/advisories/mfsa2017-02/ * [4] https://www.xudongz.com/blog/2017/idn-phishing/ ***/ user_pref("network.IDN_show_punycode", true); /* 2620: enable Firefox's built-in PDF reader [SETUP] * [SETTING] General>Applications>Portable Document Format (PDF) * This setting controls if the option "Display in Firefox" in the above setting is available * and by effect controls whether PDFs are handled in-browser or externally ("Ask" or "Open With") * PROS: pdfjs is lightweight, open source, and as secure/vetted as any pdf reader out there (more than most) * Exploits are rare (1 serious case in 4 yrs), treated seriously and patched quickly. * It doesn't break "state separation" of browser content (by not sharing with OS, independent apps). * It maintains disk avoidance and application data isolation. It's convenient. You can still save to disk. * CONS: You may prefer a different pdf reader for security reasons * CAVEAT: JS can still force a pdf to open in-browser by bundling its own code (rare) ***/ user_pref("pdfjs.disabled", false); /** DOWNLOADS ***/ /* 2650: discourage downloading to desktop (0=desktop 1=downloads 2=last used) * [SETTING] To set your default "downloads": General>Downloads>Save files to ***/ user_pref("browser.download.folderList", 2); /* 2651: enforce user interaction for security by always asking the user where to download * [SETTING] General>Downloads>Always ask you where to save files ***/ user_pref("browser.download.useDownloadDir", false); /* 2652: disable adding downloads to the system's "recent documents" list ***/ user_pref("browser.download.manager.addToRecentDocs", false); /* 2653: disable hiding mime types (Options>General>Applications) not associated with a plugin ***/ user_pref("browser.download.hide_plugins_without_extensions", false); /* 2654: disable "open with" in download dialog (FF50+) * This is very useful to enable when the browser is sandboxed (e.g. via AppArmor) * in such a way that it is forbidden to run external applications. * [SETUP] This may interfere with some users' workflow or methods * [1] https://bugzilla.mozilla.org/1281959 ***/ user_pref("browser.download.forbid_open_with", true); /** EXTENSIONS ***/ /* 2660: lock down allowed extension directories * [WARNING] This will break extensions that do not use the default XPI directories * [1] https://mike.kaply.com/2012/02/21/understanding-add-on-scopes/ * [1] archived: https://archive.is/DYjAM ***/ user_pref("extensions.enabledScopes", 1); // (hidden pref) user_pref("extensions.autoDisableScopes", 15); /* 2662: disable webextension restrictions on certain mozilla domains (also see 4503) (FF60+) * [1] https://bugzilla.mozilla.org/buglist.cgi?bug_id=1384330,1406795,1415644,1453988 ***/ // user_pref("extensions.webextensions.restrictedDomains", ""); /* 2663: enable warning when websites try to install add-ons * [SETTING] Privacy & Security>Permissions>Warn you when websites try to install add-ons ***/ user_pref("xpinstall.whitelist.required", true); // default: true /** SECURITY ***/ /* 2680: enable CSP (Content Security Policy) * [1] https://developer.mozilla.org/docs/Web/HTTP/CSP ***/ user_pref("security.csp.enable", true); // default: true /* 2681: disable CSP violation events (FF59+) * [1] https://developer.mozilla.org/docs/Web/API/SecurityPolicyViolationEvent ***/ user_pref("security.csp.enable_violation_events", false); /* 2682: enable CSP 1.1 experimental hash-source directive (FF29+) * [1] https://bugzilla.mozilla.org/buglist.cgi?bug_id=855326,883975 ***/ user_pref("security.csp.experimentalEnabled", true); /* 2683: block top level window data: URIs (FF56+) * [1] https://bugzilla.mozilla.org/1331351 * [2] https://www.wordfence.com/blog/2017/01/gmail-phishing-data-uri/ * [3] https://www.fxsitecompat.com/en-CA/docs/2017/data-url-navigations-on-top-level-window-will-be-blocked/ ***/ user_pref("security.data_uri.block_toplevel_data_uri_navigations", true); // default: true in FF59+ /* 2684: enforce a security delay on some confirmation dialogs such as install, open/save * [1] http://kb.mozillazine.org/Disable_extension_install_delay_-_Firefox * [2] https://www.squarefree.com/2004/07/01/race-conditions-in-security-dialogs/ ***/ user_pref("security.dialog_enable_delay", 700); // default: 1000 (milliseconds) /*** 2700: PERSISTENT STORAGE Data SET by websites including cookies : profile\cookies.sqlite localStorage : profile\webappsstore.sqlite indexedDB : profile\storage\default appCache : profile\OfflineCache serviceWorkers : ***/ user_pref("_user.js.parrot", "2700 syntax error: the parrot's joined the bleedin' choir invisible!"); /* 2701: disable 3rd-party cookies and site-data [SETUP] * You can set exceptions under site permissions or use an extension * 0=Accept cookies and site data, 1=Block third-party cookies, 2=Block all cookies, * 3=Block cookies from unvisited sites, 4=Block third-party trackers (FF63+) * [NOTE] value 4 is tied to the Tracking Protection lists so make sure you have 0424 + 0425 on default values! * [SETTING] Privacy & Security>History>Custom Settings>Accept cookies from sites * [NOTE] Blocking 3rd party controls 3rd party access to localStorage, IndexedDB, Cache API and Service Worker Cache. * Blocking 1st party controls access to localStorage and IndexedDB (note: Service Workers can still use IndexedDB). * [1] https://www.fxsitecompat.com/en-CA/docs/2015/web-storage-indexeddb-cache-api-now-obey-third-party-cookies-preference/ ***/ user_pref("network.cookie.cookieBehavior", 1); /* 2702: set third-party cookies (i.e ALL) (if enabled, see above pref) to session-only and (FF58+) set third-party non-secure (i.e HTTP) cookies to session-only [NOTE] .sessionOnly overrides .nonsecureSessionOnly except when .sessionOnly=false and .nonsecureSessionOnly=true. This allows you to keep HTTPS cookies, but session-only HTTP ones * [1] https://feeding.cloud.geek.nz/posts/tweaking-cookies-for-privacy-in-firefox/ * [2] http://kb.mozillazine.org/Network.cookie.thirdparty.sessionOnly ***/ user_pref("network.cookie.thirdparty.sessionOnly", true); user_pref("network.cookie.thirdparty.nonsecureSessionOnly", true); // (FF58+) /* 2703: set cookie lifetime policy * 0=until they expire (default), 2=until you close Firefox * [NOTE] 3=for n days : no longer supported in FF63+ (see 2704-deprecated) * [SETTING] Privacy & Security>History>Custom Settings>Accept cookies from sites>Keep until ***/ // user_pref("network.cookie.lifetimePolicy", 0); /* 2705: disable HTTP sites setting cookies with the "secure" directive (FF52+) * [1] https://developer.mozilla.org/Firefox/Releases/52#HTTP ***/ user_pref("network.cookie.leave-secure-alone", true); // default: true /* 2706: enable support for same-site cookies (FF60+) * [1] https://bugzilla.mozilla.org/795346 * [2] https://blog.mozilla.org/security/2018/04/24/same-site-cookies-in-firefox-60/ * [3] https://www.sjoerdlangkemper.nl/2016/04/14/preventing-csrf-with-samesite-cookie-attribute/ ***/ // user_pref("network.cookie.same-site.enabled", true); // default: true /* 2710: disable DOM (Document Object Model) Storage * [WARNING] This will break a LOT of sites' functionality AND extensions! * You are better off using an extension for more granular control ***/ // user_pref("dom.storage.enabled", false); /* 2720: enforce IndexedDB (IDB) as enabled * IDB is required for extensions and Firefox internals (even before FF63 in [1]) * To control *website* IDB data, control allowing cookies and service workers, or use * Temporary Containers. To mitigate *website* IDB, FPI helps (4001), and/or sanitize * on close (Offline Website Data, see 2800) or on-demand (Ctrl-Shift-Del), or automatically * via an extenion. Note that IDB currently cannot be sanitized by host. * [1] https://blog.mozilla.org/addons/2018/08/03/new-backend-for-storage-local-api/ ***/ user_pref("dom.indexedDB.enabled", true); // default: true /* 2730: disable offline cache ***/ user_pref("browser.cache.offline.enable", false); /* 2730b: disable offline cache on insecure sites (FF60+) * [1] https://blog.mozilla.org/security/2018/02/12/restricting-appcache-secure-contexts/ ***/ user_pref("browser.cache.offline.insecure.enable", false); // default: false in FF62+ /* 2731: enforce websites to ask to store data for offline use * [1] https://support.mozilla.org/questions/1098540 * [2] https://bugzilla.mozilla.org/959985 ***/ user_pref("offline-apps.allow_by_default", false); /* 2740: disable service workers cache and cache storage * [1] https://w3c.github.io/ServiceWorker/#privacy ***/ user_pref("dom.caches.enabled", false); /* 2750: disable Storage API (FF51+) * The API gives sites the ability to find out how much space they can use, how much * they are already using, and even control whether or not they need to be alerted * before the user agent disposes of site data in order to make room for other things. * [1] https://developer.mozilla.org/docs/Web/API/StorageManager * [2] https://developer.mozilla.org/docs/Web/API/Storage_API * [3] https://blog.mozilla.org/l10n/2017/03/07/firefox-l10n-report-aurora-54/ ***/ // user_pref("dom.storageManager.enabled", false); /*** 2800: SHUTDOWN [SETUP] You should set the values to what suits you best. - "Offline Website Data" includes appCache (2730), localStorage (2710), Service Worker cache (2740), and QuotaManager (IndexedDB (2720), asm-cache) - In both 2803 + 2804, the 'download' and 'history' prefs are combined in the Firefox interface as "Browsing & Download History" and their values will be synced ***/ user_pref("_user.js.parrot", "2800 syntax error: the parrot's bleedin' demised!"); /* 2802: enable Firefox to clear history items on shutdown * [SETTING] Privacy & Security>History>Clear history when Firefox closes ***/ user_pref("privacy.sanitize.sanitizeOnShutdown", true); /* 2803: set what history items to clear on shutdown * [SETTING] Privacy & Security>History>Clear history when Firefox closes>Settings * [NOTE] If 'history' is true, downloads will also be cleared regardless of the value * but if 'history' is false, downloads can still be cleared independently * However, this may not always be the case. The interface combines and syncs these * prefs when set from there, and the sanitize code may change at any time ***/ user_pref("privacy.clearOnShutdown.cache", true); user_pref("privacy.clearOnShutdown.cookies", true); user_pref("privacy.clearOnShutdown.downloads", true); // see note above user_pref("privacy.clearOnShutdown.formdata", true); // Form & Search History user_pref("privacy.clearOnShutdown.history", true); // Browsing & Download History user_pref("privacy.clearOnShutdown.offlineApps", true); // Offline Website Data user_pref("privacy.clearOnShutdown.sessions", true); // Active Logins user_pref("privacy.clearOnShutdown.siteSettings", false); // Site Preferences /* 2804: reset default history items to clear with Ctrl-Shift-Del (to match above) * This dialog can also be accessed from the menu History>Clear Recent History * Firefox remembers your last choices. This will reset them when you start Firefox. * [NOTE] Regardless of what you set privacy.cpd.downloads to, as soon as the dialog * for "Clear Recent History" is opened, it is synced to the same as 'history' ***/ user_pref("privacy.cpd.cache", true); user_pref("privacy.cpd.cookies", true); // user_pref("privacy.cpd.downloads", true); // not used, see note above user_pref("privacy.cpd.formdata", true); // Form & Search History user_pref("privacy.cpd.history", true); // Browsing & Download History user_pref("privacy.cpd.offlineApps", true); // Offline Website Data user_pref("privacy.cpd.passwords", false); // this is not listed user_pref("privacy.cpd.sessions", true); // Active Logins user_pref("privacy.cpd.siteSettings", false); // Site Preferences /* 2805: privacy.*.openWindows (clear session restore data) (FF34+) * [NOTE] There is a years-old bug that these cause two windows when Firefox restarts. * You do not need these anyway if session restore is disabled (see 1020) ***/ // user_pref("privacy.clearOnShutdown.openWindows", true); // user_pref("privacy.cpd.openWindows", true); /* 2806: reset default 'Time range to clear' for 'Clear Recent History' (see 2804) * Firefox remembers your last choice. This will reset the value when you start Firefox. * 0=everything, 1=last hour, 2=last two hours, 3=last four hours, * 4=today, 5=last five minutes, 6=last twenty-four hours * [NOTE] The values 5 + 6 are not listed in the dropdown, which will display a * blank value if they are used, but they do work as advertised ***/ user_pref("privacy.sanitize.timeSpan", 0); /*** 4000: FIRST PARTY ISOLATION (FPI) ** 1278037 - isolate indexedDB (FF51+) ** 1277803 - isolate favicons (FF52+) ** 1264562 - isolate OCSP cache (FF52+) ** 1268726 - isolate Shared Workers (FF52+) ** 1316283 - isolate SSL session cache (FF52+) ** 1317927 - isolate media cache (FF53+) ** 1323644 - isolate HSTS and HPKP (FF54+) ** 1334690 - isolate HTTP Alternative Services (FF54+) ** 1334693 - isolate SPDY/HTTP2 (FF55+) ** 1337893 - isolate DNS cache (FF55+) ** 1344170 - isolate blob: URI (FF55+) ** 1300671 - isolate data:, about: URLs (FF55+) ** 1473247 - isolate IP addresses (FF63+) ** 1492607 - isolate postMessage with targetOrigin "*" (requires 4002) (FF65+) NOTE: FPI has some issues depending on your Firefox release ** 1418931 - [fixed in FF58+] IndexedDB (Offline Website Data) with FPI Origin Attributes are not removed with "Clear All/Recent History" or "On Close" ** 1381197 - [fixed in FF59+] extensions cannot control cookies with FPI Origin Attributes ***/ user_pref("_user.js.parrot", "4000 syntax error: the parrot's pegged out"); /* 4001: enable First Party Isolation (FF51+) * [WARNING] May break cross-domain logins and site functionality until perfected * [1] https://bugzilla.mozilla.org/1260931 ***/ user_pref("privacy.firstparty.isolate", true); /* 4002: enforce FPI restriction for window.opener (FF54+) * [NOTE] Setting this to false may reduce the breakage in 4001 * [FF65+] blocks postMessage with targetOrigin "*" if originAttributes don't match. But * to reduce breakage it ignores the 1st-party domain (FPD) originAttribute. (see [2],[3]) * The 2nd pref removes that limitation and will only allow communication if FPDs also match. * [1] https://bugzilla.mozilla.org/1319773#c22 * [2] https://bugzilla.mozilla.org/1492607 * [3] https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage ***/ user_pref("privacy.firstparty.isolate.restrict_opener_access", true); // default: true // user_pref("privacy.firstparty.isolate.block_post_message", true); // (hidden pref) /*** 4500: privacy.resistFingerprinting (RFP) This master switch will be used for a wide range of items, many of which will **override** existing prefs from FF55+, often providing a **better** solution IMPORTANT: As existing prefs become redundant, and some of them WILL interfere with how RFP works, they will be moved to section 4600 and made inactive ** 418986 - limit window.screen & CSS media queries leaking identifiable info (FF41+) [POC] http://ip-check.info/?lang=en (screen, usable screen, and browser window will match) [NOTE] Does not cover everything yet - https://bugzilla.mozilla.org/1216800 [NOTE] This will probably make your values pretty unique until you resize or snap the inner window width + height into standard/common resolutions (such as 1366x768) To set a size, open a XUL (chrome) page (such as about:config) which is at 100% zoom, hit Shift+F4 to open the scratchpad, type window.resizeTo(1366,768), hit Ctrl+R to run. Test your window size, do some math, resize to allow for all the non inner window elements [TEST] http://browserspy.dk/screen.php ** 1281949 - spoof screen orientation (FF50+) ** 1281963 - hide the contents of navigator.plugins and navigator.mimeTypes (FF50+) FF53: Fixes GetSupportedNames in nsMimeTypeArray and nsPluginArray (1324044) ** 1330890 - spoof timezone as UTC 0 (FF55+) FF58: Date.toLocaleFormat deprecated (818634) FF60: Date.toLocaleDateString and Intl.DateTimeFormat fixed (1409973) ** 1360039 - spoof navigator.hardwareConcurrency as 2 (see 4601) (FF55+) This spoof *shouldn't* affect core chrome/Firefox performance ** 1217238 - reduce precision of time exposed by javascript (FF55+) ** 1369303 - spoof/disable performance API (see 2410-deprecated, 4602, 4603) (FF56+) ** 1333651 & 1383495 & 1396468 - spoof Navigator API (see section 4700) (FF56+) FF56: The version number will be rounded down to the nearest multiple of 10 FF57: The version number will match current ESR (1393283, 1418672, 1418162) FF59: The OS will be reported as Windows, OSX, Android, or Linux (to reduce breakage) (1404608) ** 1369319 - disable device sensor API (see 4604) (FF56+) ** 1369357 - disable site specific zoom (see 4605) (FF56+) ** 1337161 - hide gamepads from content (see 4606) (FF56+) ** 1372072 - spoof network information API as "unknown" (see 4607) (FF56+) ** 1333641 - reduce fingerprinting in WebSpeech API (see 4608) (FF56+) ** 1372069 & 1403813 & 1441295 - block geolocation requests (same as denying a site permission) (see 0201, 0211) (FF56-62) ** 1369309 - spoof media statistics (see 4610) (FF57+) ** 1382499 - reduce screen co-ordinate fingerprinting in Touch API (see 4611) (FF57+) ** 1217290 & 1409677 - enable fingerprinting resistance for WebGL (see 2010-12) (FF57+) ** 1382545 - reduce fingerprinting in Animation API (FF57+) ** 1354633 - limit MediaError.message to a whitelist (FF57+) ** 1382533 - enable fingerprinting resistance for Presentation API (FF57+) This blocks exposure of local IP Addresses via mDNS (Multicast DNS) ** 967895 - enable site permission prompt before allowing canvas data extraction (FF58+) FF59: Added to site permissions panel (1413780) Only prompt when triggered by user input (1376865) ** 1372073 - spoof/block fingerprinting in MediaDevices API (see 4612) (FF59+) ** 1039069 - warn when language prefs are set to non en-US (see 0207, 0208) (FF59+) ** 1222285 & 1433592 - spoof keyboard events and suppress keyboard modifier events (FF59+) Spoofing mimics the content language of the document. Currently it only supports en-US. Modifier events suppressed are SHIFT and both ALT keys. Chrome is not affected. FF60: Fix keydown/keyup events (1438795) ** 1337157 - disable WebGL debug renderer info (see 4613) (FF60+) ** 1459089 - disable OS locale in HTTP Accept-Language headers [ANDROID] (FF62+) ** 1363508 - spoof/suppress Pointer Events (FF64+) ***/ user_pref("_user.js.parrot", "4500 syntax error: the parrot's popped 'is clogs"); /* 4501: enable privacy.resistFingerprinting (FF41+) * [1] https://bugzilla.mozilla.org/418986 ***/ user_pref("privacy.resistFingerprinting", true); // (hidden pref) (not hidden FF55+) /* 4502: set new window sizes to round to hundreds (FF55+) [SETUP] * [NOTE] Width will round down to multiples of 200s and height to 100s, to fit your screen. * The override values are a starting point to round from if you want some control * [1] https://bugzilla.mozilla.org/1330882 * [2] https://hardware.metrics.mozilla.com/ ***/ // user_pref("privacy.window.maxInnerWidth", 1600); // (hidden pref) // user_pref("privacy.window.maxInnerHeight", 900); // (hidden pref) /* 4503: disable mozAddonManager Web API (FF57+) * [NOTE] As a side-effect in FF57-59 this allowed extensions to work on AMO. In FF60+ you also need * to sanitize or clear extensions.webextensions.restrictedDomains (see 2662) to keep that side-effect * [1] https://bugzilla.mozilla.org/buglist.cgi?bug_id=1384330,1406795,1415644,1453988 ***/ user_pref("privacy.resistFingerprinting.block_mozAddonManager", true); // (hidden pref) /* 4504: disable showing about:blank as soon as possible during startup (FF60+) * When default true (FF62+) this no longer masks the RFP resizing activity * [1] https://bugzilla.mozilla.org/1448423 ***/ user_pref("browser.startup.blankWindow", false); /*** 4600: RFP (4500) ALTERNATIVES [SETUP] * IF you DO use RFP (see 4500) then you DO NOT need these redundant prefs. In fact, some even cause RFP to not behave as you would expect and alter your fingerprint. Make sure they are RESET in about:config as per your Firefox version * IF you DO NOT use RFP or are on ESR... then turn on each ESR section below ***/ user_pref("_user.js.parrot", "4600 syntax error: the parrot's crossed the Jordan"); /* [NOTE] ESR52.x and non-RFP users replace the * with a slash on this line to enable these // FF55+ // 4601: [2514] spoof (or limit?) number of CPU cores (FF48+) // [WARNING] *may* affect core chrome/Firefox performance, will affect content. // [1] https://bugzilla.mozilla.org/1008453 // [2] https://trac.torproject.org/projects/tor/ticket/21675 // [3] https://trac.torproject.org/projects/tor/ticket/22127 // [4] https://html.spec.whatwg.org/multipage/workers.html#navigator.hardwareconcurrency // user_pref("dom.maxHardwareConcurrency", 2); // * * * / // FF56+ // 4602: [2411] disable resource/navigation timing user_pref("dom.enable_resource_timing", false); // 4603: [2412] disable timing attacks // [1] https://wiki.mozilla.org/Security/Reviews/Firefox/NavigationTimingAPI user_pref("dom.enable_performance", false); // 4604: [2512] disable device sensor API // [WARNING] [SETUP] Optional protection depending on your device // [1] https://trac.torproject.org/projects/tor/ticket/15758 // [2] https://blog.lukaszolejnik.com/stealing-sensitive-browser-data-with-the-w3c-ambient-light-sensor-api/ // [3] https://bugzilla.mozilla.org/buglist.cgi?bug_id=1357733,1292751 // user_pref("device.sensors.enabled", false); // 4605: [2515] disable site specific zoom // Zoom levels affect screen res and are highly fingerprintable. This does not stop you using // zoom, it will just not use/remember any site specific settings. Zoom levels on new tabs // and new windows are reset to default and only the current tab retains the current zoom user_pref("browser.zoom.siteSpecific", false); // 4606: [2501] disable gamepad API - USB device ID enumeration // [WARNING] [SETUP] Optional protection depending on your connected devices // [1] https://trac.torproject.org/projects/tor/ticket/13023 // user_pref("dom.gamepad.enabled", false); // 4607: [2503] disable giving away network info (FF31+) // e.g. bluetooth, cellular, ethernet, wifi, wimax, other, mixed, unknown, none // [1] https://developer.mozilla.org/docs/Web/API/Network_Information_API // [2] https://wicg.github.io/netinfo/ // [3] https://bugzilla.mozilla.org/960426 user_pref("dom.netinfo.enabled", false); // 4608: [2021] disable the SpeechSynthesis (Text-to-Speech) part of the Web Speech API // [1] https://developer.mozilla.org/docs/Web/API/Web_Speech_API // [2] https://developer.mozilla.org/docs/Web/API/SpeechSynthesis // [3] https://wiki.mozilla.org/HTML5_Speech_API user_pref("media.webspeech.synth.enabled", false); // * * * / // FF57+ // 4610: [2506] disable video statistics - JS performance fingerprinting (FF25+) // [1] https://trac.torproject.org/projects/tor/ticket/15757 // [2] https://bugzilla.mozilla.org/654550 user_pref("media.video_stats.enabled", false); // 4611: [2509] disable touch events // fingerprinting attack vector - leaks screen res & actual screen coordinates // 0=disabled, 1=enabled, 2=autodetect // [WARNING] [SETUP] Optional protection depending on your device // [1] https://developer.mozilla.org/docs/Web/API/Touch_events // [2] https://trac.torproject.org/projects/tor/ticket/10286 // user_pref("dom.w3c_touch_events.enabled", 0); // * * * / // FF59+ // 4612: [2511] disable MediaDevices change detection (FF51+) // [1] https://developer.mozilla.org/docs/Web/Events/devicechange // [2] https://developer.mozilla.org/docs/Web/API/MediaDevices/ondevicechange user_pref("media.ondevicechange.enabled", false); // * * * / // FF60+ // 4613: [2011] disable WebGL debug info being available to websites // [1] https://bugzilla.mozilla.org/1171228 // [2] https://developer.mozilla.org/docs/Web/API/WEBGL_debug_renderer_info user_pref("webgl.enable-debug-renderer-info", false); // * * * / // ***/ /*** 4700: RFP (4500) ALTERNATIVES - NAVIGATOR / USER AGENT (UA) SPOOFING This is FYI ONLY. These prefs are INSUFFICIENT(a) on their own, you need to use RFP (4500) or an extension, in which case they become POINTLESS. (a) Many of the components that make up your UA can be derived by other means. And when those values differ, you provide more bits and raise entropy. Examples of leaks include navigator objects, date locale/formats, iframes, headers, tcp/ip attributes, feature detection, and **many** more. ALL values below intentionally left blank - use RFP, or get a vetted, tested extension and mimic RFP values to *lower* entropy, or randomize to *raise* it ***/ user_pref("_user.js.parrot", "4700 syntax error: the parrot's taken 'is last bow"); /* 4701: navigator.userAgent ***/ // user_pref("general.useragent.override", ""); // (hidden pref) /* 4702: navigator.buildID * Revealed build time down to the second. In FF64+ it now returns a fixed timestamp * [1] https://bugzilla.mozilla.org/583181 * [2] https://www.fxsitecompat.com/en-CA/docs/2018/navigator-buildid-now-returns-a-fixed-timestamp/ ***/ // user_pref("general.buildID.override", ""); // (hidden pref) /* 4703: navigator.appName ***/ // user_pref("general.appname.override", ""); // (hidden pref) /* 4704: navigator.appVersion ***/ // user_pref("general.appversion.override", ""); // (hidden pref) /* 4705: navigator.platform ***/ // user_pref("general.platform.override", ""); // (hidden pref) /* 4706: navigator.oscpu ***/ // user_pref("general.oscpu.override", ""); // (hidden pref) /*** 5000: PERSONAL [SETUP] Non-project related but useful. If any of these interest you, add them to your overrides ***/ user_pref("_user.js.parrot", "5000 syntax error: this is an ex-parrot!"); /* WELCOME & WHAT's NEW NOTICES ***/ // user_pref("browser.startup.homepage_override.mstone", "ignore"); // master switch // user_pref("startup.homepage_welcome_url", ""); // user_pref("startup.homepage_welcome_url.additional", ""); // user_pref("startup.homepage_override_url", ""); // What's New page after updates /* WARNINGS ***/ // user_pref("browser.tabs.warnOnClose", false); // user_pref("browser.tabs.warnOnCloseOtherTabs", false); // user_pref("browser.tabs.warnOnOpen", false); // user_pref("full-screen-api.warning.delay", 0); // user_pref("full-screen-api.warning.timeout", 0); /* APPEARANCE ***/ // user_pref("browser.download.autohideButton", false); // (FF57+) // user_pref("toolkit.cosmeticAnimations.enabled", false); // (FF55+) /* CONTENT BEHAVIOR ***/ // user_pref("accessibility.typeaheadfind", true); // enable "Find As You Type" // user_pref("clipboard.autocopy", false); // disable autocopy default [LINUX] // user_pref("layout.spellcheckDefault", 2); // 0=none, 1-multi-line, 2=multi-line & single-line /* UX BEHAVIOR ***/ // user_pref("browser.backspace_action", 2); // 0=previous page, 1=scroll up, 2=do nothing // user_pref("browser.tabs.closeWindowWithLastTab", false); // user_pref("browser.tabs.loadBookmarksInTabs", true); // open bookmarks in a new tab (FF57+) // user_pref("browser.urlbar.decodeURLsOnCopy", true); // see Bugzilla 1320061 (FF53+) // user_pref("general.autoScroll", false); // middle-click enabling auto-scrolling [WINDOWS] [MAC] // user_pref("ui.key.menuAccessKey", 0); // disable alt key toggling the menu bar [RESTART] /* OTHER ***/ // user_pref("browser.bookmarks.max_backups", 2); // user_pref("identity.fxaccounts.enabled", false); // disable and hide Firefox Accounts and Sync (FF60+) [RESTART] // user_pref("network.manage-offline-status", false); // see Bugzilla 620472 // user_pref("reader.parse-on-load.enabled", false); // "Reader View" // user_pref("xpinstall.signatures.required", false); // enforced extension signing (Nightly/ESR) /*** 9999: DEPRECATED / REMOVED / LEGACY / RENAMED Documentation denoted as [-]. Numbers may be re-used. See [1] for a link-clickable, viewer-friendly version of the deprecated bugzilla tickets. The original state of each pref has been preserved, or changed to match the current setup, but you are advised to review them. [NOTE] Up to FF53, to enable a section change /* FFxx to // FFxx For FF53 on, we have bundled releases to cater for ESR. Change /* to // on the first line [1] https://github.com/ghacksuserjs/ghacks-user.js/issues/123 ***/ user_pref("_user.js.parrot", "9999 syntax error: the parrot's deprecated!"); /* FF42 and older // 2604: (25+) disable page thumbnails - replaced by browser.pagethumbnails.capturing_disabled // [-] https://bugzilla.mozilla.org/897811 user_pref("pageThumbs.enabled", false); // 2503: (31+) disable network API - replaced by dom.netinfo.enabled // [-] https://bugzilla.mozilla.org/960426 user_pref("dom.network.enabled", false); // 2600's: (35+) disable WebSockets // [-] https://bugzilla.mozilla.org/1091016 user_pref("network.websocket.enabled", false); // 1610: (36+) set DNT "value" to "not be tracked" (FF21+) // [1] http://kb.mozillazine.org/Privacy.donottrackheader.value // [-] https://bugzilla.mozilla.org/1042135#c101 // user_pref("privacy.donottrackheader.value", 1); // 2023: (37+) disable camera autofocus callback // The API will be superseded by the WebRTC Capture and Stream API // [1] https://developer.mozilla.org/docs/Archive/B2G_OS/API/CameraControl // [-] https://bugzilla.mozilla.org/1107683 user_pref("camera.control.autofocus_moving_callback.enabled", false); // 0415: (41+) disable reporting URLs (safe browsing) - removed or replaced by various // [-] https://bugzilla.mozilla.org/1109475 user_pref("browser.safebrowsing.reportErrorURL", ""); // browser.safebrowsing.reportPhishMistakeURL user_pref("browser.safebrowsing.reportGenericURL", ""); // removed user_pref("browser.safebrowsing.reportMalwareErrorURL", ""); // browser.safebrowsing.reportMalwareMistakeURL user_pref("browser.safebrowsing.reportMalwareURL", ""); // removed user_pref("browser.safebrowsing.reportURL", ""); // removed // 0702: (41+) disable HTTP2 (draft) // [-] https://bugzilla.mozilla.org/1132357 user_pref("network.http.spdy.enabled.http2draft", false); // 1804: (41+) disable plugin enumeration // [-] https://bugzilla.mozilla.org/1169945 user_pref("plugins.enumerable_names", ""); // 2803: (42+) clear passwords on shutdown // [-] https://bugzilla.mozilla.org/1102184 // user_pref("privacy.clearOnShutdown.passwords", false); // 5002: (42+) disable warning when a domain requests full screen // replaced by setting full-screen-api.warning.timeout to zero // [-] https://bugzilla.mozilla.org/1160017 // user_pref("full-screen-api.approval-required", false); // ***/ /* FF43 // 0410's: disable safebrowsing urls & updates - replaced by various // [-] https://bugzilla.mozilla.org/1107372 // user_pref("browser.safebrowsing.gethashURL", ""); // browser.safebrowsing.provider.google.gethashURL // user_pref("browser.safebrowsing.updateURL", ""); // browser.safebrowsing.provider.google.updateURL user_pref("browser.safebrowsing.malware.reportURL", ""); // browser.safebrowsing.provider.google.reportURL // 0420's: disable tracking protection - replaced by various // [-] https://bugzilla.mozilla.org/1107372 // user_pref("browser.trackingprotection.gethashURL", ""); // browser.safebrowsing.provider.mozilla.gethashURL // user_pref("browser.trackingprotection.updateURL", ""); // browser.safebrowsing.provider.mozilla.updateURL // 1803: remove plugin finder service // [1] http://kb.mozillazine.org/Pfs.datasource.url // [-] https://bugzilla.mozilla.org/1202193 user_pref("pfs.datasource.url", ""); // 5003: disable new search panel UI // [-] https://bugzilla.mozilla.org/1119250 // user_pref("browser.search.showOneOffButtons", false); // ***/ /* FF44 // 0414: disable safebrowsing's real-time binary checking (google) (FF43+) // [-] https://bugzilla.mozilla.org/1237103 user_pref("browser.safebrowsing.provider.google.appRepURL", ""); // browser.safebrowsing.appRepURL // 1200's: block rc4 whitelist // [-] https://bugzilla.mozilla.org/1215796 user_pref("security.tls.insecure_fallback_hosts.use_static_list", false); // 2300's: disable SharedWorkers // [1] https://trac.torproject.org/projects/tor/ticket/15562 // [-] https://bugzilla.mozilla.org/1207635 user_pref("dom.workers.sharedWorkers.enabled", false); // 2403: disable scripts changing images // [TEST] https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_img_src2 // [WARNING] Will break some sites such as Google Maps and a lot of web apps // [-] https://bugzilla.mozilla.org/773429 // user_pref("dom.disable_image_src_set", true); // ***/ /* FF45 // 1021b: disable deferred level of storing extra session data 0=all 1=http-only 2=none // extra session data contains contents of forms, scrollbar positions, cookies and POST data // [-] https://bugzilla.mozilla.org/1235379 user_pref("browser.sessionstore.privacy_level_deferred", 2); // ***/ /* FF46 // 0333: disable health report // [-] https://bugzilla.mozilla.org/1234526 user_pref("datareporting.healthreport.service.enabled", false); // (hidden pref) user_pref("datareporting.healthreport.documentServerURI", ""); // (hidden pref) // 0334b: disable FHR (Firefox Health Report) v2 data being sent to Mozilla servers // [-] https://bugzilla.mozilla.org/1234522 user_pref("datareporting.policy.dataSubmissionEnabled.v2", false); // 0414: disable safebrowsing pref - replaced by browser.safebrowsing.downloads.remote.url // [-] https://bugzilla.mozilla.org/1239587 user_pref("browser.safebrowsing.appRepURL", ""); // Google application reputation check // 0420: disable polaris (part of Tracking Protection, never used in stable) // [-] https://bugzilla.mozilla.org/1235565 // user_pref("browser.polaris.enabled", false); // 0510: disable "Pocket" - replaced by extensions.pocket.* // [-] https://bugzilla.mozilla.org/1215694 user_pref("browser.pocket.enabled", false); user_pref("browser.pocket.api", ""); user_pref("browser.pocket.site", ""); user_pref("browser.pocket.oAuthConsumerKey", ""); // ***/ /* FF47 // 0330b: set unifiedIsOptIn to make sure telemetry respects OptIn choice and that telemetry // is enabled ONLY for people that opted into it, even if unified Telemetry is enabled // [-] https://bugzilla.mozilla.org/1236580 user_pref("toolkit.telemetry.unifiedIsOptIn", true); // (hidden pref) // 0333b: disable about:healthreport page UNIFIED // [-] https://bugzilla.mozilla.org/1236580 user_pref("datareporting.healthreport.about.reportUrlUnified", "data:text/plain,"); // 0807: disable history manipulation // [1] https://developer.mozilla.org/docs/Web/API/History_API // [-] https://bugzilla.mozilla.org/1249542 user_pref("browser.history.allowPopState", false); user_pref("browser.history.allowPushState", false); user_pref("browser.history.allowReplaceState", false); // ***/ /* FF48 // 0806: disable 'unified complete': 'Search with [default search engine]' // [-] http://techdows.com/2016/05/firefox-unified-complete-aboutconfig-preference-removed.html // [-] https://bugzilla.mozilla.org/1181078 user_pref("browser.urlbar.unifiedcomplete", false); // ***/ /* FF49 // 0372: disable "Hello" // [1] https://www.mozilla.org/privacy/archive/hello/2016-03/ // [2] https://security.stackexchange.com/questions/94284/how-secure-is-firefox-hello // [-] https://bugzilla.mozilla.org/1287827 user_pref("loop.enabled", false); user_pref("loop.server", ""); user_pref("loop.feedback.formURL", ""); user_pref("loop.feedback.manualFormURL", ""); user_pref("loop.facebook.appId", ""); user_pref("loop.facebook.enabled", false); user_pref("loop.facebook.fallbackUrl", ""); user_pref("loop.facebook.shareUrl", ""); user_pref("loop.logDomains", false); // 2201: disable new window scrollbars being hidden // [-] https://bugzilla.mozilla.org/1257887 user_pref("dom.disable_window_open_feature.scrollbars", true); // 2303: disable push notification (UDP wake-up) // [-] https://bugzilla.mozilla.org/1265914 user_pref("dom.push.udp.wakeupEnabled", false); // ***/ /* FF50 // 0101: disable Windows10 intro on startup [WINDOWS] // [-] https://bugzilla.mozilla.org/1274633 user_pref("browser.usedOnWindows10.introURL", ""); // 0308: disable plugin update notifications // [-] https://bugzilla.mozilla.org/1277905 user_pref("plugins.update.notifyUser", false); // 0410: disable "Block dangerous and deceptive content" - replaced by browser.safebrowsing.phishing.enabled // [-] https://bugzilla.mozilla.org/1025965 // user_pref("browser.safebrowsing.enabled", false); // 1266: disable rc4 ciphers // [1] https://trac.torproject.org/projects/tor/ticket/17369 // [-] https://bugzilla.mozilla.org/1268728 // [-] https://www.fxsitecompat.com/en-CA/docs/2016/rc4-support-has-been-completely-removed/ user_pref("security.ssl3.ecdhe_ecdsa_rc4_128_sha", false); user_pref("security.ssl3.ecdhe_rsa_rc4_128_sha", false); user_pref("security.ssl3.rsa_rc4_128_md5", false); user_pref("security.ssl3.rsa_rc4_128_sha", false); // 1809: remove Mozilla's plugin update URL // [-] https://bugzilla.mozilla.org/1277905 user_pref("plugins.update.url", ""); // ***/ /* FF51 // 0702: disable SPDY // [-] https://bugzilla.mozilla.org/1248197 user_pref("network.http.spdy.enabled.v3-1", false); // 1851: delay play of videos until they're visible // [1] https://bugzilla.mozilla.org/1180563 // [-] https://bugzilla.mozilla.org/1262053 user_pref("media.block-play-until-visible", true); // 2504: disable virtual reality devices // [-] https://bugzilla.mozilla.org/1250244 user_pref("dom.vr.oculus050.enabled", false); // ***/ /* FF52 // 1601: disable referer from an SSL Website // [-] https://bugzilla.mozilla.org/1308725 user_pref("network.http.sendSecureXSiteReferrer", false); // 1850: disable Adobe EME "Primetime CDM" (Content Decryption Module) // [1] https://trac.torproject.org/projects/tor/ticket/16285 // [-] https://bugzilla.mozilla.org/buglist.cgi?bug_id=1329538,1337121 // FF52 // [-] https://bugzilla.mozilla.org/1329543 // FF53 user_pref("media.gmp-eme-adobe.enabled", false); user_pref("media.gmp-eme-adobe.visible", false); user_pref("media.gmp-eme-adobe.autoupdate", false); // 2405: disable WebTelephony API // [1] https://wiki.mozilla.org/WebAPI/Security/WebTelephony // [-] https://bugzilla.mozilla.org/1309719 user_pref("dom.telephony.enabled", false); // ***/ /* FF53 // 1265: block rc4 fallback // [-] https://bugzilla.mozilla.org/1130670 user_pref("security.tls.unrestricted_rc4_fallback", false); // 1806: disable Acrobat, Quicktime, WMP (the string = min version number allowed) // [-] https://bugzilla.mozilla.org/buglist.cgi?bug_id=1317108,1317109,1317110 user_pref("plugin.scan.Acrobat", "99999"); user_pref("plugin.scan.Quicktime", "99999"); user_pref("plugin.scan.WindowsMediaPlayer", "99999"); // 2022: disable screensharing // [-] https://bugzilla.mozilla.org/1329562 user_pref("media.getusermedia.screensharing.allow_on_old_platforms", false); // 2507: disable keyboard fingerprinting // [-] https://bugzilla.mozilla.org/1322736 user_pref("dom.beforeAfterKeyboardEvent.enabled", false); // ***/ /* FF54 // 0415: disable reporting URLs (safe browsing) // [-] https://bugzilla.mozilla.org/1288633 user_pref("browser.safebrowsing.reportMalwareMistakeURL", ""); user_pref("browser.safebrowsing.reportPhishMistakeURL", ""); // 1830: block websites detecting DRM is disabled // [-] https://bugzilla.mozilla.org/1242321 user_pref("media.eme.apiVisible", false); // 2425: disable Archive Reader API // i.e. reading archive contents directly in the browser, through DOM file objects // [-] https://bugzilla.mozilla.org/1342361 user_pref("dom.archivereader.enabled", false); // ***/ /* FF55 // 0209: disable geolocation on non-secure origins (FF54+) // [1] https://bugzilla.mozilla.org/1269531 // [-] https://bugzilla.mozilla.org/1072859 user_pref("geo.security.allowinsecure", false); // 0336: disable "Heartbeat" (Mozilla user rating telemetry) (FF37+) // [1] https://trac.torproject.org/projects/tor/ticket/18738 // [-] https://bugzilla.mozilla.org/1361578 user_pref("browser.selfsupport.enabled", false); // (hidden pref) user_pref("browser.selfsupport.url", ""); // 0360: disable new tab "pings" // [-] https://bugzilla.mozilla.org/1241390 user_pref("browser.newtabpage.directory.ping", "data:text/plain,"); // 0861: disable saving form history on secure websites // [-] https://bugzilla.mozilla.org/1361220 user_pref("browser.formfill.saveHttpsForms", false); // 0863: disable Form Autofill (FF54+) - replaced by extensions.formautofill.* // [-] https://bugzilla.mozilla.org/1364334 user_pref("browser.formautofill.enabled", false); // 2410: disable User Timing API // [1] https://trac.torproject.org/projects/tor/ticket/16336 // [-] https://bugzilla.mozilla.org/1344669 user_pref("dom.enable_user_timing", false); // 2507: disable keyboard fingerprinting (FF38+) (physical keyboards) // The Keyboard API allows tracking the "read parameter" of pressed keys in forms on // web pages. These parameters vary between types of keyboard layouts such as QWERTY, // AZERTY, Dvorak, and between various languages, e.g. German vs English. // [WARNING] Don't use if Android + physical keyboard // [1] https://developer.mozilla.org/docs/Web/API/KeyboardEvent/code // [2] https://www.privacy-handbuch.de/handbuch_21v.htm // [-] https://bugzilla.mozilla.org/1352949 user_pref("dom.keyboardevent.code.enabled", false); // 5015: disable tab animation - replaced by toolkit.cosmeticAnimations.enabled // [-] https://bugzilla.mozilla.org/1352069 user_pref("browser.tabs.animate", false); // 5016: disable fullscreeen animation - replaced by toolkit.cosmeticAnimations.enabled // [-] https://bugzilla.mozilla.org/1352069 user_pref("browser.fullscreen.animate", false); // ***/ /* FF56 // 0515: disable Screenshots (rollout pref only) (FF54+) // [-] https://bugzilla.mozilla.org/1386333 // user_pref("extensions.screenshots.system-disabled", true); // 0517: disable Form Autofill (FF55+) - replaced by extensions.formautofill.available // [-] https://bugzilla.mozilla.org/1385201 user_pref("extensions.formautofill.experimental", false); // ***/ /* FF57 // 0374: disable "social" integration // [1] https://developer.mozilla.org/docs/Mozilla/Projects/Social_API // [-] https://bugzilla.mozilla.org/buglist.cgi?bug_id=1388902,1406193 (some leftovers were removed in FF58) user_pref("social.whitelist", ""); user_pref("social.toast-notifications.enabled", false); user_pref("social.shareDirectory", ""); user_pref("social.remote-install.enabled", false); user_pref("social.directories", ""); user_pref("social.share.activationPanelEnabled", false); user_pref("social.enabled", false); // (hidden pref) // 1830: disable DRM's EME WideVineAdapter // [-] https://bugzilla.mozilla.org/1395468 user_pref("media.eme.chromium-api.enabled", false); // (FF55+) // 2608: disable WebIDE extension downloads (Valence) // [1] https://trac.torproject.org/projects/tor/ticket/16222 // [-] https://bugzilla.mozilla.org/1393497 user_pref("devtools.webide.autoinstallFxdtAdapters", false); // 2600's: disable SimpleServiceDiscovery - which can bypass proxy settings - e.g. Roku // [1] https://trac.torproject.org/projects/tor/ticket/16222 // [-] https://bugzilla.mozilla.org/1393582 user_pref("browser.casting.enabled", false); // 5022: hide recently bookmarked items (you still have the original bookmarks) (FF49+) // [-] https://bugzilla.mozilla.org/1401238 user_pref("browser.bookmarks.showRecentlyBookmarked", false); // ***/ /* FF59 // 0203: disable using OS locale, force APP locale - replaced by intl.locale.requested // [-] https://bugzilla.mozilla.org/1414390 user_pref("intl.locale.matchOS", false); // 0204: set APP locale - replaced by intl.locale.requested // [-] https://bugzilla.mozilla.org/1414390 user_pref("general.useragent.locale", "en-US"); // 0333b: disable about:healthreport page (which connects to Mozilla for locale/css+js+json) // If you have disabled health reports, then this about page is useless - disable it // If you want to see what health data is present, then this must be set at default // [-] https://bugzilla.mozilla.org/1352497 user_pref("datareporting.healthreport.about.reportUrl", "data:text/plain,"); // 0511: disable FlyWeb (FF49+) // Flyweb is a set of APIs for advertising and discovering local-area web servers // [1] https://flyweb.github.io/ // [2] https://wiki.mozilla.org/FlyWeb/Security_scenarios // [3] https://www.ghacks.net/2016/07/26/firefox-flyweb/ // [-] https://bugzilla.mozilla.org/1374574 user_pref("dom.flyweb.enabled", false); // 1007: disable randomized FF HTTP cache decay experiments // [1] https://trac.torproject.org/projects/tor/ticket/13575 // [-] https://bugzilla.mozilla.org/1430197 user_pref("browser.cache.frecency_experiment", -1); // 1242: enable Mixed-Content-Blocker to use the HSTS cache but disable the HSTS Priming requests (FF51+) // Allow resources from domains with an existing HSTS cache record or in the HSTS preload list // to be upgraded to HTTPS internally but disable sending out HSTS Priming requests, because // those may cause noticeable delays e.g. requests time out or are not handled well by servers // [NOTE] If you want to use the priming requests make sure 'use_hsts' is also true // [1] https://bugzilla.mozilla.org/1246540#c145 // [-] https://bugzilla.mozilla.org/1424917 user_pref("security.mixed_content.use_hsts", true); user_pref("security.mixed_content.send_hsts_priming", false); // 1606: set the default Referrer Policy - replaced by network.http.referer.defaultPolicy // [-] https://bugzilla.mozilla.org/587523 user_pref("network.http.referer.userControlPolicy", 3); // (FF53-FF58) default: 3 // 1804: disable plugins using external/untrusted scripts with XPCOM or XPConnect // [-] (part8) https://bugzilla.mozilla.org/1416703#c21 user_pref("security.xpconnect.plugin.unrestricted", false); // 2022: disable screensharing domain whitelist // [-] https://bugzilla.mozilla.org/1411742 user_pref("media.getusermedia.screensharing.allowed_domains", ""); // 2023: disable camera stuff // [-] (part7) https://bugzilla.mozilla.org/1416703#c21 user_pref("camera.control.face_detection.enabled", false); // 2202: prevent scripts from changing the status text // [-] https://bugzilla.mozilla.org/1425999 user_pref("dom.disable_window_status_change", true); // 2416: disable idle observation // [-] (part7) https://bugzilla.mozilla.org/1416703#c21 user_pref("dom.idle-observers-api.enabled", false); // ***/ /* FF60 // 0360: disable new tab tile ads & preload & marketing junk // [-] https://bugzilla.mozilla.org/buglist.cgi?bug_id=1370930,1433133 user_pref("browser.newtabpage.directory.source", "data:text/plain,"); user_pref("browser.newtabpage.enhanced", false); user_pref("browser.newtabpage.introShown", true); // 0512: disable Shield (FF53+) - replaced internally by Normandy (see 0503) // Shield is an telemetry system (including Heartbeat) that can also push and test "recipes" // [1] https://wiki.mozilla.org/Firefox/Shield // [2] https://github.com/mozilla/normandy // [-] https://bugzilla.mozilla.org/1436113 user_pref("extensions.shield-recipe-client.enabled", false); user_pref("extensions.shield-recipe-client.api_url", ""); // 0514: disable Activity Stream (FF54+) // [-] https://bugzilla.mozilla.org/1433324 user_pref("browser.newtabpage.activity-stream.enabled", false); // 2301: disable workers // [WARNING] Disabling workers *will* break sites (e.g. Google Street View, Twitter) // [NOTE] CVE-2016-5259, CVE-2016-2812, CVE-2016-1949, CVE-2016-5287 (fixed) // [-] https://bugzilla.mozilla.org/1434934 user_pref("dom.workers.enabled", false); // 5000's: open "page/selection source" in a new window // [-] https://bugzilla.mozilla.org/1418403 // user_pref("view_source.tab", false); // ***/ /* ESR60.x still uses all the following prefs // [NOTE] replace the * with a slash in the line above to re-enable them // FF61 // 0501: disable experiments // [1] https://wiki.mozilla.org/Telemetry/Experiments // [-] https://bugzilla.mozilla.org/buglist.cgi?bug_id=1420908,1450801 user_pref("experiments.enabled", false); user_pref("experiments.manifest.uri", ""); user_pref("experiments.supported", false); user_pref("experiments.activeExperiment", false); // 2612: disable remote JAR files being opened, regardless of content type (FF42+) // [1] https://bugzilla.mozilla.org/1173171 // [2] https://www.fxsitecompat.com/en-CA/docs/2015/jar-protocol-support-has-been-disabled-by-default/ // [-] https://bugzilla.mozilla.org/1427726 user_pref("network.jar.block-remote-files", true); // 2613: disable JAR from opening Unsafe File Types // [-] https://bugzilla.mozilla.org/1427726 user_pref("network.jar.open-unsafe-types", false); // * * * / // FF62 // 1803: disable Java plugin // [-] (part5) https://bugzilla.mozilla.org/1461243 user_pref("plugin.state.java", 0); // * * * / // FF63 // 0202: disable GeoIP-based search results // [NOTE] May not be hidden if Firefox has changed your settings due to your locale // [-] https://bugzilla.mozilla.org/1462015 user_pref("browser.search.countryCode", "US"); // (hidden pref) // 0301a: disable auto-update checks for Firefox // [SETTING] General>Firefox Updates>Never check for updates // [-] https://bugzilla.mozilla.org/1420514 // user_pref("app.update.enabled", false); // 0402: enable Kinto blocklist updates (FF50+) // What is Kinto?: https://wiki.mozilla.org/Firefox/Kinto#Specifications // As Firefox transitions to Kinto, the blocklists have been broken down into entries for certs to be // revoked, extensions and plugins to be disabled, and gfx environments that cause problems or crashes // [-] https://bugzilla.mozilla.org/1458917 user_pref("services.blocklist.update_enabled", true); // 0503: disable "Savant" Shield study (FF61+) // [-] https://bugzilla.mozilla.org/1457226 user_pref("shield.savant.enabled", false); // 1031: disable favicons in tabs and new bookmarks - merged into browser.chrome.site_icons // [-] https://bugzilla.mozilla.org/1453751 // user_pref("browser.chrome.favicons", false); // 2030: disable auto-play of HTML5 media - replaced by media.autoplay.default // [WARNING] This may break video playback on various sites // [-] https://bugzilla.mozilla.org/1470082 user_pref("media.autoplay.enabled", false); // 2704: set cookie lifetime in days (see 2703) // [-] https://bugzilla.mozilla.org/1457170 // user_pref("network.cookie.lifetime.days", 90); // default: 90 // 5000's: enable "Ctrl+Tab cycles through tabs in recently used order" - replaced by browser.ctrlTab.recentlyUsedOrder // [-] https://bugzilla.mozilla.org/1473595 // user_pref("browser.ctrlTab.previews", true); // * * * / // ***/ /* END: internal custom pref to test for syntax errors ***/ user_pref("_user.js.parrot", "SUCCESS: No no he's not dead, he's, he's restin'!");
saving the world bytes at a time
user.js
saving the world bytes at a time
<ide><path>ser.js <ide> /* 1241: disable insecure passive content (such as images) on https pages - mixed context ***/ <ide> user_pref("security.mixed_content.block_display_content", true); <ide> /* 1243: block unencrypted requests from Flash on encrypted pages to mitigate MitM attacks (FF59+) <del> * [1] https://bugzilla.mozilla.org/show_bug.cgi?id=1190623 ***/ <add> * [1] https://bugzilla.mozilla.org/1190623 ***/ <ide> user_pref("security.mixed_content.block_object_subrequest", true); <ide> <ide> /** CIPHERS [see the section 1200 intro] ***/
Java
mit
0a6e5ad810aa9f9955c6730f8d2c6c11421ab5d0
0
student-capture/student-capture
package assignment; import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.mock.web.MockMultipartFile; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.util.NestedServletException; import studentcapture.config.StudentCaptureApplicationTests; import java.util.HashMap; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.fileUpload; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; /** * Created by root on 5/4/16. */ public class AssignmentResourceTest extends StudentCaptureApplicationTests { @Autowired private WebApplicationContext context; private MockMvc mvc; private String json_test_string = "{\"title\":\"TheTitle\"," + "\"Info\": \"Assignment Info\"," + "\"videIntervall\":" + "{\"minTimeSeconds\":0," + "\"maxTimeSeconds\":320}," + "\"assignmentIntervall\":" + "{\"startDate\":\"2016-10-01 10:00:00\"," + "\"endDate\":\"2016-10-02 10:00:00\"," + "\"published\":\"2016-10-01 10:00:00\"}," + "\"scale\":\"NUMBER_SCALE\"," + "\"recap\":\"recap\"" + "}"; @Before public void setup() { mvc = MockMvcBuilders .webAppContextSetup(context). build(); } /** * NestedServletException is expected since the method that handles the request sends another request to another * method. This doesn't seem to work in JUnit. This test only shows that it works to post to /assignments. No side * effects are tested at all. * @throws Exception */ @Test(expected = NestedServletException.class) public void shouldWorkToSendJSONToCreateAssignment() throws Exception { mvc.perform(post("/assignments").contentType(MediaType.APPLICATION_JSON).content(json_test_string)) .andExpect(status().isOk()); } @Test public void shouldHaveBadRequestOnWrongJSON() throws Exception { mvc.perform(post("/assignments").contentType(MediaType.APPLICATION_JSON).content("{\"wrong\":\"json\"")) .andExpect(status().isBadRequest()); } @Test public void shouldWorkToSendFileAndMetaData() throws Exception { MockMultipartFile file = new MockMultipartFile("data", "assignment.webm", "form", "some video".getBytes()); HashMap<String, String> contentTypeParams = new HashMap<String, String>(); mvc.perform(fileUpload("/assignments/video").file(file).param("courseID", "1000").param("assignmentID", "3")); } }
src/test/java/assignment/AssignmentResourceTest.java
package assignment; import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.mock.web.MockMultipartFile; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.util.NestedServletException; import studentcapture.config.StudentCaptureApplicationTests; import java.util.HashMap; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.fileUpload; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; /** * Created by root on 5/4/16. */ public class AssignmentResourceTest extends StudentCaptureApplicationTests { @Autowired private WebApplicationContext context; private MockMvc mvc; private static String json_test_string = "{\"title\":\"TheTitle\"," + "\"Info\": \"Assignment Info\"," + "\"videIntervall\":" + "{\"minTimeSeconds\":0," + "\"maxTimeSeconds\":320}," + "\"assignmentIntervall\":" + "{\"startDate\":\"2016-10-01 10:00:00\"," + "\"endDate\":\"2016-10-02 10:00:00\"," + "\"published\":\"2016-10-01 10:00:00\"}," + "\"scale\":\"NUMBER_SCALE\"," + "\"recap\":\"recap\"" + "}"; @Before public void setup() { mvc = MockMvcBuilders .webAppContextSetup(context). build(); } /** * NestedServletException is expected since the method that handles the request sends another request to another * method. This doesn't seem to work in JUnit. This test only shows that it works to post to /assignments. No side * effects are tested at all. * @throws Exception */ @Test(expected = NestedServletException.class) public void shouldWorkToSendJSONToCreateAssignment() throws Exception { mvc.perform(post("/assignments").contentType(MediaType.APPLICATION_JSON).content(json_test_string)) .andExpect(status().isOk()); } @Test public void shouldHaveBadRequestOnWrongJSON() throws Exception { mvc.perform(post("/assignments").contentType(MediaType.APPLICATION_JSON).content("{\"wrong\":\"json\"")) .andExpect(status().isBadRequest()); } @Test public void shouldWorkToSendFileAndMetaData() throws Exception { MockMultipartFile file = new MockMultipartFile("data", "assignment.webm", "form", "some video".getBytes()); HashMap<String, String> contentTypeParams = new HashMap<String, String>(); mvc.perform(fileUpload("/assignments/video").file(file).param("courseID", "1000").param("assignmentID", "3")); } }
Unneccessary "static" qualifier
src/test/java/assignment/AssignmentResourceTest.java
Unneccessary "static" qualifier
<ide><path>rc/test/java/assignment/AssignmentResourceTest.java <ide> <ide> private MockMvc mvc; <ide> <del> private static String json_test_string = "{\"title\":\"TheTitle\"," + <add> private String json_test_string = "{\"title\":\"TheTitle\"," + <ide> "\"Info\": \"Assignment Info\"," + <ide> "\"videIntervall\":" + <ide> "{\"minTimeSeconds\":0," +
Java
apache-2.0
144049cf29cfb147b474c7459dee2a173a0e2952
0
xfournet/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,allotria/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,xfournet/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,allotria/intellij-community
/* * Copyright 2000-2012 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.vcs.changes.ui; import com.intellij.openapi.vcs.FilePath; import com.intellij.openapi.vcs.changes.Change; import com.intellij.openapi.vcs.changes.ChangesUtil; import com.intellij.openapi.vcs.changes.HierarchicalFilePathComparator; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.vcsUtil.VcsUtil; import org.jetbrains.annotations.NotNull; import java.util.Comparator; public class ChangesComparator { private static final Comparator<VirtualFile> VIRTUAL_FILE_FLAT = new VirtualFileComparator(true); private static final Comparator<VirtualFile> VIRTUAL_FILE_TREE = new VirtualFileComparator(false); private static final Comparator<Change> CHANGE_FLAT = new ChangeComparator(true); private static final Comparator<Change> CHANGE_TREE = new ChangeComparator(false); @NotNull public static Comparator<Change> getInstance(boolean flattened) { return flattened ? CHANGE_FLAT : CHANGE_TREE; } @NotNull public static Comparator<VirtualFile> getVirtualFileComparator(boolean flattened) { return flattened ? VIRTUAL_FILE_FLAT : VIRTUAL_FILE_TREE; } private static int comparePaths(@NotNull FilePath filePath1, @NotNull FilePath filePath2, boolean flattened) { if (!flattened) { return HierarchicalFilePathComparator.IGNORE_CASE.compare(filePath1, filePath2); } else { int delta = filePath1.getName().compareToIgnoreCase(filePath2.getName()); if (delta != 0) return delta; return filePath1.getPath().compareTo(filePath2.getPath()); } } private static class VirtualFileComparator implements Comparator<VirtualFile> { private final boolean myFlattened; public VirtualFileComparator(boolean flattened) { myFlattened = flattened; } @Override public int compare(VirtualFile o1, VirtualFile o2) { return comparePaths(VcsUtil.getFilePath(o1), VcsUtil.getFilePath(o2), myFlattened); } } private static class ChangeComparator implements Comparator<Change> { private final boolean myFlattened; public ChangeComparator(boolean flattened) { myFlattened = flattened; } @Override public int compare(Change o1, Change o2) { return comparePaths(ChangesUtil.getFilePath(o1), ChangesUtil.getFilePath(o2), myFlattened); } } }
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/ChangesComparator.java
/* * Copyright 2000-2012 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.vcs.changes.ui; import com.intellij.openapi.vcs.FilePath; import com.intellij.openapi.vcs.changes.Change; import com.intellij.openapi.vcs.changes.ChangesUtil; import com.intellij.openapi.vcs.changes.HierarchicalFilePathComparator; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.vcsUtil.VcsUtil; import org.jetbrains.annotations.NotNull; import java.util.Comparator; public class ChangesComparator { @NotNull public static Comparator<Change> getInstance(boolean flattened) { return (o1, o2) -> comparePaths(ChangesUtil.getFilePath(o1), ChangesUtil.getFilePath(o2), flattened); } @NotNull public static Comparator<VirtualFile> getVirtualFileComparator(boolean flattened) { return (o1, o2) -> comparePaths(VcsUtil.getFilePath(o1), VcsUtil.getFilePath(o2), flattened); } private static int comparePaths(@NotNull FilePath filePath1, @NotNull FilePath filePath2, boolean flattened) { if (!flattened) { return HierarchicalFilePathComparator.IGNORE_CASE.compare(filePath1, filePath2); } else { int delta = filePath1.getName().compareToIgnoreCase(filePath2.getName()); if (delta != 0) return delta; return filePath1.getPath().compareTo(filePath2.getPath()); } } }
vcs: do not create new Comparator every time
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/ChangesComparator.java
vcs: do not create new Comparator every time
<ide><path>latform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/ChangesComparator.java <ide> import java.util.Comparator; <ide> <ide> public class ChangesComparator { <add> private static final Comparator<VirtualFile> VIRTUAL_FILE_FLAT = new VirtualFileComparator(true); <add> private static final Comparator<VirtualFile> VIRTUAL_FILE_TREE = new VirtualFileComparator(false); <add> private static final Comparator<Change> CHANGE_FLAT = new ChangeComparator(true); <add> private static final Comparator<Change> CHANGE_TREE = new ChangeComparator(false); <add> <ide> @NotNull <ide> public static Comparator<Change> getInstance(boolean flattened) { <del> return (o1, o2) -> comparePaths(ChangesUtil.getFilePath(o1), ChangesUtil.getFilePath(o2), flattened); <add> return flattened ? CHANGE_FLAT : CHANGE_TREE; <ide> } <ide> <ide> @NotNull <ide> public static Comparator<VirtualFile> getVirtualFileComparator(boolean flattened) { <del> return (o1, o2) -> comparePaths(VcsUtil.getFilePath(o1), VcsUtil.getFilePath(o2), flattened); <add> return flattened ? VIRTUAL_FILE_FLAT : VIRTUAL_FILE_TREE; <ide> } <add> <ide> <ide> private static int comparePaths(@NotNull FilePath filePath1, @NotNull FilePath filePath2, boolean flattened) { <ide> if (!flattened) { <ide> return filePath1.getPath().compareTo(filePath2.getPath()); <ide> } <ide> } <add> <add> private static class VirtualFileComparator implements Comparator<VirtualFile> { <add> private final boolean myFlattened; <add> <add> public VirtualFileComparator(boolean flattened) { <add> myFlattened = flattened; <add> } <add> <add> @Override <add> public int compare(VirtualFile o1, VirtualFile o2) { <add> return comparePaths(VcsUtil.getFilePath(o1), VcsUtil.getFilePath(o2), myFlattened); <add> } <add> } <add> <add> private static class ChangeComparator implements Comparator<Change> { <add> private final boolean myFlattened; <add> <add> public ChangeComparator(boolean flattened) { <add> myFlattened = flattened; <add> } <add> <add> @Override <add> public int compare(Change o1, Change o2) { <add> return comparePaths(ChangesUtil.getFilePath(o1), ChangesUtil.getFilePath(o2), myFlattened); <add> } <add> } <ide> }
Java
apache-2.0
08074a0406c0c5dca85c90dfc101b44cb29ec611
0
bozimmerman/CoffeeMud,bozimmerman/CoffeeMud,bozimmerman/CoffeeMud,bozimmerman/CoffeeMud
package com.planet_ink.coffee_mud.Libraries; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.exceptions.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.core.collections.*; import com.planet_ink.coffee_mud.Libraries.interfaces.*; import com.planet_ink.coffee_mud.Libraries.interfaces.MoneyLibrary.MoneyDenomination; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Commands.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; import java.io.IOException; import java.util.*; import java.util.regex.*; /* Copyright 2003-2019 Bo Zimmerman Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ public class EnglishParser extends StdLibrary implements EnglishParsing { @Override public String ID() { return "EnglishParser"; } private final static String[] PREPOSITIONS = { "aboard", "about", "above", "across", "after", "against", "along", "amid", "among", "anti", "around", "as", "at", "before", "behind", "below", "beneath", "beside", "besides", "between", "beyond", "but", "by", "concerning", "considering", "despite", "down", "during", "except", "excepting", "excluding", "following", "for", "from", "in", "inside", "into", "like", "minus", "near", "of", "off", "on", "onto", "opposite", "outside", "over", "past", "per", "plus", "regarding", "round", "save", "since", "than", "through", "to", "toward", "towards", "under", "underneath", "unlike", "until", "up", "upon", "versus", "via", "with", "within", "without" }; private final static String[] ARTICLES = { "a", "an", "all of", "some one", "a pair of", "a pile of", "one of", "all", "the", "some", "each" }; public static boolean[] PUNCTUATION_TABLE = null; public final static char[] ALL_CHRS = "ALL".toCharArray(); public final static String[] fwords = { "calf", "half", "knife", "life", "wife", "elf", "self", "shelf", "leaf", "sheaf", "thief", "loaf", "wolf" }; public final static String[] frwords = { "calves", "halves", "knives", "lives", "wives", "elves", "selves", "shelves", "leaves", "sheaves", "thieves", "loaves", "wolves" }; public final static String[] fnouns = { "bison", "buffalo", "carpcod", "deer", "fish", "moose", "pike", "salmon", "sheep", "shrimp", "squid", "trout", "ore" }; public final static String[] feewords1 = { "foot", "goose", "louse", "dormouse", "man", "mouse", "tooth", "woman", "ox", "child", "brother" }; public final static String[] feewords2 = { "feet", "geese", "lice", "dormice", "men", "mice", "teeth", "women", "oxen", "children", "brethren" }; public final static List<Environmental> empty = new ReadOnlyVector<Environmental>(1); @Override public String toEnglishStringList(final String[] V) { if((V==null)||(V.length==0)) { return ""; } if(V.length==1) return V[0]; final StringBuffer s=new StringBuffer(""); for(int v=0;v<V.length-1;v++) { if(v>0) s.append(", "); s.append(V[v]); } s.append(" and "); s.append(V[V.length-1]); return s.toString(); } @Override public String toEnglishStringList(final Class<? extends Enum<?>> enumer, final boolean andOr) { final Enum<?>[] V=enumer.getEnumConstants(); if((V==null)||(V.length==0)) { return ""; } if(V.length==1) return V[0].toString(); final StringBuffer s=new StringBuffer(""); for(int v=0;v<V.length-1;v++) { if(v>0) s.append(", "); s.append(V[v].toString()); } if(andOr) s.append(" and "); else s.append(" or "); s.append(V[V.length-1].toString()); return s.toString(); } @Override public String toEnglishStringList(final Collection<? extends Object> V) { if((V==null)||(V.isEmpty())) { return ""; } if(V.size()==1) return V.iterator().next().toString(); final StringBuffer s=new StringBuffer(""); for(final Iterator<? extends Object> o=V.iterator();o.hasNext();) { final Object O = o.next(); if(!o.hasNext()) { if(V.size()==2) s.append(" and "); else s.append(", and "); } else if(s.length()>0) s.append(", "); s.append(O.toString()); } return s.toString(); } @Override public String makePastTense(String word, final String defaultWord) { if(word == null) return defaultWord; word = word.trim(); if(word.length()==0) return defaultWord; final int x=word.indexOf(' '); if(x>0) word=word.substring(x+1).trim(); if(word.endsWith("(s)")) word=word.substring(0, word.length()-3); if(word.endsWith("(es)")) word=word.substring(0, word.length()-4); if(word.endsWith("(ys)")) word=word.substring(0, word.length()-4); if(CMStrings.isVowel(word.charAt(word.length()-1))) return word+"d"; else if(!word.endsWith("ed")) return word+"ed"; else return word; } @Override public boolean isAnArticle(String s) { s=s.toLowerCase(); for (final String article : ARTICLES) { if(s.equals(article)) return true; } return false; } @Override public String makePlural(final String str) { if((str==null)||(str.length()==0)) return str; final boolean uppercase=Character.isUpperCase(str.charAt(str.length()-1)); final String lowerStr=str.toLowerCase(); if(CMStrings.contains(fnouns, lowerStr)) return str; final int x=CMParms.indexOf(feewords1, lowerStr); if(x >= 0) return uppercase ? feewords2[x].toUpperCase() : feewords2[x]; if(lowerStr.endsWith("is")) return str.substring(0,str.length()-2)+(uppercase?"ES":"es"); if(lowerStr.endsWith("s")||lowerStr.endsWith("z")||lowerStr.endsWith("x")||lowerStr.endsWith("ch")||lowerStr.endsWith("sh")) return str+(uppercase?"ES":"es"); if(lowerStr.endsWith("ay")||lowerStr.endsWith("ey")||lowerStr.endsWith("iy")||lowerStr.endsWith("oy")||lowerStr.endsWith("uy")) return str+(uppercase?"S":"s"); if(lowerStr.endsWith("y")) return str.substring(0,str.length()-1)+(uppercase?"IES":"ies"); if(CMStrings.contains(fwords, lowerStr)) return str.substring(0,str.length()-1)+(uppercase?"VES":"ves"); return str+(uppercase?"S":"s"); } @Override public String makeSingular(final String str) { if((str==null)||(str.length()==0)) return str; final boolean uppercase=Character.isUpperCase(str.charAt(str.length()-1)); final String lowerStr=str.toLowerCase(); if(lowerStr.endsWith("ses")||lowerStr.endsWith("zes")||lowerStr.endsWith("xes")||lowerStr.endsWith("ches")||lowerStr.endsWith("shes")) return str.substring(0,str.length()-2); //if(lowerStr.endsWith("is")) // return str.substring(0,str.length()-2)+(uppercase?"ES":"es"); if(lowerStr.endsWith("ays")||lowerStr.endsWith("eys")||lowerStr.endsWith("iys")||lowerStr.endsWith("oys")||lowerStr.endsWith("uys")) return str.substring(0,str.length()-1); if(lowerStr.endsWith("ies")) return str.substring(0,str.length()-3)+(uppercase?"Y":"y"); final int x=CMParms.indexOf(frwords, lowerStr); if(x>=0) return uppercase?fwords[x].toUpperCase():fwords[x]; if(str.endsWith("s")) return str.substring(0,str.length()-1); return str; } @Override public String cleanPrepositions(final String s) { final String lowStr=s.toLowerCase(); for (final String prepositino : PREPOSITIONS) { if(lowStr.startsWith(prepositino+" ")) return s.substring(prepositino.length()+1); } return s; } @Override public String properIndefiniteArticle(final String str) { int i=0; for(;i<str.length();i++) { switch(str.charAt(i)) { case '^': { i++; if(i<str.length()) { switch(str.charAt(i)) { case ColorLibrary.COLORCODE_FANSI256: i += 3; break; case ColorLibrary.COLORCODE_BANSI256: i += 3; break; case ColorLibrary.COLORCODE_BACKGROUND: i++; break; case '<': while(i<str.length()-1) { if((str.charAt(i)!='^')||(str.charAt(i+1)!='>')) i++; else { i++; break; } } break; case '&': while(i<str.length()) { if(str.charAt(i)!=';') i++; else break; } break; } } break; } case 'a': case 'e': case 'i': case 'o': case 'u': case 'A': case 'E': case 'I': case 'O': case 'U': return "an"; default: if(Character.isLetter(str.charAt(i))) return "a"; else return ""; } } return ""; } protected String getBestDistance(long d) { String min=null; final long sign=(long)Math.signum(d); d=Math.abs(d); for(final SpaceObject.Distance distance : SpaceObject.DISTANCES) { if((distance.dm * 2) < d) { double val=(double)d/(double)distance.dm; if((val<0)||(val<100)) val=Math.round(val*100.0)/100.0; else val=Math.round(val); if(val!=0.0) { String s=Double.toString(sign*val); if(s.endsWith(".0")) s=s.substring(0,s.length()-2); s+=distance.abbr; min = s; break; //if((min==null)||(min.length()>s.length())) min=s; } } } if(min==null) return (sign*d)+"dm"; return min; } @Override public String sizeDescShort(final long size) { return getBestDistance(size); } @Override public String distanceDescShort(final long distance) { return getBestDistance(distance); } @Override public String coordDescShort(final long[] coords) { return getBestDistance(coords[0])+","+getBestDistance(coords[1])+","+getBestDistance(coords[2]); } @Override public String speedDescShort(final double speed) { return getBestDistance(Math.round(speed))+"/sec"; } @Override public String directionDescShort(final double[] dir) { return Math.round(Math.toDegrees(dir[0])*100)/100.0+" mark "+Math.round(Math.toDegrees(dir[1])*100)/100.0; } @Override public String directionDescShortest(final double[] dir) { return Math.round(Math.toDegrees(dir[0])*10)/10.0+"`"+Math.round(Math.toDegrees(dir[1])*10)/10.0; } @Override public Long parseSpaceDistance(String dist) { if(dist==null) return null; dist=dist.trim(); int digits=-1; if((dist.length()>0)&&(dist.charAt(0)=='-')) digits++; while((digits<dist.length()-1)&&(Character.isDigit(dist.charAt(digits+1)))) digits++; if(digits<0) return null; final Long value=Long.valueOf(dist.substring(0,digits+1)); final String unit=dist.substring(digits+1).trim(); if(unit.length()==0) return value; SpaceObject.Distance distUnit=(SpaceObject.Distance)CMath.s_valueOf(SpaceObject.Distance.class, unit); if(distUnit==null) { for(final SpaceObject.Distance d : SpaceObject.Distance.values()) { if(d.abbr.equalsIgnoreCase(unit)) distUnit=d; } } if(distUnit==null) { for(final SpaceObject.Distance d : SpaceObject.Distance.values()) { if(d.name().equalsIgnoreCase(unit)) distUnit=d; } } if(distUnit==null) { for(final SpaceObject.Distance d : SpaceObject.Distance.values()) { if(unit.toLowerCase().startsWith(d.name().toLowerCase())) distUnit=d; } } if(distUnit==null) return null; return Long.valueOf(value.longValue() * distUnit.dm); } @Override public String getFirstWord(final String str) { int i=0; int start=-1; for(;i<str.length();i++) { switch(str.charAt(i)) { case '^': { i++; if(i<str.length()) { switch(str.charAt(i)) { case ColorLibrary.COLORCODE_FANSI256: i += 3; break; case ColorLibrary.COLORCODE_BANSI256: i += 3; break; case ColorLibrary.COLORCODE_BACKGROUND: i++; break; case '<': while(i<str.length()-1) { if((str.charAt(i)!='^')||(str.charAt(i+1)!='>')) i++; else { i++; break; } } break; case '&': while(i<str.length()) { if(str.charAt(i)!=';') i++; else break; } break; } } break; } case ' ': if(start>=0) return str.substring(start,i); break; default: if(Character.isLetter(str.charAt(i)) && (start<0)) start=i; break; } } return str; } @Override public String startWithAorAn(final String str) { if((str==null)||(str.length()==0)) return str; final String uppStr=getFirstWord(str).toUpperCase(); if((!uppStr.equals("A")) &&(!uppStr.equals("AN")) &&(!uppStr.equals("THE")) &&(!uppStr.equals("SOME"))) return (properIndefiniteArticle(str)+" "+str.trim()).trim(); return str; } @Override public boolean startsWithAnArticle(final String s) { return isAnArticle(getFirstWord(s)); } @Override public String removeArticleLead(final String s) { final String firstWord=getFirstWord(s); final int x=s.indexOf(firstWord); final String slower=(x>0) ? s.substring(x).toLowerCase() : s.toLowerCase(); for (final String article : ARTICLES) { if(slower.startsWith(article+" ")) return slower.substring(article.length()).trim(); } return s; } @Override public String insertUnColoredAdjective(String str, final String adjective) { if(str.length()==0) return str; str=CMStrings.removeColors(str.trim()); final String uppStr=str.toUpperCase(); if((uppStr.startsWith("A ")) ||(uppStr.startsWith("AN "))) return properIndefiniteArticle(adjective)+" "+adjective+" "+str.substring(2).trim(); if(uppStr.startsWith("THE ")) return properIndefiniteArticle(adjective)+" "+adjective+" "+str.substring(3).trim(); if(uppStr.startsWith("SOME ")) return properIndefiniteArticle(adjective)+" "+adjective+" "+str.substring(4).trim(); return properIndefiniteArticle(adjective)+" "+adjective+" "+str.trim(); } protected int skipSpaces(final String paragraph, int index) { while((index<paragraph.length())&&Character.isWhitespace(paragraph.charAt(index))) index++; if(index>=paragraph.length()) return -1; return index; } @Override public String insertAdjectives(final String paragraph, final String[] adjsToChoose, final int pctChance) { if((paragraph.length()==0)||(adjsToChoose==null)||(adjsToChoose.length==0)) return paragraph; final StringBuilder newParagraph = new StringBuilder(""); int startDex=skipSpaces(paragraph,0); if(startDex<0) return paragraph; newParagraph.append(paragraph.substring(0,startDex)); int spaceDex=paragraph.indexOf(' ',startDex); while(spaceDex > startDex) { final String word=paragraph.substring(startDex,spaceDex).trim(); if(isAnArticle(word) && (CMLib.dice().rollPercentage()<=pctChance)) { final String adj=adjsToChoose[CMLib.dice().roll(1, adjsToChoose.length, -1)].toLowerCase(); if(word.equalsIgnoreCase("a")||word.equalsIgnoreCase("an")) newParagraph.append(this.startWithAorAn(adj)).append(" ").append(adj); else newParagraph.append(word).append(" ").append(adj); } else newParagraph.append(paragraph.substring(startDex,spaceDex)); startDex=skipSpaces(paragraph,spaceDex); if(startDex<0) break; newParagraph.append(paragraph.substring(spaceDex,startDex)); spaceDex=paragraph.indexOf(' ',startDex); } if((spaceDex<startDex)&&(startDex>=0)&&(startDex<paragraph.length())) newParagraph.append(paragraph.substring(startDex)); return newParagraph.toString(); } @Override public CMObject findCommand(final MOB mob, final List<String> commands) { if((mob==null) ||(commands==null) ||(mob.location()==null) ||(commands.isEmpty())) return null; String firstWord=commands.get(0).toUpperCase(); if((firstWord.length()>1)&&(!Character.isLetterOrDigit(firstWord.charAt(0)))) { commands.add(1,commands.get(0).substring(1)); commands.set(0,""+firstWord.charAt(0)); firstWord=""+firstWord.charAt(0); } // first, exacting pass Command C=CMClass.findCommandByTrigger(firstWord,true); if((C!=null) &&(C.securityCheck(mob)) &&(!CMSecurity.isCommandDisabled(CMClass.classID(C).toUpperCase()))) return CMLib.leveler().deferCommandCheck(mob, C, commands); Ability A=getToEvoke(mob,new XVector<String>(commands)); if((A!=null) &&(!CMSecurity.isAbilityDisabled(A.ID().toUpperCase()))) return A; if(getAnEvokeWord(mob,firstWord)!=null) return null; Social social=CMLib.socials().fetchSocial(commands,true,true); if(social!=null) return social; for(int c=0;c<CMLib.channels().getNumChannels();c++) { final ChannelsLibrary.CMChannel chan=CMLib.channels().getChannel(c); if(chan.name().equalsIgnoreCase(firstWord)) { C=CMClass.getCommand("Channel"); if((C!=null)&&(C.securityCheck(mob))) return C; } else if(("NO"+chan.name()).equalsIgnoreCase(firstWord)) { C=CMClass.getCommand("NoChannel"); if((C!=null)&&(C.securityCheck(mob))) return C; } } for(final Enumeration<JournalsLibrary.CommandJournal> e=CMLib.journals().commandJournals();e.hasMoreElements();) { final JournalsLibrary.CommandJournal CMJ=e.nextElement(); if(CMJ.NAME().equalsIgnoreCase(firstWord)) { C=CMClass.getCommand("CommandJournal"); if((C!=null)&&(C.securityCheck(mob))) return C; } } // second, inexacting pass for(final Enumeration<Ability> a=mob.allAbilities();a.hasMoreElements();) { A=a.nextElement(); final HashSet<String> tried=new HashSet<String>(); if((A!=null)&&(A.triggerStrings()!=null)) { for(int t=0;t<A.triggerStrings().length;t++) { if((A.triggerStrings()[t].toUpperCase().startsWith(firstWord)) &&(!tried.contains(A.triggerStrings()[t]))) { final Vector<String> commands2=new XVector<String>(commands); commands2.setElementAt(A.triggerStrings()[t],0); final Ability A2=getToEvoke(mob,commands2); if((A2!=null)&&(!CMSecurity.isAbilityDisabled(A2.ID().toUpperCase()))) { commands.set(0,A.triggerStrings()[t]); return A; } } } } } //commands comes inexactly after ables //because of CA, PR, etc.. C=CMClass.findCommandByTrigger(firstWord,false); if((C!=null) &&(C.securityCheck(mob)) &&(!CMSecurity.isCommandDisabled(CMClass.classID(C).toUpperCase()))) return CMLib.leveler().deferCommandCheck(mob, C, commands); social=CMLib.socials().fetchSocial(commands,false,true); if(social!=null) { commands.set(0,social.baseName()); return social; } for(int c=0;c<CMLib.channels().getNumChannels();c++) { final ChannelsLibrary.CMChannel chan=CMLib.channels().getChannel(c); if(chan.name().startsWith(firstWord)) { commands.set(0,chan.name()); C=CMClass.getCommand("Channel"); if((C!=null)&&(C.securityCheck(mob))) return C; } else if(("NO"+chan.name()).startsWith(firstWord)) { commands.set(0,"NO"+chan.name()); C=CMClass.getCommand("NoChannel"); if((C!=null)&&(C.securityCheck(mob))) return C; } } for(final Enumeration<JournalsLibrary.CommandJournal> e=CMLib.journals().commandJournals();e.hasMoreElements();) { final JournalsLibrary.CommandJournal CMJ=e.nextElement(); if(CMJ.NAME().startsWith(firstWord)) { C=CMClass.getCommand("CommandJournal"); if((C!=null)&&(C.securityCheck(mob))) return C; } } return CMLib.leveler().deferCommandCheck(mob, null, commands); } @Override public boolean evokedBy(final Ability thisAbility, final String thisWord) { for(int i=0;i<thisAbility.triggerStrings().length;i++) { if(thisAbility.triggerStrings()[i].equalsIgnoreCase(thisWord)) return true; } return false; } private String collapsedName(final Ability thisAbility) { final int x=thisAbility.name().indexOf(' '); if(x>=0) return CMStrings.replaceAll(thisAbility.name()," ",""); return thisAbility.Name(); } @Override public boolean evokedBy(final Ability thisAbility, final String thisWord, final String secondWord) { for(int i=0;i<thisAbility.triggerStrings().length;i++) { if(thisAbility.triggerStrings()[i].equalsIgnoreCase(thisWord)) { if(((thisAbility.name().toUpperCase().startsWith(secondWord))) ||(collapsedName(thisAbility).toUpperCase().startsWith(secondWord))) return true; } } return false; } @Override public String getAnEvokeWord(final MOB mob, String word) { if(mob==null) return null; Ability A=null; final HashSet<String[]> done=new HashSet<String[]>(); word=word.toUpperCase().trim(); for(final Enumeration<Ability> a=mob.allAbilities();a.hasMoreElements();) { A=a.nextElement(); if((A!=null) &&(A.triggerStrings()!=null) &&(!done.contains(A.triggerStrings()))) { done.add(A.triggerStrings()); for(int t=0;t<A.triggerStrings().length;t++) { if(word.equals(A.triggerStrings()[t])) { if((t>0)&&(A.triggerStrings()[0].startsWith(word))) return A.triggerStrings()[0]; else return A.triggerStrings()[t]; } } } } return null; } @Override public Ability getToEvoke(final MOB mob, final List<String> commands) { final String evokeWord=commands.get(0).toUpperCase(); boolean foundMoreThanOne=false; Ability evokableAbility=null; for(final Enumeration<Ability> a=mob.allAbilities();a.hasMoreElements();) { final Ability A=a.nextElement(); if((A!=null) &&(evokedBy(A,evokeWord))) { if((evokableAbility!=null)&&(!A.ID().equals(evokableAbility.ID()))) { foundMoreThanOne=true; evokableAbility=null; break; } evokableAbility=A; } } if((evokableAbility!=null)&&(commands.size()>1)) { final int classCode=evokableAbility.classificationCode()&Ability.ALL_ACODES; switch(classCode) { case Ability.ACODE_SPELL: case Ability.ACODE_SONG: case Ability.ACODE_PRAYER: case Ability.ACODE_CHANT: evokableAbility=null; foundMoreThanOne=true; break; default: break; } } if(evokableAbility!=null) commands.remove(0); else if((foundMoreThanOne)&&(commands.size()>1)) { commands.remove(0); foundMoreThanOne=false; final String secondWord=commands.get(0).toUpperCase(); for(final Enumeration<Ability> a=mob.allAbilities();a.hasMoreElements();) { final Ability A=a.nextElement(); if((A!=null) &&(evokedBy(A,evokeWord,secondWord.toUpperCase()))) { if((A.name().equalsIgnoreCase(secondWord)) ||(collapsedName(A).equalsIgnoreCase(secondWord))) { evokableAbility=A; foundMoreThanOne=false; break; } else if((evokableAbility!=null)&&(!A.ID().equals(evokableAbility.ID()))) foundMoreThanOne=true; else evokableAbility=A; } } if((evokableAbility!=null)&&(!foundMoreThanOne)) commands.remove(0); else if((foundMoreThanOne)&&(commands.size()>1)) { final String secondAndThirdWord=secondWord+" "+commands.get(1).toUpperCase(); for(final Enumeration<Ability> a=mob.allAbilities();a.hasMoreElements();) { final Ability A=a.nextElement(); if((A!=null) && (evokedBy(A,evokeWord,secondAndThirdWord.toUpperCase()))) { evokableAbility=A; break; } } if(evokableAbility!=null) { commands.remove(0); commands.remove(0); } } else { for(final Enumeration<Ability> a=mob.allAbilities();a.hasMoreElements();) { final Ability A=a.nextElement(); if((A!=null) &&(evokedBy(A,evokeWord)) &&(A.name().toUpperCase().indexOf(" "+secondWord.toUpperCase())>0)) { evokableAbility=A; commands.remove(0); break; } } } } return evokableAbility; } @Override public boolean preEvoke(final MOB mob, List<String> commands, final int secondsElapsed, final double actionsRemaining) { commands=new Vector<String>(commands); final Ability evokableAbility=getToEvoke(mob,commands); if(evokableAbility==null) { mob.tell(L("You don't know how to do that.")); return false; } if((CMLib.ableMapper().qualifyingLevel(mob,evokableAbility)>=0) &&(!CMLib.ableMapper().qualifiesByLevel(mob,evokableAbility)) &&(!CMSecurity.isAllowed(mob,mob.location(),CMSecurity.SecFlag.ALLSKILLS))) { mob.tell(L("You are not high enough level to do that.")); return false; } return evokableAbility.preInvoke(mob,commands,null,false,0,secondsElapsed,actionsRemaining); } @Override public void evoke(final MOB mob, final Vector<String> commands) { final Ability evokableAbility=getToEvoke(mob,commands); if(evokableAbility==null) { mob.tell(L("You don't know how to do that.")); return; } if((CMLib.ableMapper().qualifyingLevel(mob,evokableAbility)>=0) &&(!CMLib.ableMapper().qualifiesByLevel(mob,evokableAbility)) &&(!CMSecurity.isAllowed(mob,mob.location(),CMSecurity.SecFlag.ALLSKILLS))) { mob.tell(L("You are not high enough level to do that.")); return; } evokableAbility.invoke(mob,commands,null,false,0); } private boolean[] PUNCTUATION_TABLE() { if(PUNCTUATION_TABLE==null) { final boolean[] PUNCTUATION_TEMP_TABLE=new boolean[255]; for(int c=0;c<255;c++) switch(c) { case '`': case '~': case '!': case '@': case '#': case '$': case '%': case '^': case '&': case '*': case '(': case ')': case '_': case '-': case '+': case '=': case '[': case ']': case '{': case '}': case '\\': case '|': case ';': case ':': case '\'': case '\"': case ',': case '<': case '.': case '>': case '/': case '?': PUNCTUATION_TEMP_TABLE[c]=true; break; default: PUNCTUATION_TEMP_TABLE[c]=false; } PUNCTUATION_TABLE=PUNCTUATION_TEMP_TABLE; } return PUNCTUATION_TABLE; } @Override public boolean isPunctuation(final byte b) { if((b<0)||(b>255)) return false; return PUNCTUATION_TABLE[b]; } @Override public boolean hasPunctuation(final String str) { if((str==null)||(str.length()==0)) return false; boolean puncFound=false; PUNCTUATION_TABLE(); for(int x=0;x<str.length();x++) { if(isPunctuation((byte)str.charAt(x))) { puncFound=true; break; } } return puncFound; } @Override public String stripPunctuation(final String str) { if(!hasPunctuation(str)) return str; final char[] strc=str.toCharArray(); final char[] str2=new char[strc.length]; int s=0; for(int x=0;x<strc.length;x++) { if(!isPunctuation((byte)strc[x])) { str2[s]=strc[x]; s++; } } return new String(str2,0,s); } @Override public List<String> parseWords(final String thisStr) { if((thisStr==null)||(thisStr.length()==0)) return new Vector<String>(1); return CMParms.parseSpaces(stripPunctuation(thisStr), true); } public boolean equalsPunctuationless(final char[] strC, final char[] str2C) { if((strC.length==0)&&(str2C.length==0)) return true; PUNCTUATION_TABLE(); int s1=0; int s2=0; int s1len=strC.length; while((s1len>0)&&(Character.isWhitespace(strC[s1len-1])||isPunctuation((byte)strC[s1len-1]))) s1len--; int s2len=str2C.length; while((s2len>0)&&(Character.isWhitespace(str2C[s2len-1])||isPunctuation((byte)str2C[s2len-1]))) s2len--; while(s1<s1len) { while((s1<s1len)&&(isPunctuation((byte)strC[s1]))) s1++; while((s2<s2len)&&(isPunctuation((byte)str2C[s2]))) s2++; if(s1==s1len) { if(s2==s2len) return true; return false; } if(s2==s2len) return false; if(strC[s1]!=str2C[s2]) return false; s1++; s2++; } if(s2==s2len) return true; return false; } @Override public boolean containsString(final String toSrchStr, final String srchStr) { if((toSrchStr==null)||(srchStr==null)) return false; if((toSrchStr.length()==0)&&(srchStr.length()>0)) return false; char[] srchC=srchStr.toCharArray(); final char[] toSrchC=toSrchStr.toCharArray(); for(int c=0;c<srchC.length;c++) srchC[c]=Character.toUpperCase(srchC[c]); for(int c=0;c<toSrchC.length;c++) toSrchC[c]=Character.toUpperCase(toSrchC[c]); if(java.util.Arrays.equals(srchC,ALL_CHRS)) return true; if(java.util.Arrays.equals(srchC,toSrchC)) return true; if(equalsPunctuationless(srchC,toSrchC)) return true; boolean topOnly=false; if((srchC.length>1)&&(srchC[0]=='$')) { srchC=new String(srchC,1,srchC.length-1).toCharArray(); topOnly=true; } int tos=0; boolean found=false; while((!found)&&(tos<toSrchC.length)) { for(int x=0;x<srchC.length;x++) { if(tos>=toSrchC.length) { if(srchC[x]=='$') found=true; break; } switch(toSrchC[tos]) { case '^': tos++; if(tos<toSrchC.length) { switch(toSrchC[tos]) { case ColorLibrary.COLORCODE_BACKGROUND: if(tos < toSrchC.length-1) tos+=2; break; case ColorLibrary.COLORCODE_FANSI256: case ColorLibrary.COLORCODE_BANSI256: if(tos < toSrchC.length-4) tos+=4; break; default: tos++; break; } } break; case ',': case '?': case '!': case '.': case ';': tos++; break; } switch(srchC[x]) { case '^': x++; if(x<srchC.length) { switch(srchC[x]) { case ColorLibrary.COLORCODE_BACKGROUND: if(x < srchC.length-1) x+=2; break; case ColorLibrary.COLORCODE_FANSI256: case ColorLibrary.COLORCODE_BANSI256: if(x < srchC.length-4) x+=4; break; default: x++; break; } } break; case ',': case '?': case '!': case '.': case ';': x++; break; } if(x<srchC.length) { if(tos<toSrchC.length) { if(srchC[x]!=toSrchC[tos]) break; else if(x==(srchC.length-1)) found=true; else tos++; } else if(srchC[x]=='$') found=true; else break; } else { found=true; break; } } if((topOnly)&&(!found)) break; while((!found)&&(tos<toSrchC.length)&&(Character.isLetter(toSrchC[tos]))) tos++; tos++; } return found; } @Override public String bumpDotNumber(final String srchStr) { final FetchFlags flags=fetchFlags(srchStr); if(flags==null) return srchStr; if(flags.allFlag) return srchStr; if(flags.occurrance==0) return "1."+flags.srchStr; return (flags.occurrance+1)+"."+flags.srchStr; } @Override public int getContextNumber(final ItemCollection cont, final Environmental E) { return getContextNumber(toCollection(cont),E); } @Override public int getContextNumber(final Environmental[] list, final Environmental E) { return getContextNumber(new XVector<Environmental>(list),E); } @Override public int getContextNumber(final Collection<? extends Environmental> list, final Environmental E) { if(list==null) return 0; int context=1; for(final Environmental O : list) { if((O.Name().equalsIgnoreCase(E.Name())) ||(O.name().equalsIgnoreCase(E.name()))) { if(O==E) return context<2?0:context; if((!(O instanceof Item)) ||(!(E instanceof Item)) ||(((Item)E).container()==((Item)O).container())) context++; } } return -1; } private Collection<? extends Environmental> toCollection(final ItemCollection cont) { final LinkedList<Item> list=new LinkedList<Item>(); for(final Enumeration<Item> i=cont.items();i.hasMoreElements();) list.add(i.nextElement()); return list; } @Override public int getContextSameNumber(final ItemCollection cont, final Environmental E) { return getContextSameNumber(toCollection(cont),E); } @Override public int getContextSameNumber(final Environmental[] list, final Environmental E) { return getContextSameNumber(new XVector<Environmental>(list),E); } @Override public int getContextSameNumber(final Collection<? extends Environmental> list, final Environmental E) { if(list==null) return 0; int context=1; for(final Object O : list) { if((((Environmental)O).Name().equalsIgnoreCase(E.Name())) ||(((Environmental)O).name().equalsIgnoreCase(E.name()))) { if(E.sameAs((Environmental)O)) return context<2?0:context; if((!(O instanceof Item)) ||(!(E instanceof Item)) ||(((Item)E).container()==((Item)O).container())) context++; } } return -1; } @Override public String getContextName(final ItemCollection cont, final Environmental E) { return getContextName(toCollection(cont),E); } @Override public String getContextName(final Environmental[] list, final Environmental E) { return getContextName(new XVector<Environmental>(list),E); } @Override public String getContextName(final Collection<? extends Environmental> list, final Environmental E) { if(list==null) return E.name(); final int number=getContextNumber(list,E); if(number<0) return null; if(number<2) return E.name(); return E.name()+"."+number; } @Override public List<String> getAllContextNames(final Collection<? extends Environmental> list, final Filterer<Environmental> filter) { if(list==null) return new ArrayList<String>(); final List<String> flist = new Vector<String>(list.size()); final Map<String,int[]> prevFound = new HashMap<String,int[]>(); for(final Environmental E : list) { if((filter!=null)&&(!filter.passesFilter(E))) { flist.add(""); continue; } final String key = E.Name()+((E instanceof Item)?("/"+((Item)E).container()):""); if(!prevFound.containsKey(key)) { final int[] ct=new int[]{1}; prevFound.put(key, ct); flist.add(E.name()); } else { final int[] ct=prevFound.get(key); ct[0]++; flist.add(E.name()+"."+ct[0]); } } return flist; } @Override public String getContextSameName(final ItemCollection cont, final Environmental E) { return getContextSameName(toCollection(cont),E); } @Override public String getContextSameName(final Environmental[] list, final Environmental E) { return getContextSameName(new XVector<Environmental>(list),E); } @Override public String getContextSameName(final Collection<? extends Environmental> list, final Environmental E) { if(list==null) return E.name(); final int number=getContextSameNumber(list,E); if(number<0) return null; if(number<2) return E.name(); return E.name()+"."+number; } @Override public Environmental parseShopkeeper(final MOB mob, final List<String> commands, final String error) { if(commands.isEmpty()) { if(error.length()>0) mob.tell(error); return null; } commands.remove(0); final List<Environmental> V=CMLib.coffeeShops().getAllShopkeepers(mob.location(),mob); if(V.isEmpty()) { if(error.length()>0) mob.tell(error); return null; } if(V.size()>1) { if(commands.size()<2) { if(error.length()>0) mob.tell(error); return null; } final String what=commands.get(commands.size()-1); Environmental shopkeeper=fetchEnvironmental(V,what,false); if((shopkeeper==null)&&(what.equals("shop")||what.equals("the shop"))) { for(int v=0;v<V.size();v++) { if(V.get(v) instanceof Area) { shopkeeper = V.get(v); break; } } } if((shopkeeper!=null) &&(CMLib.coffeeShops().getShopKeeper(shopkeeper)!=null) &&(CMLib.flags().canBeSeenBy(shopkeeper,mob))) commands.remove(commands.size()-1); else { CMLib.commands().postCommandFail(mob,new XVector<String>(commands), L("You don't see anyone called '@x1' here buying or selling.",commands.get(commands.size()-1))); return null; } return shopkeeper; } Environmental shopkeeper=V.get(0); if(commands.size()>1) { final MOB M=mob.location().fetchInhabitant(commands.get(commands.size()-1)); if((M!=null)&&(CMLib.coffeeShops().getShopKeeper(M)!=null)&&(CMLib.flags().canBeSeenBy(M,mob))) { shopkeeper=M; commands.remove(commands.size()-1); } } return shopkeeper; } @Override public List<Item> fetchItemList(final Environmental from, final MOB mob, final Item container, final List<String> commands, final Filterer<Environmental> filter, final boolean visionMatters) { int addendum=1; String addendumStr=""; List<Item> V=new Vector<Item>(); int maxToItem=Integer.MAX_VALUE; if((commands.size()>1) &&(CMath.s_int(commands.get(0))>0)) { maxToItem=CMath.s_int(commands.get(0)); commands.set(0,"all"); } String name=CMParms.combine(commands,0); boolean allFlag = (!commands.isEmpty()) ? commands.get(0).equalsIgnoreCase("all") : false; if (name.toUpperCase().startsWith("ALL.")) { allFlag = true; name = "ALL " + name.substring(4); } if (name.toUpperCase().endsWith(".ALL")) { allFlag = true; name = "ALL " + name.substring(0, name.length() - 4); } boolean doBugFix = true; boolean wornOnly = true; boolean unwornOnly = true; while(doBugFix || ((allFlag)&&(addendum<=maxToItem))) { doBugFix=false; Environmental item=null; if(from instanceof MOB) { item=((MOB)from).fetchItem(container,filter,name+addendumStr); // all this for single underlayer items with the same name.. ugh... if((item instanceof Armor) && (!allFlag) && (filter == Wearable.FILTER_WORNONLY) && (addendumStr.length()==0)) { int subAddendum = 0; Item item2=((MOB)from).fetchItem(container,filter,name+"."+(++subAddendum)); while(item2 != null) { if((item2 instanceof Armor) &&(((Armor)item2).getClothingLayer() > ((Armor)item).getClothingLayer())) item=item2; item2=((MOB)from).fetchItem(container,filter,name+"."+(++subAddendum)); } } } else if(from instanceof Room) item=((Room)from).fetchFromMOBRoomFavorsItems(mob,container,name+addendumStr,filter); if((item!=null) &&(item instanceof Item) &&((!visionMatters)||(CMLib.flags().canBeSeenBy(item,mob))||(item instanceof Light)) &&(!V.contains(item))) { V.add((Item)item); if(((Item)item).amWearingAt(Wearable.IN_INVENTORY)) wornOnly=false; else unwornOnly=false; } if(item==null) break; addendumStr="."+(++addendum); } if(wornOnly && (!V.isEmpty())) { final Vector<Item> V2=new Vector<Item>(); // return value short topLayer=0; short curLayer=0; int which=-1; while(!V.isEmpty()) { Item I=V.get(0); topLayer=(I instanceof Armor)?((Armor)I).getClothingLayer():0; which=0; for(int v=1;v<V.size();v++) { I=V.get(v); curLayer=(I instanceof Armor)?((Armor)I).getClothingLayer():0; if(curLayer>topLayer) { which = v; topLayer = curLayer; } } V2.addElement(V.get(which)); V.remove(which); } V=V2; } else if(unwornOnly && (!V.isEmpty())) { final Vector<Item> V2=new Vector<Item>(); // return value short topLayer=0; short curLayer=0; int which=-1; while(!V.isEmpty()) { Item I=V.get(0); topLayer=(I instanceof Armor)?((Armor)I).getClothingLayer():0; which=0; for(int v=1;v<V.size();v++) { I=V.get(v); curLayer=(I instanceof Armor)?((Armor)I).getClothingLayer():0; if(curLayer<topLayer) { which=v; topLayer=curLayer; } } V2.addElement(V.get(which)); V.remove(which); } V=V2; } return V; } @Override public long parseNumPossibleGold(final Environmental mine, String moneyStr) { if(moneyStr.toUpperCase().trim().startsWith("A PILE OF ")) moneyStr=moneyStr.substring(10); if(CMath.isInteger(moneyStr)) { final long num=CMath.s_long(moneyStr); if(mine instanceof MOB) { List<Coins> V=CMLib.beanCounter().getStandardCurrency((MOB)mine,CMLib.beanCounter().getCurrency(mine)); for(int v=0;v<V.size();v++) { if(V.get(v).getNumberOfCoins()>=num) return num; } V=CMLib.beanCounter().getStandardCurrency((MOB)mine,null); for(int v=0;v<V.size();v++) { if(V.get(v).getNumberOfCoins()>=num) return num; } } return CMath.s_long(moneyStr); } final Vector<String> V=CMParms.parse(moneyStr); if((V.size()>1) &&((CMath.isInteger(V.firstElement())) &&(matchAnyCurrencySet(CMParms.combine(V,1))!=null))) return CMath.s_long(V.firstElement()); else if((V.size()>1)&&(V.firstElement().equalsIgnoreCase("all"))) { final String currency=matchAnyCurrencySet(CMParms.combine(V,1)); if(currency!=null) { if(mine instanceof MOB) { final List<Coins> V2=CMLib.beanCounter().getStandardCurrency((MOB)mine,currency); final double denomination=matchAnyDenomination(currency,CMParms.combine(V,1)); Coins C=null; for(int v2=0;v2<V2.size();v2++) { C=V2.get(v2); if(C.getDenomination()==denomination) return C.getNumberOfCoins(); } } return 1; } } else if((!V.isEmpty())&&(matchAnyCurrencySet(CMParms.combine(V,0))!=null)) return 1; return 0; } @Override public String parseNumPossibleGoldCurrency(final Environmental mine, String moneyStr) { if(moneyStr.toUpperCase().trim().startsWith("A PILE OF ")) moneyStr=moneyStr.substring(10); if(CMath.isInteger(moneyStr)) { final long num=CMath.s_long(moneyStr); if(mine instanceof MOB) { List<Coins> V=CMLib.beanCounter().getStandardCurrency((MOB)mine,CMLib.beanCounter().getCurrency(mine)); for(int v=0;v<V.size();v++) { if(V.get(v).getNumberOfCoins()>=num) return V.get(v).getCurrency(); } V=CMLib.beanCounter().getStandardCurrency((MOB)mine,null); for(int v=0;v<V.size();v++) { if(V.get(v).getNumberOfCoins()>=num) return V.get(v).getCurrency(); } } return CMLib.beanCounter().getCurrency(mine); } final Vector<String> V=CMParms.parse(moneyStr); if((V.size()>1)&&(CMath.isInteger(V.firstElement()))) return matchAnyCurrencySet(CMParms.combine(V,1)); else if((V.size()>1)&&(V.firstElement().equalsIgnoreCase("all"))) return matchAnyCurrencySet(CMParms.combine(V,1)); else if(!V.isEmpty()) return matchAnyCurrencySet(CMParms.combine(V,0)); return CMLib.beanCounter().getCurrency(mine); } @Override public long getMillisMultiplierByName(String timeName) { timeName=timeName.toLowerCase(); if("ticks".startsWith(timeName)) return CMProps.getTickMillis(); else if("seconds".startsWith(timeName)) return 1000; else if("minutes".startsWith(timeName)) return 1000*60; else if("hours".startsWith(timeName)) return 1000*60*60; else if("days".startsWith(timeName)) return 1000*60*60*24; else if("weeks".startsWith(timeName)) return 1000*60*60*24*7; else return -1; } @Override public double parseNumPossibleGoldDenomination(final Environmental mine, final String currency, String moneyStr) { if(moneyStr.toUpperCase().trim().startsWith("A PILE OF ")) moneyStr=moneyStr.substring(10); if(CMath.isInteger(moneyStr)) { final long num=CMath.s_long(moneyStr); if(mine instanceof MOB) { final List<Coins> V=CMLib.beanCounter().getStandardCurrency((MOB)mine,currency); for(int v=0;v<V.size();v++) { if(V.get(v).getNumberOfCoins()>=num) return V.get(v).getDenomination(); } } return CMLib.beanCounter().getLowestDenomination(currency); } final Vector<String> V=CMParms.parse(moneyStr); if((V.size()>1)&&(CMath.isInteger(V.firstElement()))) return matchAnyDenomination(currency,CMParms.combine(V,1)); else if((V.size()>1)&&(V.firstElement().equalsIgnoreCase("all"))) return matchAnyDenomination(currency,CMParms.combine(V,1)); else if(!V.isEmpty()) return matchAnyDenomination(currency,CMParms.combine(V,0)); return 0; } @Override public String matchAnyCurrencySet(final String moneyStr) { final List<String> V=CMLib.beanCounter().getAllCurrencies(); List<String> V2=null; for(int v=0;v<V.size();v++) { V2=CMLib.beanCounter().getDenominationNameSet(V.get(v)); for(int v2=0;v2<V2.size();v2++) { String s=V2.get(v2); if(s.toLowerCase().endsWith("(s)")) s=s.substring(0,s.length()-3)+"s"; if(containsString(s,moneyStr)) return V.get(v); } } return null; } @Override public double matchAnyDenomination(final String currency, String moneyStr) { if(currency == null) { for(final String curr : CMLib.beanCounter().getAllCurrencies()) { final MoneyLibrary.MoneyDenomination[] DV=CMLib.beanCounter().getCurrencySet(curr); moneyStr=moneyStr.toUpperCase(); String s=null; if(DV!=null) { for (final MoneyDenomination element : DV) { s=element.name().toUpperCase(); if(s.endsWith("(S)")) s=s.substring(0,s.length()-3)+"S"; if(containsString(s,moneyStr)) return element.value(); else if((s.length()>0) &&(containsString(s,moneyStr))) return element.value(); } } } } else { final MoneyLibrary.MoneyDenomination[] DV=CMLib.beanCounter().getCurrencySet(currency); moneyStr=moneyStr.toUpperCase(); String s=null; if(DV!=null) { for (final MoneyDenomination element : DV) { s=element.name().toUpperCase(); if(s.endsWith("(S)")) s=s.substring(0,s.length()-3)+"S"; if(containsString(s,moneyStr)) return element.value(); else if((s.length()>0) &&(containsString(s,moneyStr))) return element.value(); } } } return 0.0; } @Override public Item parsePossibleRoomGold(final MOB seer, final Room room, final Container container, String moneyStr) { if(moneyStr.toUpperCase().trim().startsWith("A PILE OF ")) moneyStr=moneyStr.substring(10); long gold=0; if(CMath.isInteger(moneyStr)) { gold=CMath.s_long(moneyStr); moneyStr=""; } else { final Vector<String> V=CMParms.parse(moneyStr); if((V.size()>1)&&(CMath.isInteger(V.firstElement()))) gold=CMath.s_long(V.firstElement()); else return null; moneyStr=CMParms.combine(V,1); } if(gold>0) { for(int i=0;i<room.numItems();i++) { final Item I=room.getItem(i); if((I.container()==container) &&(I instanceof Coins) &&(CMLib.flags().canBeSeenBy(I,seer)) &&((moneyStr.length()==0)||(containsString(I.name(),moneyStr)))) { if(((Coins)I).getNumberOfCoins()<=gold) return I; ((Coins)I).setNumberOfCoins(((Coins)I).getNumberOfCoins()-gold); final Coins C=(Coins)CMClass.getItem("StdCoins"); C.setCurrency(((Coins)I).getCurrency()); C.setNumberOfCoins(gold); C.setDenomination(((Coins)I).getDenomination()); C.setContainer(container); C.recoverPhyStats(); room.addItem(C); C.setExpirationDate(I.expirationDate()); return C; } } } return null; } @Override public Item parseBestPossibleGold(final MOB mob, final Container container, String itemID) { if(itemID.toUpperCase().trim().startsWith("A PILE OF ")) itemID=itemID.substring(10); long gold=0; double denomination=0.0; String currency=CMLib.beanCounter().getCurrency(mob); if(CMath.isInteger(itemID)) { gold=CMath.s_long(itemID); //final double totalAmount=CMLib.beanCounter().getTotalAbsoluteValue(mob,currency); double bestDenomination=CMLib.beanCounter().getBestDenomination(currency,(int)gold,gold); if(bestDenomination==0.0) { bestDenomination=CMLib.beanCounter().getBestDenomination(null,(int)gold,gold); if(bestDenomination>0.0) currency=null; } if(bestDenomination==0.0) return null; denomination=bestDenomination; } else { final Vector<String> V=CMParms.parse(itemID); if(V.size()<1) return null; if((!CMath.isInteger(V.firstElement())) &&(!V.firstElement().equalsIgnoreCase("all"))) V.insertElementAt("1",0); final Item I=mob.findItem(container,CMParms.combine(V,1)); if(I instanceof Coins) { if(V.firstElement().equalsIgnoreCase("all")) gold=((Coins)I).getNumberOfCoins(); else gold=CMath.s_long(V.firstElement()); currency=((Coins)I).getCurrency(); denomination=((Coins)I).getDenomination(); } else return null; } if(gold>0) { final double amt = CMLib.beanCounter().getTotalAbsoluteValue(mob, currency); if(amt>=CMath.mul(denomination,gold)) { final double expectedAmt = amt - CMath.mul(denomination,gold); CMLib.beanCounter().subtractMoney(mob,currency,denomination,CMath.mul(denomination,gold)); final double newAmt = CMLib.beanCounter().getTotalAbsoluteValue(mob, currency); if(newAmt > expectedAmt) CMLib.beanCounter().subtractMoney(mob,currency,(newAmt - expectedAmt)); final Coins C=(Coins)CMClass.getItem("StdCoins"); C.setCurrency(currency); C.setDenomination(denomination); C.setNumberOfCoins(gold); C.recoverPhyStats(); mob.addItem(C); return C; } mob.tell(L("You don't have that much @x1.",CMLib.beanCounter().getDenominationName(currency,denomination))); final List<Coins> V=CMLib.beanCounter().getStandardCurrency(mob,currency); for(int v=0;v<V.size();v++) { if(V.get(v).getDenomination()==denomination) return V.get(v); } } return null; } @Override public List<Container> parsePossibleContainers(final MOB mob, final List<String> commands, final Filterer<Environmental> filter, final boolean withContentOnly) { final Vector<Container> V=new Vector<Container>(1); if(commands.size()==1) return V; int fromDex=-1; int containerDex=commands.size()-1; for(int i=commands.size()-2;i>0;i--) { if(commands.get(i).equalsIgnoreCase("from")) { fromDex=i; containerDex=i+1; if(((containerDex+1)<commands.size()) &&((commands.get(containerDex).equalsIgnoreCase("all")) ||(CMath.s_int(commands.get(containerDex))>0))) containerDex++; break; } } String possibleContainerID=CMParms.combine(commands,containerDex); boolean allFlag=false; String preWord=""; if(possibleContainerID.equalsIgnoreCase("all")) allFlag=true; else if(containerDex>1) preWord=commands.get(containerDex-1); int maxContained=Integer.MAX_VALUE; if(CMath.s_int(preWord)>0) { maxContained=CMath.s_int(preWord); commands.set(containerDex-1,"all"); containerDex--; preWord="all"; } if (preWord.equalsIgnoreCase("all")) { allFlag = true; possibleContainerID = "ALL " + possibleContainerID; } else if (possibleContainerID.toUpperCase().startsWith("ALL.")) { allFlag = true; possibleContainerID = "ALL " + possibleContainerID.substring(4); } else if (possibleContainerID.toUpperCase().endsWith(".ALL")) { allFlag = true; possibleContainerID = "ALL " + possibleContainerID.substring(0, possibleContainerID.length() - 4); } int addendum=1; String addendumStr=""; boolean doBugFix = true; while(doBugFix || ((allFlag)&&(addendum<=maxContained))) { doBugFix=false; final Environmental E=mob.location().fetchFromMOBRoomFavorsItems(mob,null,possibleContainerID+addendumStr,filter); if((E!=null) &&(E instanceof Item) &&(((Item)E) instanceof Container) &&((!withContentOnly)||(((Container)E).hasContent())) &&(CMLib.flags().canBeSeenBy(E,mob)||mob.isMine(E))) { V.addElement((Container)E); if(V.size()==1) { while((fromDex>=0)&&(commands.size()>fromDex)) commands.remove(fromDex); while(commands.size()>containerDex) commands.remove(containerDex); preWord=""; } } if(E==null) return V; addendumStr="."+(++addendum); } return V; } @Override public Item parsePossibleContainer(final MOB mob, final List<String> commands, final boolean withStuff, final Filterer<Environmental> filter) { if(commands.size()==1) return null; final Room R=(mob==null)?null:mob.location(); if(R==null) return null; int fromDex=-1; int containerDex=commands.size()-1; for(int i=commands.size()-2;i>=1;i--) { if(commands.get(i).equalsIgnoreCase("from") || commands.get(i).equalsIgnoreCase("in")|| commands.get(i).equalsIgnoreCase("on")) { fromDex=i; containerDex=i+1; break; } } final String possibleContainerID=CMParms.combine(commands,containerDex); Environmental E=R.fetchFromMOBRoomFavorsItems(mob,null,possibleContainerID,filter); if(E==null) { final CMFlagLibrary flagLib=CMLib.flags(); for(int i=0;i<R.numItems();i++) { final Item I=R.getItem(i); if(flagLib.isOpenAccessibleContainer(I)) { E=R.fetchFromMOBRoomFavorsItems(mob,I,possibleContainerID,filter); if(E instanceof Container) break; } } } if((E!=null) &&(E instanceof Item) &&(((Item)E) instanceof Container) &&((!withStuff)||(((Container)E).hasContent()))) { while((fromDex>=0)&&(commands.size()>fromDex)) commands.remove(fromDex); while(commands.size()>containerDex) commands.remove(containerDex); return (Item)E; } return null; } @Override public String stringifyElapsedTimeOrTicks(long millis, final long ticks) { String avg=""; if(ticks>0) avg=", Average="+(millis/ticks)+"ms"; if(millis<1000) return millis+"ms"+avg; long seconds=millis/1000; millis-=(seconds*1000); if(seconds<60) return seconds+"s "+millis+"ms"+avg; long minutes=seconds/60; seconds-=(minutes*60); if(minutes<60) return minutes+"m "+seconds+"s "+millis+"ms"+avg; long hours=minutes/60; minutes-=(hours*60); if(hours<24) return hours+"h "+minutes+"m "+seconds+"s "+millis+"ms"+avg; final long days=hours/24; hours-=(days*24); return days+"d "+hours+"h "+minutes+"m "+seconds+"s "+millis+"ms"+avg; } @Override public Triad<String, Double, Long> parseMoneyStringSDL(final MOB mob, final String moneyStr, String correctCurrency) { double b=0; String myCurrency=CMLib.beanCounter().getCurrency(mob); double denomination=1.0; if(correctCurrency==null) correctCurrency=myCurrency; if(moneyStr.length()>0) { myCurrency=parseNumPossibleGoldCurrency(mob,moneyStr); if(myCurrency!=null) { denomination=parseNumPossibleGoldDenomination(null,correctCurrency,moneyStr); final long num=parseNumPossibleGold(null,moneyStr); b=CMath.mul(denomination,num); } else myCurrency=CMLib.beanCounter().getCurrency(mob); } if((denomination == 0)||(b == 0)) return null; return new Triad<String,Double,Long>(myCurrency,Double.valueOf(denomination),Long.valueOf(Math.round(b/denomination))); } @Override public int parseMaxToGive(final MOB mob, final List<String> commands, final boolean breakPackages, final Environmental checkWhat, final boolean getOnly) { int maxToGive=Integer.MAX_VALUE; if((commands.size()>1) &&(parseNumPossibleGold(mob,CMParms.combine(commands,0))==0)) { if(CMath.s_int(commands.get(0))>0) { maxToGive=CMath.s_int(commands.get(0)); commands.set(0,"all"); if(breakPackages) { boolean throwError=false; if((commands.size()>2)&&("FROM".startsWith(commands.get(1).toUpperCase()))) { throwError=true; commands.remove(1); } final String packCheckName=CMParms.combine(commands,1); Environmental fromWhat=null; if(checkWhat instanceof MOB) fromWhat=mob.findItem(null,packCheckName); else if(checkWhat instanceof Room) fromWhat=((Room)checkWhat).fetchFromMOBRoomFavorsItems(mob,null,packCheckName,Wearable.FILTER_UNWORNONLY); if(fromWhat instanceof Item) { int max=mob.maxCarry(); if(max>3000) max=3000; if(maxToGive>max) { CMLib.commands().postCommandFail(mob,new XVector<String>(commands),L("You can only handle @x1 at a time.",""+max)); return -1; } final Environmental toWhat=CMLib.materials().unbundle((Item)fromWhat,maxToGive,null); if(toWhat==null) { if(throwError) { CMLib.commands().postCommandFail(mob,new XVector<String>(commands),L("You can't get anything from @x1.",fromWhat.name())); return -1; } } else if(getOnly&&mob.isMine(fromWhat)&&mob.isMine(toWhat)) { mob.tell(L("Ok")); return -1; } else if(commands.size()==1) commands.add(toWhat.name()); else { final String O=commands.get(0); commands.clear(); commands.add(O); commands.add(toWhat.name()); } } else if(throwError) { CMLib.commands().postCommandFail(mob,new XVector<String>(commands),L("You don't see '@x1' here.",packCheckName)); return -1; } } } else if(!CMath.isInteger(commands.get(0))) { final int x = CMParms.indexOfIgnoreCase(commands,"FROM"); if((x>0)&&(x<commands.size()-1)) { final String packCheckName=CMParms.combine(commands,x+1); final String getName = CMParms.combine(commands,0,x); Environmental fromWhat=null; if(checkWhat instanceof MOB) fromWhat=mob.findItem(null,packCheckName); else if(checkWhat instanceof Room) fromWhat=((Room)checkWhat).fetchFromMOBRoomFavorsItems(mob,null,packCheckName,Wearable.FILTER_UNWORNONLY); if(fromWhat instanceof Item) { final Environmental toWhat=CMLib.materials().unbundle((Item)fromWhat,1,null); if((toWhat==null) ||((!containsString(toWhat.name(), getName)) &&(!containsString(toWhat.displayText(), getName)))) { return maxToGive; } else if(getOnly&&mob.isMine(fromWhat)&&mob.isMine(toWhat)) { mob.tell(L("Ok")); return -1; } else { maxToGive = 1; commands.clear(); commands.add(toWhat.name()); } } } } } return maxToGive; } @Override public int probabilityOfBeingEnglish(final String str) { if(str.length()<100) return 100; final double[] englishFreq = new double[]{ 0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015, // A-G 0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749, // H-N 0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758, // O-U 0.00978, 0.02360, 0.00150, 0.01974, 0.00074 // V-Z }; double punctuationCount=0; double wordCount=0; double totalLetters=0; double thisLetterCount=0; final int[] lettersUsed = new int[26]; final double len=str.length(); for(int i=0;i<str.length();i++) { final char c=str.charAt(i); if(Character.isLetter(c)) { thisLetterCount+=1; lettersUsed[Character.toLowerCase(c)-'a']++; } else if((c==' ')||(isPunctuation((byte)c))) { if(thisLetterCount>0) { totalLetters+=thisLetterCount; wordCount+=1.0; thisLetterCount=0; } if(c!=' ') punctuationCount++; } else punctuationCount++; } if(thisLetterCount>0) { totalLetters+=thisLetterCount; wordCount+=1.0; thisLetterCount=0; } final double pctPunctuation=punctuationCount/len; if(pctPunctuation > .2) return 0; final double avgWordSize=totalLetters/wordCount; if((avgWordSize < 2.0)||(avgWordSize > 8.0)) return 0; double wordCountChi=avgWordSize-4.7; wordCountChi=(wordCountChi*wordCountChi)/4.7; double chi2=10.0*wordCountChi; for (int i = 0; i < 26; i++) { final double observed = lettersUsed[i]; final double expected = totalLetters * englishFreq[i]; final double difference = observed - expected; chi2 += (difference*difference) / expected / 26.0; } final int finalChance=(int)Math.round(100.0 - chi2); if(finalChance<0) return 0; if(finalChance>100) return 100; return finalChance; } protected static class FetchFlags { public String srchStr; public int occurrance; public boolean allFlag; public FetchFlags(final String ss, final int oc, final boolean af) { srchStr = ss; occurrance = oc; allFlag = af; } } public FetchFlags fetchFlags(String srchStr) { if(srchStr.length()==0) return null; srchStr=srchStr.toUpperCase(); if((srchStr.length()<2)||(srchStr.equals("THE"))) return null; boolean allFlag=false; if(srchStr.startsWith("ALL ")) { srchStr=srchStr.substring(4); allFlag=true; } else if(srchStr.equals("ALL")) allFlag=true; int dot=srchStr.lastIndexOf('.'); int occurrance=0; if(dot>0) { String sub=srchStr.substring(dot+1); occurrance=CMath.s_int(sub); if(occurrance>0) srchStr=srchStr.substring(0,dot); else { dot=srchStr.indexOf('.'); sub=srchStr.substring(0,dot); occurrance=CMath.s_int(sub); if(occurrance>0) srchStr=srchStr.substring(dot+1); else occurrance=0; } } return new FetchFlags(srchStr,occurrance,allFlag); } protected String cleanExtraneousDollarMarkers(final String srchStr) { if(srchStr.startsWith("$")) { if(srchStr.endsWith("$")&&(srchStr.length()>1)) return srchStr.substring(1,srchStr.length()-1); else return srchStr.substring(1); } else if(srchStr.endsWith("$")) return srchStr.substring(0,srchStr.length()-1); return srchStr; } @Override public Environmental fetchEnvironmental(final Iterable<? extends Environmental> list, String srchStr, final boolean exactOnly) { final FetchFlags flags=fetchFlags(srchStr); if(flags==null) return null; srchStr=flags.srchStr; int myOccurrance=flags.occurrance; final boolean allFlag=flags.allFlag; try { if(exactOnly) { srchStr=cleanExtraneousDollarMarkers(srchStr); for (final Environmental E : list) { if(E!=null) { if(E.ID().equalsIgnoreCase(srchStr) ||E.name().equalsIgnoreCase(srchStr) ||E.Name().equalsIgnoreCase(srchStr)) { if((!allFlag)||(E instanceof Ability)||((E.displayText()!=null)&&(E.displayText().length()>0))) { if((--myOccurrance)<=0) return E; } } } } } else { myOccurrance=flags.occurrance; for (final Environmental E : list) { if((E!=null) &&(containsString(E.name(),srchStr)||containsString(E.Name(),srchStr)) &&((!allFlag)||(E instanceof Ability)||((E.displayText()!=null)&&(E.displayText().length()>0)))) { if((--myOccurrance)<=0) return E; } } myOccurrance=flags.occurrance; for (final Environmental E : list) { if((E!=null) &&(!(E instanceof Ability)) &&(containsString(E.displayText(),srchStr) ||((E instanceof MOB)&&containsString(((MOB)E).genericName(),srchStr)))) { if((--myOccurrance)<=0) return E; } } } } catch (final java.lang.ArrayIndexOutOfBoundsException x) { } return null; } @Override public Exit fetchExit(final Iterable<? extends Environmental> list, String srchStr, final boolean exactOnly) { final FetchFlags flags=fetchFlags(srchStr); if(flags==null) return null; srchStr=flags.srchStr; int myOccurrance=flags.occurrance; final boolean allFlag=flags.allFlag; try { if(exactOnly) { srchStr=cleanExtraneousDollarMarkers(srchStr); for (final Environmental E : list) { if(E instanceof Exit) { if(E.ID().equalsIgnoreCase(srchStr) ||E.name().equalsIgnoreCase(srchStr) ||E.Name().equalsIgnoreCase(srchStr) ||((Exit)E).doorName().equalsIgnoreCase(srchStr) ||((Exit)E).closedText().equalsIgnoreCase(srchStr)) { if((!allFlag)||((E.displayText()!=null)&&(E.displayText().length()>0))) { if((--myOccurrance)<=0) return (Exit)E; } } } } } else { myOccurrance=flags.occurrance; for (final Environmental E : list) { if((E instanceof Exit) &&(containsString(E.name(),srchStr) ||containsString(E.Name(),srchStr) ||containsString(((Exit)E).doorName(),srchStr) ||containsString(((Exit)E).closedText(),srchStr)) &&((!allFlag)||((E.displayText()!=null)&&(E.displayText().length()>0)))) { if((--myOccurrance)<=0) return (Exit)E; } } myOccurrance=flags.occurrance; for (final Environmental E : list) { if((E instanceof Exit) &&(containsString(E.displayText(),srchStr))) { if((--myOccurrance)<=0) return (Exit)E; } } } } catch (final java.lang.ArrayIndexOutOfBoundsException x) { } return null; } @Override public Environmental fetchEnvironmental(final Iterator<? extends Environmental> iter, String srchStr, final boolean exactOnly) { final FetchFlags flags=fetchFlags(srchStr); if(flags==null) return null; srchStr=flags.srchStr; int myOccurrance=flags.occurrance; final boolean allFlag=flags.allFlag; try { if(exactOnly) { srchStr=cleanExtraneousDollarMarkers(srchStr); for (;iter.hasNext();) { final Environmental E=iter.next(); if(E!=null) { if(E.ID().equalsIgnoreCase(srchStr) ||E.name().equalsIgnoreCase(srchStr) ||E.Name().equalsIgnoreCase(srchStr)) { if((!allFlag) ||(E instanceof Ability) ||((E.displayText()!=null)&&(E.displayText().length()>0))) { if((--myOccurrance)<=0) return E; } } } } } else { myOccurrance=flags.occurrance; for (;iter.hasNext();) { final Environmental E=iter.next(); if((E!=null) &&(containsString(E.name(),srchStr) ||containsString(E.Name(),srchStr) ||containsString(E.displayText(),srchStr) ||((E instanceof MOB)&&containsString(((MOB)E).genericName(),srchStr))) &&((!allFlag) ||(E instanceof Ability) ||((E.displayText()!=null)&&(E.displayText().length()>0)))) { if((--myOccurrance)<=0) return E; } } } } catch (final java.lang.ArrayIndexOutOfBoundsException x) { } return null; } @Override public Environmental fetchEnvironmental(final Enumeration<? extends Environmental> iter, String srchStr, final boolean exactOnly) { final FetchFlags flags=fetchFlags(srchStr); if(flags==null) return null; srchStr=flags.srchStr; int myOccurrance=flags.occurrance; final boolean allFlag=flags.allFlag; try { if(exactOnly) { srchStr=cleanExtraneousDollarMarkers(srchStr); for (;iter.hasMoreElements();) { final Environmental E=iter.nextElement(); if(E!=null) { if(E.ID().equalsIgnoreCase(srchStr) ||E.name().equalsIgnoreCase(srchStr) ||E.Name().equalsIgnoreCase(srchStr)) { if((!allFlag)||(E instanceof Ability)||((E.displayText()!=null)&&(E.displayText().length()>0))) { if((--myOccurrance)<=0) return E; } } } } } else { myOccurrance=flags.occurrance; for (;iter.hasMoreElements();) { final Environmental E=iter.nextElement(); if((E!=null) &&(containsString(E.name(),srchStr) ||containsString(E.Name(),srchStr) ||containsString(E.displayText(),srchStr) ||((E instanceof MOB)&&containsString(((MOB)E).genericName(),srchStr))) &&((!allFlag) ||(E instanceof Ability) ||((E.displayText()!=null)&&(E.displayText().length()>0)))) { if((--myOccurrance)<=0) return E; } } } } catch (final java.lang.ArrayIndexOutOfBoundsException x) { } return null; } @Override public List<Environmental> fetchEnvironmentals(final List<? extends Environmental> list, String srchStr, final boolean exactOnly) { final Vector<Environmental> matches=new Vector<Environmental>(1); if(list.isEmpty()) return matches; final FetchFlags flags=fetchFlags(srchStr); if(flags==null) return matches; srchStr=flags.srchStr; int myOccurrance=flags.occurrance; final boolean allFlag=flags.allFlag; try { if(exactOnly) { srchStr=cleanExtraneousDollarMarkers(srchStr); for (final Environmental E : list) { if(E!=null) { if(E.ID().equalsIgnoreCase(srchStr) ||E.name().equalsIgnoreCase(srchStr) ||E.Name().equalsIgnoreCase(srchStr)) { if((!allFlag)||(E instanceof Ability)||((E.displayText()!=null)&&(E.displayText().length()>0))) { if((--myOccurrance)<=0) matches.addElement(E); } } } } } else { myOccurrance=flags.occurrance; for (final Environmental E : list) { if((E!=null) &&(containsString(E.name(),srchStr)||containsString(E.Name(),srchStr)) &&((!allFlag)||(E instanceof Ability)||((E.displayText()!=null)&&(E.displayText().length()>0)))) { if((--myOccurrance)<=0) matches.addElement(E); } } if(matches.isEmpty()) { myOccurrance=flags.occurrance; for (final Environmental E : list) { if((E!=null) &&(!(E instanceof Ability)) &&(containsString(E.displayText(),srchStr) ||((E instanceof MOB)&&containsString(((MOB)E).genericName(),srchStr)))) { if((--myOccurrance)<=0) matches.addElement(E); } } } } } catch (final java.lang.ArrayIndexOutOfBoundsException x) { } return matches; } @Override public Environmental fetchEnvironmental(final Map<String, ? extends Environmental> list, String srchStr, final boolean exactOnly) { if(list.isEmpty()) return null; final FetchFlags flags=fetchFlags(srchStr); if(flags==null) return null; srchStr=flags.srchStr; int myOccurrance=flags.occurrance; final boolean allFlag=flags.allFlag; if(list.get(srchStr)!=null) return list.get(srchStr); Environmental E=null; if(exactOnly) { srchStr=cleanExtraneousDollarMarkers(srchStr); for (final String string : list.keySet()) { E=list.get(string); if(E!=null) { if(E.ID().equalsIgnoreCase(srchStr) ||E.Name().equalsIgnoreCase(srchStr) ||E.name().equalsIgnoreCase(srchStr)) { if((!allFlag)||(E instanceof Ability)||((E.displayText()!=null)&&(E.displayText().length()>0))) { if((--myOccurrance)<=0) return E; } } } } } else { myOccurrance=flags.occurrance; for (final String string : list.keySet()) { E=list.get(string); if((E!=null) &&(containsString(E.name(),srchStr)||containsString(E.Name(),srchStr)) &&((!allFlag)||(E instanceof Ability)||((E.displayText()!=null)&&(E.displayText().length()>0)))) { if((--myOccurrance)<=0) return E; } } myOccurrance=flags.occurrance; for (final String string : list.keySet()) { E=list.get(string); if(E!=null) { if((containsString(E.displayText(),srchStr)) ||((E instanceof MOB) && containsString(((MOB)E).genericName(),srchStr))) { if((--myOccurrance)<=0) return E; } } } } return null; } @Override public Item fetchAvailableItem(final List<Item> list, String srchStr, final Item goodLocation, final Filterer<Environmental> filter, final boolean exactOnly) { if(list.isEmpty()) return null; final FetchFlags flags=fetchFlags(srchStr); if(flags==null) return null; srchStr=flags.srchStr; int myOccurrance=flags.occurrance; final boolean allFlag=flags.allFlag; if(exactOnly) { try { srchStr=cleanExtraneousDollarMarkers(srchStr); for (final Item I : list) { if(I==null) continue; if((I.container()==goodLocation) &&(filter.passesFilter(I)) &&(I.ID().equalsIgnoreCase(srchStr) ||(I.Name().equalsIgnoreCase(srchStr)) ||(I.name().equalsIgnoreCase(srchStr)))) { if((!allFlag) ||((I.displayText()!=null)&&(I.displayText().length()>0))) { if((--myOccurrance)<=0) return I; } } } } catch (final java.lang.ArrayIndexOutOfBoundsException x) { } } else { try { for (final Item I : list) { if((I!=null) &&(I.container()==goodLocation) &&(filter.passesFilter(I)) &&(containsString(I.name(),srchStr)||containsString(I.Name(),srchStr)) &&((!allFlag) ||((I.displayText()!=null)&&(I.displayText().length()>0)))) { if((--myOccurrance)<=0) return I; } } } catch (final java.lang.ArrayIndexOutOfBoundsException x) { } myOccurrance=flags.occurrance; try { for (final Item I : list) { if((I!=null) &&(I.container()==goodLocation) &&(filter.passesFilter(I)) &&(containsString(I.displayText(),srchStr))) { if((--myOccurrance)<=0) return I; } } } catch (final java.lang.ArrayIndexOutOfBoundsException x) { } } return null; } @Override public List<Item> fetchAvailableItems(final List<Item> list, String srchStr, final Item goodLocation, final Filterer<Environmental> filter, final boolean exactOnly) { final Vector<Item> matches=new Vector<Item>(1); // return value if(list.isEmpty()) return matches; final FetchFlags flags=fetchFlags(srchStr); if(flags==null) return matches; srchStr=flags.srchStr; int myOccurrance=flags.occurrance; final boolean allFlag=flags.allFlag; try { if(exactOnly) { srchStr=cleanExtraneousDollarMarkers(srchStr); for (final Item I : list) { if(I==null) continue; if((I.container()==goodLocation) &&(filter.passesFilter(I)) &&(I.ID().equalsIgnoreCase(srchStr) ||(I.Name().equalsIgnoreCase(srchStr)) ||(I.name().equalsIgnoreCase(srchStr)))) { if((!allFlag)||((I.displayText()!=null)&&(I.displayText().length()>0))) { if((--myOccurrance)<=0) matches.addElement(I); } } } } else { for (final Item I : list) { if(I==null) continue; if((I.container()==goodLocation) &&(filter.passesFilter(I)) &&(containsString(I.name(),srchStr)||containsString(I.Name(),srchStr)) &&((!allFlag)||((I.displayText()!=null)&&(I.displayText().length()>0)))) { if((--myOccurrance)<=0) matches.addElement(I); } } if(matches.isEmpty()) { myOccurrance=flags.occurrance; for (final Item I : list) { if(I==null) continue; if((I.container()==goodLocation) &&(filter.passesFilter(I)) &&(containsString(I.displayText(),srchStr))) { if((--myOccurrance)<=0) matches.addElement(I); } } } } } catch (final java.lang.ArrayIndexOutOfBoundsException x) { } return matches; } @Override public Environmental fetchAvailable(final Collection<? extends Environmental> list, String srchStr, final Item goodLocation, final Filterer<Environmental> filter, final boolean exactOnly, final int[] counterSlap) { if(list.isEmpty()) return null; final FetchFlags flags=fetchFlags(srchStr); if(flags==null) return null; srchStr=flags.srchStr; int myOccurrance=flags.occurrance - counterSlap[0]; final boolean allFlag=flags.allFlag; Item I=null; try { if(exactOnly) { srchStr=cleanExtraneousDollarMarkers(srchStr); for (final Environmental E : list) { if(E instanceof Item) { I=(Item)E; if((I.container()==goodLocation) &&(filter.passesFilter(I)) &&(I.ID().equalsIgnoreCase(srchStr) ||(I.Name().equalsIgnoreCase(srchStr)) ||(I.name().equalsIgnoreCase(srchStr)))) { if((!allFlag)||(E instanceof Ability)||((I.displayText()!=null)&&(I.displayText().length()>0))) { if((--myOccurrance)<=0) return I; } } } else if(E!=null) { if(E.ID().equalsIgnoreCase(srchStr) ||E.Name().equalsIgnoreCase(srchStr) ||E.name().equalsIgnoreCase(srchStr)) { if((!allFlag)||(E instanceof Ability)||((E.displayText()!=null)&&(E.displayText().length()>0))) { if((--myOccurrance)<=0) return E; } } } } } else { for (final Environmental E : list) { if(E instanceof Item) { I=(Item)E; if((I.container()==goodLocation) &&(filter.passesFilter(I)) &&(containsString(I.name(),srchStr)||containsString(I.Name(),srchStr)) &&((!allFlag)||(E instanceof Ability)||((I.displayText()!=null)&&(I.displayText().length()>0)))) { if((--myOccurrance)<=0) return I; } } else if((E!=null) &&(containsString(E.name(),srchStr)||containsString(E.Name(),srchStr)) &&((!allFlag)||(E instanceof Ability)||((E.displayText()!=null)&&(E.displayText().length()>0)))) { if((--myOccurrance)<=0) return E; } } myOccurrance=flags.occurrance - counterSlap[0]; for (final Environmental E : list) { if(E instanceof Item) { I=(Item)E; if((I.container()==goodLocation) &&(filter.passesFilter(I)) &&(containsString(I.displayText(),srchStr))) { if((--myOccurrance)<=0) return I; } } else if(E!=null) { if((containsString(E.displayText(),srchStr)) ||((E instanceof MOB)&&containsString(((MOB)E).genericName(),srchStr))) { if((--myOccurrance)<=0) return E; } } } } } catch (final java.lang.ArrayIndexOutOfBoundsException x) { } counterSlap[0]+=(flags.occurrance-myOccurrance); return null; } @Override public Environmental fetchAvailable(final Collection<? extends Environmental> list, String srchStr, final Item goodLocation, final Filterer<Environmental> filter, final boolean exactOnly) { if(list.isEmpty()) return null; final FetchFlags flags=fetchFlags(srchStr); if(flags==null) return null; srchStr=flags.srchStr; int myOccurrance=flags.occurrance; final boolean allFlag=flags.allFlag; Item I=null; try { if(exactOnly) { srchStr=cleanExtraneousDollarMarkers(srchStr); for (final Environmental E : list) { if(E instanceof Item) { I=(Item)E; if((I.container()==goodLocation) &&(filter.passesFilter(I)) &&(I.ID().equalsIgnoreCase(srchStr) ||(I.Name().equalsIgnoreCase(srchStr)) ||(I.name().equalsIgnoreCase(srchStr)))) { if((!allFlag)||(E instanceof Ability)||((I.displayText()!=null)&&(I.displayText().length()>0))) { if((--myOccurrance)<=0) return I; } } } else if(E!=null) { if(E.ID().equalsIgnoreCase(srchStr) ||E.Name().equalsIgnoreCase(srchStr) ||E.name().equalsIgnoreCase(srchStr)) { if((!allFlag) ||(E instanceof Ability) ||((E.displayText()!=null)&&(E.displayText().length()>0))) { if((--myOccurrance)<=0) return E; } } } } } else { for (final Environmental E : list) { if(E instanceof Item) { I=(Item)E; if((I.container()==goodLocation) &&(filter.passesFilter(I)) &&(containsString(I.name(),srchStr)||containsString(I.Name(),srchStr)) &&((!allFlag)||(E instanceof Ability)||((I.displayText()!=null)&&(I.displayText().length()>0)))) { if((--myOccurrance)<=0) return I; } } else if((E!=null) &&(containsString(E.name(),srchStr)||containsString(E.Name(),srchStr)) &&((!allFlag)||(E instanceof Ability)||((E.displayText()!=null)&&(E.displayText().length()>0)))) { if((--myOccurrance)<=0) return E; } } myOccurrance=flags.occurrance; for (final Environmental E : list) { if(E instanceof Item) { I=(Item)E; if((I.container()==goodLocation) &&(filter.passesFilter(I)) &&(containsString(I.displayText(),srchStr))) { if((--myOccurrance)<=0) return I; } } else if(E!=null) { if((containsString(E.displayText(),srchStr)) ||((E instanceof MOB)&&containsString(((MOB)E).genericName(),srchStr))) { if((--myOccurrance)<=0) return E; } } } } } catch (final java.lang.ArrayIndexOutOfBoundsException x) { } return null; } }
com/planet_ink/coffee_mud/Libraries/EnglishParser.java
package com.planet_ink.coffee_mud.Libraries; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.exceptions.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.core.collections.*; import com.planet_ink.coffee_mud.Libraries.interfaces.*; import com.planet_ink.coffee_mud.Libraries.interfaces.MoneyLibrary.MoneyDenomination; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Commands.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; import java.io.IOException; import java.util.*; import java.util.regex.*; /* Copyright 2003-2019 Bo Zimmerman Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ public class EnglishParser extends StdLibrary implements EnglishParsing { @Override public String ID() { return "EnglishParser"; } private final static String[] PREPOSITIONS = { "aboard", "about", "above", "across", "after", "against", "along", "amid", "among", "anti", "around", "as", "at", "before", "behind", "below", "beneath", "beside", "besides", "between", "beyond", "but", "by", "concerning", "considering", "despite", "down", "during", "except", "excepting", "excluding", "following", "for", "from", "in", "inside", "into", "like", "minus", "near", "of", "off", "on", "onto", "opposite", "outside", "over", "past", "per", "plus", "regarding", "round", "save", "since", "than", "through", "to", "toward", "towards", "under", "underneath", "unlike", "until", "up", "upon", "versus", "via", "with", "within", "without" }; private final static String[] ARTICLES = { "a", "an", "all of", "some one", "a pair of", "a pile of", "one of", "all", "the", "some", "each" }; public static boolean[] PUNCTUATION_TABLE = null; public final static char[] ALL_CHRS = "ALL".toCharArray(); public final static String[] fwords = { "calf", "half", "knife", "life", "wife", "elf", "self", "shelf", "leaf", "sheaf", "thief", "loaf", "wolf" }; public final static String[] frwords = { "calves", "halves", "knives", "lives", "wives", "elves", "selves", "shelves", "leaves", "sheaves", "thieves", "loaves", "wolves" }; public final static String[] fnouns = { "bison", "buffalo", "carpcod", "deer", "fish", "moose", "pike", "salmon", "sheep", "shrimp", "squid", "trout", "ore" }; public final static String[] feewords1 = { "foot", "goose", "louse", "dormouse", "man", "mouse", "tooth", "woman", "ox", "child", "brother" }; public final static String[] feewords2 = { "feet", "geese", "lice", "dormice", "men", "mice", "teeth", "women", "oxen", "children", "brethren" }; public final static List<Environmental> empty = new ReadOnlyVector<Environmental>(1); @Override public String toEnglishStringList(final String[] V) { if((V==null)||(V.length==0)) { return ""; } if(V.length==1) return V[0]; final StringBuffer s=new StringBuffer(""); for(int v=0;v<V.length-1;v++) { if(v>0) s.append(", "); s.append(V[v]); } s.append(" and "); s.append(V[V.length-1]); return s.toString(); } @Override public String toEnglishStringList(final Class<? extends Enum<?>> enumer, final boolean andOr) { final Enum<?>[] V=enumer.getEnumConstants(); if((V==null)||(V.length==0)) { return ""; } if(V.length==1) return V[0].toString(); final StringBuffer s=new StringBuffer(""); for(int v=0;v<V.length-1;v++) { if(v>0) s.append(", "); s.append(V[v].toString()); } if(andOr) s.append(" and "); else s.append(" or "); s.append(V[V.length-1].toString()); return s.toString(); } @Override public String toEnglishStringList(final Collection<? extends Object> V) { if((V==null)||(V.isEmpty())) { return ""; } if(V.size()==1) return V.iterator().next().toString(); final StringBuffer s=new StringBuffer(""); for(final Iterator<? extends Object> o=V.iterator();o.hasNext();) { final Object O = o.next(); if(!o.hasNext()) { if(V.size()==2) s.append(" and "); else s.append(", and "); } else if(s.length()>0) s.append(", "); s.append(O.toString()); } return s.toString(); } @Override public String makePastTense(String word, final String defaultWord) { if(word == null) return defaultWord; word = word.trim(); if(word.length()==0) return defaultWord; final int x=word.indexOf(' '); if(x>0) word=word.substring(x+1).trim(); if(CMStrings.isVowel(word.charAt(word.length()-1))) return word+"d"; else if(!word.endsWith("ed")) return word+"ed"; else return word; } @Override public boolean isAnArticle(String s) { s=s.toLowerCase(); for (final String article : ARTICLES) { if(s.equals(article)) return true; } return false; } @Override public String makePlural(final String str) { if((str==null)||(str.length()==0)) return str; final boolean uppercase=Character.isUpperCase(str.charAt(str.length()-1)); final String lowerStr=str.toLowerCase(); if(CMStrings.contains(fnouns, lowerStr)) return str; final int x=CMParms.indexOf(feewords1, lowerStr); if(x >= 0) return uppercase ? feewords2[x].toUpperCase() : feewords2[x]; if(lowerStr.endsWith("is")) return str.substring(0,str.length()-2)+(uppercase?"ES":"es"); if(lowerStr.endsWith("s")||lowerStr.endsWith("z")||lowerStr.endsWith("x")||lowerStr.endsWith("ch")||lowerStr.endsWith("sh")) return str+(uppercase?"ES":"es"); if(lowerStr.endsWith("ay")||lowerStr.endsWith("ey")||lowerStr.endsWith("iy")||lowerStr.endsWith("oy")||lowerStr.endsWith("uy")) return str+(uppercase?"S":"s"); if(lowerStr.endsWith("y")) return str.substring(0,str.length()-1)+(uppercase?"IES":"ies"); if(CMStrings.contains(fwords, lowerStr)) return str.substring(0,str.length()-1)+(uppercase?"VES":"ves"); return str+(uppercase?"S":"s"); } @Override public String makeSingular(final String str) { if((str==null)||(str.length()==0)) return str; final boolean uppercase=Character.isUpperCase(str.charAt(str.length()-1)); final String lowerStr=str.toLowerCase(); if(lowerStr.endsWith("ses")||lowerStr.endsWith("zes")||lowerStr.endsWith("xes")||lowerStr.endsWith("ches")||lowerStr.endsWith("shes")) return str.substring(0,str.length()-2); //if(lowerStr.endsWith("is")) // return str.substring(0,str.length()-2)+(uppercase?"ES":"es"); if(lowerStr.endsWith("ays")||lowerStr.endsWith("eys")||lowerStr.endsWith("iys")||lowerStr.endsWith("oys")||lowerStr.endsWith("uys")) return str.substring(0,str.length()-1); if(lowerStr.endsWith("ies")) return str.substring(0,str.length()-3)+(uppercase?"Y":"y"); final int x=CMParms.indexOf(frwords, lowerStr); if(x>=0) return uppercase?fwords[x].toUpperCase():fwords[x]; if(str.endsWith("s")) return str.substring(0,str.length()-1); return str; } @Override public String cleanPrepositions(final String s) { final String lowStr=s.toLowerCase(); for (final String prepositino : PREPOSITIONS) { if(lowStr.startsWith(prepositino+" ")) return s.substring(prepositino.length()+1); } return s; } @Override public String properIndefiniteArticle(final String str) { int i=0; for(;i<str.length();i++) { switch(str.charAt(i)) { case '^': { i++; if(i<str.length()) { switch(str.charAt(i)) { case ColorLibrary.COLORCODE_FANSI256: i += 3; break; case ColorLibrary.COLORCODE_BANSI256: i += 3; break; case ColorLibrary.COLORCODE_BACKGROUND: i++; break; case '<': while(i<str.length()-1) { if((str.charAt(i)!='^')||(str.charAt(i+1)!='>')) i++; else { i++; break; } } break; case '&': while(i<str.length()) { if(str.charAt(i)!=';') i++; else break; } break; } } break; } case 'a': case 'e': case 'i': case 'o': case 'u': case 'A': case 'E': case 'I': case 'O': case 'U': return "an"; default: if(Character.isLetter(str.charAt(i))) return "a"; else return ""; } } return ""; } protected String getBestDistance(long d) { String min=null; final long sign=(long)Math.signum(d); d=Math.abs(d); for(final SpaceObject.Distance distance : SpaceObject.DISTANCES) { if((distance.dm * 2) < d) { double val=(double)d/(double)distance.dm; if((val<0)||(val<100)) val=Math.round(val*100.0)/100.0; else val=Math.round(val); if(val!=0.0) { String s=Double.toString(sign*val); if(s.endsWith(".0")) s=s.substring(0,s.length()-2); s+=distance.abbr; min = s; break; //if((min==null)||(min.length()>s.length())) min=s; } } } if(min==null) return (sign*d)+"dm"; return min; } @Override public String sizeDescShort(final long size) { return getBestDistance(size); } @Override public String distanceDescShort(final long distance) { return getBestDistance(distance); } @Override public String coordDescShort(final long[] coords) { return getBestDistance(coords[0])+","+getBestDistance(coords[1])+","+getBestDistance(coords[2]); } @Override public String speedDescShort(final double speed) { return getBestDistance(Math.round(speed))+"/sec"; } @Override public String directionDescShort(final double[] dir) { return Math.round(Math.toDegrees(dir[0])*100)/100.0+" mark "+Math.round(Math.toDegrees(dir[1])*100)/100.0; } @Override public String directionDescShortest(final double[] dir) { return Math.round(Math.toDegrees(dir[0])*10)/10.0+"`"+Math.round(Math.toDegrees(dir[1])*10)/10.0; } @Override public Long parseSpaceDistance(String dist) { if(dist==null) return null; dist=dist.trim(); int digits=-1; if((dist.length()>0)&&(dist.charAt(0)=='-')) digits++; while((digits<dist.length()-1)&&(Character.isDigit(dist.charAt(digits+1)))) digits++; if(digits<0) return null; final Long value=Long.valueOf(dist.substring(0,digits+1)); final String unit=dist.substring(digits+1).trim(); if(unit.length()==0) return value; SpaceObject.Distance distUnit=(SpaceObject.Distance)CMath.s_valueOf(SpaceObject.Distance.class, unit); if(distUnit==null) { for(final SpaceObject.Distance d : SpaceObject.Distance.values()) { if(d.abbr.equalsIgnoreCase(unit)) distUnit=d; } } if(distUnit==null) { for(final SpaceObject.Distance d : SpaceObject.Distance.values()) { if(d.name().equalsIgnoreCase(unit)) distUnit=d; } } if(distUnit==null) { for(final SpaceObject.Distance d : SpaceObject.Distance.values()) { if(unit.toLowerCase().startsWith(d.name().toLowerCase())) distUnit=d; } } if(distUnit==null) return null; return Long.valueOf(value.longValue() * distUnit.dm); } @Override public String getFirstWord(final String str) { int i=0; int start=-1; for(;i<str.length();i++) { switch(str.charAt(i)) { case '^': { i++; if(i<str.length()) { switch(str.charAt(i)) { case ColorLibrary.COLORCODE_FANSI256: i += 3; break; case ColorLibrary.COLORCODE_BANSI256: i += 3; break; case ColorLibrary.COLORCODE_BACKGROUND: i++; break; case '<': while(i<str.length()-1) { if((str.charAt(i)!='^')||(str.charAt(i+1)!='>')) i++; else { i++; break; } } break; case '&': while(i<str.length()) { if(str.charAt(i)!=';') i++; else break; } break; } } break; } case ' ': if(start>=0) return str.substring(start,i); break; default: if(Character.isLetter(str.charAt(i)) && (start<0)) start=i; break; } } return str; } @Override public String startWithAorAn(final String str) { if((str==null)||(str.length()==0)) return str; final String uppStr=getFirstWord(str).toUpperCase(); if((!uppStr.equals("A")) &&(!uppStr.equals("AN")) &&(!uppStr.equals("THE")) &&(!uppStr.equals("SOME"))) return (properIndefiniteArticle(str)+" "+str.trim()).trim(); return str; } @Override public boolean startsWithAnArticle(final String s) { return isAnArticle(getFirstWord(s)); } @Override public String removeArticleLead(final String s) { final String firstWord=getFirstWord(s); final int x=s.indexOf(firstWord); final String slower=(x>0) ? s.substring(x).toLowerCase() : s.toLowerCase(); for (final String article : ARTICLES) { if(slower.startsWith(article+" ")) return slower.substring(article.length()).trim(); } return s; } @Override public String insertUnColoredAdjective(String str, final String adjective) { if(str.length()==0) return str; str=CMStrings.removeColors(str.trim()); final String uppStr=str.toUpperCase(); if((uppStr.startsWith("A ")) ||(uppStr.startsWith("AN "))) return properIndefiniteArticle(adjective)+" "+adjective+" "+str.substring(2).trim(); if(uppStr.startsWith("THE ")) return properIndefiniteArticle(adjective)+" "+adjective+" "+str.substring(3).trim(); if(uppStr.startsWith("SOME ")) return properIndefiniteArticle(adjective)+" "+adjective+" "+str.substring(4).trim(); return properIndefiniteArticle(adjective)+" "+adjective+" "+str.trim(); } protected int skipSpaces(final String paragraph, int index) { while((index<paragraph.length())&&Character.isWhitespace(paragraph.charAt(index))) index++; if(index>=paragraph.length()) return -1; return index; } @Override public String insertAdjectives(final String paragraph, final String[] adjsToChoose, final int pctChance) { if((paragraph.length()==0)||(adjsToChoose==null)||(adjsToChoose.length==0)) return paragraph; final StringBuilder newParagraph = new StringBuilder(""); int startDex=skipSpaces(paragraph,0); if(startDex<0) return paragraph; newParagraph.append(paragraph.substring(0,startDex)); int spaceDex=paragraph.indexOf(' ',startDex); while(spaceDex > startDex) { final String word=paragraph.substring(startDex,spaceDex).trim(); if(isAnArticle(word) && (CMLib.dice().rollPercentage()<=pctChance)) { final String adj=adjsToChoose[CMLib.dice().roll(1, adjsToChoose.length, -1)].toLowerCase(); if(word.equalsIgnoreCase("a")||word.equalsIgnoreCase("an")) newParagraph.append(this.startWithAorAn(adj)).append(" ").append(adj); else newParagraph.append(word).append(" ").append(adj); } else newParagraph.append(paragraph.substring(startDex,spaceDex)); startDex=skipSpaces(paragraph,spaceDex); if(startDex<0) break; newParagraph.append(paragraph.substring(spaceDex,startDex)); spaceDex=paragraph.indexOf(' ',startDex); } if((spaceDex<startDex)&&(startDex>=0)&&(startDex<paragraph.length())) newParagraph.append(paragraph.substring(startDex)); return newParagraph.toString(); } @Override public CMObject findCommand(final MOB mob, final List<String> commands) { if((mob==null) ||(commands==null) ||(mob.location()==null) ||(commands.isEmpty())) return null; String firstWord=commands.get(0).toUpperCase(); if((firstWord.length()>1)&&(!Character.isLetterOrDigit(firstWord.charAt(0)))) { commands.add(1,commands.get(0).substring(1)); commands.set(0,""+firstWord.charAt(0)); firstWord=""+firstWord.charAt(0); } // first, exacting pass Command C=CMClass.findCommandByTrigger(firstWord,true); if((C!=null) &&(C.securityCheck(mob)) &&(!CMSecurity.isCommandDisabled(CMClass.classID(C).toUpperCase()))) return CMLib.leveler().deferCommandCheck(mob, C, commands); Ability A=getToEvoke(mob,new XVector<String>(commands)); if((A!=null) &&(!CMSecurity.isAbilityDisabled(A.ID().toUpperCase()))) return A; if(getAnEvokeWord(mob,firstWord)!=null) return null; Social social=CMLib.socials().fetchSocial(commands,true,true); if(social!=null) return social; for(int c=0;c<CMLib.channels().getNumChannels();c++) { final ChannelsLibrary.CMChannel chan=CMLib.channels().getChannel(c); if(chan.name().equalsIgnoreCase(firstWord)) { C=CMClass.getCommand("Channel"); if((C!=null)&&(C.securityCheck(mob))) return C; } else if(("NO"+chan.name()).equalsIgnoreCase(firstWord)) { C=CMClass.getCommand("NoChannel"); if((C!=null)&&(C.securityCheck(mob))) return C; } } for(final Enumeration<JournalsLibrary.CommandJournal> e=CMLib.journals().commandJournals();e.hasMoreElements();) { final JournalsLibrary.CommandJournal CMJ=e.nextElement(); if(CMJ.NAME().equalsIgnoreCase(firstWord)) { C=CMClass.getCommand("CommandJournal"); if((C!=null)&&(C.securityCheck(mob))) return C; } } // second, inexacting pass for(final Enumeration<Ability> a=mob.allAbilities();a.hasMoreElements();) { A=a.nextElement(); final HashSet<String> tried=new HashSet<String>(); if((A!=null)&&(A.triggerStrings()!=null)) { for(int t=0;t<A.triggerStrings().length;t++) { if((A.triggerStrings()[t].toUpperCase().startsWith(firstWord)) &&(!tried.contains(A.triggerStrings()[t]))) { final Vector<String> commands2=new XVector<String>(commands); commands2.setElementAt(A.triggerStrings()[t],0); final Ability A2=getToEvoke(mob,commands2); if((A2!=null)&&(!CMSecurity.isAbilityDisabled(A2.ID().toUpperCase()))) { commands.set(0,A.triggerStrings()[t]); return A; } } } } } //commands comes inexactly after ables //because of CA, PR, etc.. C=CMClass.findCommandByTrigger(firstWord,false); if((C!=null) &&(C.securityCheck(mob)) &&(!CMSecurity.isCommandDisabled(CMClass.classID(C).toUpperCase()))) return CMLib.leveler().deferCommandCheck(mob, C, commands); social=CMLib.socials().fetchSocial(commands,false,true); if(social!=null) { commands.set(0,social.baseName()); return social; } for(int c=0;c<CMLib.channels().getNumChannels();c++) { final ChannelsLibrary.CMChannel chan=CMLib.channels().getChannel(c); if(chan.name().startsWith(firstWord)) { commands.set(0,chan.name()); C=CMClass.getCommand("Channel"); if((C!=null)&&(C.securityCheck(mob))) return C; } else if(("NO"+chan.name()).startsWith(firstWord)) { commands.set(0,"NO"+chan.name()); C=CMClass.getCommand("NoChannel"); if((C!=null)&&(C.securityCheck(mob))) return C; } } for(final Enumeration<JournalsLibrary.CommandJournal> e=CMLib.journals().commandJournals();e.hasMoreElements();) { final JournalsLibrary.CommandJournal CMJ=e.nextElement(); if(CMJ.NAME().startsWith(firstWord)) { C=CMClass.getCommand("CommandJournal"); if((C!=null)&&(C.securityCheck(mob))) return C; } } return CMLib.leveler().deferCommandCheck(mob, null, commands); } @Override public boolean evokedBy(final Ability thisAbility, final String thisWord) { for(int i=0;i<thisAbility.triggerStrings().length;i++) { if(thisAbility.triggerStrings()[i].equalsIgnoreCase(thisWord)) return true; } return false; } private String collapsedName(final Ability thisAbility) { final int x=thisAbility.name().indexOf(' '); if(x>=0) return CMStrings.replaceAll(thisAbility.name()," ",""); return thisAbility.Name(); } @Override public boolean evokedBy(final Ability thisAbility, final String thisWord, final String secondWord) { for(int i=0;i<thisAbility.triggerStrings().length;i++) { if(thisAbility.triggerStrings()[i].equalsIgnoreCase(thisWord)) { if(((thisAbility.name().toUpperCase().startsWith(secondWord))) ||(collapsedName(thisAbility).toUpperCase().startsWith(secondWord))) return true; } } return false; } @Override public String getAnEvokeWord(final MOB mob, String word) { if(mob==null) return null; Ability A=null; final HashSet<String[]> done=new HashSet<String[]>(); word=word.toUpperCase().trim(); for(final Enumeration<Ability> a=mob.allAbilities();a.hasMoreElements();) { A=a.nextElement(); if((A!=null) &&(A.triggerStrings()!=null) &&(!done.contains(A.triggerStrings()))) { done.add(A.triggerStrings()); for(int t=0;t<A.triggerStrings().length;t++) { if(word.equals(A.triggerStrings()[t])) { if((t>0)&&(A.triggerStrings()[0].startsWith(word))) return A.triggerStrings()[0]; else return A.triggerStrings()[t]; } } } } return null; } @Override public Ability getToEvoke(final MOB mob, final List<String> commands) { final String evokeWord=commands.get(0).toUpperCase(); boolean foundMoreThanOne=false; Ability evokableAbility=null; for(final Enumeration<Ability> a=mob.allAbilities();a.hasMoreElements();) { final Ability A=a.nextElement(); if((A!=null) &&(evokedBy(A,evokeWord))) { if((evokableAbility!=null)&&(!A.ID().equals(evokableAbility.ID()))) { foundMoreThanOne=true; evokableAbility=null; break; } evokableAbility=A; } } if((evokableAbility!=null)&&(commands.size()>1)) { final int classCode=evokableAbility.classificationCode()&Ability.ALL_ACODES; switch(classCode) { case Ability.ACODE_SPELL: case Ability.ACODE_SONG: case Ability.ACODE_PRAYER: case Ability.ACODE_CHANT: evokableAbility=null; foundMoreThanOne=true; break; default: break; } } if(evokableAbility!=null) commands.remove(0); else if((foundMoreThanOne)&&(commands.size()>1)) { commands.remove(0); foundMoreThanOne=false; final String secondWord=commands.get(0).toUpperCase(); for(final Enumeration<Ability> a=mob.allAbilities();a.hasMoreElements();) { final Ability A=a.nextElement(); if((A!=null) &&(evokedBy(A,evokeWord,secondWord.toUpperCase()))) { if((A.name().equalsIgnoreCase(secondWord)) ||(collapsedName(A).equalsIgnoreCase(secondWord))) { evokableAbility=A; foundMoreThanOne=false; break; } else if((evokableAbility!=null)&&(!A.ID().equals(evokableAbility.ID()))) foundMoreThanOne=true; else evokableAbility=A; } } if((evokableAbility!=null)&&(!foundMoreThanOne)) commands.remove(0); else if((foundMoreThanOne)&&(commands.size()>1)) { final String secondAndThirdWord=secondWord+" "+commands.get(1).toUpperCase(); for(final Enumeration<Ability> a=mob.allAbilities();a.hasMoreElements();) { final Ability A=a.nextElement(); if((A!=null) && (evokedBy(A,evokeWord,secondAndThirdWord.toUpperCase()))) { evokableAbility=A; break; } } if(evokableAbility!=null) { commands.remove(0); commands.remove(0); } } else { for(final Enumeration<Ability> a=mob.allAbilities();a.hasMoreElements();) { final Ability A=a.nextElement(); if((A!=null) &&(evokedBy(A,evokeWord)) &&(A.name().toUpperCase().indexOf(" "+secondWord.toUpperCase())>0)) { evokableAbility=A; commands.remove(0); break; } } } } return evokableAbility; } @Override public boolean preEvoke(final MOB mob, List<String> commands, final int secondsElapsed, final double actionsRemaining) { commands=new Vector<String>(commands); final Ability evokableAbility=getToEvoke(mob,commands); if(evokableAbility==null) { mob.tell(L("You don't know how to do that.")); return false; } if((CMLib.ableMapper().qualifyingLevel(mob,evokableAbility)>=0) &&(!CMLib.ableMapper().qualifiesByLevel(mob,evokableAbility)) &&(!CMSecurity.isAllowed(mob,mob.location(),CMSecurity.SecFlag.ALLSKILLS))) { mob.tell(L("You are not high enough level to do that.")); return false; } return evokableAbility.preInvoke(mob,commands,null,false,0,secondsElapsed,actionsRemaining); } @Override public void evoke(final MOB mob, final Vector<String> commands) { final Ability evokableAbility=getToEvoke(mob,commands); if(evokableAbility==null) { mob.tell(L("You don't know how to do that.")); return; } if((CMLib.ableMapper().qualifyingLevel(mob,evokableAbility)>=0) &&(!CMLib.ableMapper().qualifiesByLevel(mob,evokableAbility)) &&(!CMSecurity.isAllowed(mob,mob.location(),CMSecurity.SecFlag.ALLSKILLS))) { mob.tell(L("You are not high enough level to do that.")); return; } evokableAbility.invoke(mob,commands,null,false,0); } private boolean[] PUNCTUATION_TABLE() { if(PUNCTUATION_TABLE==null) { final boolean[] PUNCTUATION_TEMP_TABLE=new boolean[255]; for(int c=0;c<255;c++) switch(c) { case '`': case '~': case '!': case '@': case '#': case '$': case '%': case '^': case '&': case '*': case '(': case ')': case '_': case '-': case '+': case '=': case '[': case ']': case '{': case '}': case '\\': case '|': case ';': case ':': case '\'': case '\"': case ',': case '<': case '.': case '>': case '/': case '?': PUNCTUATION_TEMP_TABLE[c]=true; break; default: PUNCTUATION_TEMP_TABLE[c]=false; } PUNCTUATION_TABLE=PUNCTUATION_TEMP_TABLE; } return PUNCTUATION_TABLE; } @Override public boolean isPunctuation(final byte b) { if((b<0)||(b>255)) return false; return PUNCTUATION_TABLE[b]; } @Override public boolean hasPunctuation(final String str) { if((str==null)||(str.length()==0)) return false; boolean puncFound=false; PUNCTUATION_TABLE(); for(int x=0;x<str.length();x++) { if(isPunctuation((byte)str.charAt(x))) { puncFound=true; break; } } return puncFound; } @Override public String stripPunctuation(final String str) { if(!hasPunctuation(str)) return str; final char[] strc=str.toCharArray(); final char[] str2=new char[strc.length]; int s=0; for(int x=0;x<strc.length;x++) { if(!isPunctuation((byte)strc[x])) { str2[s]=strc[x]; s++; } } return new String(str2,0,s); } @Override public List<String> parseWords(final String thisStr) { if((thisStr==null)||(thisStr.length()==0)) return new Vector<String>(1); return CMParms.parseSpaces(stripPunctuation(thisStr), true); } public boolean equalsPunctuationless(final char[] strC, final char[] str2C) { if((strC.length==0)&&(str2C.length==0)) return true; PUNCTUATION_TABLE(); int s1=0; int s2=0; int s1len=strC.length; while((s1len>0)&&(Character.isWhitespace(strC[s1len-1])||isPunctuation((byte)strC[s1len-1]))) s1len--; int s2len=str2C.length; while((s2len>0)&&(Character.isWhitespace(str2C[s2len-1])||isPunctuation((byte)str2C[s2len-1]))) s2len--; while(s1<s1len) { while((s1<s1len)&&(isPunctuation((byte)strC[s1]))) s1++; while((s2<s2len)&&(isPunctuation((byte)str2C[s2]))) s2++; if(s1==s1len) { if(s2==s2len) return true; return false; } if(s2==s2len) return false; if(strC[s1]!=str2C[s2]) return false; s1++; s2++; } if(s2==s2len) return true; return false; } @Override public boolean containsString(final String toSrchStr, final String srchStr) { if((toSrchStr==null)||(srchStr==null)) return false; if((toSrchStr.length()==0)&&(srchStr.length()>0)) return false; char[] srchC=srchStr.toCharArray(); final char[] toSrchC=toSrchStr.toCharArray(); for(int c=0;c<srchC.length;c++) srchC[c]=Character.toUpperCase(srchC[c]); for(int c=0;c<toSrchC.length;c++) toSrchC[c]=Character.toUpperCase(toSrchC[c]); if(java.util.Arrays.equals(srchC,ALL_CHRS)) return true; if(java.util.Arrays.equals(srchC,toSrchC)) return true; if(equalsPunctuationless(srchC,toSrchC)) return true; boolean topOnly=false; if((srchC.length>1)&&(srchC[0]=='$')) { srchC=new String(srchC,1,srchC.length-1).toCharArray(); topOnly=true; } int tos=0; boolean found=false; while((!found)&&(tos<toSrchC.length)) { for(int x=0;x<srchC.length;x++) { if(tos>=toSrchC.length) { if(srchC[x]=='$') found=true; break; } switch(toSrchC[tos]) { case '^': tos++; if(tos<toSrchC.length) { switch(toSrchC[tos]) { case ColorLibrary.COLORCODE_BACKGROUND: if(tos < toSrchC.length-1) tos+=2; break; case ColorLibrary.COLORCODE_FANSI256: case ColorLibrary.COLORCODE_BANSI256: if(tos < toSrchC.length-4) tos+=4; break; default: tos++; break; } } break; case ',': case '?': case '!': case '.': case ';': tos++; break; } switch(srchC[x]) { case '^': x++; if(x<srchC.length) { switch(srchC[x]) { case ColorLibrary.COLORCODE_BACKGROUND: if(x < srchC.length-1) x+=2; break; case ColorLibrary.COLORCODE_FANSI256: case ColorLibrary.COLORCODE_BANSI256: if(x < srchC.length-4) x+=4; break; default: x++; break; } } break; case ',': case '?': case '!': case '.': case ';': x++; break; } if(x<srchC.length) { if(tos<toSrchC.length) { if(srchC[x]!=toSrchC[tos]) break; else if(x==(srchC.length-1)) found=true; else tos++; } else if(srchC[x]=='$') found=true; else break; } else { found=true; break; } } if((topOnly)&&(!found)) break; while((!found)&&(tos<toSrchC.length)&&(Character.isLetter(toSrchC[tos]))) tos++; tos++; } return found; } @Override public String bumpDotNumber(final String srchStr) { final FetchFlags flags=fetchFlags(srchStr); if(flags==null) return srchStr; if(flags.allFlag) return srchStr; if(flags.occurrance==0) return "1."+flags.srchStr; return (flags.occurrance+1)+"."+flags.srchStr; } @Override public int getContextNumber(final ItemCollection cont, final Environmental E) { return getContextNumber(toCollection(cont),E); } @Override public int getContextNumber(final Environmental[] list, final Environmental E) { return getContextNumber(new XVector<Environmental>(list),E); } @Override public int getContextNumber(final Collection<? extends Environmental> list, final Environmental E) { if(list==null) return 0; int context=1; for(final Environmental O : list) { if((O.Name().equalsIgnoreCase(E.Name())) ||(O.name().equalsIgnoreCase(E.name()))) { if(O==E) return context<2?0:context; if((!(O instanceof Item)) ||(!(E instanceof Item)) ||(((Item)E).container()==((Item)O).container())) context++; } } return -1; } private Collection<? extends Environmental> toCollection(final ItemCollection cont) { final LinkedList<Item> list=new LinkedList<Item>(); for(final Enumeration<Item> i=cont.items();i.hasMoreElements();) list.add(i.nextElement()); return list; } @Override public int getContextSameNumber(final ItemCollection cont, final Environmental E) { return getContextSameNumber(toCollection(cont),E); } @Override public int getContextSameNumber(final Environmental[] list, final Environmental E) { return getContextSameNumber(new XVector<Environmental>(list),E); } @Override public int getContextSameNumber(final Collection<? extends Environmental> list, final Environmental E) { if(list==null) return 0; int context=1; for(final Object O : list) { if((((Environmental)O).Name().equalsIgnoreCase(E.Name())) ||(((Environmental)O).name().equalsIgnoreCase(E.name()))) { if(E.sameAs((Environmental)O)) return context<2?0:context; if((!(O instanceof Item)) ||(!(E instanceof Item)) ||(((Item)E).container()==((Item)O).container())) context++; } } return -1; } @Override public String getContextName(final ItemCollection cont, final Environmental E) { return getContextName(toCollection(cont),E); } @Override public String getContextName(final Environmental[] list, final Environmental E) { return getContextName(new XVector<Environmental>(list),E); } @Override public String getContextName(final Collection<? extends Environmental> list, final Environmental E) { if(list==null) return E.name(); final int number=getContextNumber(list,E); if(number<0) return null; if(number<2) return E.name(); return E.name()+"."+number; } @Override public List<String> getAllContextNames(final Collection<? extends Environmental> list, final Filterer<Environmental> filter) { if(list==null) return new ArrayList<String>(); final List<String> flist = new Vector<String>(list.size()); final Map<String,int[]> prevFound = new HashMap<String,int[]>(); for(final Environmental E : list) { if((filter!=null)&&(!filter.passesFilter(E))) { flist.add(""); continue; } final String key = E.Name()+((E instanceof Item)?("/"+((Item)E).container()):""); if(!prevFound.containsKey(key)) { final int[] ct=new int[]{1}; prevFound.put(key, ct); flist.add(E.name()); } else { final int[] ct=prevFound.get(key); ct[0]++; flist.add(E.name()+"."+ct[0]); } } return flist; } @Override public String getContextSameName(final ItemCollection cont, final Environmental E) { return getContextSameName(toCollection(cont),E); } @Override public String getContextSameName(final Environmental[] list, final Environmental E) { return getContextSameName(new XVector<Environmental>(list),E); } @Override public String getContextSameName(final Collection<? extends Environmental> list, final Environmental E) { if(list==null) return E.name(); final int number=getContextSameNumber(list,E); if(number<0) return null; if(number<2) return E.name(); return E.name()+"."+number; } @Override public Environmental parseShopkeeper(final MOB mob, final List<String> commands, final String error) { if(commands.isEmpty()) { if(error.length()>0) mob.tell(error); return null; } commands.remove(0); final List<Environmental> V=CMLib.coffeeShops().getAllShopkeepers(mob.location(),mob); if(V.isEmpty()) { if(error.length()>0) mob.tell(error); return null; } if(V.size()>1) { if(commands.size()<2) { if(error.length()>0) mob.tell(error); return null; } final String what=commands.get(commands.size()-1); Environmental shopkeeper=fetchEnvironmental(V,what,false); if((shopkeeper==null)&&(what.equals("shop")||what.equals("the shop"))) { for(int v=0;v<V.size();v++) { if(V.get(v) instanceof Area) { shopkeeper = V.get(v); break; } } } if((shopkeeper!=null) &&(CMLib.coffeeShops().getShopKeeper(shopkeeper)!=null) &&(CMLib.flags().canBeSeenBy(shopkeeper,mob))) commands.remove(commands.size()-1); else { CMLib.commands().postCommandFail(mob,new XVector<String>(commands), L("You don't see anyone called '@x1' here buying or selling.",commands.get(commands.size()-1))); return null; } return shopkeeper; } Environmental shopkeeper=V.get(0); if(commands.size()>1) { final MOB M=mob.location().fetchInhabitant(commands.get(commands.size()-1)); if((M!=null)&&(CMLib.coffeeShops().getShopKeeper(M)!=null)&&(CMLib.flags().canBeSeenBy(M,mob))) { shopkeeper=M; commands.remove(commands.size()-1); } } return shopkeeper; } @Override public List<Item> fetchItemList(final Environmental from, final MOB mob, final Item container, final List<String> commands, final Filterer<Environmental> filter, final boolean visionMatters) { int addendum=1; String addendumStr=""; List<Item> V=new Vector<Item>(); int maxToItem=Integer.MAX_VALUE; if((commands.size()>1) &&(CMath.s_int(commands.get(0))>0)) { maxToItem=CMath.s_int(commands.get(0)); commands.set(0,"all"); } String name=CMParms.combine(commands,0); boolean allFlag = (!commands.isEmpty()) ? commands.get(0).equalsIgnoreCase("all") : false; if (name.toUpperCase().startsWith("ALL.")) { allFlag = true; name = "ALL " + name.substring(4); } if (name.toUpperCase().endsWith(".ALL")) { allFlag = true; name = "ALL " + name.substring(0, name.length() - 4); } boolean doBugFix = true; boolean wornOnly = true; boolean unwornOnly = true; while(doBugFix || ((allFlag)&&(addendum<=maxToItem))) { doBugFix=false; Environmental item=null; if(from instanceof MOB) { item=((MOB)from).fetchItem(container,filter,name+addendumStr); // all this for single underlayer items with the same name.. ugh... if((item instanceof Armor) && (!allFlag) && (filter == Wearable.FILTER_WORNONLY) && (addendumStr.length()==0)) { int subAddendum = 0; Item item2=((MOB)from).fetchItem(container,filter,name+"."+(++subAddendum)); while(item2 != null) { if((item2 instanceof Armor) &&(((Armor)item2).getClothingLayer() > ((Armor)item).getClothingLayer())) item=item2; item2=((MOB)from).fetchItem(container,filter,name+"."+(++subAddendum)); } } } else if(from instanceof Room) item=((Room)from).fetchFromMOBRoomFavorsItems(mob,container,name+addendumStr,filter); if((item!=null) &&(item instanceof Item) &&((!visionMatters)||(CMLib.flags().canBeSeenBy(item,mob))||(item instanceof Light)) &&(!V.contains(item))) { V.add((Item)item); if(((Item)item).amWearingAt(Wearable.IN_INVENTORY)) wornOnly=false; else unwornOnly=false; } if(item==null) break; addendumStr="."+(++addendum); } if(wornOnly && (!V.isEmpty())) { final Vector<Item> V2=new Vector<Item>(); // return value short topLayer=0; short curLayer=0; int which=-1; while(!V.isEmpty()) { Item I=V.get(0); topLayer=(I instanceof Armor)?((Armor)I).getClothingLayer():0; which=0; for(int v=1;v<V.size();v++) { I=V.get(v); curLayer=(I instanceof Armor)?((Armor)I).getClothingLayer():0; if(curLayer>topLayer) { which = v; topLayer = curLayer; } } V2.addElement(V.get(which)); V.remove(which); } V=V2; } else if(unwornOnly && (!V.isEmpty())) { final Vector<Item> V2=new Vector<Item>(); // return value short topLayer=0; short curLayer=0; int which=-1; while(!V.isEmpty()) { Item I=V.get(0); topLayer=(I instanceof Armor)?((Armor)I).getClothingLayer():0; which=0; for(int v=1;v<V.size();v++) { I=V.get(v); curLayer=(I instanceof Armor)?((Armor)I).getClothingLayer():0; if(curLayer<topLayer) { which=v; topLayer=curLayer; } } V2.addElement(V.get(which)); V.remove(which); } V=V2; } return V; } @Override public long parseNumPossibleGold(final Environmental mine, String moneyStr) { if(moneyStr.toUpperCase().trim().startsWith("A PILE OF ")) moneyStr=moneyStr.substring(10); if(CMath.isInteger(moneyStr)) { final long num=CMath.s_long(moneyStr); if(mine instanceof MOB) { List<Coins> V=CMLib.beanCounter().getStandardCurrency((MOB)mine,CMLib.beanCounter().getCurrency(mine)); for(int v=0;v<V.size();v++) { if(V.get(v).getNumberOfCoins()>=num) return num; } V=CMLib.beanCounter().getStandardCurrency((MOB)mine,null); for(int v=0;v<V.size();v++) { if(V.get(v).getNumberOfCoins()>=num) return num; } } return CMath.s_long(moneyStr); } final Vector<String> V=CMParms.parse(moneyStr); if((V.size()>1) &&((CMath.isInteger(V.firstElement())) &&(matchAnyCurrencySet(CMParms.combine(V,1))!=null))) return CMath.s_long(V.firstElement()); else if((V.size()>1)&&(V.firstElement().equalsIgnoreCase("all"))) { final String currency=matchAnyCurrencySet(CMParms.combine(V,1)); if(currency!=null) { if(mine instanceof MOB) { final List<Coins> V2=CMLib.beanCounter().getStandardCurrency((MOB)mine,currency); final double denomination=matchAnyDenomination(currency,CMParms.combine(V,1)); Coins C=null; for(int v2=0;v2<V2.size();v2++) { C=V2.get(v2); if(C.getDenomination()==denomination) return C.getNumberOfCoins(); } } return 1; } } else if((!V.isEmpty())&&(matchAnyCurrencySet(CMParms.combine(V,0))!=null)) return 1; return 0; } @Override public String parseNumPossibleGoldCurrency(final Environmental mine, String moneyStr) { if(moneyStr.toUpperCase().trim().startsWith("A PILE OF ")) moneyStr=moneyStr.substring(10); if(CMath.isInteger(moneyStr)) { final long num=CMath.s_long(moneyStr); if(mine instanceof MOB) { List<Coins> V=CMLib.beanCounter().getStandardCurrency((MOB)mine,CMLib.beanCounter().getCurrency(mine)); for(int v=0;v<V.size();v++) { if(V.get(v).getNumberOfCoins()>=num) return V.get(v).getCurrency(); } V=CMLib.beanCounter().getStandardCurrency((MOB)mine,null); for(int v=0;v<V.size();v++) { if(V.get(v).getNumberOfCoins()>=num) return V.get(v).getCurrency(); } } return CMLib.beanCounter().getCurrency(mine); } final Vector<String> V=CMParms.parse(moneyStr); if((V.size()>1)&&(CMath.isInteger(V.firstElement()))) return matchAnyCurrencySet(CMParms.combine(V,1)); else if((V.size()>1)&&(V.firstElement().equalsIgnoreCase("all"))) return matchAnyCurrencySet(CMParms.combine(V,1)); else if(!V.isEmpty()) return matchAnyCurrencySet(CMParms.combine(V,0)); return CMLib.beanCounter().getCurrency(mine); } @Override public long getMillisMultiplierByName(String timeName) { timeName=timeName.toLowerCase(); if("ticks".startsWith(timeName)) return CMProps.getTickMillis(); else if("seconds".startsWith(timeName)) return 1000; else if("minutes".startsWith(timeName)) return 1000*60; else if("hours".startsWith(timeName)) return 1000*60*60; else if("days".startsWith(timeName)) return 1000*60*60*24; else if("weeks".startsWith(timeName)) return 1000*60*60*24*7; else return -1; } @Override public double parseNumPossibleGoldDenomination(final Environmental mine, final String currency, String moneyStr) { if(moneyStr.toUpperCase().trim().startsWith("A PILE OF ")) moneyStr=moneyStr.substring(10); if(CMath.isInteger(moneyStr)) { final long num=CMath.s_long(moneyStr); if(mine instanceof MOB) { final List<Coins> V=CMLib.beanCounter().getStandardCurrency((MOB)mine,currency); for(int v=0;v<V.size();v++) { if(V.get(v).getNumberOfCoins()>=num) return V.get(v).getDenomination(); } } return CMLib.beanCounter().getLowestDenomination(currency); } final Vector<String> V=CMParms.parse(moneyStr); if((V.size()>1)&&(CMath.isInteger(V.firstElement()))) return matchAnyDenomination(currency,CMParms.combine(V,1)); else if((V.size()>1)&&(V.firstElement().equalsIgnoreCase("all"))) return matchAnyDenomination(currency,CMParms.combine(V,1)); else if(!V.isEmpty()) return matchAnyDenomination(currency,CMParms.combine(V,0)); return 0; } @Override public String matchAnyCurrencySet(final String moneyStr) { final List<String> V=CMLib.beanCounter().getAllCurrencies(); List<String> V2=null; for(int v=0;v<V.size();v++) { V2=CMLib.beanCounter().getDenominationNameSet(V.get(v)); for(int v2=0;v2<V2.size();v2++) { String s=V2.get(v2); if(s.toLowerCase().endsWith("(s)")) s=s.substring(0,s.length()-3)+"s"; if(containsString(s,moneyStr)) return V.get(v); } } return null; } @Override public double matchAnyDenomination(final String currency, String moneyStr) { if(currency == null) { for(final String curr : CMLib.beanCounter().getAllCurrencies()) { final MoneyLibrary.MoneyDenomination[] DV=CMLib.beanCounter().getCurrencySet(curr); moneyStr=moneyStr.toUpperCase(); String s=null; if(DV!=null) { for (final MoneyDenomination element : DV) { s=element.name().toUpperCase(); if(s.endsWith("(S)")) s=s.substring(0,s.length()-3)+"S"; if(containsString(s,moneyStr)) return element.value(); else if((s.length()>0) &&(containsString(s,moneyStr))) return element.value(); } } } } else { final MoneyLibrary.MoneyDenomination[] DV=CMLib.beanCounter().getCurrencySet(currency); moneyStr=moneyStr.toUpperCase(); String s=null; if(DV!=null) { for (final MoneyDenomination element : DV) { s=element.name().toUpperCase(); if(s.endsWith("(S)")) s=s.substring(0,s.length()-3)+"S"; if(containsString(s,moneyStr)) return element.value(); else if((s.length()>0) &&(containsString(s,moneyStr))) return element.value(); } } } return 0.0; } @Override public Item parsePossibleRoomGold(final MOB seer, final Room room, final Container container, String moneyStr) { if(moneyStr.toUpperCase().trim().startsWith("A PILE OF ")) moneyStr=moneyStr.substring(10); long gold=0; if(CMath.isInteger(moneyStr)) { gold=CMath.s_long(moneyStr); moneyStr=""; } else { final Vector<String> V=CMParms.parse(moneyStr); if((V.size()>1)&&(CMath.isInteger(V.firstElement()))) gold=CMath.s_long(V.firstElement()); else return null; moneyStr=CMParms.combine(V,1); } if(gold>0) { for(int i=0;i<room.numItems();i++) { final Item I=room.getItem(i); if((I.container()==container) &&(I instanceof Coins) &&(CMLib.flags().canBeSeenBy(I,seer)) &&((moneyStr.length()==0)||(containsString(I.name(),moneyStr)))) { if(((Coins)I).getNumberOfCoins()<=gold) return I; ((Coins)I).setNumberOfCoins(((Coins)I).getNumberOfCoins()-gold); final Coins C=(Coins)CMClass.getItem("StdCoins"); C.setCurrency(((Coins)I).getCurrency()); C.setNumberOfCoins(gold); C.setDenomination(((Coins)I).getDenomination()); C.setContainer(container); C.recoverPhyStats(); room.addItem(C); C.setExpirationDate(I.expirationDate()); return C; } } } return null; } @Override public Item parseBestPossibleGold(final MOB mob, final Container container, String itemID) { if(itemID.toUpperCase().trim().startsWith("A PILE OF ")) itemID=itemID.substring(10); long gold=0; double denomination=0.0; String currency=CMLib.beanCounter().getCurrency(mob); if(CMath.isInteger(itemID)) { gold=CMath.s_long(itemID); //final double totalAmount=CMLib.beanCounter().getTotalAbsoluteValue(mob,currency); double bestDenomination=CMLib.beanCounter().getBestDenomination(currency,(int)gold,gold); if(bestDenomination==0.0) { bestDenomination=CMLib.beanCounter().getBestDenomination(null,(int)gold,gold); if(bestDenomination>0.0) currency=null; } if(bestDenomination==0.0) return null; denomination=bestDenomination; } else { final Vector<String> V=CMParms.parse(itemID); if(V.size()<1) return null; if((!CMath.isInteger(V.firstElement())) &&(!V.firstElement().equalsIgnoreCase("all"))) V.insertElementAt("1",0); final Item I=mob.findItem(container,CMParms.combine(V,1)); if(I instanceof Coins) { if(V.firstElement().equalsIgnoreCase("all")) gold=((Coins)I).getNumberOfCoins(); else gold=CMath.s_long(V.firstElement()); currency=((Coins)I).getCurrency(); denomination=((Coins)I).getDenomination(); } else return null; } if(gold>0) { final double amt = CMLib.beanCounter().getTotalAbsoluteValue(mob, currency); if(amt>=CMath.mul(denomination,gold)) { final double expectedAmt = amt - CMath.mul(denomination,gold); CMLib.beanCounter().subtractMoney(mob,currency,denomination,CMath.mul(denomination,gold)); final double newAmt = CMLib.beanCounter().getTotalAbsoluteValue(mob, currency); if(newAmt > expectedAmt) CMLib.beanCounter().subtractMoney(mob,currency,(newAmt - expectedAmt)); final Coins C=(Coins)CMClass.getItem("StdCoins"); C.setCurrency(currency); C.setDenomination(denomination); C.setNumberOfCoins(gold); C.recoverPhyStats(); mob.addItem(C); return C; } mob.tell(L("You don't have that much @x1.",CMLib.beanCounter().getDenominationName(currency,denomination))); final List<Coins> V=CMLib.beanCounter().getStandardCurrency(mob,currency); for(int v=0;v<V.size();v++) { if(V.get(v).getDenomination()==denomination) return V.get(v); } } return null; } @Override public List<Container> parsePossibleContainers(final MOB mob, final List<String> commands, final Filterer<Environmental> filter, final boolean withContentOnly) { final Vector<Container> V=new Vector<Container>(1); if(commands.size()==1) return V; int fromDex=-1; int containerDex=commands.size()-1; for(int i=commands.size()-2;i>0;i--) { if(commands.get(i).equalsIgnoreCase("from")) { fromDex=i; containerDex=i+1; if(((containerDex+1)<commands.size()) &&((commands.get(containerDex).equalsIgnoreCase("all")) ||(CMath.s_int(commands.get(containerDex))>0))) containerDex++; break; } } String possibleContainerID=CMParms.combine(commands,containerDex); boolean allFlag=false; String preWord=""; if(possibleContainerID.equalsIgnoreCase("all")) allFlag=true; else if(containerDex>1) preWord=commands.get(containerDex-1); int maxContained=Integer.MAX_VALUE; if(CMath.s_int(preWord)>0) { maxContained=CMath.s_int(preWord); commands.set(containerDex-1,"all"); containerDex--; preWord="all"; } if (preWord.equalsIgnoreCase("all")) { allFlag = true; possibleContainerID = "ALL " + possibleContainerID; } else if (possibleContainerID.toUpperCase().startsWith("ALL.")) { allFlag = true; possibleContainerID = "ALL " + possibleContainerID.substring(4); } else if (possibleContainerID.toUpperCase().endsWith(".ALL")) { allFlag = true; possibleContainerID = "ALL " + possibleContainerID.substring(0, possibleContainerID.length() - 4); } int addendum=1; String addendumStr=""; boolean doBugFix = true; while(doBugFix || ((allFlag)&&(addendum<=maxContained))) { doBugFix=false; final Environmental E=mob.location().fetchFromMOBRoomFavorsItems(mob,null,possibleContainerID+addendumStr,filter); if((E!=null) &&(E instanceof Item) &&(((Item)E) instanceof Container) &&((!withContentOnly)||(((Container)E).hasContent())) &&(CMLib.flags().canBeSeenBy(E,mob)||mob.isMine(E))) { V.addElement((Container)E); if(V.size()==1) { while((fromDex>=0)&&(commands.size()>fromDex)) commands.remove(fromDex); while(commands.size()>containerDex) commands.remove(containerDex); preWord=""; } } if(E==null) return V; addendumStr="."+(++addendum); } return V; } @Override public Item parsePossibleContainer(final MOB mob, final List<String> commands, final boolean withStuff, final Filterer<Environmental> filter) { if(commands.size()==1) return null; final Room R=(mob==null)?null:mob.location(); if(R==null) return null; int fromDex=-1; int containerDex=commands.size()-1; for(int i=commands.size()-2;i>=1;i--) { if(commands.get(i).equalsIgnoreCase("from") || commands.get(i).equalsIgnoreCase("in")|| commands.get(i).equalsIgnoreCase("on")) { fromDex=i; containerDex=i+1; break; } } final String possibleContainerID=CMParms.combine(commands,containerDex); Environmental E=R.fetchFromMOBRoomFavorsItems(mob,null,possibleContainerID,filter); if(E==null) { final CMFlagLibrary flagLib=CMLib.flags(); for(int i=0;i<R.numItems();i++) { final Item I=R.getItem(i); if(flagLib.isOpenAccessibleContainer(I)) { E=R.fetchFromMOBRoomFavorsItems(mob,I,possibleContainerID,filter); if(E instanceof Container) break; } } } if((E!=null) &&(E instanceof Item) &&(((Item)E) instanceof Container) &&((!withStuff)||(((Container)E).hasContent()))) { while((fromDex>=0)&&(commands.size()>fromDex)) commands.remove(fromDex); while(commands.size()>containerDex) commands.remove(containerDex); return (Item)E; } return null; } @Override public String stringifyElapsedTimeOrTicks(long millis, final long ticks) { String avg=""; if(ticks>0) avg=", Average="+(millis/ticks)+"ms"; if(millis<1000) return millis+"ms"+avg; long seconds=millis/1000; millis-=(seconds*1000); if(seconds<60) return seconds+"s "+millis+"ms"+avg; long minutes=seconds/60; seconds-=(minutes*60); if(minutes<60) return minutes+"m "+seconds+"s "+millis+"ms"+avg; long hours=minutes/60; minutes-=(hours*60); if(hours<24) return hours+"h "+minutes+"m "+seconds+"s "+millis+"ms"+avg; final long days=hours/24; hours-=(days*24); return days+"d "+hours+"h "+minutes+"m "+seconds+"s "+millis+"ms"+avg; } @Override public Triad<String, Double, Long> parseMoneyStringSDL(final MOB mob, final String moneyStr, String correctCurrency) { double b=0; String myCurrency=CMLib.beanCounter().getCurrency(mob); double denomination=1.0; if(correctCurrency==null) correctCurrency=myCurrency; if(moneyStr.length()>0) { myCurrency=parseNumPossibleGoldCurrency(mob,moneyStr); if(myCurrency!=null) { denomination=parseNumPossibleGoldDenomination(null,correctCurrency,moneyStr); final long num=parseNumPossibleGold(null,moneyStr); b=CMath.mul(denomination,num); } else myCurrency=CMLib.beanCounter().getCurrency(mob); } if((denomination == 0)||(b == 0)) return null; return new Triad<String,Double,Long>(myCurrency,Double.valueOf(denomination),Long.valueOf(Math.round(b/denomination))); } @Override public int parseMaxToGive(final MOB mob, final List<String> commands, final boolean breakPackages, final Environmental checkWhat, final boolean getOnly) { int maxToGive=Integer.MAX_VALUE; if((commands.size()>1) &&(parseNumPossibleGold(mob,CMParms.combine(commands,0))==0)) { if(CMath.s_int(commands.get(0))>0) { maxToGive=CMath.s_int(commands.get(0)); commands.set(0,"all"); if(breakPackages) { boolean throwError=false; if((commands.size()>2)&&("FROM".startsWith(commands.get(1).toUpperCase()))) { throwError=true; commands.remove(1); } final String packCheckName=CMParms.combine(commands,1); Environmental fromWhat=null; if(checkWhat instanceof MOB) fromWhat=mob.findItem(null,packCheckName); else if(checkWhat instanceof Room) fromWhat=((Room)checkWhat).fetchFromMOBRoomFavorsItems(mob,null,packCheckName,Wearable.FILTER_UNWORNONLY); if(fromWhat instanceof Item) { int max=mob.maxCarry(); if(max>3000) max=3000; if(maxToGive>max) { CMLib.commands().postCommandFail(mob,new XVector<String>(commands),L("You can only handle @x1 at a time.",""+max)); return -1; } final Environmental toWhat=CMLib.materials().unbundle((Item)fromWhat,maxToGive,null); if(toWhat==null) { if(throwError) { CMLib.commands().postCommandFail(mob,new XVector<String>(commands),L("You can't get anything from @x1.",fromWhat.name())); return -1; } } else if(getOnly&&mob.isMine(fromWhat)&&mob.isMine(toWhat)) { mob.tell(L("Ok")); return -1; } else if(commands.size()==1) commands.add(toWhat.name()); else { final String O=commands.get(0); commands.clear(); commands.add(O); commands.add(toWhat.name()); } } else if(throwError) { CMLib.commands().postCommandFail(mob,new XVector<String>(commands),L("You don't see '@x1' here.",packCheckName)); return -1; } } } else if(!CMath.isInteger(commands.get(0))) { final int x = CMParms.indexOfIgnoreCase(commands,"FROM"); if((x>0)&&(x<commands.size()-1)) { final String packCheckName=CMParms.combine(commands,x+1); final String getName = CMParms.combine(commands,0,x); Environmental fromWhat=null; if(checkWhat instanceof MOB) fromWhat=mob.findItem(null,packCheckName); else if(checkWhat instanceof Room) fromWhat=((Room)checkWhat).fetchFromMOBRoomFavorsItems(mob,null,packCheckName,Wearable.FILTER_UNWORNONLY); if(fromWhat instanceof Item) { final Environmental toWhat=CMLib.materials().unbundle((Item)fromWhat,1,null); if((toWhat==null) ||((!containsString(toWhat.name(), getName)) &&(!containsString(toWhat.displayText(), getName)))) { return maxToGive; } else if(getOnly&&mob.isMine(fromWhat)&&mob.isMine(toWhat)) { mob.tell(L("Ok")); return -1; } else { maxToGive = 1; commands.clear(); commands.add(toWhat.name()); } } } } } return maxToGive; } @Override public int probabilityOfBeingEnglish(final String str) { if(str.length()<100) return 100; final double[] englishFreq = new double[]{ 0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015, // A-G 0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749, // H-N 0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758, // O-U 0.00978, 0.02360, 0.00150, 0.01974, 0.00074 // V-Z }; double punctuationCount=0; double wordCount=0; double totalLetters=0; double thisLetterCount=0; final int[] lettersUsed = new int[26]; final double len=str.length(); for(int i=0;i<str.length();i++) { final char c=str.charAt(i); if(Character.isLetter(c)) { thisLetterCount+=1; lettersUsed[Character.toLowerCase(c)-'a']++; } else if((c==' ')||(isPunctuation((byte)c))) { if(thisLetterCount>0) { totalLetters+=thisLetterCount; wordCount+=1.0; thisLetterCount=0; } if(c!=' ') punctuationCount++; } else punctuationCount++; } if(thisLetterCount>0) { totalLetters+=thisLetterCount; wordCount+=1.0; thisLetterCount=0; } final double pctPunctuation=punctuationCount/len; if(pctPunctuation > .2) return 0; final double avgWordSize=totalLetters/wordCount; if((avgWordSize < 2.0)||(avgWordSize > 8.0)) return 0; double wordCountChi=avgWordSize-4.7; wordCountChi=(wordCountChi*wordCountChi)/4.7; double chi2=10.0*wordCountChi; for (int i = 0; i < 26; i++) { final double observed = lettersUsed[i]; final double expected = totalLetters * englishFreq[i]; final double difference = observed - expected; chi2 += (difference*difference) / expected / 26.0; } final int finalChance=(int)Math.round(100.0 - chi2); if(finalChance<0) return 0; if(finalChance>100) return 100; return finalChance; } protected static class FetchFlags { public String srchStr; public int occurrance; public boolean allFlag; public FetchFlags(final String ss, final int oc, final boolean af) { srchStr = ss; occurrance = oc; allFlag = af; } } public FetchFlags fetchFlags(String srchStr) { if(srchStr.length()==0) return null; srchStr=srchStr.toUpperCase(); if((srchStr.length()<2)||(srchStr.equals("THE"))) return null; boolean allFlag=false; if(srchStr.startsWith("ALL ")) { srchStr=srchStr.substring(4); allFlag=true; } else if(srchStr.equals("ALL")) allFlag=true; int dot=srchStr.lastIndexOf('.'); int occurrance=0; if(dot>0) { String sub=srchStr.substring(dot+1); occurrance=CMath.s_int(sub); if(occurrance>0) srchStr=srchStr.substring(0,dot); else { dot=srchStr.indexOf('.'); sub=srchStr.substring(0,dot); occurrance=CMath.s_int(sub); if(occurrance>0) srchStr=srchStr.substring(dot+1); else occurrance=0; } } return new FetchFlags(srchStr,occurrance,allFlag); } protected String cleanExtraneousDollarMarkers(final String srchStr) { if(srchStr.startsWith("$")) { if(srchStr.endsWith("$")&&(srchStr.length()>1)) return srchStr.substring(1,srchStr.length()-1); else return srchStr.substring(1); } else if(srchStr.endsWith("$")) return srchStr.substring(0,srchStr.length()-1); return srchStr; } @Override public Environmental fetchEnvironmental(final Iterable<? extends Environmental> list, String srchStr, final boolean exactOnly) { final FetchFlags flags=fetchFlags(srchStr); if(flags==null) return null; srchStr=flags.srchStr; int myOccurrance=flags.occurrance; final boolean allFlag=flags.allFlag; try { if(exactOnly) { srchStr=cleanExtraneousDollarMarkers(srchStr); for (final Environmental E : list) { if(E!=null) { if(E.ID().equalsIgnoreCase(srchStr) ||E.name().equalsIgnoreCase(srchStr) ||E.Name().equalsIgnoreCase(srchStr)) { if((!allFlag)||(E instanceof Ability)||((E.displayText()!=null)&&(E.displayText().length()>0))) { if((--myOccurrance)<=0) return E; } } } } } else { myOccurrance=flags.occurrance; for (final Environmental E : list) { if((E!=null) &&(containsString(E.name(),srchStr)||containsString(E.Name(),srchStr)) &&((!allFlag)||(E instanceof Ability)||((E.displayText()!=null)&&(E.displayText().length()>0)))) { if((--myOccurrance)<=0) return E; } } myOccurrance=flags.occurrance; for (final Environmental E : list) { if((E!=null) &&(!(E instanceof Ability)) &&(containsString(E.displayText(),srchStr) ||((E instanceof MOB)&&containsString(((MOB)E).genericName(),srchStr)))) { if((--myOccurrance)<=0) return E; } } } } catch (final java.lang.ArrayIndexOutOfBoundsException x) { } return null; } @Override public Exit fetchExit(final Iterable<? extends Environmental> list, String srchStr, final boolean exactOnly) { final FetchFlags flags=fetchFlags(srchStr); if(flags==null) return null; srchStr=flags.srchStr; int myOccurrance=flags.occurrance; final boolean allFlag=flags.allFlag; try { if(exactOnly) { srchStr=cleanExtraneousDollarMarkers(srchStr); for (final Environmental E : list) { if(E instanceof Exit) { if(E.ID().equalsIgnoreCase(srchStr) ||E.name().equalsIgnoreCase(srchStr) ||E.Name().equalsIgnoreCase(srchStr) ||((Exit)E).doorName().equalsIgnoreCase(srchStr) ||((Exit)E).closedText().equalsIgnoreCase(srchStr)) { if((!allFlag)||((E.displayText()!=null)&&(E.displayText().length()>0))) { if((--myOccurrance)<=0) return (Exit)E; } } } } } else { myOccurrance=flags.occurrance; for (final Environmental E : list) { if((E instanceof Exit) &&(containsString(E.name(),srchStr) ||containsString(E.Name(),srchStr) ||containsString(((Exit)E).doorName(),srchStr) ||containsString(((Exit)E).closedText(),srchStr)) &&((!allFlag)||((E.displayText()!=null)&&(E.displayText().length()>0)))) { if((--myOccurrance)<=0) return (Exit)E; } } myOccurrance=flags.occurrance; for (final Environmental E : list) { if((E instanceof Exit) &&(containsString(E.displayText(),srchStr))) { if((--myOccurrance)<=0) return (Exit)E; } } } } catch (final java.lang.ArrayIndexOutOfBoundsException x) { } return null; } @Override public Environmental fetchEnvironmental(final Iterator<? extends Environmental> iter, String srchStr, final boolean exactOnly) { final FetchFlags flags=fetchFlags(srchStr); if(flags==null) return null; srchStr=flags.srchStr; int myOccurrance=flags.occurrance; final boolean allFlag=flags.allFlag; try { if(exactOnly) { srchStr=cleanExtraneousDollarMarkers(srchStr); for (;iter.hasNext();) { final Environmental E=iter.next(); if(E!=null) { if(E.ID().equalsIgnoreCase(srchStr) ||E.name().equalsIgnoreCase(srchStr) ||E.Name().equalsIgnoreCase(srchStr)) { if((!allFlag) ||(E instanceof Ability) ||((E.displayText()!=null)&&(E.displayText().length()>0))) { if((--myOccurrance)<=0) return E; } } } } } else { myOccurrance=flags.occurrance; for (;iter.hasNext();) { final Environmental E=iter.next(); if((E!=null) &&(containsString(E.name(),srchStr) ||containsString(E.Name(),srchStr) ||containsString(E.displayText(),srchStr) ||((E instanceof MOB)&&containsString(((MOB)E).genericName(),srchStr))) &&((!allFlag) ||(E instanceof Ability) ||((E.displayText()!=null)&&(E.displayText().length()>0)))) { if((--myOccurrance)<=0) return E; } } } } catch (final java.lang.ArrayIndexOutOfBoundsException x) { } return null; } @Override public Environmental fetchEnvironmental(final Enumeration<? extends Environmental> iter, String srchStr, final boolean exactOnly) { final FetchFlags flags=fetchFlags(srchStr); if(flags==null) return null; srchStr=flags.srchStr; int myOccurrance=flags.occurrance; final boolean allFlag=flags.allFlag; try { if(exactOnly) { srchStr=cleanExtraneousDollarMarkers(srchStr); for (;iter.hasMoreElements();) { final Environmental E=iter.nextElement(); if(E!=null) { if(E.ID().equalsIgnoreCase(srchStr) ||E.name().equalsIgnoreCase(srchStr) ||E.Name().equalsIgnoreCase(srchStr)) { if((!allFlag)||(E instanceof Ability)||((E.displayText()!=null)&&(E.displayText().length()>0))) { if((--myOccurrance)<=0) return E; } } } } } else { myOccurrance=flags.occurrance; for (;iter.hasMoreElements();) { final Environmental E=iter.nextElement(); if((E!=null) &&(containsString(E.name(),srchStr) ||containsString(E.Name(),srchStr) ||containsString(E.displayText(),srchStr) ||((E instanceof MOB)&&containsString(((MOB)E).genericName(),srchStr))) &&((!allFlag) ||(E instanceof Ability) ||((E.displayText()!=null)&&(E.displayText().length()>0)))) { if((--myOccurrance)<=0) return E; } } } } catch (final java.lang.ArrayIndexOutOfBoundsException x) { } return null; } @Override public List<Environmental> fetchEnvironmentals(final List<? extends Environmental> list, String srchStr, final boolean exactOnly) { final Vector<Environmental> matches=new Vector<Environmental>(1); if(list.isEmpty()) return matches; final FetchFlags flags=fetchFlags(srchStr); if(flags==null) return matches; srchStr=flags.srchStr; int myOccurrance=flags.occurrance; final boolean allFlag=flags.allFlag; try { if(exactOnly) { srchStr=cleanExtraneousDollarMarkers(srchStr); for (final Environmental E : list) { if(E!=null) { if(E.ID().equalsIgnoreCase(srchStr) ||E.name().equalsIgnoreCase(srchStr) ||E.Name().equalsIgnoreCase(srchStr)) { if((!allFlag)||(E instanceof Ability)||((E.displayText()!=null)&&(E.displayText().length()>0))) { if((--myOccurrance)<=0) matches.addElement(E); } } } } } else { myOccurrance=flags.occurrance; for (final Environmental E : list) { if((E!=null) &&(containsString(E.name(),srchStr)||containsString(E.Name(),srchStr)) &&((!allFlag)||(E instanceof Ability)||((E.displayText()!=null)&&(E.displayText().length()>0)))) { if((--myOccurrance)<=0) matches.addElement(E); } } if(matches.isEmpty()) { myOccurrance=flags.occurrance; for (final Environmental E : list) { if((E!=null) &&(!(E instanceof Ability)) &&(containsString(E.displayText(),srchStr) ||((E instanceof MOB)&&containsString(((MOB)E).genericName(),srchStr)))) { if((--myOccurrance)<=0) matches.addElement(E); } } } } } catch (final java.lang.ArrayIndexOutOfBoundsException x) { } return matches; } @Override public Environmental fetchEnvironmental(final Map<String, ? extends Environmental> list, String srchStr, final boolean exactOnly) { if(list.isEmpty()) return null; final FetchFlags flags=fetchFlags(srchStr); if(flags==null) return null; srchStr=flags.srchStr; int myOccurrance=flags.occurrance; final boolean allFlag=flags.allFlag; if(list.get(srchStr)!=null) return list.get(srchStr); Environmental E=null; if(exactOnly) { srchStr=cleanExtraneousDollarMarkers(srchStr); for (final String string : list.keySet()) { E=list.get(string); if(E!=null) { if(E.ID().equalsIgnoreCase(srchStr) ||E.Name().equalsIgnoreCase(srchStr) ||E.name().equalsIgnoreCase(srchStr)) { if((!allFlag)||(E instanceof Ability)||((E.displayText()!=null)&&(E.displayText().length()>0))) { if((--myOccurrance)<=0) return E; } } } } } else { myOccurrance=flags.occurrance; for (final String string : list.keySet()) { E=list.get(string); if((E!=null) &&(containsString(E.name(),srchStr)||containsString(E.Name(),srchStr)) &&((!allFlag)||(E instanceof Ability)||((E.displayText()!=null)&&(E.displayText().length()>0)))) { if((--myOccurrance)<=0) return E; } } myOccurrance=flags.occurrance; for (final String string : list.keySet()) { E=list.get(string); if(E!=null) { if((containsString(E.displayText(),srchStr)) ||((E instanceof MOB) && containsString(((MOB)E).genericName(),srchStr))) { if((--myOccurrance)<=0) return E; } } } } return null; } @Override public Item fetchAvailableItem(final List<Item> list, String srchStr, final Item goodLocation, final Filterer<Environmental> filter, final boolean exactOnly) { if(list.isEmpty()) return null; final FetchFlags flags=fetchFlags(srchStr); if(flags==null) return null; srchStr=flags.srchStr; int myOccurrance=flags.occurrance; final boolean allFlag=flags.allFlag; if(exactOnly) { try { srchStr=cleanExtraneousDollarMarkers(srchStr); for (final Item I : list) { if(I==null) continue; if((I.container()==goodLocation) &&(filter.passesFilter(I)) &&(I.ID().equalsIgnoreCase(srchStr) ||(I.Name().equalsIgnoreCase(srchStr)) ||(I.name().equalsIgnoreCase(srchStr)))) { if((!allFlag) ||((I.displayText()!=null)&&(I.displayText().length()>0))) { if((--myOccurrance)<=0) return I; } } } } catch (final java.lang.ArrayIndexOutOfBoundsException x) { } } else { try { for (final Item I : list) { if((I!=null) &&(I.container()==goodLocation) &&(filter.passesFilter(I)) &&(containsString(I.name(),srchStr)||containsString(I.Name(),srchStr)) &&((!allFlag) ||((I.displayText()!=null)&&(I.displayText().length()>0)))) { if((--myOccurrance)<=0) return I; } } } catch (final java.lang.ArrayIndexOutOfBoundsException x) { } myOccurrance=flags.occurrance; try { for (final Item I : list) { if((I!=null) &&(I.container()==goodLocation) &&(filter.passesFilter(I)) &&(containsString(I.displayText(),srchStr))) { if((--myOccurrance)<=0) return I; } } } catch (final java.lang.ArrayIndexOutOfBoundsException x) { } } return null; } @Override public List<Item> fetchAvailableItems(final List<Item> list, String srchStr, final Item goodLocation, final Filterer<Environmental> filter, final boolean exactOnly) { final Vector<Item> matches=new Vector<Item>(1); // return value if(list.isEmpty()) return matches; final FetchFlags flags=fetchFlags(srchStr); if(flags==null) return matches; srchStr=flags.srchStr; int myOccurrance=flags.occurrance; final boolean allFlag=flags.allFlag; try { if(exactOnly) { srchStr=cleanExtraneousDollarMarkers(srchStr); for (final Item I : list) { if(I==null) continue; if((I.container()==goodLocation) &&(filter.passesFilter(I)) &&(I.ID().equalsIgnoreCase(srchStr) ||(I.Name().equalsIgnoreCase(srchStr)) ||(I.name().equalsIgnoreCase(srchStr)))) { if((!allFlag)||((I.displayText()!=null)&&(I.displayText().length()>0))) { if((--myOccurrance)<=0) matches.addElement(I); } } } } else { for (final Item I : list) { if(I==null) continue; if((I.container()==goodLocation) &&(filter.passesFilter(I)) &&(containsString(I.name(),srchStr)||containsString(I.Name(),srchStr)) &&((!allFlag)||((I.displayText()!=null)&&(I.displayText().length()>0)))) { if((--myOccurrance)<=0) matches.addElement(I); } } if(matches.isEmpty()) { myOccurrance=flags.occurrance; for (final Item I : list) { if(I==null) continue; if((I.container()==goodLocation) &&(filter.passesFilter(I)) &&(containsString(I.displayText(),srchStr))) { if((--myOccurrance)<=0) matches.addElement(I); } } } } } catch (final java.lang.ArrayIndexOutOfBoundsException x) { } return matches; } @Override public Environmental fetchAvailable(final Collection<? extends Environmental> list, String srchStr, final Item goodLocation, final Filterer<Environmental> filter, final boolean exactOnly, final int[] counterSlap) { if(list.isEmpty()) return null; final FetchFlags flags=fetchFlags(srchStr); if(flags==null) return null; srchStr=flags.srchStr; int myOccurrance=flags.occurrance - counterSlap[0]; final boolean allFlag=flags.allFlag; Item I=null; try { if(exactOnly) { srchStr=cleanExtraneousDollarMarkers(srchStr); for (final Environmental E : list) { if(E instanceof Item) { I=(Item)E; if((I.container()==goodLocation) &&(filter.passesFilter(I)) &&(I.ID().equalsIgnoreCase(srchStr) ||(I.Name().equalsIgnoreCase(srchStr)) ||(I.name().equalsIgnoreCase(srchStr)))) { if((!allFlag)||(E instanceof Ability)||((I.displayText()!=null)&&(I.displayText().length()>0))) { if((--myOccurrance)<=0) return I; } } } else if(E!=null) { if(E.ID().equalsIgnoreCase(srchStr) ||E.Name().equalsIgnoreCase(srchStr) ||E.name().equalsIgnoreCase(srchStr)) { if((!allFlag)||(E instanceof Ability)||((E.displayText()!=null)&&(E.displayText().length()>0))) { if((--myOccurrance)<=0) return E; } } } } } else { for (final Environmental E : list) { if(E instanceof Item) { I=(Item)E; if((I.container()==goodLocation) &&(filter.passesFilter(I)) &&(containsString(I.name(),srchStr)||containsString(I.Name(),srchStr)) &&((!allFlag)||(E instanceof Ability)||((I.displayText()!=null)&&(I.displayText().length()>0)))) { if((--myOccurrance)<=0) return I; } } else if((E!=null) &&(containsString(E.name(),srchStr)||containsString(E.Name(),srchStr)) &&((!allFlag)||(E instanceof Ability)||((E.displayText()!=null)&&(E.displayText().length()>0)))) { if((--myOccurrance)<=0) return E; } } myOccurrance=flags.occurrance - counterSlap[0]; for (final Environmental E : list) { if(E instanceof Item) { I=(Item)E; if((I.container()==goodLocation) &&(filter.passesFilter(I)) &&(containsString(I.displayText(),srchStr))) { if((--myOccurrance)<=0) return I; } } else if(E!=null) { if((containsString(E.displayText(),srchStr)) ||((E instanceof MOB)&&containsString(((MOB)E).genericName(),srchStr))) { if((--myOccurrance)<=0) return E; } } } } } catch (final java.lang.ArrayIndexOutOfBoundsException x) { } counterSlap[0]+=(flags.occurrance-myOccurrance); return null; } @Override public Environmental fetchAvailable(final Collection<? extends Environmental> list, String srchStr, final Item goodLocation, final Filterer<Environmental> filter, final boolean exactOnly) { if(list.isEmpty()) return null; final FetchFlags flags=fetchFlags(srchStr); if(flags==null) return null; srchStr=flags.srchStr; int myOccurrance=flags.occurrance; final boolean allFlag=flags.allFlag; Item I=null; try { if(exactOnly) { srchStr=cleanExtraneousDollarMarkers(srchStr); for (final Environmental E : list) { if(E instanceof Item) { I=(Item)E; if((I.container()==goodLocation) &&(filter.passesFilter(I)) &&(I.ID().equalsIgnoreCase(srchStr) ||(I.Name().equalsIgnoreCase(srchStr)) ||(I.name().equalsIgnoreCase(srchStr)))) { if((!allFlag)||(E instanceof Ability)||((I.displayText()!=null)&&(I.displayText().length()>0))) { if((--myOccurrance)<=0) return I; } } } else if(E!=null) { if(E.ID().equalsIgnoreCase(srchStr) ||E.Name().equalsIgnoreCase(srchStr) ||E.name().equalsIgnoreCase(srchStr)) { if((!allFlag) ||(E instanceof Ability) ||((E.displayText()!=null)&&(E.displayText().length()>0))) { if((--myOccurrance)<=0) return E; } } } } } else { for (final Environmental E : list) { if(E instanceof Item) { I=(Item)E; if((I.container()==goodLocation) &&(filter.passesFilter(I)) &&(containsString(I.name(),srchStr)||containsString(I.Name(),srchStr)) &&((!allFlag)||(E instanceof Ability)||((I.displayText()!=null)&&(I.displayText().length()>0)))) { if((--myOccurrance)<=0) return I; } } else if((E!=null) &&(containsString(E.name(),srchStr)||containsString(E.Name(),srchStr)) &&((!allFlag)||(E instanceof Ability)||((E.displayText()!=null)&&(E.displayText().length()>0)))) { if((--myOccurrance)<=0) return E; } } myOccurrance=flags.occurrance; for (final Environmental E : list) { if(E instanceof Item) { I=(Item)E; if((I.container()==goodLocation) &&(filter.passesFilter(I)) &&(containsString(I.displayText(),srchStr))) { if((--myOccurrance)<=0) return I; } } else if(E!=null) { if((containsString(E.displayText(),srchStr)) ||((E instanceof MOB)&&containsString(((MOB)E).genericName(),srchStr))) { if((--myOccurrance)<=0) return E; } } } } } catch (final java.lang.ArrayIndexOutOfBoundsException x) { } return null; } }
Moved and improved past-tense wordifier into English parsing. git-svn-id: 0cdf8356e41b2d8ccbb41bb76c82068fe80b2514@18196 0d6f1817-ed0e-0410-87c9-987e46238f29
com/planet_ink/coffee_mud/Libraries/EnglishParser.java
Moved and improved past-tense wordifier into English parsing.
<ide><path>om/planet_ink/coffee_mud/Libraries/EnglishParser.java <ide> final int x=word.indexOf(' '); <ide> if(x>0) <ide> word=word.substring(x+1).trim(); <add> if(word.endsWith("(s)")) <add> word=word.substring(0, word.length()-3); <add> if(word.endsWith("(es)")) <add> word=word.substring(0, word.length()-4); <add> if(word.endsWith("(ys)")) <add> word=word.substring(0, word.length()-4); <ide> if(CMStrings.isVowel(word.charAt(word.length()-1))) <ide> return word+"d"; <ide> else
Java
epl-1.0
3d2cee888ada796bdc12fce9129bd5f36036733a
0
ESSICS/cs-studio,ControlSystemStudio/cs-studio,ControlSystemStudio/cs-studio,ESSICS/cs-studio,ESSICS/cs-studio,css-iter/cs-studio,ControlSystemStudio/cs-studio,css-iter/cs-studio,ControlSystemStudio/cs-studio,ESSICS/cs-studio,ControlSystemStudio/cs-studio,css-iter/cs-studio,ESSICS/cs-studio,css-iter/cs-studio,ESSICS/cs-studio,css-iter/cs-studio,ESSICS/cs-studio,css-iter/cs-studio,ControlSystemStudio/cs-studio,css-iter/cs-studio
/* * Copyright (c) 2008 Stiftung Deutsches Elektronen-Synchrotron, * Member of the Helmholtz Association, (DESY), HAMBURG, GERMANY. * * THIS SOFTWARE IS PROVIDED UNDER THIS LICENSE ON AN "../AS IS" BASIS. * WITHOUT WARRANTY OF ANY KIND, EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED * TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR PARTICULAR PURPOSE AND * NON-INFRINGEMENT. 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. SHOULD THE SOFTWARE PROVE DEFECTIVE * IN ANY RESPECT, THE USER ASSUMES THE COST OF ANY NECESSARY SERVICING, REPAIR OR * CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. * NO USE OF ANY SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS DISCLAIMER. * DESY HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, * OR MODIFICATIONS. * THE FULL LICENSE SPECIFYING FOR THE SOFTWARE THE REDISTRIBUTION, MODIFICATION, * USAGE AND OTHER RIGHTS AND OBLIGATIONS IS INCLUDED WITH THE DISTRIBUTION OF THIS * PROJECT IN THE FILE LICENSE.HTML. IF THE LICENSE IS NOT INCLUDED YOU MAY FIND A COPY * AT HTTP://WWW.DESY.DE/LEGAL/LICENSE.HTM */ package org.csstudio.alarm.treeView.views; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.csstudio.alarm.table.SendAcknowledge; import org.csstudio.alarm.treeView.AlarmTreePlugin; import org.csstudio.alarm.treeView.jms.JmsConnectionException; import org.csstudio.alarm.treeView.jms.JmsConnector; import org.csstudio.alarm.treeView.ldap.DirectoryEditException; import org.csstudio.alarm.treeView.ldap.DirectoryEditor; import org.csstudio.alarm.treeView.ldap.LdapDirectoryReader; import org.csstudio.alarm.treeView.ldap.LdapDirectoryStructureReader; import org.csstudio.alarm.treeView.model.IAlarmTreeNode; import org.csstudio.alarm.treeView.model.ObjectClass; import org.csstudio.alarm.treeView.model.ProcessVariableNode; import org.csstudio.alarm.treeView.model.Severity; import org.csstudio.alarm.treeView.model.SubtreeNode; import org.csstudio.platform.logging.CentralLogger; import org.csstudio.platform.model.IProcessVariable; import org.csstudio.platform.ui.internal.dataexchange.ProcessVariableNameTransfer; import org.csstudio.platform.ui.util.EditorUtil; import org.csstudio.platform.utility.jms.IConnectionMonitor; import org.csstudio.sds.ui.runmode.RunModeService; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.IJobChangeEvent; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.core.runtime.jobs.JobChangeAdapter; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.dialogs.IInputValidator; import org.eclipse.jface.dialogs.InputDialog; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.util.LocalSelectionTransfer; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.ViewerComparator; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.jface.window.Window; import org.eclipse.swt.SWT; import org.eclipse.swt.dnd.DND; import org.eclipse.swt.dnd.DragSourceAdapter; import org.eclipse.swt.dnd.DragSourceEvent; import org.eclipse.swt.dnd.DropTargetAdapter; import org.eclipse.swt.dnd.DropTargetEvent; import org.eclipse.swt.dnd.DropTargetListener; import org.eclipse.swt.dnd.TextTransfer; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.TreeItem; import org.eclipse.ui.IActionBars; import org.eclipse.ui.IWorkbenchActionConstants; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.browser.IWebBrowser; import org.eclipse.ui.part.ViewPart; import org.eclipse.ui.progress.IWorkbenchSiteProgressService; import org.eclipse.ui.progress.PendingUpdateAdapter; import org.eclipse.ui.views.IViewDescriptor; import org.eclipse.ui.views.IViewRegistry; /** * Tree view of process variables and their alarm state. This view uses LDAP * to get a hierarchy of process variables and displays them in a tree view. * Process variables which are in an alarm state are visually marked in the * view. * * @author Joerg Rathlev */ public class AlarmTreeView extends ViewPart { /** * Monitors the connection to the JMS backend system and displays a message * in the tree view if the JMS connection fails. When the JMS connection is * established or restored, triggers loading the current state from the * LDAP directory. */ private final class AlarmTreeConnectionMonitor implements IConnectionMonitor { /** * {@inheritDoc} */ public void onConnected() { Display.getDefault().asyncExec(new Runnable() { public void run() { hideMessage(); // TODO: This rebuilds the whole tree from // scratch. It would be better for the // usability to resynchronize only. startDirectoryReaderJob(); } }); } /** * {@inheritDoc} */ public void onDisconnected() { Display.getDefault().asyncExec(new Runnable() { public void run() { setMessage( SWT.ICON_WARNING, "Connection error", "Some or all of the information displayed " + "may be outdated. The alarm tree is currently " + "not connected to all alarm servers."); } }); } } /** * Implements drag support for the alarm tree. */ private final class AlarmTreeDragListener extends DragSourceAdapter { private ArrayList<ProcessVariableNode> _selectedPVs; @Override public void dragStart(DragSourceEvent event) { ISelection selection = _viewer.getSelection(); if (selection instanceof IStructuredSelection) { _selectedPVs = new ArrayList<ProcessVariableNode>(); IStructuredSelection sel = (IStructuredSelection) selection; for (Iterator<?> i = sel.iterator(); i.hasNext(); ) { Object o = i.next(); if (o instanceof ProcessVariableNode) { _selectedPVs.add((ProcessVariableNode) o); } else { // If any of the selected items is not a PV, the drag // operation is not allowed. event.doit = false; _selectedPVs = null; return; } } } else { event.doit = false; return; } } @Override public void dragSetData(DragSourceEvent event) { if (LocalSelectionTransfer.getTransfer().isSupportedType( event.dataType)) { LocalSelectionTransfer.getTransfer().setSelection( _viewer.getSelection()); } if (ProcessVariableNameTransfer.getInstance().isSupportedType( event.dataType)) { event.data = _selectedPVs.toArray(new IProcessVariable[_selectedPVs.size()]); } else if (TextTransfer.getInstance().isSupportedType(event.dataType)) { StringBuilder text = new StringBuilder(); for (Iterator<ProcessVariableNode> i = _selectedPVs.iterator(); i.hasNext(); ) { text.append(i.next().getName()); if (i.hasNext()) { text.append(", "); } } event.data = text.toString(); } } /** * {@inheritDoc} */ @Override public void dragFinished(DragSourceEvent event) { if (event.detail == DND.DROP_MOVE) { for (ProcessVariableNode node : _selectedPVs) { try { DirectoryEditor.delete(node); } catch (DirectoryEditException e) { _log.error(this, "Could not delete node after drag&drop move operation: " + node); } } _viewer.refresh(); } _selectedPVs = null; } } /** * Implements drop support for the alarm tree. This implementation supports * dropping process variables (<code>IProcessVariable</code>) onto subtree * nodes. */ private final class AlarmTreeDropListener extends DropTargetAdapter { /** * The drop operation that the user wants to perform. This drop listener * sets event.detail to DROP_NONE when the user drags over a tree item * which does not support dropping; when the user later drags over * another tree item, the operation remembered in this variable will be * restored. * * See also http://dev.eclipse.org/newslists/news.eclipse.platform.swt/msg11183.html */ int _operation; @Override public void dragEnter(final DropTargetEvent event) { _operation = event.detail; } @Override public void dragOperationChanged(final DropTargetEvent event) { _operation = event.detail; } /** * This implementation of <code>dragOver</code> permits dropping if the * target item is a subtree node. If the mouse is not hovering over any * item in the tree or if the item is a process variable node, dropping * is not permitted. * * @param event * the event. * @see DropTargetListener#dragOver(DropTargetEvent) */ @Override public void dragOver(final DropTargetEvent event) { event.feedback = DND.FEEDBACK_SCROLL | DND.FEEDBACK_EXPAND; // Allow the drag&drop operation if the mouse is dragged over a tree // item and the item is a subtree node. if ((event.item instanceof TreeItem) && ((TreeItem) event.item).getData() instanceof SubtreeNode) { event.detail = _operation; event.feedback |= DND.FEEDBACK_SELECT; return; } else { event.detail = DND.DROP_NONE; return; } } /** * This implementation of <code>drop</code> performs the drop, if * possible. * * @param event * the event. * @see DropTargetListener#drop(DropTargetEvent) */ @Override public void drop(final DropTargetEvent event) { // Get the node the PVs are dropped into. If for some reason // the node is not a subtree node, reject the drop. TreeItem item = (TreeItem) event.item; if (item != null && item.getData() instanceof SubtreeNode) { SubtreeNode node = (SubtreeNode) item.getData(); IProcessVariable[] droppedPVs = null; if (ProcessVariableNameTransfer.getInstance().isSupportedType(event.currentDataType)) { droppedPVs = (IProcessVariable[]) event.data; } else if (LocalSelectionTransfer.getTransfer().isSupportedType(event.currentDataType)) { ISelection sel = LocalSelectionTransfer.getTransfer().getSelection(); List<IProcessVariable> pvs = new ArrayList<IProcessVariable>(); if (sel instanceof IStructuredSelection) { IStructuredSelection selection = (IStructuredSelection) sel; for (Iterator<?> i = selection.iterator(); i.hasNext(); ) { Object selected = i.next(); if (selected instanceof IProcessVariable) { pvs.add((IProcessVariable) selected); } } } droppedPVs = (IProcessVariable[]) pvs.toArray(new IProcessVariable[pvs .size()]); } else { // Unknown transfer type event.detail = DND.DROP_NONE; return; } boolean errors = false; for (IProcessVariable pv : droppedPVs) { try { DirectoryEditor.createProcessVariableRecord(node, pv.getName()); } catch (DirectoryEditException e) { errors = true; } } _viewer.refresh(node); if (errors) { MessageDialog.openError(getSite().getShell(), "Create New Records", "One or more of the records could not be created."); } } else { event.detail = DND.DROP_NONE; } } } /** * This action opens the strip chart associated with the selected node. */ private class OpenStripChartAction extends Action { /** * {@inheritDoc} */ @Override public void run() { IAlarmTreeNode node = getSelectedNode(); if (node != null) { IPath path = new Path(node.getCssStripChart()); // The following code assumes that the path is relative to // the Eclipse workspace. IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(path); IWorkbenchPage page = getSite().getPage(); try { EditorUtil.openEditor(page, file); } catch (PartInitException e) { MessageDialog.openError(getSite().getShell(), "Alarm Tree", e.getMessage()); } } } /** * Returns the node that is currently selected in the tree. * * @return the selected node, or <code>null</code> if the selection is * empty or the selected node is not of type * <code>IAlarmTreeNode</code>. */ private IAlarmTreeNode getSelectedNode() { IStructuredSelection selection = (IStructuredSelection) _viewer.getSelection(); Object selected = selection.getFirstElement(); if (selected instanceof IAlarmTreeNode) { return (IAlarmTreeNode) selected; } return null; } } /** * The ID of this view. */ private static final String ID = "org.csstudio.alarm.treeView.views.LdapTView"; /** * The ID of the property view. */ private static final String PROPERTY_VIEW_ID = "org.eclipse.ui.views.PropertySheet"; /** * The tree viewer that displays the alarm objects. */ private TreeViewer _viewer; /** * The reload action. */ private Action _reloadAction; /** * The subscriber to the JMS alarm topic. */ private JmsConnector _jmsConnector; /** * The acknowledge action. */ private Action _acknowledgeAction; /** * The Run CSS Alarm Display action. */ private Action _runCssAlarmDisplayAction; /** * The Run CSS Display action. */ private Action _runCssDisplayAction; /** * The Open CSS Strip Chart action. */ private Action _openCssStripChartAction; /** * The Show Help Page action. */ private Action _showHelpPageAction; /** * The Show Help Guidance action. */ private Action _showHelpGuidanceAction; /** * The Create Record action. */ private Action _createRecordAction; /** * The Create Component action. */ private Action _createComponentAction; /** * The Delete action. */ private Action _deleteNodeAction; /** * The Show Property View action. */ private Action _showPropertyViewAction; /** * The message area which can display error messages inside the view part. */ private Composite _messageArea; /** * The icon displayed in the message area. */ private Label _messageAreaIcon; /** * The message displayed in the message area. */ private Label _messageAreaMessage; /** * The description displayed in the message area. */ private Label _messageAreaDescription; /** * A filter which hides all nodes which are not currently in an alarm state. */ private ViewerFilter _currentAlarmFilter; /** * The action which toggles the filter on and off. */ private Action _toggleFilterAction; /** * Whether the filter is active. */ private boolean _isFilterActive; /** * The connection monitor instance which monitors the JMS connection of * this tree view. */ private AlarmTreeConnectionMonitor _connectionMonitor; /** * The logger used by this view. */ private final CentralLogger _log = CentralLogger.getInstance(); /** * Returns the id of this view. * @return the id of this view. */ public static String getID(){ return ID; } /** * Creates an LDAP tree viewer. */ public AlarmTreeView() { } /** * {@inheritDoc} */ public final void createPartControl(final Composite parent) { GridLayout layout = new GridLayout(1, false); layout.marginHeight = 0; layout.marginWidth = 0; parent.setLayout(layout); _messageArea = new Composite(parent, SWT.NONE); final GridData messageAreaLayoutData = new GridData(SWT.FILL, SWT.FILL, true, false); messageAreaLayoutData.exclude = true; _messageArea.setVisible(false); _messageArea.setLayoutData(messageAreaLayoutData); _messageArea.setLayout(new GridLayout(2, false)); _messageAreaIcon = new Label(_messageArea, SWT.NONE); _messageAreaIcon.setLayoutData(new GridData(SWT.BEGINNING, SWT.BEGINNING, false, false, 1, 2)); _messageAreaIcon.setImage(Display.getCurrent().getSystemImage(SWT.ICON_WARNING)); _messageAreaMessage = new Label(_messageArea, SWT.WRAP); _messageAreaMessage.setText("Test message"); // Be careful if changing the GridData below! The label will not wrap // correctly for some settings. _messageAreaMessage.setLayoutData(new GridData(SWT.FILL, SWT.BEGINNING, true, false)); _messageAreaDescription = new Label(_messageArea, SWT.WRAP); _messageAreaDescription.setText("This is an explanation of the test message."); // Be careful if changing the GridData below! The label will not wrap // correctly for some settings. _messageAreaDescription.setLayoutData(new GridData(SWT.FILL, SWT.BEGINNING, true, false)); _viewer = new TreeViewer(parent, SWT.BORDER | SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL); _viewer.getControl().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); _viewer.setContentProvider(new AlarmTreeContentProvider()); _viewer.setLabelProvider(new AlarmTreeLabelProvider()); _viewer.setComparator(new ViewerComparator()); _currentAlarmFilter = new CurrentAlarmFilter(); initializeContextMenu(); makeActions(); contributeToActionBars(); getSite().setSelectionProvider(_viewer); startJmsConnection(); _viewer.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(final SelectionChangedEvent event) { AlarmTreeView.this.selectionChanged(event); } }); addDragAndDropSupport(); } /** * Starts the JMS connection. */ private void startJmsConnection() { _log.debug(this, "Starting JMS connection."); if (_jmsConnector != null) { // There is still an old connection. This shouldn't happen. _jmsConnector.disconnect(); _log.warn(this, "There was an active JMS connection when starting a new connection"); } final IWorkbenchSiteProgressService progressService = (IWorkbenchSiteProgressService) getSite().getAdapter( IWorkbenchSiteProgressService.class); Job jmsConnectionJob = new Job("Connecting to JMS brokers") { @Override protected IStatus run(final IProgressMonitor monitor) { monitor.beginTask("Connecting to JMS servers", IProgressMonitor.UNKNOWN); _jmsConnector = new JmsConnector(); _connectionMonitor = new AlarmTreeConnectionMonitor(); _jmsConnector.addConnectionMonitor(_connectionMonitor); try { _jmsConnector.connect(); } catch (JmsConnectionException e) { throw new RuntimeException("Could not connect to JMS brokers.", e); } return Status.OK_STATUS; } }; progressService.schedule(jmsConnectionJob, 0, true); } /** * Adds drag and drop support to the tree viewer. */ private void addDragAndDropSupport() { // The transfer types final Transfer pvTransfer = ProcessVariableNameTransfer.getInstance(); final Transfer textTransfer = TextTransfer.getInstance(); final Transfer localTransfer = LocalSelectionTransfer.getTransfer(); _viewer.addDropSupport(DND.DROP_COPY | DND.DROP_MOVE, new Transfer[] {pvTransfer}, new AlarmTreeDropListener()); _viewer.addDragSupport(DND.DROP_COPY | DND.DROP_MOVE, new Transfer[] {pvTransfer, textTransfer}, new AlarmTreeDragListener()); } /** * Starts a job which reads the contents of the directory in the background. */ private void startDirectoryReaderJob() { _log.debug(this, "Starting directory reader."); final IWorkbenchSiteProgressService progressService = (IWorkbenchSiteProgressService) getSite().getAdapter( IWorkbenchSiteProgressService.class); final SubtreeNode rootNode = new SubtreeNode("ROOT"); Job directoryReader = new LdapDirectoryReader(rootNode); // Add a listener that sets the viewers input to the root node // when the reader job is finished. directoryReader.addJobChangeListener(new JobChangeAdapter() { @Override public void done(final IJobChangeEvent event) { // Display the new tree. asyncSetViewerInput(rootNode); Job directoryUpdater = new LdapDirectoryStructureReader(rootNode); directoryUpdater.addJobChangeListener(new JobChangeAdapter() { @Override public void done(final IJobChangeEvent event) { // Apply updates to the new tree _jmsConnector.setUpdateTarget(rootNode); getSite().getShell().getDisplay().asyncExec(new Runnable() { public void run() { _viewer.refresh(); } }); } }); progressService.schedule(directoryUpdater, 0, true); } }); // Set the tree to which updates are applied to null. This means updates // will be queued for later application. _jmsConnector.setUpdateTarget(null); // The directory is read in the background. Until then, set the viewer's // input to a placeholder object. _viewer.setInput(new Object[] {new PendingUpdateAdapter()}); // Start the directory reader job. progressService.schedule(directoryReader, 0, true); } /** * Stops the alarm queue subscriber. */ private void disposeJmsListener() { // Remove the connection monitor, so that it doesn't try to display an // error message in this disposed view when the connection is closed. _jmsConnector.removeConnectionMonitor(_connectionMonitor); _connectionMonitor = null; _jmsConnector.disconnect(); } /** * Sets the message displayed in the message area of this view part. * * @param icon * the icon to be displayed next to the message. Must be one of * <code>SWT.ICON_ERROR</code>, * <code>SWT.ICON_INFORMATION</code>, * <code>SWT.ICON_WARNING</code>, * <code>SWT.ICON_QUESTION</code>. * @param message * the message. * @param description * a descriptive text. */ private void setMessage(final int icon, final String message, final String description) { _messageAreaIcon.setImage(Display.getCurrent().getSystemImage(icon)); _messageAreaMessage.setText(message); _messageAreaDescription.setText(description); _messageArea.layout(); _messageArea.setVisible(true); ((GridData) _messageArea.getLayoutData()).exclude = false; _messageArea.getParent().layout(); } /** * Hides the message displayed in this view part. */ private void hideMessage() { _messageArea.setVisible(false); ((GridData) _messageArea.getLayoutData()).exclude = true; _messageArea.getParent().layout(); } /** * Sets the input for the tree. The actual work will be done asynchronously * in the UI thread. * @param inputElement the new input element. */ private void asyncSetViewerInput(final SubtreeNode inputElement) { getSite().getShell().getDisplay().asyncExec(new Runnable() { public void run() { _viewer.setInput(inputElement); } }); } /** * {@inheritDoc} */ @Override public final void dispose() { disposeJmsListener(); super.dispose(); } /** * Called when the selection of the tree changes. * @param event the selection event. */ private void selectionChanged(final SelectionChangedEvent event) { IStructuredSelection sel = (IStructuredSelection) event.getSelection(); _acknowledgeAction.setEnabled(containsNodeWithUnackAlarm(sel)); _runCssAlarmDisplayAction.setEnabled(hasCssAlarmDisplay(sel.getFirstElement())); _runCssDisplayAction.setEnabled(hasCssDisplay(sel.getFirstElement())); _openCssStripChartAction.setEnabled(hasCssStripChart(sel.getFirstElement())); _showHelpGuidanceAction.setEnabled(hasHelpGuidance(sel.getFirstElement())); _showHelpPageAction.setEnabled(hasHelpPage(sel.getFirstElement())); } /** * Returns whether the given node has a CSS strip chart. * * @param node the node. * @return <code>true</code> if the node has a strip chart, * <code>false</code> otherwise. */ private boolean hasCssStripChart(final Object node) { if (node instanceof IAlarmTreeNode) { return ((IAlarmTreeNode) node).getCssStripChart() != null; } return false; } /** * Returns whether the given node has a CSS display. * * @param node the node. * @return <code>true</code> if the node has a display, <code>false</code> * otherwise. */ private boolean hasCssDisplay(final Object node) { if (node instanceof IAlarmTreeNode) { return ((IAlarmTreeNode) node).getCssDisplay() != null; } return false; } /** * Return whether help guidance is available for the given node. * @param node the node. * @return <code>true</code> if the node has a help guidance string, * <code>false</code> otherwise. */ private boolean hasHelpGuidance(final Object node) { if (node instanceof IAlarmTreeNode) { return ((IAlarmTreeNode) node).getHelpGuidance() != null; } return false; } /** * Return whether the given node has an associated help page. * * @param node the node. * @return <code>true</code> if the node has an associated help page, * <code>false</code> otherwise. */ private boolean hasHelpPage(final Object node) { if (node instanceof IAlarmTreeNode) { return ((IAlarmTreeNode) node).getHelpPage() != null; } return false; } /** * Returns whether the given process variable node in the tree has an * associated CSS alarm display configured. * * @param node the node. * @return <code>true</code> if a CSS alarm display is configured for the * node, <code>false</code> otherwise. */ private boolean hasCssAlarmDisplay(final Object node) { if (node instanceof IAlarmTreeNode) { String display = ((IAlarmTreeNode) node).getCssAlarmDisplay(); return display != null && display.matches(".+\\.css-sds"); } return false; } /** * Returns whether the given selection contains at least one node with * an unacknowledged alarm. * * @param sel the selection. * @return <code>true</code> if the selection contains a node with an * unacknowledged alarm, <code>false</code> otherwise. */ private boolean containsNodeWithUnackAlarm(final IStructuredSelection sel) { Object selectedElement = sel.getFirstElement(); // Note: selectedElement is not instance of IAlarmTreeNode if nothing // is selected (selectedElement == null), and during initialization, // when it is an instance of PendingUpdateAdapter. if (selectedElement instanceof IAlarmTreeNode) { return ((IAlarmTreeNode) selectedElement) .getUnacknowledgedAlarmSeverity() != Severity.NO_ALARM; } return false; } /** * Adds a context menu to the tree view. */ private void initializeContextMenu() { MenuManager menuMgr = new MenuManager("#PopupMenu"); menuMgr.setRemoveAllWhenShown(true); // add menu items to the context menu when it is about to show menuMgr.addMenuListener(new IMenuListener() { public void menuAboutToShow(final IMenuManager manager) { AlarmTreeView.this.fillContextMenu(manager); } }); // add the context menu to the tree viewer Menu contextMenu = menuMgr.createContextMenu(_viewer.getTree()); _viewer.getTree().setMenu(contextMenu); // register the context menu for extension by other plug-ins getSite().registerContextMenu(menuMgr, _viewer); } /** * Adds tool buttons and menu items to the action bar of this view. */ private void contributeToActionBars() { IActionBars bars = getViewSite().getActionBars(); fillLocalPullDown(bars.getMenuManager()); fillLocalToolBar(bars.getToolBarManager()); } /** * Adds the actions for the action bar's pull down menu. * @param manager the menu manager. */ private void fillLocalPullDown(final IMenuManager manager) { } /** * Adds the context menu actions. * @param menu the menu manager. */ private void fillContextMenu(final IMenuManager menu) { IStructuredSelection selection = (IStructuredSelection) _viewer .getSelection(); if (selection.size() > 0) { menu.add(_acknowledgeAction); } if (selection.size() == 1) { menu.add(_runCssAlarmDisplayAction); menu.add(_runCssDisplayAction); menu.add(_openCssStripChartAction); menu.add(_showHelpGuidanceAction); menu.add(_showHelpPageAction); menu.add(new Separator("edit")); menu.add(_deleteNodeAction); } if (selection.size() == 1 && selection.getFirstElement() instanceof SubtreeNode) { menu.add(_createRecordAction); updateCreateComponentActionText(); menu.add(_createComponentAction); } // adds a separator after which contributed actions from other plug-ins // will be displayed menu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS)); } /** * Updates the text of the Create Component action based on the object class * of the currently selected node. */ private void updateCreateComponentActionText() { SubtreeNode node = (SubtreeNode) ((IStructuredSelection) _viewer. getSelection()).getFirstElement(); ObjectClass oclass = node.getRecommendedChildSubtreeClass(); if (oclass == ObjectClass.SUBCOMPONENT) { _createComponentAction.setText("Create Subcomponent"); } else { _createComponentAction.setText("Create Component"); } } /** * Adds the tool bar actions. * @param manager the menu manager. */ private void fillLocalToolBar(final IToolBarManager manager) { manager.add(_toggleFilterAction); manager.add(new Separator()); manager.add(_showPropertyViewAction); manager.add(_reloadAction); } /** * Creates the actions offered by this view. */ private void makeActions() { _reloadAction = new Action() { public void run() { startDirectoryReaderJob(); } }; _reloadAction.setText("Reload"); _reloadAction.setToolTipText("Reload"); _reloadAction.setImageDescriptor( AlarmTreePlugin.getImageDescriptor("./icons/refresh.gif")); _acknowledgeAction = new Action() { @Override public void run() { Set<Map<String, String>> messages = new HashSet<Map<String, String>>(); IStructuredSelection selection = (IStructuredSelection) _viewer .getSelection(); for (Iterator<?> i = selection.iterator(); i .hasNext();) { Object o = i.next(); if (o instanceof SubtreeNode) { SubtreeNode snode = (SubtreeNode) o; for (ProcessVariableNode pvnode : snode.collectUnacknowledgedAlarms()) { String name = pvnode.getName(); Severity severity = pvnode.getUnacknowledgedAlarmSeverity(); Map<String, String> properties = new HashMap<String, String>(); properties.put("NAME", name); properties.put("SEVERITY", severity.toString()); messages.add(properties); } } else if (o instanceof ProcessVariableNode) { ProcessVariableNode pvnode = (ProcessVariableNode) o; String name = pvnode.getName(); Severity severity = pvnode.getUnacknowledgedAlarmSeverity(); Map<String, String> properties = new HashMap<String, String>(); properties.put("NAME", name); properties.put("SEVERITY", severity.toString()); messages.add(properties); } } if (!messages.isEmpty()) { CentralLogger.getInstance().debug(this, "Scheduling send acknowledgement (" + messages.size() + " messages)"); SendAcknowledge ackJob = SendAcknowledge.newFromProperties(messages); ackJob.schedule(); } } }; _acknowledgeAction.setText("Send Acknowledgement"); _acknowledgeAction.setToolTipText("Send alarm acknowledgement"); _acknowledgeAction.setEnabled(false); _runCssAlarmDisplayAction = new Action() { @Override public void run() { IStructuredSelection selection = (IStructuredSelection) _viewer .getSelection(); Object selected = selection.getFirstElement(); if (selected instanceof IAlarmTreeNode) { IAlarmTreeNode node = (IAlarmTreeNode) selected; IPath path = new Path(node.getCssAlarmDisplay()); Map<String, String> aliases = new HashMap<String, String>(); if (node instanceof ProcessVariableNode) { aliases.put("channel", node.getName()); } CentralLogger.getInstance().debug(this, "Opening display: " + path); RunModeService.getInstance().openDisplayShellInRunMode(path, aliases); } } }; _runCssAlarmDisplayAction.setText("Run Alarm Display"); _runCssAlarmDisplayAction.setToolTipText("Run the alarm display for this PV"); _runCssAlarmDisplayAction.setEnabled(false); _runCssDisplayAction = new Action() { @Override public void run() { IStructuredSelection selection = (IStructuredSelection) _viewer.getSelection(); Object selected = selection.getFirstElement(); if (selected instanceof IAlarmTreeNode) { IAlarmTreeNode node = (IAlarmTreeNode) selected; IPath path = new Path(node.getCssDisplay()); Map<String,String> aliases = new HashMap<String, String>(); if (node instanceof ProcessVariableNode) { aliases.put("channel", node.getName()); } CentralLogger.getInstance().debug(this, "Opening display: " + path); RunModeService.getInstance().openDisplayShellInRunMode(path, aliases); } } }; _runCssDisplayAction.setText("Run Display"); _runCssDisplayAction.setToolTipText("Run the display for this PV"); _runCssDisplayAction.setEnabled(false); _openCssStripChartAction = new OpenStripChartAction(); _openCssStripChartAction.setText("Open Strip Chart"); _openCssStripChartAction.setToolTipText("Open the strip chart for this node"); _openCssStripChartAction.setEnabled(false); _showHelpGuidanceAction = new Action() { @Override public void run() { IStructuredSelection selection = (IStructuredSelection) _viewer .getSelection(); Object selected = selection.getFirstElement(); if (selected instanceof IAlarmTreeNode) { IAlarmTreeNode node = (IAlarmTreeNode) selected; String helpGuidance = node.getHelpGuidance(); if (helpGuidance != null) { MessageDialog.openInformation(getSite().getShell(), node.getName(), helpGuidance); } } } }; _showHelpGuidanceAction.setText("Show Help Guidance"); _showHelpGuidanceAction.setToolTipText("Show the help guidance for this node"); _showHelpGuidanceAction.setEnabled(false); _showHelpPageAction = new Action() { @Override public void run() { IStructuredSelection selection = (IStructuredSelection) _viewer .getSelection(); Object selected = selection.getFirstElement(); if (selected instanceof IAlarmTreeNode) { IAlarmTreeNode node = (IAlarmTreeNode) selected; URL helpPage = node.getHelpPage(); if (helpPage != null) { try { // Note: we have to pass a browser id here to work // around a bug in eclipse. The method documentation // says that createBrowser accepts null but it will // throw a NullPointerException. // See https://bugs.eclipse.org/bugs/show_bug.cgi?id=194988 IWebBrowser browser = PlatformUI.getWorkbench() .getBrowserSupport() .createBrowser("workaround"); browser.openURL(helpPage); } catch (PartInitException e) { CentralLogger.getInstance().error(this, "Failed to initialize workbench browser.", e); } } } } }; _showHelpPageAction.setText("Open Help Page"); _showHelpPageAction.setToolTipText("Open the help page for this node in the web browser"); _showHelpPageAction.setEnabled(false); _createRecordAction = new Action() { @Override public void run() { IStructuredSelection selection = (IStructuredSelection) _viewer.getSelection(); Object selected = selection.getFirstElement(); if (selected instanceof SubtreeNode) { SubtreeNode parent = (SubtreeNode) selected; String name = promptForRecordName(); if (name != null && !name.equals("")) { try { DirectoryEditor.createProcessVariableRecord(parent, name); } catch (DirectoryEditException e) { MessageDialog.openError(getSite().getShell(), "Create New Record", "Could not create the new record: " + e.getMessage()); } _viewer.refresh(parent); } } } private String promptForRecordName() { InputDialog dialog = new InputDialog(getSite().getShell(), "Create New Record", "Record name:", null, new IInputValidator() { public String isValid(final String newText) { if (newText.equals("")) { return "Please enter a name."; } else if (newText.indexOf("=") != -1 || newText.indexOf("/") != -1 || newText.indexOf(",") != -1) { return "The following characters are not allowed " + "in names: = / ,"; } else { return null; } } }); if (Window.OK == dialog.open()) { return dialog.getValue(); } return null; } }; _createRecordAction.setText("Create Record"); _createComponentAction = new Action() { @Override public void run() { IStructuredSelection selection = (IStructuredSelection) _viewer.getSelection(); Object selected = selection.getFirstElement(); if (selected instanceof SubtreeNode) { SubtreeNode parent = (SubtreeNode) selected; String name = promptForRecordName(); if (name != null && !name.equals("")) { try { DirectoryEditor.createComponent(parent, name); } catch (DirectoryEditException e) { MessageDialog.openError(getSite().getShell(), "Create New Component", "Could not create the new component: " + e.getMessage()); } _viewer.refresh(parent); } } } private String promptForRecordName() { InputDialog dialog = new InputDialog(getSite().getShell(), "Create New Component", "Component name:", null, new IInputValidator() { public String isValid(final String newText) { if (newText.equals("")) { return "Please enter a name."; } else if (newText.indexOf("=") != -1 || newText.indexOf("/") != -1 || newText.indexOf(",") != -1) { return "The following characters are not allowed " + "in names: = / ,"; } else { return null; } } }); if (Window.OK == dialog.open()) { return dialog.getValue(); } return null; } }; _createComponentAction.setText("Create Component"); _deleteNodeAction = new Action() { @Override public void run() { IStructuredSelection selection = (IStructuredSelection) _viewer.getSelection(); Object selected = selection.getFirstElement(); if (selected instanceof IAlarmTreeNode) { IAlarmTreeNode nodeToDelete = (IAlarmTreeNode) selected; SubtreeNode parent = nodeToDelete.getParent(); try { DirectoryEditor.delete(nodeToDelete); _viewer.refresh(parent); } catch (DirectoryEditException e) { MessageDialog.openError(getSite().getShell(), "Delete", "Could not delete this node: " + e.getMessage()); } } } }; _deleteNodeAction.setText("Delete"); _showPropertyViewAction = new Action() { @Override public void run() { try { getSite().getPage().showView(PROPERTY_VIEW_ID); } catch (PartInitException e) { MessageDialog.openError(getSite().getShell(), "Alarm Tree", e.getMessage()); } } }; _showPropertyViewAction.setText("Properties"); _showPropertyViewAction.setToolTipText("Show property view"); IViewRegistry viewRegistry = getSite().getWorkbenchWindow().getWorkbench().getViewRegistry(); IViewDescriptor viewDesc = viewRegistry.find(PROPERTY_VIEW_ID); _showPropertyViewAction.setImageDescriptor(viewDesc.getImageDescriptor()); _toggleFilterAction = new Action("Show Only Alarms", Action.AS_CHECK_BOX) { @Override public void run() { if (_isFilterActive) { _viewer.removeFilter(_currentAlarmFilter); _isFilterActive = false; } else { _viewer.addFilter(_currentAlarmFilter); _isFilterActive = true; } } }; _toggleFilterAction.setToolTipText("Show Only Alarms"); _toggleFilterAction.setChecked(_isFilterActive); _toggleFilterAction.setImageDescriptor( AlarmTreePlugin.getImageDescriptor("./icons/no_alarm_filter.png")); } /** * Passes the focus request to the viewer's control. */ public final void setFocus() { _viewer.getControl().setFocus(); } /** * Refreshes this view. */ public final void refresh(){ _viewer.refresh(); } }
applications/plugins/org.csstudio.alarm.treeView/src/org/csstudio/alarm/treeView/views/AlarmTreeView.java
/* * Copyright (c) 2008 Stiftung Deutsches Elektronen-Synchrotron, * Member of the Helmholtz Association, (DESY), HAMBURG, GERMANY. * * THIS SOFTWARE IS PROVIDED UNDER THIS LICENSE ON AN "../AS IS" BASIS. * WITHOUT WARRANTY OF ANY KIND, EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED * TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR PARTICULAR PURPOSE AND * NON-INFRINGEMENT. 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. SHOULD THE SOFTWARE PROVE DEFECTIVE * IN ANY RESPECT, THE USER ASSUMES THE COST OF ANY NECESSARY SERVICING, REPAIR OR * CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. * NO USE OF ANY SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS DISCLAIMER. * DESY HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, * OR MODIFICATIONS. * THE FULL LICENSE SPECIFYING FOR THE SOFTWARE THE REDISTRIBUTION, MODIFICATION, * USAGE AND OTHER RIGHTS AND OBLIGATIONS IS INCLUDED WITH THE DISTRIBUTION OF THIS * PROJECT IN THE FILE LICENSE.HTML. IF THE LICENSE IS NOT INCLUDED YOU MAY FIND A COPY * AT HTTP://WWW.DESY.DE/LEGAL/LICENSE.HTM */ package org.csstudio.alarm.treeView.views; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.csstudio.alarm.table.SendAcknowledge; import org.csstudio.alarm.treeView.AlarmTreePlugin; import org.csstudio.alarm.treeView.jms.JmsConnectionException; import org.csstudio.alarm.treeView.jms.JmsConnector; import org.csstudio.alarm.treeView.ldap.DirectoryEditException; import org.csstudio.alarm.treeView.ldap.DirectoryEditor; import org.csstudio.alarm.treeView.ldap.LdapDirectoryReader; import org.csstudio.alarm.treeView.ldap.LdapDirectoryStructureReader; import org.csstudio.alarm.treeView.model.IAlarmTreeNode; import org.csstudio.alarm.treeView.model.ObjectClass; import org.csstudio.alarm.treeView.model.ProcessVariableNode; import org.csstudio.alarm.treeView.model.Severity; import org.csstudio.alarm.treeView.model.SubtreeNode; import org.csstudio.platform.logging.CentralLogger; import org.csstudio.platform.model.IProcessVariable; import org.csstudio.platform.ui.internal.dataexchange.ProcessVariableNameTransfer; import org.csstudio.platform.ui.util.EditorUtil; import org.csstudio.platform.utility.jms.IConnectionMonitor; import org.csstudio.sds.ui.runmode.RunModeService; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.IJobChangeEvent; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.core.runtime.jobs.JobChangeAdapter; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.dialogs.IInputValidator; import org.eclipse.jface.dialogs.InputDialog; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.ViewerComparator; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.jface.window.Window; import org.eclipse.swt.SWT; import org.eclipse.swt.dnd.DND; import org.eclipse.swt.dnd.DragSourceAdapter; import org.eclipse.swt.dnd.DragSourceEvent; import org.eclipse.swt.dnd.DropTargetAdapter; import org.eclipse.swt.dnd.DropTargetEvent; import org.eclipse.swt.dnd.DropTargetListener; import org.eclipse.swt.dnd.TextTransfer; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.TreeItem; import org.eclipse.ui.IActionBars; import org.eclipse.ui.IWorkbenchActionConstants; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.browser.IWebBrowser; import org.eclipse.ui.part.ViewPart; import org.eclipse.ui.progress.IWorkbenchSiteProgressService; import org.eclipse.ui.progress.PendingUpdateAdapter; import org.eclipse.ui.views.IViewDescriptor; import org.eclipse.ui.views.IViewRegistry; /** * Tree view of process variables and their alarm state. This view uses LDAP * to get a hierarchy of process variables and displays them in a tree view. * Process variables which are in an alarm state are visually marked in the * view. * * @author Joerg Rathlev */ public class AlarmTreeView extends ViewPart { /** * Monitors the connection to the JMS backend system and displays a message * in the tree view if the JMS connection fails. When the JMS connection is * established or restored, triggers loading the current state from the * LDAP directory. */ private final class AlarmTreeConnectionMonitor implements IConnectionMonitor { /** * {@inheritDoc} */ public void onConnected() { Display.getDefault().asyncExec(new Runnable() { public void run() { hideMessage(); // TODO: This rebuilds the whole tree from // scratch. It would be better for the // usability to resynchronize only. startDirectoryReaderJob(); } }); } /** * {@inheritDoc} */ public void onDisconnected() { Display.getDefault().asyncExec(new Runnable() { public void run() { setMessage( SWT.ICON_WARNING, "Connection error", "Some or all of the information displayed " + "may be outdated. The alarm tree is currently " + "not connected to all alarm servers."); } }); } } /** * Implements drag support for the alarm tree. */ private final class AlarmTreeDragListener extends DragSourceAdapter { private ArrayList<ProcessVariableNode> _selectedPVs; @Override public void dragStart(DragSourceEvent event) { ISelection selection = _viewer.getSelection(); if (selection instanceof IStructuredSelection) { _selectedPVs = new ArrayList<ProcessVariableNode>(); IStructuredSelection sel = (IStructuredSelection) selection; for (Iterator<?> i = sel.iterator(); i.hasNext(); ) { Object o = i.next(); if (o instanceof ProcessVariableNode) { _selectedPVs.add((ProcessVariableNode) o); } else { // If any of the selected items is not a PV, the drag // operation is not allowed. event.doit = false; _selectedPVs = null; return; } } } else { event.doit = false; return; } } @Override public void dragSetData(DragSourceEvent event) { ArrayList<IProcessVariable> list = new ArrayList<IProcessVariable>(_selectedPVs); if (ProcessVariableNameTransfer.getInstance().isSupportedType( event.dataType)) { event.data = list; } else if (TextTransfer.getInstance().isSupportedType(event.dataType)) { StringBuilder text = new StringBuilder(); for (Iterator<IProcessVariable> i = list.iterator(); i.hasNext(); ) { text.append(i.next().getName()); if (i.hasNext()) { text.append(", "); } } event.data = text.toString(); } } /** * {@inheritDoc} */ @Override public void dragFinished(DragSourceEvent event) { if (event.detail == DND.DROP_MOVE) { for (ProcessVariableNode node : _selectedPVs) { try { DirectoryEditor.delete(node); } catch (DirectoryEditException e) { _log.error(this, "Could not delete node after drag&drop move operation: " + node); } } _viewer.refresh(); } _selectedPVs = null; } } /** * Implements drop support for the alarm tree. This implementation supports * dropping process variables (<code>IProcessVariable</code>) onto subtree * nodes. */ private final class AlarmTreeDropListener extends DropTargetAdapter { /** * The drop operation that the user wants to perform. This drop listener * sets event.detail to DROP_NONE when the user drags over a tree item * which does not support dropping; when the user later drags over * another tree item, the operation remembered in this variable will be * restored. * * See also http://dev.eclipse.org/newslists/news.eclipse.platform.swt/msg11183.html */ int _operation; @Override public void dragEnter(final DropTargetEvent event) { _operation = event.detail; } @Override public void dragOperationChanged(final DropTargetEvent event) { _operation = event.detail; } /** * This implementation of <code>dragOver</code> permits dropping if the * target item is a subtree node. If the mouse is not hovering over any * item in the tree or if the item is a process variable node, dropping * is not permitted. * * @param event * the event. * @see DropTargetListener#dragOver(DropTargetEvent) */ @Override public void dragOver(final DropTargetEvent event) { event.feedback = DND.FEEDBACK_SCROLL | DND.FEEDBACK_EXPAND; // Allow the drag&drop operation if the mouse is dragged over a tree // item and the item is a subtree node. if ((event.item instanceof TreeItem) && ((TreeItem) event.item).getData() instanceof SubtreeNode) { event.detail = _operation; event.feedback |= DND.FEEDBACK_SELECT; return; } else { event.detail = DND.DROP_NONE; return; } } /** * This implementation of <code>drop</code> performs the drop, if * possible. * * @param event * the event. * @see DropTargetListener#drop(DropTargetEvent) */ @Override public void drop(final DropTargetEvent event) { // Get the node the PVs are dropped into. If for some reason // the node is not a subtree node, reject the drop. TreeItem item = (TreeItem) event.item; if (item != null && item.getData() instanceof SubtreeNode) { SubtreeNode node = (SubtreeNode) item.getData(); IProcessVariable[] data = (IProcessVariable[]) event.data; boolean errors = false; for (IProcessVariable pv : data) { try { DirectoryEditor.createProcessVariableRecord(node, pv.getName()); } catch (DirectoryEditException e) { errors = true; } } _viewer.refresh(node); if (errors) { MessageDialog.openError(getSite().getShell(), "Create New Records", "One or more of the records could not be created."); } } else { event.detail = DND.DROP_NONE; } } } /** * This action opens the strip chart associated with the selected node. */ private class OpenStripChartAction extends Action { /** * {@inheritDoc} */ @Override public void run() { IAlarmTreeNode node = getSelectedNode(); if (node != null) { IPath path = new Path(node.getCssStripChart()); // The following code assumes that the path is relative to // the Eclipse workspace. IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(path); IWorkbenchPage page = getSite().getPage(); try { EditorUtil.openEditor(page, file); } catch (PartInitException e) { MessageDialog.openError(getSite().getShell(), "Alarm Tree", e.getMessage()); } } } /** * Returns the node that is currently selected in the tree. * * @return the selected node, or <code>null</code> if the selection is * empty or the selected node is not of type * <code>IAlarmTreeNode</code>. */ private IAlarmTreeNode getSelectedNode() { IStructuredSelection selection = (IStructuredSelection) _viewer.getSelection(); Object selected = selection.getFirstElement(); if (selected instanceof IAlarmTreeNode) { return (IAlarmTreeNode) selected; } return null; } } /** * The ID of this view. */ private static final String ID = "org.csstudio.alarm.treeView.views.LdapTView"; /** * The ID of the property view. */ private static final String PROPERTY_VIEW_ID = "org.eclipse.ui.views.PropertySheet"; /** * The tree viewer that displays the alarm objects. */ private TreeViewer _viewer; /** * The reload action. */ private Action _reloadAction; /** * The subscriber to the JMS alarm topic. */ private JmsConnector _jmsConnector; /** * The acknowledge action. */ private Action _acknowledgeAction; /** * The Run CSS Alarm Display action. */ private Action _runCssAlarmDisplayAction; /** * The Run CSS Display action. */ private Action _runCssDisplayAction; /** * The Open CSS Strip Chart action. */ private Action _openCssStripChartAction; /** * The Show Help Page action. */ private Action _showHelpPageAction; /** * The Show Help Guidance action. */ private Action _showHelpGuidanceAction; /** * The Create Record action. */ private Action _createRecordAction; /** * The Create Component action. */ private Action _createComponentAction; /** * The Delete action. */ private Action _deleteNodeAction; /** * The Show Property View action. */ private Action _showPropertyViewAction; /** * The message area which can display error messages inside the view part. */ private Composite _messageArea; /** * The icon displayed in the message area. */ private Label _messageAreaIcon; /** * The message displayed in the message area. */ private Label _messageAreaMessage; /** * The description displayed in the message area. */ private Label _messageAreaDescription; /** * A filter which hides all nodes which are not currently in an alarm state. */ private ViewerFilter _currentAlarmFilter; /** * The action which toggles the filter on and off. */ private Action _toggleFilterAction; /** * Whether the filter is active. */ private boolean _isFilterActive; /** * The connection monitor instance which monitors the JMS connection of * this tree view. */ private AlarmTreeConnectionMonitor _connectionMonitor; /** * The logger used by this view. */ private final CentralLogger _log = CentralLogger.getInstance(); /** * Returns the id of this view. * @return the id of this view. */ public static String getID(){ return ID; } /** * Creates an LDAP tree viewer. */ public AlarmTreeView() { } /** * {@inheritDoc} */ public final void createPartControl(final Composite parent) { GridLayout layout = new GridLayout(1, false); layout.marginHeight = 0; layout.marginWidth = 0; parent.setLayout(layout); _messageArea = new Composite(parent, SWT.NONE); final GridData messageAreaLayoutData = new GridData(SWT.FILL, SWT.FILL, true, false); messageAreaLayoutData.exclude = true; _messageArea.setVisible(false); _messageArea.setLayoutData(messageAreaLayoutData); _messageArea.setLayout(new GridLayout(2, false)); _messageAreaIcon = new Label(_messageArea, SWT.NONE); _messageAreaIcon.setLayoutData(new GridData(SWT.BEGINNING, SWT.BEGINNING, false, false, 1, 2)); _messageAreaIcon.setImage(Display.getCurrent().getSystemImage(SWT.ICON_WARNING)); _messageAreaMessage = new Label(_messageArea, SWT.WRAP); _messageAreaMessage.setText("Test message"); // Be careful if changing the GridData below! The label will not wrap // correctly for some settings. _messageAreaMessage.setLayoutData(new GridData(SWT.FILL, SWT.BEGINNING, true, false)); _messageAreaDescription = new Label(_messageArea, SWT.WRAP); _messageAreaDescription.setText("This is an explanation of the test message."); // Be careful if changing the GridData below! The label will not wrap // correctly for some settings. _messageAreaDescription.setLayoutData(new GridData(SWT.FILL, SWT.BEGINNING, true, false)); _viewer = new TreeViewer(parent, SWT.BORDER | SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL); _viewer.getControl().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); _viewer.setContentProvider(new AlarmTreeContentProvider()); _viewer.setLabelProvider(new AlarmTreeLabelProvider()); _viewer.setComparator(new ViewerComparator()); _currentAlarmFilter = new CurrentAlarmFilter(); initializeContextMenu(); makeActions(); contributeToActionBars(); getSite().setSelectionProvider(_viewer); startJmsConnection(); _viewer.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(final SelectionChangedEvent event) { AlarmTreeView.this.selectionChanged(event); } }); addDragAndDropSupport(); } /** * Starts the JMS connection. */ private void startJmsConnection() { _log.debug(this, "Starting JMS connection."); if (_jmsConnector != null) { // There is still an old connection. This shouldn't happen. _jmsConnector.disconnect(); _log.warn(this, "There was an active JMS connection when starting a new connection"); } final IWorkbenchSiteProgressService progressService = (IWorkbenchSiteProgressService) getSite().getAdapter( IWorkbenchSiteProgressService.class); Job jmsConnectionJob = new Job("Connecting to JMS brokers") { @Override protected IStatus run(final IProgressMonitor monitor) { monitor.beginTask("Connecting to JMS servers", IProgressMonitor.UNKNOWN); _jmsConnector = new JmsConnector(); _connectionMonitor = new AlarmTreeConnectionMonitor(); _jmsConnector.addConnectionMonitor(_connectionMonitor); try { _jmsConnector.connect(); } catch (JmsConnectionException e) { throw new RuntimeException("Could not connect to JMS brokers.", e); } return Status.OK_STATUS; } }; progressService.schedule(jmsConnectionJob, 0, true); } /** * Adds drag and drop support to the tree viewer. */ private void addDragAndDropSupport() { // The transfer types final Transfer pvTransfer = ProcessVariableNameTransfer.getInstance(); final Transfer textTransfer = TextTransfer.getInstance(); _viewer.addDropSupport(DND.DROP_COPY | DND.DROP_MOVE, new Transfer[] {pvTransfer}, new AlarmTreeDropListener()); _viewer.addDragSupport(DND.DROP_COPY | DND.DROP_MOVE, new Transfer[] {pvTransfer, textTransfer}, new AlarmTreeDragListener()); } /** * Starts a job which reads the contents of the directory in the background. */ private void startDirectoryReaderJob() { _log.debug(this, "Starting directory reader."); final IWorkbenchSiteProgressService progressService = (IWorkbenchSiteProgressService) getSite().getAdapter( IWorkbenchSiteProgressService.class); final SubtreeNode rootNode = new SubtreeNode("ROOT"); Job directoryReader = new LdapDirectoryReader(rootNode); // Add a listener that sets the viewers input to the root node // when the reader job is finished. directoryReader.addJobChangeListener(new JobChangeAdapter() { @Override public void done(final IJobChangeEvent event) { // Display the new tree. asyncSetViewerInput(rootNode); Job directoryUpdater = new LdapDirectoryStructureReader(rootNode); directoryUpdater.addJobChangeListener(new JobChangeAdapter() { @Override public void done(final IJobChangeEvent event) { // Apply updates to the new tree _jmsConnector.setUpdateTarget(rootNode); getSite().getShell().getDisplay().asyncExec(new Runnable() { public void run() { _viewer.refresh(); } }); } }); progressService.schedule(directoryUpdater, 0, true); } }); // Set the tree to which updates are applied to null. This means updates // will be queued for later application. _jmsConnector.setUpdateTarget(null); // The directory is read in the background. Until then, set the viewer's // input to a placeholder object. _viewer.setInput(new Object[] {new PendingUpdateAdapter()}); // Start the directory reader job. progressService.schedule(directoryReader, 0, true); } /** * Stops the alarm queue subscriber. */ private void disposeJmsListener() { // Remove the connection monitor, so that it doesn't try to display an // error message in this disposed view when the connection is closed. _jmsConnector.removeConnectionMonitor(_connectionMonitor); _connectionMonitor = null; _jmsConnector.disconnect(); } /** * Sets the message displayed in the message area of this view part. * * @param icon * the icon to be displayed next to the message. Must be one of * <code>SWT.ICON_ERROR</code>, * <code>SWT.ICON_INFORMATION</code>, * <code>SWT.ICON_WARNING</code>, * <code>SWT.ICON_QUESTION</code>. * @param message * the message. * @param description * a descriptive text. */ private void setMessage(final int icon, final String message, final String description) { _messageAreaIcon.setImage(Display.getCurrent().getSystemImage(icon)); _messageAreaMessage.setText(message); _messageAreaDescription.setText(description); _messageArea.layout(); _messageArea.setVisible(true); ((GridData) _messageArea.getLayoutData()).exclude = false; _messageArea.getParent().layout(); } /** * Hides the message displayed in this view part. */ private void hideMessage() { _messageArea.setVisible(false); ((GridData) _messageArea.getLayoutData()).exclude = true; _messageArea.getParent().layout(); } /** * Sets the input for the tree. The actual work will be done asynchronously * in the UI thread. * @param inputElement the new input element. */ private void asyncSetViewerInput(final SubtreeNode inputElement) { getSite().getShell().getDisplay().asyncExec(new Runnable() { public void run() { _viewer.setInput(inputElement); } }); } /** * {@inheritDoc} */ @Override public final void dispose() { disposeJmsListener(); super.dispose(); } /** * Called when the selection of the tree changes. * @param event the selection event. */ private void selectionChanged(final SelectionChangedEvent event) { IStructuredSelection sel = (IStructuredSelection) event.getSelection(); _acknowledgeAction.setEnabled(containsNodeWithUnackAlarm(sel)); _runCssAlarmDisplayAction.setEnabled(hasCssAlarmDisplay(sel.getFirstElement())); _runCssDisplayAction.setEnabled(hasCssDisplay(sel.getFirstElement())); _openCssStripChartAction.setEnabled(hasCssStripChart(sel.getFirstElement())); _showHelpGuidanceAction.setEnabled(hasHelpGuidance(sel.getFirstElement())); _showHelpPageAction.setEnabled(hasHelpPage(sel.getFirstElement())); } /** * Returns whether the given node has a CSS strip chart. * * @param node the node. * @return <code>true</code> if the node has a strip chart, * <code>false</code> otherwise. */ private boolean hasCssStripChart(final Object node) { if (node instanceof IAlarmTreeNode) { return ((IAlarmTreeNode) node).getCssStripChart() != null; } return false; } /** * Returns whether the given node has a CSS display. * * @param node the node. * @return <code>true</code> if the node has a display, <code>false</code> * otherwise. */ private boolean hasCssDisplay(final Object node) { if (node instanceof IAlarmTreeNode) { return ((IAlarmTreeNode) node).getCssDisplay() != null; } return false; } /** * Return whether help guidance is available for the given node. * @param node the node. * @return <code>true</code> if the node has a help guidance string, * <code>false</code> otherwise. */ private boolean hasHelpGuidance(final Object node) { if (node instanceof IAlarmTreeNode) { return ((IAlarmTreeNode) node).getHelpGuidance() != null; } return false; } /** * Return whether the given node has an associated help page. * * @param node the node. * @return <code>true</code> if the node has an associated help page, * <code>false</code> otherwise. */ private boolean hasHelpPage(final Object node) { if (node instanceof IAlarmTreeNode) { return ((IAlarmTreeNode) node).getHelpPage() != null; } return false; } /** * Returns whether the given process variable node in the tree has an * associated CSS alarm display configured. * * @param node the node. * @return <code>true</code> if a CSS alarm display is configured for the * node, <code>false</code> otherwise. */ private boolean hasCssAlarmDisplay(final Object node) { if (node instanceof IAlarmTreeNode) { String display = ((IAlarmTreeNode) node).getCssAlarmDisplay(); return display != null && display.matches(".+\\.css-sds"); } return false; } /** * Returns whether the given selection contains at least one node with * an unacknowledged alarm. * * @param sel the selection. * @return <code>true</code> if the selection contains a node with an * unacknowledged alarm, <code>false</code> otherwise. */ private boolean containsNodeWithUnackAlarm(final IStructuredSelection sel) { Object selectedElement = sel.getFirstElement(); // Note: selectedElement is not instance of IAlarmTreeNode if nothing // is selected (selectedElement == null), and during initialization, // when it is an instance of PendingUpdateAdapter. if (selectedElement instanceof IAlarmTreeNode) { return ((IAlarmTreeNode) selectedElement) .getUnacknowledgedAlarmSeverity() != Severity.NO_ALARM; } return false; } /** * Adds a context menu to the tree view. */ private void initializeContextMenu() { MenuManager menuMgr = new MenuManager("#PopupMenu"); menuMgr.setRemoveAllWhenShown(true); // add menu items to the context menu when it is about to show menuMgr.addMenuListener(new IMenuListener() { public void menuAboutToShow(final IMenuManager manager) { AlarmTreeView.this.fillContextMenu(manager); } }); // add the context menu to the tree viewer Menu contextMenu = menuMgr.createContextMenu(_viewer.getTree()); _viewer.getTree().setMenu(contextMenu); // register the context menu for extension by other plug-ins getSite().registerContextMenu(menuMgr, _viewer); } /** * Adds tool buttons and menu items to the action bar of this view. */ private void contributeToActionBars() { IActionBars bars = getViewSite().getActionBars(); fillLocalPullDown(bars.getMenuManager()); fillLocalToolBar(bars.getToolBarManager()); } /** * Adds the actions for the action bar's pull down menu. * @param manager the menu manager. */ private void fillLocalPullDown(final IMenuManager manager) { } /** * Adds the context menu actions. * @param menu the menu manager. */ private void fillContextMenu(final IMenuManager menu) { IStructuredSelection selection = (IStructuredSelection) _viewer .getSelection(); if (selection.size() > 0) { menu.add(_acknowledgeAction); } if (selection.size() == 1) { menu.add(_runCssAlarmDisplayAction); menu.add(_runCssDisplayAction); menu.add(_openCssStripChartAction); menu.add(_showHelpGuidanceAction); menu.add(_showHelpPageAction); menu.add(new Separator("edit")); menu.add(_deleteNodeAction); } if (selection.size() == 1 && selection.getFirstElement() instanceof SubtreeNode) { menu.add(_createRecordAction); updateCreateComponentActionText(); menu.add(_createComponentAction); } // adds a separator after which contributed actions from other plug-ins // will be displayed menu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS)); } /** * Updates the text of the Create Component action based on the object class * of the currently selected node. */ private void updateCreateComponentActionText() { SubtreeNode node = (SubtreeNode) ((IStructuredSelection) _viewer. getSelection()).getFirstElement(); ObjectClass oclass = node.getRecommendedChildSubtreeClass(); if (oclass == ObjectClass.SUBCOMPONENT) { _createComponentAction.setText("Create Subcomponent"); } else { _createComponentAction.setText("Create Component"); } } /** * Adds the tool bar actions. * @param manager the menu manager. */ private void fillLocalToolBar(final IToolBarManager manager) { manager.add(_toggleFilterAction); manager.add(new Separator()); manager.add(_showPropertyViewAction); manager.add(_reloadAction); } /** * Creates the actions offered by this view. */ private void makeActions() { _reloadAction = new Action() { public void run() { startDirectoryReaderJob(); } }; _reloadAction.setText("Reload"); _reloadAction.setToolTipText("Reload"); _reloadAction.setImageDescriptor( AlarmTreePlugin.getImageDescriptor("./icons/refresh.gif")); _acknowledgeAction = new Action() { @Override public void run() { Set<Map<String, String>> messages = new HashSet<Map<String, String>>(); IStructuredSelection selection = (IStructuredSelection) _viewer .getSelection(); for (Iterator<?> i = selection.iterator(); i .hasNext();) { Object o = i.next(); if (o instanceof SubtreeNode) { SubtreeNode snode = (SubtreeNode) o; for (ProcessVariableNode pvnode : snode.collectUnacknowledgedAlarms()) { String name = pvnode.getName(); Severity severity = pvnode.getUnacknowledgedAlarmSeverity(); Map<String, String> properties = new HashMap<String, String>(); properties.put("NAME", name); properties.put("SEVERITY", severity.toString()); messages.add(properties); } } else if (o instanceof ProcessVariableNode) { ProcessVariableNode pvnode = (ProcessVariableNode) o; String name = pvnode.getName(); Severity severity = pvnode.getUnacknowledgedAlarmSeverity(); Map<String, String> properties = new HashMap<String, String>(); properties.put("NAME", name); properties.put("SEVERITY", severity.toString()); messages.add(properties); } } if (!messages.isEmpty()) { CentralLogger.getInstance().debug(this, "Scheduling send acknowledgement (" + messages.size() + " messages)"); SendAcknowledge ackJob = SendAcknowledge.newFromProperties(messages); ackJob.schedule(); } } }; _acknowledgeAction.setText("Send Acknowledgement"); _acknowledgeAction.setToolTipText("Send alarm acknowledgement"); _acknowledgeAction.setEnabled(false); _runCssAlarmDisplayAction = new Action() { @Override public void run() { IStructuredSelection selection = (IStructuredSelection) _viewer .getSelection(); Object selected = selection.getFirstElement(); if (selected instanceof IAlarmTreeNode) { IAlarmTreeNode node = (IAlarmTreeNode) selected; IPath path = new Path(node.getCssAlarmDisplay()); Map<String, String> aliases = new HashMap<String, String>(); if (node instanceof ProcessVariableNode) { aliases.put("channel", node.getName()); } CentralLogger.getInstance().debug(this, "Opening display: " + path); RunModeService.getInstance().openDisplayShellInRunMode(path, aliases); } } }; _runCssAlarmDisplayAction.setText("Run Alarm Display"); _runCssAlarmDisplayAction.setToolTipText("Run the alarm display for this PV"); _runCssAlarmDisplayAction.setEnabled(false); _runCssDisplayAction = new Action() { @Override public void run() { IStructuredSelection selection = (IStructuredSelection) _viewer.getSelection(); Object selected = selection.getFirstElement(); if (selected instanceof IAlarmTreeNode) { IAlarmTreeNode node = (IAlarmTreeNode) selected; IPath path = new Path(node.getCssDisplay()); Map<String,String> aliases = new HashMap<String, String>(); if (node instanceof ProcessVariableNode) { aliases.put("channel", node.getName()); } CentralLogger.getInstance().debug(this, "Opening display: " + path); RunModeService.getInstance().openDisplayShellInRunMode(path, aliases); } } }; _runCssDisplayAction.setText("Run Display"); _runCssDisplayAction.setToolTipText("Run the display for this PV"); _runCssDisplayAction.setEnabled(false); _openCssStripChartAction = new OpenStripChartAction(); _openCssStripChartAction.setText("Open Strip Chart"); _openCssStripChartAction.setToolTipText("Open the strip chart for this node"); _openCssStripChartAction.setEnabled(false); _showHelpGuidanceAction = new Action() { @Override public void run() { IStructuredSelection selection = (IStructuredSelection) _viewer .getSelection(); Object selected = selection.getFirstElement(); if (selected instanceof IAlarmTreeNode) { IAlarmTreeNode node = (IAlarmTreeNode) selected; String helpGuidance = node.getHelpGuidance(); if (helpGuidance != null) { MessageDialog.openInformation(getSite().getShell(), node.getName(), helpGuidance); } } } }; _showHelpGuidanceAction.setText("Show Help Guidance"); _showHelpGuidanceAction.setToolTipText("Show the help guidance for this node"); _showHelpGuidanceAction.setEnabled(false); _showHelpPageAction = new Action() { @Override public void run() { IStructuredSelection selection = (IStructuredSelection) _viewer .getSelection(); Object selected = selection.getFirstElement(); if (selected instanceof IAlarmTreeNode) { IAlarmTreeNode node = (IAlarmTreeNode) selected; URL helpPage = node.getHelpPage(); if (helpPage != null) { try { // Note: we have to pass a browser id here to work // around a bug in eclipse. The method documentation // says that createBrowser accepts null but it will // throw a NullPointerException. // See https://bugs.eclipse.org/bugs/show_bug.cgi?id=194988 IWebBrowser browser = PlatformUI.getWorkbench() .getBrowserSupport() .createBrowser("workaround"); browser.openURL(helpPage); } catch (PartInitException e) { CentralLogger.getInstance().error(this, "Failed to initialize workbench browser.", e); } } } } }; _showHelpPageAction.setText("Open Help Page"); _showHelpPageAction.setToolTipText("Open the help page for this node in the web browser"); _showHelpPageAction.setEnabled(false); _createRecordAction = new Action() { @Override public void run() { IStructuredSelection selection = (IStructuredSelection) _viewer.getSelection(); Object selected = selection.getFirstElement(); if (selected instanceof SubtreeNode) { SubtreeNode parent = (SubtreeNode) selected; String name = promptForRecordName(); if (name != null && !name.equals("")) { try { DirectoryEditor.createProcessVariableRecord(parent, name); } catch (DirectoryEditException e) { MessageDialog.openError(getSite().getShell(), "Create New Record", "Could not create the new record: " + e.getMessage()); } _viewer.refresh(parent); } } } private String promptForRecordName() { InputDialog dialog = new InputDialog(getSite().getShell(), "Create New Record", "Record name:", null, new IInputValidator() { public String isValid(final String newText) { if (newText.equals("")) { return "Please enter a name."; } else if (newText.indexOf("=") != -1 || newText.indexOf("/") != -1 || newText.indexOf(",") != -1) { return "The following characters are not allowed " + "in names: = / ,"; } else { return null; } } }); if (Window.OK == dialog.open()) { return dialog.getValue(); } return null; } }; _createRecordAction.setText("Create Record"); _createComponentAction = new Action() { @Override public void run() { IStructuredSelection selection = (IStructuredSelection) _viewer.getSelection(); Object selected = selection.getFirstElement(); if (selected instanceof SubtreeNode) { SubtreeNode parent = (SubtreeNode) selected; String name = promptForRecordName(); if (name != null && !name.equals("")) { try { DirectoryEditor.createComponent(parent, name); } catch (DirectoryEditException e) { MessageDialog.openError(getSite().getShell(), "Create New Component", "Could not create the new component: " + e.getMessage()); } _viewer.refresh(parent); } } } private String promptForRecordName() { InputDialog dialog = new InputDialog(getSite().getShell(), "Create New Component", "Component name:", null, new IInputValidator() { public String isValid(final String newText) { if (newText.equals("")) { return "Please enter a name."; } else if (newText.indexOf("=") != -1 || newText.indexOf("/") != -1 || newText.indexOf(",") != -1) { return "The following characters are not allowed " + "in names: = / ,"; } else { return null; } } }); if (Window.OK == dialog.open()) { return dialog.getValue(); } return null; } }; _createComponentAction.setText("Create Component"); _deleteNodeAction = new Action() { @Override public void run() { IStructuredSelection selection = (IStructuredSelection) _viewer.getSelection(); Object selected = selection.getFirstElement(); if (selected instanceof IAlarmTreeNode) { IAlarmTreeNode nodeToDelete = (IAlarmTreeNode) selected; SubtreeNode parent = nodeToDelete.getParent(); try { DirectoryEditor.delete(nodeToDelete); _viewer.refresh(parent); } catch (DirectoryEditException e) { MessageDialog.openError(getSite().getShell(), "Delete", "Could not delete this node: " + e.getMessage()); } } } }; _deleteNodeAction.setText("Delete"); _showPropertyViewAction = new Action() { @Override public void run() { try { getSite().getPage().showView(PROPERTY_VIEW_ID); } catch (PartInitException e) { MessageDialog.openError(getSite().getShell(), "Alarm Tree", e.getMessage()); } } }; _showPropertyViewAction.setText("Properties"); _showPropertyViewAction.setToolTipText("Show property view"); IViewRegistry viewRegistry = getSite().getWorkbenchWindow().getWorkbench().getViewRegistry(); IViewDescriptor viewDesc = viewRegistry.find(PROPERTY_VIEW_ID); _showPropertyViewAction.setImageDescriptor(viewDesc.getImageDescriptor()); _toggleFilterAction = new Action("Show Only Alarms", Action.AS_CHECK_BOX) { @Override public void run() { if (_isFilterActive) { _viewer.removeFilter(_currentAlarmFilter); _isFilterActive = false; } else { _viewer.addFilter(_currentAlarmFilter); _isFilterActive = true; } } }; _toggleFilterAction.setToolTipText("Show Only Alarms"); _toggleFilterAction.setChecked(_isFilterActive); _toggleFilterAction.setImageDescriptor( AlarmTreePlugin.getImageDescriptor("./icons/no_alarm_filter.png")); } /** * Passes the focus request to the viewer's control. */ public final void setFocus() { _viewer.getControl().setFocus(); } /** * Refreshes this view. */ public final void refresh(){ _viewer.refresh(); } }
Started implementing support for local drag & drop within the tree.
applications/plugins/org.csstudio.alarm.treeView/src/org/csstudio/alarm/treeView/views/AlarmTreeView.java
Started implementing support for local drag & drop within the tree.
<ide><path>pplications/plugins/org.csstudio.alarm.treeView/src/org/csstudio/alarm/treeView/views/AlarmTreeView.java <ide> import java.util.HashMap; <ide> import java.util.HashSet; <ide> import java.util.Iterator; <add>import java.util.List; <ide> import java.util.Map; <ide> import java.util.Set; <ide> <ide> import org.eclipse.jface.dialogs.IInputValidator; <ide> import org.eclipse.jface.dialogs.InputDialog; <ide> import org.eclipse.jface.dialogs.MessageDialog; <add>import org.eclipse.jface.util.LocalSelectionTransfer; <ide> import org.eclipse.jface.viewers.ISelection; <ide> import org.eclipse.jface.viewers.ISelectionChangedListener; <ide> import org.eclipse.jface.viewers.IStructuredSelection; <ide> <ide> @Override <ide> public void dragSetData(DragSourceEvent event) { <del> ArrayList<IProcessVariable> list = new ArrayList<IProcessVariable>(_selectedPVs); <add> if (LocalSelectionTransfer.getTransfer().isSupportedType( <add> event.dataType)) { <add> LocalSelectionTransfer.getTransfer().setSelection( <add> _viewer.getSelection()); <add> } <ide> if (ProcessVariableNameTransfer.getInstance().isSupportedType( <ide> event.dataType)) { <del> event.data = list; <add> event.data = _selectedPVs.toArray(new IProcessVariable[_selectedPVs.size()]); <ide> } else if (TextTransfer.getInstance().isSupportedType(event.dataType)) { <ide> StringBuilder text = new StringBuilder(); <del> for (Iterator<IProcessVariable> i = list.iterator(); i.hasNext(); ) { <add> for (Iterator<ProcessVariableNode> i = _selectedPVs.iterator(); i.hasNext(); ) { <ide> text.append(i.next().getName()); <ide> if (i.hasNext()) { <ide> text.append(", "); <ide> _selectedPVs = null; <ide> } <ide> } <del> <add> <ide> /** <ide> * Implements drop support for the alarm tree. This implementation supports <ide> * dropping process variables (<code>IProcessVariable</code>) onto subtree <ide> TreeItem item = (TreeItem) event.item; <ide> if (item != null && item.getData() instanceof SubtreeNode) { <ide> SubtreeNode node = (SubtreeNode) item.getData(); <del> IProcessVariable[] data = (IProcessVariable[]) event.data; <add> IProcessVariable[] droppedPVs = null; <add> if (ProcessVariableNameTransfer.getInstance().isSupportedType(event.currentDataType)) { <add> droppedPVs = (IProcessVariable[]) event.data; <add> } else if (LocalSelectionTransfer.getTransfer().isSupportedType(event.currentDataType)) { <add> ISelection sel = LocalSelectionTransfer.getTransfer().getSelection(); <add> List<IProcessVariable> pvs = new ArrayList<IProcessVariable>(); <add> if (sel instanceof IStructuredSelection) { <add> IStructuredSelection selection = (IStructuredSelection) sel; <add> for (Iterator<?> i = selection.iterator(); i.hasNext(); ) { <add> Object selected = i.next(); <add> if (selected instanceof IProcessVariable) { <add> pvs.add((IProcessVariable) selected); <add> } <add> } <add> } <add> droppedPVs = (IProcessVariable[]) pvs.toArray(new IProcessVariable[pvs <add> .size()]); <add> } else { <add> // Unknown transfer type <add> event.detail = DND.DROP_NONE; <add> return; <add> } <ide> boolean errors = false; <del> for (IProcessVariable pv : data) { <add> for (IProcessVariable pv : droppedPVs) { <ide> try { <ide> DirectoryEditor.createProcessVariableRecord(node, pv.getName()); <ide> } catch (DirectoryEditException e) { <ide> // The transfer types <ide> final Transfer pvTransfer = ProcessVariableNameTransfer.getInstance(); <ide> final Transfer textTransfer = TextTransfer.getInstance(); <add> final Transfer localTransfer = LocalSelectionTransfer.getTransfer(); <ide> <ide> _viewer.addDropSupport(DND.DROP_COPY | DND.DROP_MOVE, <ide> new Transfer[] {pvTransfer},
Java
apache-2.0
f0fe9bc574f85ab4e6431ec2f7eec76dbdfd2635
0
mjanicek/rembulan,kroepke/luna
package net.sandius.rembulan.compiler.gen; import net.sandius.rembulan.compiler.gen.block.AccountingNode; import net.sandius.rembulan.compiler.gen.block.Capture; import net.sandius.rembulan.compiler.gen.block.Entry; import net.sandius.rembulan.compiler.gen.block.LineInfo; import net.sandius.rembulan.compiler.gen.block.Linear; import net.sandius.rembulan.compiler.gen.block.LinearSeq; import net.sandius.rembulan.compiler.gen.block.LinearSeqTransformation; import net.sandius.rembulan.compiler.gen.block.LocalVariableEffect; import net.sandius.rembulan.compiler.gen.block.Node; import net.sandius.rembulan.compiler.gen.block.NodeVisitor; import net.sandius.rembulan.compiler.gen.block.Nodes; import net.sandius.rembulan.compiler.gen.block.Sink; import net.sandius.rembulan.compiler.gen.block.SlotEffect; import net.sandius.rembulan.compiler.gen.block.Target; import net.sandius.rembulan.compiler.gen.block.UnconditionalJump; import net.sandius.rembulan.lbc.Prototype; import net.sandius.rembulan.util.Check; import net.sandius.rembulan.util.IntBuffer; import net.sandius.rembulan.util.IntVector; import net.sandius.rembulan.util.ReadOnlyArray; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Set; public class FlowIt { public final Prototype prototype; public Entry callEntry; public Set<Entry> entryPoints; public Map<Node, Edges> reachabilityGraph; public Map<Node, Slots> slots; public FlowIt(Prototype prototype) { this.prototype = prototype; } public void go() { IntVector code = prototype.getCode(); Target[] targets = new Target[code.length()]; for (int pc = 0; pc < targets.length; pc++) { targets[pc] = new Target(Integer.toString(pc + 1)); } ReadOnlyArray<Target> pcLabels = ReadOnlyArray.wrap(targets); LuaInstructionToNodeTranslator translator = new LuaInstructionToNodeTranslator(); for (int pc = 0; pc < pcLabels.size(); pc++) { translator.translate(code.get(pc), pc, prototype.getLineAtPC(pc), pcLabels); } // System.out.println("["); // for (int i = 0; i < pcLabels.size(); i++) { // NLabel label = pcLabels.get(i); // System.out.println(i + ": " + label.toString()); // } // System.out.println("]"); callEntry = new Entry("main", pcLabels.get(0)); entryPoints = new HashSet<>(); entryPoints.add(callEntry); inlineInnerJumps(); makeBlocks(); applyTransformation(entryPoints, new CollectCPUAccounting()); // remove repeated line info nodes applyTransformation(entryPoints, new RemoveRedundantLineNodes()); // dissolve blocks dissolveBlocks(entryPoints); // remove all line info nodes // applyTransformation(entryPoints, new LinearSeqTransformation.Remove(Predicates.isClass(LineInfo.class))); // System.out.println(); // printNodes(entryPoints); updateReachability(); updateDataFlow(); // add capture nodes insertCaptureNodes(); addResumptionPoints(); makeBlocks(); updateReachability(); updateDataFlow(); } private static class CollectCPUAccounting extends LinearSeqTransformation { @Override public void apply(LinearSeq seq) { List<AccountingNode> toBeRemoved = new ArrayList<>(); int cost = 0; for (Linear n : seq.nodes()) { if (n instanceof AccountingNode) { AccountingNode an = (AccountingNode) n; if (n instanceof AccountingNode.Tick) { cost += 1; toBeRemoved.add(an); } else if (n instanceof AccountingNode.Sum) { cost += ((AccountingNode.Sum) n).cost; toBeRemoved.add(an); } } } for (AccountingNode an : toBeRemoved) { // remove all nodes an.remove(); } if (cost > 0) { // insert cost node at the beginning seq.insertAtBeginning(new AccountingNode.Sum(cost)); } } } private static class RemoveRedundantLineNodes extends LinearSeqTransformation { @Override public void apply(LinearSeq seq) { int line = -1; List<Linear> toBeRemoved = new ArrayList<>(); for (Linear n : seq.nodes()) { if (n instanceof LineInfo) { LineInfo lineInfoNode = (LineInfo) n; if (lineInfoNode.line == line) { // no need to keep this one toBeRemoved.add(lineInfoNode); } line = lineInfoNode.line; } } for (Linear n : toBeRemoved) { n.remove(); } } } private void applyTransformation(Iterable<Entry> entryPoints, LinearSeqTransformation tf) { for (Node n : reachableNodes(entryPoints)) { if (n instanceof LinearSeq) { LinearSeq seq = (LinearSeq) n; seq.apply(tf); } } } private void inlineInnerJumps() { for (Node n : reachableNodes(entryPoints)) { if (n instanceof Target) { Target t = (Target) n; UnconditionalJump jmp = t.optIncomingJump(); if (jmp != null) { Nodes.inline(jmp); } } } } private void makeBlocks() { for (Node n : reachableNodes(entryPoints)) { if (n instanceof Target) { Target t = (Target) n; if (t.next() instanceof Linear) { // only insert blocks where they have a chance to grow LinearSeq block = new LinearSeq(); block.insertAfter(t); block.grow(); } } } } private void addResumptionPoints() { for (Node n : reachableNodes(entryPoints)) { if (n instanceof AccountingNode) { insertResumptionAfter((AccountingNode) n); } } } private void dissolveBlocks(Iterable<Entry> entryPoints) { applyTransformation(entryPoints, new LinearSeqTransformation() { @Override public void apply(LinearSeq seq) { seq.dissolve(); } }); } public void updateReachability() { reachabilityGraph = reachabilityEdges(entryPoints); } public void insertCaptureNodes() { for (Node n : reachabilityGraph.keySet()) { if (n instanceof Sink && !(n instanceof LocalVariableEffect)) { Slots s_n = slots.get(n); if (s_n != null) { IntBuffer uncaptured = new IntBuffer(); for (Node m : reachabilityGraph.get(n).out) { Slots s_m = slots.get(m); for (int i = 0; i < s_n.size(); i++) { if (!s_n.getState(i).isCaptured() && s_m.getState(i).isCaptured()) { // need to capture i uncaptured.append(i); } } } if (!uncaptured.isEmpty()) { Capture captureNode = new Capture(uncaptured.toVector()); captureNode.insertBefore((Sink) n); } } } } } public void insertResumptionAfter(Linear n) { Sink next = n.next(); Target tgt = new Target(); UnconditionalJump jmp = new UnconditionalJump(tgt); n.appendSink(jmp); tgt.appendSink(next); Entry resumeEntry = new Entry(tgt); entryPoints.add(resumeEntry); } public static class Edges { // FIXME: may in principle be multisets public final Set<Node> in; public final Set<Node> out; public Edges() { this.in = new HashSet<>(); this.out = new HashSet<>(); } } private Map<Node, Slots> initSlots(Set<Entry> entryPoints) { Map<Node, Slots> slots = new HashMap<>(); for (Node n : reachableNodes(entryPoints)) { slots.put(n, null); } return slots; } private Slots effect(Node n, Slots in) { if (n instanceof SlotEffect) { SlotEffect eff = (SlotEffect) n; return eff.effect(in, prototype); } else { return in; } } private boolean joinWith(Map<Node, Slots> slots, Node n, Slots addIn) { Check.notNull(slots); Check.notNull(addIn); Slots oldIn = slots.get(n); Slots newIn = oldIn == null ? addIn : oldIn.join(addIn); if (!newIn.equals(oldIn)) { slots.put(n, newIn); return true; } else { return false; } } public void updateDataFlow() { slots = dataFlow(callEntry, entryPoints); } public Map<Node, Slots> dataFlow(Entry entryPoint, Set<Entry> entryPoints) { Map<Node, Edges> edges = reachabilityEdges(entryPoints); Map<Node, Slots> slots = initSlots(entryPoints); Slots entrySlots = entrySlots(); Queue<Node> workList = new ArrayDeque<>(); // push entry point's slots to the immediate successors for (Node n : edges.get(entryPoint).out) { if (joinWith(slots, n, entrySlots)) { workList.add(n); } } while (!workList.isEmpty()) { Node n = workList.remove(); assert (n != null); assert (slots.get(n) != null); // compute effect and push it to outputs Slots o = effect(n, slots.get(n)); for (Node m : edges.get(n).out) { if (joinWith(slots, m, o)) { workList.add(m); } } } return slots; } private Map<Node, Edges> reachabilityEdges(Iterable<Entry> entryPoints) { final Map<Node, Integer> timesVisited = new HashMap<>(); final Map<Node, Edges> edges = new HashMap<>(); NodeVisitor visitor = new NodeVisitor() { @Override public boolean visitNode(Node node) { if (timesVisited.containsKey(node)) { timesVisited.put(node, timesVisited.get(node) + 1); return false; } else { timesVisited.put(node, 1); if (!edges.containsKey(node)) { edges.put(node, new Edges()); } return true; } } @Override public void visitEdge(Node from, Node to) { if (!edges.containsKey(from)) { edges.put(from, new Edges()); } if (!edges.containsKey(to)) { edges.put(to, new Edges()); } Edges fromEdges = edges.get(from); Edges toEdges = edges.get(to); fromEdges.out.add(to); toEdges.in.add(from); } }; for (Entry entry : entryPoints) { entry.accept(visitor); } return Collections.unmodifiableMap(edges); } private void printNodes(Iterable<Entry> entryPoints) { ArrayList<Node> nodes = new ArrayList<>(); Map<Node, Edges> edges = reachabilityEdges(entryPoints); for (Node n : edges.keySet()) { nodes.add(n); } System.out.println("["); for (int i = 0; i < nodes.size(); i++) { Node n = nodes.get(i); Edges e = edges.get(n); System.out.print("\t" + i + ": "); System.out.print("{ "); for (Node m : e.in) { int idx = nodes.indexOf(m); System.out.print(idx + " "); } System.out.print("} -> "); System.out.print(n.toString()); System.out.print(" -> { "); for (Node m : e.out) { int idx = nodes.indexOf(m); System.out.print(idx + " "); } System.out.print("}"); System.out.println(); } System.out.println("]"); } private Iterable<Node> reachableNodes(Iterable<Entry> entryPoints) { return reachability(entryPoints).keySet(); } private Map<Node, Integer> reachability(Iterable<Entry> entryPoints) { final Map<Node, Integer> inDegree = new HashMap<>(); NodeVisitor visitor = new NodeVisitor() { @Override public boolean visitNode(Node n) { if (inDegree.containsKey(n)) { inDegree.put(n, inDegree.get(n) + 1); return false; } else { inDegree.put(n, 1); return true; } } @Override public void visitEdge(Node from, Node to) { // no-op } }; for (Entry entry : entryPoints) { entry.accept(visitor); } return Collections.unmodifiableMap(inDegree); } private Slots entrySlots() { Slots s = Slots.init(prototype.getMaximumStackSize()); for (int i = 0; i < prototype.getNumberOfParameters(); i++) { s = s.updateType(i, Slots.SlotType.ANY); } return s; } }
rembulan-compiler/src/main/java/net/sandius/rembulan/compiler/gen/FlowIt.java
package net.sandius.rembulan.compiler.gen; import net.sandius.rembulan.compiler.gen.block.AccountingNode; import net.sandius.rembulan.compiler.gen.block.Capture; import net.sandius.rembulan.compiler.gen.block.Entry; import net.sandius.rembulan.compiler.gen.block.LineInfo; import net.sandius.rembulan.compiler.gen.block.Linear; import net.sandius.rembulan.compiler.gen.block.LinearSeq; import net.sandius.rembulan.compiler.gen.block.LinearSeqTransformation; import net.sandius.rembulan.compiler.gen.block.LocalVariableEffect; import net.sandius.rembulan.compiler.gen.block.Node; import net.sandius.rembulan.compiler.gen.block.NodeVisitor; import net.sandius.rembulan.compiler.gen.block.Nodes; import net.sandius.rembulan.compiler.gen.block.Sink; import net.sandius.rembulan.compiler.gen.block.SlotEffect; import net.sandius.rembulan.compiler.gen.block.Target; import net.sandius.rembulan.compiler.gen.block.UnconditionalJump; import net.sandius.rembulan.lbc.Prototype; import net.sandius.rembulan.util.Check; import net.sandius.rembulan.util.IntBuffer; import net.sandius.rembulan.util.IntVector; import net.sandius.rembulan.util.ReadOnlyArray; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Set; public class FlowIt { public final Prototype prototype; public Entry callEntry; public Set<Entry> entryPoints; public Map<Node, Edges> reachabilityGraph; public Map<Node, Slots> slots; public FlowIt(Prototype prototype) { this.prototype = prototype; } public void go() { IntVector code = prototype.getCode(); Target[] targets = new Target[code.length()]; for (int pc = 0; pc < targets.length; pc++) { targets[pc] = new Target(Integer.toString(pc + 1)); } ReadOnlyArray<Target> pcLabels = ReadOnlyArray.wrap(targets); LuaInstructionToNodeTranslator translator = new LuaInstructionToNodeTranslator(); for (int pc = 0; pc < pcLabels.size(); pc++) { translator.translate(code.get(pc), pc, prototype.getLineAtPC(pc), pcLabels); } // System.out.println("["); // for (int i = 0; i < pcLabels.size(); i++) { // NLabel label = pcLabels.get(i); // System.out.println(i + ": " + label.toString()); // } // System.out.println("]"); callEntry = new Entry("main", pcLabels.get(0)); entryPoints = new HashSet<>(); entryPoints.add(callEntry); inlineInnerJumps(); makeBlocks(); applyTransformation(entryPoints, new CollectCPUAccounting()); // remove repeated line info nodes applyTransformation(entryPoints, new RemoveRedundantLineNodes()); // dissolve blocks dissolveBlocks(entryPoints); // remove all line info nodes // applyTransformation(entryPoints, new LinearSeqTransformation.Remove(Predicates.isClass(LineInfo.class))); // System.out.println(); // printNodes(entryPoints); updateReachability(); updateDataFlow(); // add capture nodes insertCaptureNodes(); makeBlocks(); updateReachability(); updateDataFlow(); } private static class CollectCPUAccounting extends LinearSeqTransformation { @Override public void apply(LinearSeq seq) { List<AccountingNode> toBeRemoved = new ArrayList<>(); int cost = 0; for (Linear n : seq.nodes()) { if (n instanceof AccountingNode) { AccountingNode an = (AccountingNode) n; if (n instanceof AccountingNode.Tick) { cost += 1; toBeRemoved.add(an); } else if (n instanceof AccountingNode.Sum) { cost += ((AccountingNode.Sum) n).cost; toBeRemoved.add(an); } } } for (AccountingNode an : toBeRemoved) { // remove all nodes an.remove(); } if (cost > 0) { // insert cost node at the beginning seq.insertAtBeginning(new AccountingNode.Sum(cost)); } } } private static class RemoveRedundantLineNodes extends LinearSeqTransformation { @Override public void apply(LinearSeq seq) { int line = -1; List<Linear> toBeRemoved = new ArrayList<>(); for (Linear n : seq.nodes()) { if (n instanceof LineInfo) { LineInfo lineInfoNode = (LineInfo) n; if (lineInfoNode.line == line) { // no need to keep this one toBeRemoved.add(lineInfoNode); } line = lineInfoNode.line; } } for (Linear n : toBeRemoved) { n.remove(); } } } private void applyTransformation(Iterable<Entry> entryPoints, LinearSeqTransformation tf) { for (Node n : reachableNodes(entryPoints)) { if (n instanceof LinearSeq) { LinearSeq seq = (LinearSeq) n; seq.apply(tf); } } } private void inlineInnerJumps() { for (Node n : reachableNodes(entryPoints)) { if (n instanceof Target) { Target t = (Target) n; UnconditionalJump jmp = t.optIncomingJump(); if (jmp != null) { Nodes.inline(jmp); } } } } private void makeBlocks() { for (Node n : reachableNodes(entryPoints)) { if (n instanceof Target) { Target t = (Target) n; LinearSeq block = new LinearSeq(); block.insertAfter(t); block.grow(); } } } private void dissolveBlocks(Iterable<Entry> entryPoints) { applyTransformation(entryPoints, new LinearSeqTransformation() { @Override public void apply(LinearSeq seq) { seq.dissolve(); } }); } public void updateReachability() { reachabilityGraph = reachabilityEdges(entryPoints); } public void insertCaptureNodes() { for (Node n : reachabilityGraph.keySet()) { if (n instanceof Sink && !(n instanceof LocalVariableEffect)) { Slots s_n = slots.get(n); if (s_n != null) { IntBuffer uncaptured = new IntBuffer(); for (Node m : reachabilityGraph.get(n).out) { Slots s_m = slots.get(m); for (int i = 0; i < s_n.size(); i++) { if (!s_n.getState(i).isCaptured() && s_m.getState(i).isCaptured()) { // need to capture i uncaptured.append(i); } } } if (!uncaptured.isEmpty()) { Capture captureNode = new Capture(uncaptured.toVector()); captureNode.insertBefore((Sink) n); } } } } } public static class Edges { // FIXME: may in principle be multisets public final Set<Node> in; public final Set<Node> out; public Edges() { this.in = new HashSet<>(); this.out = new HashSet<>(); } } private Map<Node, Slots> initSlots(Entry entryPoint) { Map<Node, Slots> slots = new HashMap<>(); for (Node n : reachableNodes(Collections.singleton(entryPoint))) { slots.put(n, null); } return slots; } private Slots effect(Node n, Slots in) { if (n instanceof SlotEffect) { SlotEffect eff = (SlotEffect) n; return eff.effect(in, prototype); } else { return in; } } private boolean joinWith(Map<Node, Slots> slots, Node n, Slots addIn) { Check.notNull(slots); Check.notNull(addIn); Slots oldIn = slots.get(n); Slots newIn = oldIn == null ? addIn : oldIn.join(addIn); if (!newIn.equals(oldIn)) { slots.put(n, newIn); return true; } else { return false; } } public void updateDataFlow() { slots = dataFlow(callEntry); } public Map<Node, Slots> dataFlow(Entry entryPoint) { Map<Node, Edges> edges = reachabilityEdges(Collections.singleton(entryPoint)); Map<Node, Slots> slots = initSlots(entryPoint); Slots entrySlots = entrySlots(); Queue<Node> workList = new ArrayDeque<>(); // push entry point's slots to the immediate successors for (Node n : edges.get(entryPoint).out) { if (joinWith(slots, n, entrySlots)) { workList.add(n); } } while (!workList.isEmpty()) { Node n = workList.remove(); assert (n != null); assert (slots.get(n) != null); // compute effect and push it to outputs Slots o = effect(n, slots.get(n)); for (Node m : edges.get(n).out) { if (joinWith(slots, m, o)) { workList.add(m); } } } return slots; } private Map<Node, Edges> reachabilityEdges(Iterable<Entry> entryPoints) { final Map<Node, Integer> timesVisited = new HashMap<>(); final Map<Node, Edges> edges = new HashMap<>(); NodeVisitor visitor = new NodeVisitor() { @Override public boolean visitNode(Node node) { if (timesVisited.containsKey(node)) { timesVisited.put(node, timesVisited.get(node) + 1); return false; } else { timesVisited.put(node, 1); if (!edges.containsKey(node)) { edges.put(node, new Edges()); } return true; } } @Override public void visitEdge(Node from, Node to) { if (!edges.containsKey(from)) { edges.put(from, new Edges()); } if (!edges.containsKey(to)) { edges.put(to, new Edges()); } Edges fromEdges = edges.get(from); Edges toEdges = edges.get(to); fromEdges.out.add(to); toEdges.in.add(from); } }; for (Entry entry : entryPoints) { entry.accept(visitor); } return Collections.unmodifiableMap(edges); } private void printNodes(Iterable<Entry> entryPoints) { ArrayList<Node> nodes = new ArrayList<>(); Map<Node, Edges> edges = reachabilityEdges(entryPoints); for (Node n : edges.keySet()) { nodes.add(n); } System.out.println("["); for (int i = 0; i < nodes.size(); i++) { Node n = nodes.get(i); Edges e = edges.get(n); System.out.print("\t" + i + ": "); System.out.print("{ "); for (Node m : e.in) { int idx = nodes.indexOf(m); System.out.print(idx + " "); } System.out.print("} -> "); System.out.print(n.toString()); System.out.print(" -> { "); for (Node m : e.out) { int idx = nodes.indexOf(m); System.out.print(idx + " "); } System.out.print("}"); System.out.println(); } System.out.println("]"); } private Iterable<Node> reachableNodes(Iterable<Entry> entryPoints) { return reachability(entryPoints).keySet(); } private Map<Node, Integer> reachability(Iterable<Entry> entryPoints) { final Map<Node, Integer> inDegree = new HashMap<>(); NodeVisitor visitor = new NodeVisitor() { @Override public boolean visitNode(Node n) { if (inDegree.containsKey(n)) { inDegree.put(n, inDegree.get(n) + 1); return false; } else { inDegree.put(n, 1); return true; } } @Override public void visitEdge(Node from, Node to) { // no-op } }; for (Entry entry : entryPoints) { entry.accept(visitor); } return Collections.unmodifiableMap(inDegree); } private Slots entrySlots() { Slots s = Slots.init(prototype.getMaximumStackSize()); for (int i = 0; i < prototype.getNumberOfParameters(); i++) { s = s.updateType(i, Slots.SlotType.ANY); } return s; } }
Inserting resumption points after each accounting node.
rembulan-compiler/src/main/java/net/sandius/rembulan/compiler/gen/FlowIt.java
Inserting resumption points after each accounting node.
<ide><path>embulan-compiler/src/main/java/net/sandius/rembulan/compiler/gen/FlowIt.java <ide> // add capture nodes <ide> insertCaptureNodes(); <ide> <add> addResumptionPoints(); <add> <ide> makeBlocks(); <ide> <ide> updateReachability(); <ide> for (Node n : reachableNodes(entryPoints)) { <ide> if (n instanceof Target) { <ide> Target t = (Target) n; <del> LinearSeq block = new LinearSeq(); <del> block.insertAfter(t); <del> block.grow(); <add> if (t.next() instanceof Linear) { <add> // only insert blocks where they have a chance to grow <add> LinearSeq block = new LinearSeq(); <add> block.insertAfter(t); <add> block.grow(); <add> } <add> } <add> } <add> } <add> <add> private void addResumptionPoints() { <add> for (Node n : reachableNodes(entryPoints)) { <add> if (n instanceof AccountingNode) { <add> insertResumptionAfter((AccountingNode) n); <ide> } <ide> } <ide> } <ide> } <ide> } <ide> <add> public void insertResumptionAfter(Linear n) { <add> Sink next = n.next(); <add> <add> Target tgt = new Target(); <add> UnconditionalJump jmp = new UnconditionalJump(tgt); <add> <add> n.appendSink(jmp); <add> tgt.appendSink(next); <add> <add> Entry resumeEntry = new Entry(tgt); <add> entryPoints.add(resumeEntry); <add> } <add> <ide> public static class Edges { <ide> // FIXME: may in principle be multisets <ide> public final Set<Node> in; <ide> } <ide> } <ide> <del> private Map<Node, Slots> initSlots(Entry entryPoint) { <add> private Map<Node, Slots> initSlots(Set<Entry> entryPoints) { <ide> Map<Node, Slots> slots = new HashMap<>(); <del> for (Node n : reachableNodes(Collections.singleton(entryPoint))) { <add> for (Node n : reachableNodes(entryPoints)) { <ide> slots.put(n, null); <ide> } <ide> return slots; <ide> } <ide> <ide> public void updateDataFlow() { <del> slots = dataFlow(callEntry); <del> } <del> <del> public Map<Node, Slots> dataFlow(Entry entryPoint) { <del> Map<Node, Edges> edges = reachabilityEdges(Collections.singleton(entryPoint)); <del> Map<Node, Slots> slots = initSlots(entryPoint); <add> slots = dataFlow(callEntry, entryPoints); <add> } <add> <add> public Map<Node, Slots> dataFlow(Entry entryPoint, Set<Entry> entryPoints) { <add> Map<Node, Edges> edges = reachabilityEdges(entryPoints); <add> Map<Node, Slots> slots = initSlots(entryPoints); <ide> <ide> Slots entrySlots = entrySlots(); <ide>
Java
bsd-3-clause
80006b420691e84cd0de0d1ca9a5c2019a6f52c3
0
bdezonia/zorbage,bdezonia/zorbage
/* * Zorbage: an algebraic data hierarchy for use in numeric processing. * * Copyright (C) 2016-2018 Barry DeZonia * * 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. * * 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 HOLDERS 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 nom.bdezonia.zorbage.type.data.float64.complex; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.junit.Test; import nom.bdezonia.zorbage.algorithm.MatrixMaximumAbsoluteColumnSumNorm; import nom.bdezonia.zorbage.algorithm.MatrixMaximumAbsoluteRowSumNorm; import nom.bdezonia.zorbage.groups.G; import nom.bdezonia.zorbage.type.data.float64.real.Float64Member; /** * * @author Barry DeZonia * */ public class TestFloat64ComplexMatrixNorms { @Test public void test1() { Float64Member norm = new Float64Member(); ComplexFloat64MatrixMember matrix = new ComplexFloat64MatrixMember( 2, 2, new double[] {4,0,-3, 0, 18, 0, -11, 0}); MatrixMaximumAbsoluteColumnSumNorm.compute(G.CDBL, G.DBL, matrix, norm); assertEquals(22, norm.v(), 0); } @Test public void test2() { Float64Member norm = new Float64Member(); ComplexFloat64MatrixMember matrix = new ComplexFloat64MatrixMember( 2, 2, new double[] {4,0,-3, 0, 18, 0, -11, 0}); MatrixMaximumAbsoluteRowSumNorm.compute(G.CDBL, G.DBL, matrix, norm); assertEquals(29, norm.v(), 0); } }
src/test/java/nom/bdezonia/zorbage/type/data/float64/complex/TestFloat64ComplexMatrixNorms.java
/* * Zorbage: an algebraic data hierarchy for use in numeric processing. * * Copyright (C) 2016-2018 Barry DeZonia * * 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. * * 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 HOLDERS 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 nom.bdezonia.zorbage.type.data.float64.complex; import static org.junit.Assert.assertTrue; import org.junit.Test; import nom.bdezonia.zorbage.algorithm.MatrixMaximumAbsoluteColumnSumNorm; import nom.bdezonia.zorbage.algorithm.MatrixMaximumAbsoluteRowSumNorm; import nom.bdezonia.zorbage.groups.G; import nom.bdezonia.zorbage.type.data.float64.real.Float64Member; /** * * @author Barry DeZonia * */ public class TestFloat64ComplexMatrixNorms { @Test public void test1() { Float64Member norm = new Float64Member(); ComplexFloat64MatrixMember matrix = new ComplexFloat64MatrixMember(); MatrixMaximumAbsoluteColumnSumNorm.compute(G.CDBL, G.DBL, matrix, norm); assertTrue(true); } @Test public void test2() { Float64Member norm = new Float64Member(); ComplexFloat64MatrixMember matrix = new ComplexFloat64MatrixMember(); MatrixMaximumAbsoluteRowSumNorm.compute(G.CDBL, G.DBL, matrix, norm); assertTrue(true); } }
Flesh out a couple tests
src/test/java/nom/bdezonia/zorbage/type/data/float64/complex/TestFloat64ComplexMatrixNorms.java
Flesh out a couple tests
<ide><path>rc/test/java/nom/bdezonia/zorbage/type/data/float64/complex/TestFloat64ComplexMatrixNorms.java <ide> */ <ide> package nom.bdezonia.zorbage.type.data.float64.complex; <ide> <add>import static org.junit.Assert.assertEquals; <ide> import static org.junit.Assert.assertTrue; <ide> <ide> import org.junit.Test; <ide> @Test <ide> public void test1() { <ide> Float64Member norm = new Float64Member(); <del> ComplexFloat64MatrixMember matrix = new ComplexFloat64MatrixMember(); <add> ComplexFloat64MatrixMember matrix = new ComplexFloat64MatrixMember( <add> 2, 2, new double[] {4,0,-3, 0, 18, 0, -11, 0}); <ide> MatrixMaximumAbsoluteColumnSumNorm.compute(G.CDBL, G.DBL, matrix, norm); <del> assertTrue(true); <add> assertEquals(22, norm.v(), 0); <ide> } <ide> <ide> @Test <ide> public void test2() { <ide> Float64Member norm = new Float64Member(); <del> ComplexFloat64MatrixMember matrix = new ComplexFloat64MatrixMember(); <add> ComplexFloat64MatrixMember matrix = new ComplexFloat64MatrixMember( <add> 2, 2, new double[] {4,0,-3, 0, 18, 0, -11, 0}); <ide> MatrixMaximumAbsoluteRowSumNorm.compute(G.CDBL, G.DBL, matrix, norm); <del> assertTrue(true); <add> assertEquals(29, norm.v(), 0); <ide> } <ide> }
Java
apache-2.0
6c3ac93538526a5505a6322dc893d3e19ed0623a
0
skptl/speech-android-sdk,jithsjoy/speech-android-sdk,watson-developer-cloud/speech-android-sdk
package com.ibm.cio.opus; import com.ibm.cio.util.Logger; public class OggOpus { private static final String TAG = OggOpus.class.getSimpleName().toString(); public static native void initAudio(); public static native void startRecorder( int sample_rate); public static native void stopRecorder(); public static native int encode( String s, int sample_rate ); public static native int decode( String s, String o, int sample_rate ); public static native float volume(); static { System.loadLibrary("oggopus"); Logger.e(TAG, "OggOpus library is loaded..."); } }
speech-android-wrapper/src/main/java/com/ibm/cio/opus/OggOpus.java
package com.ibm.cio.opus; import com.ibm.cio.util.Logger; public class OggOpus { private static final String TAG = OggOpus.class.getSimpleName().toString(); public static native int decode( String s, String o, int srate ); static { System.loadLibrary("oggopus"); Logger.e(TAG, "OggOpus library is loaded..."); } }
Adding native methods
speech-android-wrapper/src/main/java/com/ibm/cio/opus/OggOpus.java
Adding native methods
<ide><path>peech-android-wrapper/src/main/java/com/ibm/cio/opus/OggOpus.java <ide> <ide> public class OggOpus { <ide> private static final String TAG = OggOpus.class.getSimpleName().toString(); <del> <del> public static native int decode( String s, String o, int srate ); <del> <add> public static native void initAudio(); <add> public static native void startRecorder( int sample_rate); <add> public static native void stopRecorder(); <add> public static native int encode( String s, int sample_rate ); <add> public static native int decode( String s, String o, int sample_rate ); <add> public static native float volume(); <ide> static { <ide> System.loadLibrary("oggopus"); <ide> Logger.e(TAG, "OggOpus library is loaded...");
Java
apache-2.0
19fc4f2f2d47550b368281fce5deaea3545aa9a1
0
apache/uima-sandbox,apache/uima-sandbox,apache/uima-sandbox
/* * 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.uima.aae.controller; import java.util.ArrayList; import java.util.List; import org.apache.uima.UIMAFramework; import org.apache.uima.aae.AsynchAECasManager; import org.apache.uima.aae.InProcessCache; import org.apache.uima.aae.UIMAEE_Constants; import org.apache.uima.aae.UimaClassFactory; import org.apache.uima.aae.InProcessCache.CacheEntry; import org.apache.uima.aae.controller.LocalCache.CasStateEntry; import org.apache.uima.aae.error.AsynchAEException; import org.apache.uima.aae.error.ErrorContext; import org.apache.uima.aae.error.ErrorHandler; import org.apache.uima.aae.error.ServiceShutdownException; import org.apache.uima.aae.jmx.JmxManagement; import org.apache.uima.aae.jmx.PrimitiveServiceInfo; import org.apache.uima.aae.jmx.ServicePerformance; import org.apache.uima.aae.message.AsynchAEMessage; import org.apache.uima.aae.message.MessageContext; import org.apache.uima.aae.monitor.Monitor; import org.apache.uima.aae.spi.transport.UimaMessage; import org.apache.uima.aae.spi.transport.UimaTransport; import org.apache.uima.analysis_engine.AnalysisEngine; import org.apache.uima.analysis_engine.AnalysisEngineDescription; import org.apache.uima.analysis_engine.CasIterator; import org.apache.uima.analysis_engine.metadata.AnalysisEngineMetaData; import org.apache.uima.cas.CAS; import org.apache.uima.cas.impl.CASImpl; import org.apache.uima.cas.impl.OutOfTypeSystemData; import org.apache.uima.resource.ResourceInitializationException; import org.apache.uima.resource.ResourceSpecifier; import org.apache.uima.resource.metadata.ConfigurationParameter; import org.apache.uima.resource.metadata.impl.ConfigurationParameter_impl; import org.apache.uima.util.InvalidXMLException; import org.apache.uima.util.Level; public class PrimitiveAnalysisEngineController_impl extends BaseAnalysisEngineController implements PrimitiveAnalysisEngineController { private static final Class CLASS_NAME = PrimitiveAnalysisEngineController_impl.class; // Stores AE metadata private AnalysisEngineMetaData analysisEngineMetadata; // Number of AE instances private int analysisEnginePoolSize; // Mutex protected Object notifyObj = new Object(); // Temp list holding instances of AE private List aeList = new ArrayList(); // Stores service info for JMX private PrimitiveServiceInfo serviceInfo = null; // Pool containing instances of AE. The default implementation provides Thread affinity // meaning each thread executes the same AE instance. private AnalysisEngineInstancePool aeInstancePool = null; private String abortedCASReferenceId = null; private Object mux = new Object(); private Object mux2 = new Object(); public PrimitiveAnalysisEngineController_impl(String anEndpointName, String anAnalysisEngineDescriptor, AsynchAECasManager aCasManager, InProcessCache anInProcessCache, int aWorkQueueSize, int anAnalysisEnginePoolSize) throws Exception { this(null, anEndpointName, anAnalysisEngineDescriptor, aCasManager, anInProcessCache, aWorkQueueSize, anAnalysisEnginePoolSize, 0); } public PrimitiveAnalysisEngineController_impl(AnalysisEngineController aParentController, String anEndpointName, String anAnalysisEngineDescriptor, AsynchAECasManager aCasManager, InProcessCache anInProcessCache, int aWorkQueueSize, int anAnalysisEnginePoolSize) throws Exception { this(aParentController, anEndpointName, anAnalysisEngineDescriptor, aCasManager, anInProcessCache, aWorkQueueSize, anAnalysisEnginePoolSize, 0); } public PrimitiveAnalysisEngineController_impl(AnalysisEngineController aParentController, String anEndpointName, String anAnalysisEngineDescriptor, AsynchAECasManager aCasManager, InProcessCache anInProcessCache, int aWorkQueueSize, int anAnalysisEnginePoolSize, int aComponentCasPoolSize) throws Exception { this(aParentController, anEndpointName, anAnalysisEngineDescriptor, aCasManager, anInProcessCache, aWorkQueueSize, anAnalysisEnginePoolSize, aComponentCasPoolSize, null); } public PrimitiveAnalysisEngineController_impl(AnalysisEngineController aParentController, String anEndpointName, String anAnalysisEngineDescriptor, AsynchAECasManager aCasManager, InProcessCache anInProcessCache, int aWorkQueueSize, int anAnalysisEnginePoolSize, int aComponentCasPoolSize, long anInitialCasHeapSize) throws Exception { this(aParentController, anEndpointName, anAnalysisEngineDescriptor, aCasManager, anInProcessCache, aWorkQueueSize, anAnalysisEnginePoolSize, aComponentCasPoolSize, anInitialCasHeapSize, null); } public PrimitiveAnalysisEngineController_impl(AnalysisEngineController aParentController, String anEndpointName, String anAnalysisEngineDescriptor, AsynchAECasManager aCasManager, InProcessCache anInProcessCache, int aWorkQueueSize, int anAnalysisEnginePoolSize, int aComponentCasPoolSize, JmxManagement aJmxManagement) throws Exception { this(aParentController, anEndpointName, anAnalysisEngineDescriptor, aCasManager, anInProcessCache, aWorkQueueSize, anAnalysisEnginePoolSize, aComponentCasPoolSize,0, aJmxManagement); } public PrimitiveAnalysisEngineController_impl(AnalysisEngineController aParentController, String anEndpointName, String anAnalysisEngineDescriptor, AsynchAECasManager aCasManager, InProcessCache anInProcessCache, int aWorkQueueSize, int anAnalysisEnginePoolSize, int aComponentCasPoolSize, long anInitialCasHeapSize, JmxManagement aJmxManagement) throws Exception { super(aParentController, aComponentCasPoolSize, anInitialCasHeapSize, anEndpointName, anAnalysisEngineDescriptor, aCasManager, anInProcessCache, null, aJmxManagement); analysisEnginePoolSize = anAnalysisEnginePoolSize; } public PrimitiveAnalysisEngineController_impl(AnalysisEngineController aParentController, String anEndpointName, String anAnalysisEngineDescriptor, AsynchAECasManager aCasManager, InProcessCache anInProcessCache, int aWorkQueueSize, int anAnalysisEnginePoolSize, JmxManagement aJmxManagement) throws Exception { this(aParentController, anEndpointName, anAnalysisEngineDescriptor, aCasManager, anInProcessCache, aWorkQueueSize, anAnalysisEnginePoolSize, 0, aJmxManagement); } public int getAEInstanceCount() { return analysisEnginePoolSize; } public void initializeAnalysisEngine() throws ResourceInitializationException { ResourceSpecifier rSpecifier = null; // Parse the descriptor in the calling thread. try { rSpecifier = UimaClassFactory.produceResourceSpecifier(super.aeDescriptor); } catch ( Exception e) { e.printStackTrace(); throw new ResourceInitializationException(e); } synchronized( mux ) { AnalysisEngine ae = UIMAFramework.produceAnalysisEngine(rSpecifier, paramsMap); System.out.println(">>>>> Controller:"+getComponentName()+" Completed Initialization of New AE Instance In Thread::"+Thread.currentThread().getId()+" AE Instance Hashcode:"+ae.hashCode()); if ( aeInstancePool == null ) { aeInstancePool = new AnalysisEngineInstancePoolWithThreadAffinity(analysisEnginePoolSize); } try { aeInstancePool.checkin(ae); } catch( Exception e) { throw new ResourceInitializationException(e); } assignServiceMetadata(); if ( aeInstancePool.size() == analysisEnginePoolSize ) { try { System.out.println("Controller:"+getComponentName()+ " All AE Instances Have Been Instantiated. Completing Initialization"); postInitialize(); } catch ( Exception e) { e.printStackTrace(); throw new ResourceInitializationException(e); } } } } public boolean threadAssignedToAE() { if ( aeInstancePool == null ) { return false; } return aeInstancePool.exists(); } private void assignServiceMetadata() { if ( analysisEngineMetadata == null ) { AnalysisEngineDescription specifier = (AnalysisEngineDescription) super.getResourceSpecifier(); analysisEngineMetadata = specifier.getAnalysisEngineMetaData(); } } public void initialize() throws AsynchAEException { } /** * This method is called after all AE instances initialize. It is called once. * It initializes service Cas Pool, notifies the deployer that initialization * completed and finally loweres a semaphore allowing messages to be processed. * * @throws AsynchAEException */ private void postInitialize() throws AsynchAEException { try { if (errorHandlerChain == null) { super.plugInDefaultErrorHandlerChain(); } if (UIMAFramework.getLogger(CLASS_NAME).isLoggable(Level.CONFIG)) { UIMAFramework.getLogger(CLASS_NAME).logrb(Level.CONFIG, getClass().getName(), "initialize", UIMAEE_Constants.JMS_LOG_RESOURCE_BUNDLE, "UIMAEE_primitive_ctrl_init_info__CONFIG", new Object[] { analysisEnginePoolSize }); } assignServiceMetadata(); if ( serviceInfo == null ) { serviceInfo = new PrimitiveServiceInfo(isCasMultiplier()); } serviceInfo.setAnalysisEngineInstanceCount(analysisEnginePoolSize); if ( !isStopped() ) { getMonitor().setThresholds(getErrorHandlerChain().getThresholds()); // Initialize Cas Manager if (getCasManagerWrapper() != null) { try { if (getCasManagerWrapper().isInitialized()) { getCasManagerWrapper().addMetadata(getAnalysisEngineMetadata()); if (isTopLevelComponent()) { getCasManagerWrapper().initialize("PrimitiveAEService"); CAS cas = getCasManagerWrapper().getNewCas("PrimitiveAEService"); cas.release(); System.out.println("++++ Controller::"+getComponentName()+" Initialized its Cas Pool"); } } if ( isTopLevelComponent() ) { super.notifyListenersWithInitializationStatus(null); } // All internal components of this Primitive have been initialized. Open the latch // so that this service can start processing requests. latch.openLatch(getName(), isTopLevelComponent(), true); } catch ( Exception e) { e.printStackTrace(); throw new AsynchAEException(e); } } else { if (UIMAFramework.getLogger(CLASS_NAME).isLoggable(Level.CONFIG)) { UIMAFramework.getLogger(CLASS_NAME).logrb(Level.CONFIG, getClass().getName(), "initialize", UIMAEE_Constants.JMS_LOG_RESOURCE_BUNDLE, "UIMAEE_cas_manager_wrapper_notdefined__CONFIG", new Object[] {}); } } } } catch ( AsynchAEException e) { if (UIMAFramework.getLogger(CLASS_NAME).isLoggable(Level.WARNING)) { UIMAFramework.getLogger(CLASS_NAME).logrb(Level.WARNING, getClass().getName(), "initialize", UIMAEE_Constants.JMS_LOG_RESOURCE_BUNDLE, "UIMAEE_exception__WARNING", new Object[] { e }); } e.printStackTrace(); throw e; } catch ( Exception e) { if (UIMAFramework.getLogger(CLASS_NAME).isLoggable(Level.WARNING)) { UIMAFramework.getLogger(CLASS_NAME).logrb(Level.WARNING, getClass().getName(), "initialize", UIMAEE_Constants.JMS_LOG_RESOURCE_BUNDLE, "UIMAEE_exception__WARNING", new Object[] { e }); } e.printStackTrace(); throw new AsynchAEException(e); } if (UIMAFramework.getLogger(CLASS_NAME).isLoggable(Level.INFO)) { UIMAFramework.getLogger(CLASS_NAME).logrb(Level.INFO, CLASS_NAME.getName(), "initialize", UIMAEE_Constants.JMS_LOG_RESOURCE_BUNDLE, "UIMAEE_initialized_controller__INFO", new Object[] { getComponentName() }); } super.serviceInitialized = true; } /** * Forces initialization of a Cas Pool if this is a Cas Multiplier delegate collocated with * an aggregate. The parent aggregate calls this method when all type systems have been * merged. */ public synchronized void onInitialize() { // Component's Cas Pool is registered lazily, when the process() is called for // the first time. For monitoring purposes, we need the comoponent's Cas Pool // MBeans to register during initialization of the service. For a Cas Multiplier // force creation of the Cas Pool and registration of a Cas Pool with the JMX Server. // Just get the CAS and release it back to the component's Cas Pool. if ( isCasMultiplier() && !isTopLevelComponent() ) { System.out.println(Thread.currentThread().getId()+" >>>>>> CAS Multiplier::"+getComponentName()+" Initializing its Cas Pool"); CAS cas = (CAS)getUimaContext().getEmptyCas(CAS.class); cas.release(); } } /** * */ public void collectionProcessComplete(Endpoint anEndpoint)// throws AsynchAEException { AnalysisEngine ae = null; long start = super.getCpuTime(); localCache.dumpContents(); try { ae = aeInstancePool.checkout(); if ( ae != null) { ae.collectionProcessComplete(); } if (UIMAFramework.getLogger(CLASS_NAME).isLoggable(Level.FINEST)) { UIMAFramework.getLogger(CLASS_NAME).logrb(Level.FINEST, getClass().getName(), "collectionProcessComplete", UIMAEE_Constants.JMS_LOG_RESOURCE_BUNDLE, "UIMAEE_cpc_all_cases_processed__FINEST", new Object[] { getComponentName() }); } getServicePerformance().incrementAnalysisTime(super.getCpuTime()-start); if ( !anEndpoint.isRemote()) { UimaTransport transport = getTransport(anEndpoint.getEndpoint()); UimaMessage message = transport.produceMessage(AsynchAEMessage.CollectionProcessComplete,AsynchAEMessage.Response,getName()); // Send CPC completion reply back to the client. Use internal (non-jms) transport transport.getUimaMessageDispatcher(anEndpoint.getEndpoint()).dispatch(message); } else { getOutputChannel().sendReply(AsynchAEMessage.CollectionProcessComplete, anEndpoint); } if (UIMAFramework.getLogger(CLASS_NAME).isLoggable(Level.FINE)) { UIMAFramework.getLogger(CLASS_NAME).logrb(Level.FINE, getClass().getName(), "collectionProcessComplete", UIMAEE_Constants.JMS_LOG_RESOURCE_BUNDLE, "UIMAEE_cpc_completed__FINE", new Object[] { getComponentName()}); } } catch ( Exception e) { ErrorContext errorContext = new ErrorContext(); errorContext.add(AsynchAEMessage.Command, AsynchAEMessage.CollectionProcessComplete); errorContext.add(AsynchAEMessage.Endpoint, anEndpoint); getErrorHandlerChain().handle(e, errorContext, this); } finally { clearStats(); if ( ae != null ) { try { aeInstancePool.checkin(ae); } catch( Exception ex) { ex.printStackTrace(); if (UIMAFramework.getLogger(CLASS_NAME).isLoggable(Level.WARNING)) { UIMAFramework.getLogger(CLASS_NAME).logrb(Level.WARNING, getClass().getName(), "collectionProcessComplete", UIMAEE_Constants.JMS_LOG_RESOURCE_BUNDLE, "UIMAEE_unable_to_check_ae_back_to_pool__WARNING", new Object[] { getComponentName(), ex}); } } } } } public void addAbortedCasReferenceId( String aCasReferenceId ) { abortedCASReferenceId = aCasReferenceId; } private boolean abortGeneratingCASes( String aCasReferenceId ) { return ( aCasReferenceId.equals(abortedCASReferenceId)); } public void process(CAS aCAS, String aCasReferenceId, Endpoint anEndpoint) { if ( stopped ) { return; } // Create a new entry in the local cache for the input CAS CasStateEntry parentCasStateEntry = getLocalCache().createCasStateEntry(aCasReferenceId); long totalProcessTime = 0; // stored total time spent producing ALL CASes boolean inputCASReturned = false; boolean processingFailed = false; // This is a primitive controller. No more processing is to be done on the Cas. Mark the destination as final and return CAS in reply. anEndpoint.setFinal(true); AnalysisEngine ae = null; try { // Checkout an instance of AE from the pool ae = aeInstancePool.checkout(); // Get input CAS entry from the InProcess cache CacheEntry inputCASEntry = getInProcessCache().getCacheEntryForCAS(aCasReferenceId); long time = super.getCpuTime(); CasIterator casIterator = ae.processAndOutputNewCASes(aCAS); // Store how long it took to call processAndOutputNewCASes() totalProcessTime = ( super.getCpuTime() - time); long sequence = 1; long hasNextTime = 0; // stores time in hasNext() long getNextTime = 0; // stores time in next(); boolean moreCASesToProcess = true; while (moreCASesToProcess) { long timeToProcessCAS = 0; // stores time in hasNext() and next() for each CAS hasNextTime = super.getCpuTime(); if ( !casIterator.hasNext() ) { moreCASesToProcess = false; // Measure how long it took to call hasNext() timeToProcessCAS = (super.getCpuTime()-hasNextTime); totalProcessTime += timeToProcessCAS; break; // from while } // Measure how long it took to call hasNext() timeToProcessCAS = (super.getCpuTime()-hasNextTime); getNextTime = super.getCpuTime(); CAS casProduced = casIterator.next(); // Add how long it took to call next() timeToProcessCAS += (super.getCpuTime()- getNextTime); // Add time to call hasNext() and next() to the running total totalProcessTime += timeToProcessCAS; // If the service is stopped or aborted, stop generating new CASes and just return the input CAS if ( stopped || abortGeneratingCASes(aCasReferenceId)) { if ( getInProcessCache() != null && getInProcessCache().getSize() > 0 && getInProcessCache().entryExists(aCasReferenceId)) { try { // Set a flag on the input CAS to indicate that the processing was aborted getInProcessCache().getCacheEntryForCAS(aCasReferenceId).setAborted(true); } catch( Exception e ) { // An exception be be thrown here if the service is being stopped. // The top level controller may have already cleaned up the cache // and the getCacheEntryForCAS() will throw an exception. Ignore it // here, we are shutting down. } finally { // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // We are terminating the iterator here, release the internal CAS lock // so that we can release the CAS. This approach may need to be changed // as there may potentially be a problem with a Class Loader. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ((CASImpl)aCAS).enableReset(true); } } return; } OutOfTypeSystemData otsd = getInProcessCache().getOutOfTypeSystemData(aCasReferenceId); MessageContext mContext = getInProcessCache().getMessageAccessorByReference(aCasReferenceId); CacheEntry newEntry = getInProcessCache().register( casProduced, mContext, otsd); // if this Cas Multiplier is not Top Level service, add new Cas Id to the private // cache of the parent aggregate controller. The Aggregate needs to know about // all CASes it has in play that were generated from the input CAS. CasStateEntry childCasStateEntry = null; if ( !isTopLevelComponent() ) { // Create CAS state entry in the aggregate's local cache childCasStateEntry = parentController.getLocalCache().createCasStateEntry(newEntry.getCasReferenceId()); // Fetch the parent CAS state entry from the aggregate's local cache. We need to increment // number of child CASes associated with it. parentCasStateEntry = parentController.getLocalCache().lookupEntry(aCasReferenceId); } else { childCasStateEntry = getLocalCache().createCasStateEntry(newEntry.getCasReferenceId()); parentCasStateEntry = getLocalCache().lookupEntry(aCasReferenceId); } // Associate parent CAS (input CAS) with the new CAS. childCasStateEntry.setInputCasReferenceId(aCasReferenceId); // Increment number of child CASes generated from the input CAS parentCasStateEntry.incrementSubordinateCasInPlayCount(); // Associate input CAS with the new CAS newEntry.setInputCasReferenceId(aCasReferenceId); newEntry.setCasSequence(sequence); // Add to the cache how long it took to process the generated (subordinate) CAS getCasStatistics(newEntry.getCasReferenceId()).incrementAnalysisTime(timeToProcessCAS); if (UIMAFramework.getLogger(CLASS_NAME).isLoggable(Level.FINE)) { UIMAFramework.getLogger(CLASS_NAME).logrb(Level.FINE, getClass().getName(), "process", UIMAEE_Constants.JMS_LOG_RESOURCE_BUNDLE, "UIMAEE_produced_new_cas__FINE", new Object[] { Thread.currentThread().getName(),getComponentName(),newEntry.getCasReferenceId(), aCasReferenceId }); } // Add the generated CAS to the outstanding CAS Map. Client notification will release // this CAS back to its pool synchronized(syncObject) { if ( isTopLevelComponent() ) { // Add the id of the generated CAS to the map holding outstanding CASes. This // map will be referenced when a client sends Free CAS Notification. The map // stores the id of the CAS both as a key and a value. Map is used to facilitate // quick lookup cmOutstandingCASes.put(newEntry.getCasReferenceId(),newEntry.getCasReferenceId()); } // Increment number of CASes processed by this service sequence++; } if ( !anEndpoint.isRemote()) { UimaTransport transport = getTransport(anEndpoint.getEndpoint()); UimaMessage message = transport.produceMessage(AsynchAEMessage.Process,AsynchAEMessage.Request,getName()); message.addStringProperty(AsynchAEMessage.CasReference, newEntry.getCasReferenceId()); message.addStringProperty(AsynchAEMessage.InputCasReference, aCasReferenceId); message.addLongProperty(AsynchAEMessage.CasSequence, sequence); ServicePerformance casStats = getCasStatistics(aCasReferenceId); message.addLongProperty(AsynchAEMessage.TimeToSerializeCAS, casStats.getRawCasSerializationTime()); message.addLongProperty(AsynchAEMessage.TimeToDeserializeCAS, casStats.getRawCasDeserializationTime()); message.addLongProperty(AsynchAEMessage.TimeInProcessCAS, casStats.getRawAnalysisTime()); long iT = getIdleTimeBetweenProcessCalls(AsynchAEMessage.Process); message.addLongProperty(AsynchAEMessage.IdleTime, iT ); transport.getUimaMessageDispatcher(anEndpoint.getEndpoint()).dispatch(message); } else { // Send generated CAS to the client getOutputChannel().sendReply(newEntry, anEndpoint); } // Remove the new CAS state entry from the local cache if this a top level primitive. // If not top level, the client (an Aggregate) will remove this entry when this new // generated CAS reaches Final State. if ( isTopLevelComponent() ) { localCache.remove(newEntry.getCasReferenceId()); } // Remove Stats from the global Map associated with the new CAS // These stats for this CAS were added to the response message // and are no longer needed dropCasStatistics(newEntry.getCasReferenceId()); } // while if (UIMAFramework.getLogger(CLASS_NAME).isLoggable(Level.FINEST)) { UIMAFramework.getLogger(CLASS_NAME).logrb(Level.FINEST, getClass().getName(), "process", UIMAEE_Constants.JMS_LOG_RESOURCE_BUNDLE, "UIMAEE_completed_analysis__FINEST", new Object[] { Thread.currentThread().getName(), getComponentName(), aCasReferenceId, (double) (super.getCpuTime() - time) / (double) 1000000 }); } getMonitor().resetCountingStatistic("", Monitor.ProcessErrorCount); // Store total time spent processing this input CAS getCasStatistics(aCasReferenceId).incrementAnalysisTime(totalProcessTime); if ( !anEndpoint.isRemote()) { inputCASReturned = true; UimaTransport transport = getTransport(anEndpoint.getEndpoint()); UimaMessage message = transport.produceMessage(AsynchAEMessage.Process,AsynchAEMessage.Response,getName()); message.addStringProperty(AsynchAEMessage.CasReference, aCasReferenceId); ServicePerformance casStats = getCasStatistics(aCasReferenceId); message.addLongProperty(AsynchAEMessage.TimeToSerializeCAS, casStats.getRawCasSerializationTime()); message.addLongProperty(AsynchAEMessage.TimeToDeserializeCAS, casStats.getRawCasDeserializationTime()); message.addLongProperty(AsynchAEMessage.TimeInProcessCAS, casStats.getRawAnalysisTime()); long iT = getIdleTimeBetweenProcessCalls(AsynchAEMessage.Process); message.addLongProperty(AsynchAEMessage.IdleTime, iT ); // Send reply back to the client. Use internal (non-jms) transport transport.getUimaMessageDispatcher(anEndpoint.getEndpoint()).dispatch(message); } else { boolean sendReply = false; synchronized( cmOutstandingCASes ) { if ( cmOutstandingCASes.size() == 0) { inputCASReturned = true; sendReply = true; } else { // Change the state of the input CAS. Since the input CAS is not returned to the client // until all children of this CAS has been fully processed we keep the input in the cache. // The client will send Free CAS Notifications to release CASes produced here. When the // last child CAS is freed, the input CAS is allowed to be returned to the client. inputCASEntry.setPendingReply(true); } } if ( sendReply ) { // Return an input CAS to the client if there are no outstanding child CASes in play getOutputChannel().sendReply(aCasReferenceId, anEndpoint); } } // Remove input CAS state entry from the local cache if ( !isTopLevelComponent() ) { localCache.remove(aCasReferenceId); } } catch ( Throwable e) { e.printStackTrace(); processingFailed = true; ErrorContext errorContext = new ErrorContext(); errorContext.add(AsynchAEMessage.CasReference, aCasReferenceId); errorContext.add(AsynchAEMessage.Command, AsynchAEMessage.Process); errorContext.add(AsynchAEMessage.MessageType, AsynchAEMessage.Request); errorContext.add(AsynchAEMessage.Endpoint, anEndpoint); // Handle the exception. Pass reference to the PrimitiveController instance getErrorHandlerChain().handle(e, errorContext, this); } finally { dropCasStatistics(aCasReferenceId); if ( ae != null ) { try { aeInstancePool.checkin(ae); } catch( Exception e) { e.printStackTrace(); } } // drop the CAS if it has been successfully processed. If there was a failure, the Error Handler // will drop the CAS if ( isTopLevelComponent() && !processingFailed) { // Release CASes produced from the input CAS if the input CAS has been aborted if ( abortGeneratingCASes(aCasReferenceId) ) { if (UIMAFramework.getLogger(CLASS_NAME).isLoggable(Level.INFO)) { UIMAFramework.getLogger(CLASS_NAME).logrb(Level.INFO, CLASS_NAME.getName(), "process", UIMAEE_Constants.JMS_LOG_RESOURCE_BUNDLE, "UIMAEE_remove_cache_entry__INFO", new Object[] { getComponentName(), aCasReferenceId }); } getInProcessCache().releaseCASesProducedFromInputCAS(aCasReferenceId); } else if ( inputCASReturned ) { // Remove input CAS cache entry if the CAS has been sent to the client dropCAS(aCasReferenceId, true); localCache.dumpContents(); } } } } private void addConfigIntParameter( String aParamName, int aParamValue) { ConfigurationParameter cp = new ConfigurationParameter_impl(); cp.setMandatory(false); cp.setMultiValued(false); cp.setName(aParamName); cp.setType("Integer"); getAnalysisEngineMetadata().getConfigurationParameterDeclarations().addConfigurationParameter(cp); getAnalysisEngineMetadata().getConfigurationParameterSettings().setParameterValue(aParamName, aParamValue); } // Return metadata public void sendMetadata(Endpoint anEndpoint) throws AsynchAEException { addConfigIntParameter(AnalysisEngineController.AEInstanceCount, analysisEnginePoolSize); if ( getAnalysisEngineMetadata().getOperationalProperties().getOutputsNewCASes() ) { addConfigIntParameter(AnalysisEngineController.CasPoolSize, super.componentCasPoolSize); } super.sendMetadata(anEndpoint, getAnalysisEngineMetadata()); } private AnalysisEngineMetaData getAnalysisEngineMetadata() { return analysisEngineMetadata; } /** * Executes action on error. Primitive Controller allows two types of actions TERMINATE and DROPCAS. */ public void takeAction(String anAction, String anEndpointName, ErrorContext anErrorContext) { try { if (ErrorHandler.TERMINATE.equalsIgnoreCase(anAction) || ErrorHandler.DROPCAS.equalsIgnoreCase(anAction)) { super.handleAction(anAction, anEndpointName, anErrorContext); } } catch ( Exception e) { e.printStackTrace(); if (UIMAFramework.getLogger(CLASS_NAME).isLoggable(Level.WARNING)) { UIMAFramework.getLogger(CLASS_NAME).logrb(Level.WARNING, getClass().getName(), "takeAction", UIMAEE_Constants.JMS_LOG_RESOURCE_BUNDLE, "UIMAEE_exception__WARNING", new Object[] { e }); } } } public String getServiceEndpointName() { return getName(); } public synchronized ControllerLatch getControllerLatch() { return latch; } public boolean isPrimitive() { return true; } public Monitor getMonitor() { return super.monitor; } public void setMonitor(Monitor monitor) { this.monitor = monitor; } public void handleDelegateLifeCycleEvent( String anEndpoint, int aDelegateCount) { if ( aDelegateCount == 0 ) { // tbi } } protected String getNameFromMetadata() { return super.getMetaData().getName(); } public void setAnalysisEngineInstancePool( AnalysisEngineInstancePool aPool) { aeInstancePool = aPool; } public PrimitiveServiceInfo getServiceInfo() { if ( serviceInfo == null ) { serviceInfo = new PrimitiveServiceInfo(); } if ( isTopLevelComponent() && getInputChannel() != null ) { serviceInfo.setInputQueueName(getInputChannel().getServiceInfo().getInputQueueName()); serviceInfo.setBrokerURL(getInputChannel().getServiceInfo().getBrokerURL()); } serviceInfo.setState("Running"); if ( isCasMultiplier() ) { serviceInfo.setCASMultiplier(); } return serviceInfo; } public void stop() { System.out.println(">>>>> Stopping Controller:"+getComponentName()); super.stop(); stopInputChannel(); if ( aeInstancePool != null ) { try { aeInstancePool.destroy(); stopTransportLayer(); } catch( Exception e){ e.printStackTrace();} } if ( cmOutstandingCASes != null ) { cmOutstandingCASes.clear(); } if ( aeList != null ) { aeList.clear(); aeList = null; } System.out.println(">>>>> Done Stopping Controller:"+getComponentName()); } }
uima-as/uimaj-as-core/src/main/java/org/apache/uima/aae/controller/PrimitiveAnalysisEngineController_impl.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.uima.aae.controller; import java.util.ArrayList; import java.util.List; import org.apache.uima.UIMAFramework; import org.apache.uima.aae.AsynchAECasManager; import org.apache.uima.aae.InProcessCache; import org.apache.uima.aae.UIMAEE_Constants; import org.apache.uima.aae.UimaClassFactory; import org.apache.uima.aae.InProcessCache.CacheEntry; import org.apache.uima.aae.controller.LocalCache.CasStateEntry; import org.apache.uima.aae.error.AsynchAEException; import org.apache.uima.aae.error.ErrorContext; import org.apache.uima.aae.error.ErrorHandler; import org.apache.uima.aae.error.ServiceShutdownException; import org.apache.uima.aae.jmx.JmxManagement; import org.apache.uima.aae.jmx.PrimitiveServiceInfo; import org.apache.uima.aae.jmx.ServicePerformance; import org.apache.uima.aae.message.AsynchAEMessage; import org.apache.uima.aae.message.MessageContext; import org.apache.uima.aae.monitor.Monitor; import org.apache.uima.aae.spi.transport.UimaMessage; import org.apache.uima.aae.spi.transport.UimaTransport; import org.apache.uima.analysis_engine.AnalysisEngine; import org.apache.uima.analysis_engine.AnalysisEngineDescription; import org.apache.uima.analysis_engine.CasIterator; import org.apache.uima.analysis_engine.metadata.AnalysisEngineMetaData; import org.apache.uima.cas.CAS; import org.apache.uima.cas.impl.CASImpl; import org.apache.uima.cas.impl.OutOfTypeSystemData; import org.apache.uima.resource.ResourceInitializationException; import org.apache.uima.resource.ResourceSpecifier; import org.apache.uima.resource.metadata.ConfigurationParameter; import org.apache.uima.resource.metadata.impl.ConfigurationParameter_impl; import org.apache.uima.util.InvalidXMLException; import org.apache.uima.util.Level; public class PrimitiveAnalysisEngineController_impl extends BaseAnalysisEngineController implements PrimitiveAnalysisEngineController { private static final Class CLASS_NAME = PrimitiveAnalysisEngineController_impl.class; // Stores AE metadata private AnalysisEngineMetaData analysisEngineMetadata; // Number of AE instances private int analysisEnginePoolSize; // Mutex protected Object notifyObj = new Object(); // Temp list holding instances of AE private List aeList = new ArrayList(); // Stores service info for JMX private PrimitiveServiceInfo serviceInfo = null; // Pool containing instances of AE. The default implementation provides Thread affinity // meaning each thread executes the same AE instance. private AnalysisEngineInstancePool aeInstancePool = null; private String abortedCASReferenceId = null; private Object mux = new Object(); private Object mux2 = new Object(); public PrimitiveAnalysisEngineController_impl(String anEndpointName, String anAnalysisEngineDescriptor, AsynchAECasManager aCasManager, InProcessCache anInProcessCache, int aWorkQueueSize, int anAnalysisEnginePoolSize) throws Exception { this(null, anEndpointName, anAnalysisEngineDescriptor, aCasManager, anInProcessCache, aWorkQueueSize, anAnalysisEnginePoolSize, 0); } public PrimitiveAnalysisEngineController_impl(AnalysisEngineController aParentController, String anEndpointName, String anAnalysisEngineDescriptor, AsynchAECasManager aCasManager, InProcessCache anInProcessCache, int aWorkQueueSize, int anAnalysisEnginePoolSize) throws Exception { this(aParentController, anEndpointName, anAnalysisEngineDescriptor, aCasManager, anInProcessCache, aWorkQueueSize, anAnalysisEnginePoolSize, 0); } public PrimitiveAnalysisEngineController_impl(AnalysisEngineController aParentController, String anEndpointName, String anAnalysisEngineDescriptor, AsynchAECasManager aCasManager, InProcessCache anInProcessCache, int aWorkQueueSize, int anAnalysisEnginePoolSize, int aComponentCasPoolSize) throws Exception { this(aParentController, anEndpointName, anAnalysisEngineDescriptor, aCasManager, anInProcessCache, aWorkQueueSize, anAnalysisEnginePoolSize, aComponentCasPoolSize, null); } public PrimitiveAnalysisEngineController_impl(AnalysisEngineController aParentController, String anEndpointName, String anAnalysisEngineDescriptor, AsynchAECasManager aCasManager, InProcessCache anInProcessCache, int aWorkQueueSize, int anAnalysisEnginePoolSize, int aComponentCasPoolSize, long anInitialCasHeapSize) throws Exception { this(aParentController, anEndpointName, anAnalysisEngineDescriptor, aCasManager, anInProcessCache, aWorkQueueSize, anAnalysisEnginePoolSize, aComponentCasPoolSize, anInitialCasHeapSize, null); } public PrimitiveAnalysisEngineController_impl(AnalysisEngineController aParentController, String anEndpointName, String anAnalysisEngineDescriptor, AsynchAECasManager aCasManager, InProcessCache anInProcessCache, int aWorkQueueSize, int anAnalysisEnginePoolSize, int aComponentCasPoolSize, JmxManagement aJmxManagement) throws Exception { this(aParentController, anEndpointName, anAnalysisEngineDescriptor, aCasManager, anInProcessCache, aWorkQueueSize, anAnalysisEnginePoolSize, aComponentCasPoolSize,0, aJmxManagement); } public PrimitiveAnalysisEngineController_impl(AnalysisEngineController aParentController, String anEndpointName, String anAnalysisEngineDescriptor, AsynchAECasManager aCasManager, InProcessCache anInProcessCache, int aWorkQueueSize, int anAnalysisEnginePoolSize, int aComponentCasPoolSize, long anInitialCasHeapSize, JmxManagement aJmxManagement) throws Exception { super(aParentController, aComponentCasPoolSize, anInitialCasHeapSize, anEndpointName, anAnalysisEngineDescriptor, aCasManager, anInProcessCache, null, aJmxManagement); analysisEnginePoolSize = anAnalysisEnginePoolSize; } public PrimitiveAnalysisEngineController_impl(AnalysisEngineController aParentController, String anEndpointName, String anAnalysisEngineDescriptor, AsynchAECasManager aCasManager, InProcessCache anInProcessCache, int aWorkQueueSize, int anAnalysisEnginePoolSize, JmxManagement aJmxManagement) throws Exception { this(aParentController, anEndpointName, anAnalysisEngineDescriptor, aCasManager, anInProcessCache, aWorkQueueSize, anAnalysisEnginePoolSize, 0, aJmxManagement); } public int getAEInstanceCount() { return analysisEnginePoolSize; } public void initializeAnalysisEngine() throws ResourceInitializationException { ResourceSpecifier rSpecifier = null; // Parse the descriptor in the calling thread. try { rSpecifier = UimaClassFactory.produceResourceSpecifier(super.aeDescriptor); } catch ( Exception e) { e.printStackTrace(); throw new ResourceInitializationException(e); } AnalysisEngine ae = UIMAFramework.produceAnalysisEngine(rSpecifier, paramsMap); System.out.println(">>>>> Controller:"+getComponentName()+" Completed Initialization of New AE Instance In Thread::"+Thread.currentThread().getId()+" AE Instance Hashcode:"+ae.hashCode()); synchronized( mux ) { if ( aeInstancePool == null ) { aeInstancePool = new AnalysisEngineInstancePoolWithThreadAffinity(analysisEnginePoolSize); } try { aeInstancePool.checkin(ae); } catch( Exception e) { throw new ResourceInitializationException(e); } assignServiceMetadata(); if ( aeInstancePool.size() == analysisEnginePoolSize ) { try { System.out.println("Controller:"+getComponentName()+ " All AE Instances Have Been Instantiated. Completing Initialization"); postInitialize(); } catch ( Exception e) { e.printStackTrace(); throw new ResourceInitializationException(e); } } } } public boolean threadAssignedToAE() { if ( aeInstancePool == null ) { return false; } return aeInstancePool.exists(); } private void assignServiceMetadata() { if ( analysisEngineMetadata == null ) { AnalysisEngineDescription specifier = (AnalysisEngineDescription) super.getResourceSpecifier(); analysisEngineMetadata = specifier.getAnalysisEngineMetaData(); } } public void initialize() throws AsynchAEException { } /** * This method is called after all AE instances initialize. It is called once. * It initializes service Cas Pool, notifies the deployer that initialization * completed and finally loweres a semaphore allowing messages to be processed. * * @throws AsynchAEException */ private void postInitialize() throws AsynchAEException { try { if (errorHandlerChain == null) { super.plugInDefaultErrorHandlerChain(); } if (UIMAFramework.getLogger(CLASS_NAME).isLoggable(Level.CONFIG)) { UIMAFramework.getLogger(CLASS_NAME).logrb(Level.CONFIG, getClass().getName(), "initialize", UIMAEE_Constants.JMS_LOG_RESOURCE_BUNDLE, "UIMAEE_primitive_ctrl_init_info__CONFIG", new Object[] { analysisEnginePoolSize }); } assignServiceMetadata(); if ( serviceInfo == null ) { serviceInfo = new PrimitiveServiceInfo(isCasMultiplier()); } serviceInfo.setAnalysisEngineInstanceCount(analysisEnginePoolSize); if ( !isStopped() ) { getMonitor().setThresholds(getErrorHandlerChain().getThresholds()); // Initialize Cas Manager if (getCasManagerWrapper() != null) { try { if (getCasManagerWrapper().isInitialized()) { getCasManagerWrapper().addMetadata(getAnalysisEngineMetadata()); if (isTopLevelComponent()) { getCasManagerWrapper().initialize("PrimitiveAEService"); CAS cas = getCasManagerWrapper().getNewCas("PrimitiveAEService"); cas.release(); System.out.println("++++ Controller::"+getComponentName()+" Initialized its Cas Pool"); } } if ( isTopLevelComponent() ) { super.notifyListenersWithInitializationStatus(null); } // All internal components of this Primitive have been initialized. Open the latch // so that this service can start processing requests. latch.openLatch(getName(), isTopLevelComponent(), true); } catch ( Exception e) { e.printStackTrace(); throw new AsynchAEException(e); } } else { if (UIMAFramework.getLogger(CLASS_NAME).isLoggable(Level.CONFIG)) { UIMAFramework.getLogger(CLASS_NAME).logrb(Level.CONFIG, getClass().getName(), "initialize", UIMAEE_Constants.JMS_LOG_RESOURCE_BUNDLE, "UIMAEE_cas_manager_wrapper_notdefined__CONFIG", new Object[] {}); } } } } catch ( AsynchAEException e) { if (UIMAFramework.getLogger(CLASS_NAME).isLoggable(Level.WARNING)) { UIMAFramework.getLogger(CLASS_NAME).logrb(Level.WARNING, getClass().getName(), "initialize", UIMAEE_Constants.JMS_LOG_RESOURCE_BUNDLE, "UIMAEE_exception__WARNING", new Object[] { e }); } e.printStackTrace(); throw e; } catch ( Exception e) { if (UIMAFramework.getLogger(CLASS_NAME).isLoggable(Level.WARNING)) { UIMAFramework.getLogger(CLASS_NAME).logrb(Level.WARNING, getClass().getName(), "initialize", UIMAEE_Constants.JMS_LOG_RESOURCE_BUNDLE, "UIMAEE_exception__WARNING", new Object[] { e }); } e.printStackTrace(); throw new AsynchAEException(e); } if (UIMAFramework.getLogger(CLASS_NAME).isLoggable(Level.INFO)) { UIMAFramework.getLogger(CLASS_NAME).logrb(Level.INFO, CLASS_NAME.getName(), "initialize", UIMAEE_Constants.JMS_LOG_RESOURCE_BUNDLE, "UIMAEE_initialized_controller__INFO", new Object[] { getComponentName() }); } super.serviceInitialized = true; } /** * Forces initialization of a Cas Pool if this is a Cas Multiplier delegate collocated with * an aggregate. The parent aggregate calls this method when all type systems have been * merged. */ public synchronized void onInitialize() { // Component's Cas Pool is registered lazily, when the process() is called for // the first time. For monitoring purposes, we need the comoponent's Cas Pool // MBeans to register during initialization of the service. For a Cas Multiplier // force creation of the Cas Pool and registration of a Cas Pool with the JMX Server. // Just get the CAS and release it back to the component's Cas Pool. if ( isCasMultiplier() && !isTopLevelComponent() ) { System.out.println(Thread.currentThread().getId()+" >>>>>> CAS Multiplier::"+getComponentName()+" Initializing its Cas Pool"); CAS cas = (CAS)getUimaContext().getEmptyCas(CAS.class); cas.release(); } } /** * */ public void collectionProcessComplete(Endpoint anEndpoint)// throws AsynchAEException { AnalysisEngine ae = null; long start = super.getCpuTime(); localCache.dumpContents(); try { ae = aeInstancePool.checkout(); if ( ae != null) { ae.collectionProcessComplete(); } if (UIMAFramework.getLogger(CLASS_NAME).isLoggable(Level.FINEST)) { UIMAFramework.getLogger(CLASS_NAME).logrb(Level.FINEST, getClass().getName(), "collectionProcessComplete", UIMAEE_Constants.JMS_LOG_RESOURCE_BUNDLE, "UIMAEE_cpc_all_cases_processed__FINEST", new Object[] { getComponentName() }); } getServicePerformance().incrementAnalysisTime(super.getCpuTime()-start); if ( !anEndpoint.isRemote()) { UimaTransport transport = getTransport(anEndpoint.getEndpoint()); UimaMessage message = transport.produceMessage(AsynchAEMessage.CollectionProcessComplete,AsynchAEMessage.Response,getName()); // Send CPC completion reply back to the client. Use internal (non-jms) transport transport.getUimaMessageDispatcher(anEndpoint.getEndpoint()).dispatch(message); } else { getOutputChannel().sendReply(AsynchAEMessage.CollectionProcessComplete, anEndpoint); } if (UIMAFramework.getLogger(CLASS_NAME).isLoggable(Level.FINE)) { UIMAFramework.getLogger(CLASS_NAME).logrb(Level.FINE, getClass().getName(), "collectionProcessComplete", UIMAEE_Constants.JMS_LOG_RESOURCE_BUNDLE, "UIMAEE_cpc_completed__FINE", new Object[] { getComponentName()}); } } catch ( Exception e) { ErrorContext errorContext = new ErrorContext(); errorContext.add(AsynchAEMessage.Command, AsynchAEMessage.CollectionProcessComplete); errorContext.add(AsynchAEMessage.Endpoint, anEndpoint); getErrorHandlerChain().handle(e, errorContext, this); } finally { clearStats(); if ( ae != null ) { try { aeInstancePool.checkin(ae); } catch( Exception ex) { ex.printStackTrace(); if (UIMAFramework.getLogger(CLASS_NAME).isLoggable(Level.WARNING)) { UIMAFramework.getLogger(CLASS_NAME).logrb(Level.WARNING, getClass().getName(), "collectionProcessComplete", UIMAEE_Constants.JMS_LOG_RESOURCE_BUNDLE, "UIMAEE_unable_to_check_ae_back_to_pool__WARNING", new Object[] { getComponentName(), ex}); } } } } } public void addAbortedCasReferenceId( String aCasReferenceId ) { abortedCASReferenceId = aCasReferenceId; } private boolean abortGeneratingCASes( String aCasReferenceId ) { return ( aCasReferenceId.equals(abortedCASReferenceId)); } public void process(CAS aCAS, String aCasReferenceId, Endpoint anEndpoint) { if ( stopped ) { return; } // Create a new entry in the local cache for the input CAS CasStateEntry parentCasStateEntry = getLocalCache().createCasStateEntry(aCasReferenceId); long totalProcessTime = 0; // stored total time spent producing ALL CASes boolean inputCASReturned = false; boolean processingFailed = false; // This is a primitive controller. No more processing is to be done on the Cas. Mark the destination as final and return CAS in reply. anEndpoint.setFinal(true); AnalysisEngine ae = null; try { // Checkout an instance of AE from the pool ae = aeInstancePool.checkout(); // Get input CAS entry from the InProcess cache CacheEntry inputCASEntry = getInProcessCache().getCacheEntryForCAS(aCasReferenceId); long time = super.getCpuTime(); CasIterator casIterator = ae.processAndOutputNewCASes(aCAS); // Store how long it took to call processAndOutputNewCASes() totalProcessTime = ( super.getCpuTime() - time); long sequence = 1; long hasNextTime = 0; // stores time in hasNext() long getNextTime = 0; // stores time in next(); boolean moreCASesToProcess = true; while (moreCASesToProcess) { long timeToProcessCAS = 0; // stores time in hasNext() and next() for each CAS hasNextTime = super.getCpuTime(); if ( !casIterator.hasNext() ) { moreCASesToProcess = false; // Measure how long it took to call hasNext() timeToProcessCAS = (super.getCpuTime()-hasNextTime); totalProcessTime += timeToProcessCAS; break; // from while } // Measure how long it took to call hasNext() timeToProcessCAS = (super.getCpuTime()-hasNextTime); getNextTime = super.getCpuTime(); CAS casProduced = casIterator.next(); // Add how long it took to call next() timeToProcessCAS += (super.getCpuTime()- getNextTime); // Add time to call hasNext() and next() to the running total totalProcessTime += timeToProcessCAS; // If the service is stopped or aborted, stop generating new CASes and just return the input CAS if ( stopped || abortGeneratingCASes(aCasReferenceId)) { if ( getInProcessCache() != null && getInProcessCache().getSize() > 0 && getInProcessCache().entryExists(aCasReferenceId)) { try { // Set a flag on the input CAS to indicate that the processing was aborted getInProcessCache().getCacheEntryForCAS(aCasReferenceId).setAborted(true); } catch( Exception e ) { // An exception be be thrown here if the service is being stopped. // The top level controller may have already cleaned up the cache // and the getCacheEntryForCAS() will throw an exception. Ignore it // here, we are shutting down. } finally { // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // We are terminating the iterator here, release the internal CAS lock // so that we can release the CAS. This approach may need to be changed // as there may potentially be a problem with a Class Loader. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ((CASImpl)aCAS).enableReset(true); } } return; } OutOfTypeSystemData otsd = getInProcessCache().getOutOfTypeSystemData(aCasReferenceId); MessageContext mContext = getInProcessCache().getMessageAccessorByReference(aCasReferenceId); CacheEntry newEntry = getInProcessCache().register( casProduced, mContext, otsd); // if this Cas Multiplier is not Top Level service, add new Cas Id to the private // cache of the parent aggregate controller. The Aggregate needs to know about // all CASes it has in play that were generated from the input CAS. CasStateEntry childCasStateEntry = null; if ( !isTopLevelComponent() ) { // Create CAS state entry in the aggregate's local cache childCasStateEntry = parentController.getLocalCache().createCasStateEntry(newEntry.getCasReferenceId()); // Fetch the parent CAS state entry from the aggregate's local cache. We need to increment // number of child CASes associated with it. parentCasStateEntry = parentController.getLocalCache().lookupEntry(aCasReferenceId); } else { childCasStateEntry = getLocalCache().createCasStateEntry(newEntry.getCasReferenceId()); parentCasStateEntry = getLocalCache().lookupEntry(aCasReferenceId); } // Associate parent CAS (input CAS) with the new CAS. childCasStateEntry.setInputCasReferenceId(aCasReferenceId); // Increment number of child CASes generated from the input CAS parentCasStateEntry.incrementSubordinateCasInPlayCount(); // Associate input CAS with the new CAS newEntry.setInputCasReferenceId(aCasReferenceId); newEntry.setCasSequence(sequence); // Add to the cache how long it took to process the generated (subordinate) CAS getCasStatistics(newEntry.getCasReferenceId()).incrementAnalysisTime(timeToProcessCAS); if (UIMAFramework.getLogger(CLASS_NAME).isLoggable(Level.FINE)) { UIMAFramework.getLogger(CLASS_NAME).logrb(Level.FINE, getClass().getName(), "process", UIMAEE_Constants.JMS_LOG_RESOURCE_BUNDLE, "UIMAEE_produced_new_cas__FINE", new Object[] { Thread.currentThread().getName(),getComponentName(),newEntry.getCasReferenceId(), aCasReferenceId }); } // Add the generated CAS to the outstanding CAS Map. Client notification will release // this CAS back to its pool synchronized(syncObject) { if ( isTopLevelComponent() ) { // Add the id of the generated CAS to the map holding outstanding CASes. This // map will be referenced when a client sends Free CAS Notification. The map // stores the id of the CAS both as a key and a value. Map is used to facilitate // quick lookup cmOutstandingCASes.put(newEntry.getCasReferenceId(),newEntry.getCasReferenceId()); } // Increment number of CASes processed by this service sequence++; } if ( !anEndpoint.isRemote()) { UimaTransport transport = getTransport(anEndpoint.getEndpoint()); UimaMessage message = transport.produceMessage(AsynchAEMessage.Process,AsynchAEMessage.Request,getName()); message.addStringProperty(AsynchAEMessage.CasReference, newEntry.getCasReferenceId()); message.addStringProperty(AsynchAEMessage.InputCasReference, aCasReferenceId); message.addLongProperty(AsynchAEMessage.CasSequence, sequence); ServicePerformance casStats = getCasStatistics(aCasReferenceId); message.addLongProperty(AsynchAEMessage.TimeToSerializeCAS, casStats.getRawCasSerializationTime()); message.addLongProperty(AsynchAEMessage.TimeToDeserializeCAS, casStats.getRawCasDeserializationTime()); message.addLongProperty(AsynchAEMessage.TimeInProcessCAS, casStats.getRawAnalysisTime()); long iT = getIdleTimeBetweenProcessCalls(AsynchAEMessage.Process); message.addLongProperty(AsynchAEMessage.IdleTime, iT ); transport.getUimaMessageDispatcher(anEndpoint.getEndpoint()).dispatch(message); } else { // Send generated CAS to the client getOutputChannel().sendReply(newEntry, anEndpoint); } // Remove the new CAS state entry from the local cache if this a top level primitive. // If not top level, the client (an Aggregate) will remove this entry when this new // generated CAS reaches Final State. if ( isTopLevelComponent() ) { localCache.remove(newEntry.getCasReferenceId()); } // Remove Stats from the global Map associated with the new CAS // These stats for this CAS were added to the response message // and are no longer needed dropCasStatistics(newEntry.getCasReferenceId()); } // while if (UIMAFramework.getLogger(CLASS_NAME).isLoggable(Level.FINEST)) { UIMAFramework.getLogger(CLASS_NAME).logrb(Level.FINEST, getClass().getName(), "process", UIMAEE_Constants.JMS_LOG_RESOURCE_BUNDLE, "UIMAEE_completed_analysis__FINEST", new Object[] { Thread.currentThread().getName(), getComponentName(), aCasReferenceId, (double) (super.getCpuTime() - time) / (double) 1000000 }); } getMonitor().resetCountingStatistic("", Monitor.ProcessErrorCount); // Store total time spent processing this input CAS getCasStatistics(aCasReferenceId).incrementAnalysisTime(totalProcessTime); if ( !anEndpoint.isRemote()) { inputCASReturned = true; UimaTransport transport = getTransport(anEndpoint.getEndpoint()); UimaMessage message = transport.produceMessage(AsynchAEMessage.Process,AsynchAEMessage.Response,getName()); message.addStringProperty(AsynchAEMessage.CasReference, aCasReferenceId); ServicePerformance casStats = getCasStatistics(aCasReferenceId); message.addLongProperty(AsynchAEMessage.TimeToSerializeCAS, casStats.getRawCasSerializationTime()); message.addLongProperty(AsynchAEMessage.TimeToDeserializeCAS, casStats.getRawCasDeserializationTime()); message.addLongProperty(AsynchAEMessage.TimeInProcessCAS, casStats.getRawAnalysisTime()); long iT = getIdleTimeBetweenProcessCalls(AsynchAEMessage.Process); message.addLongProperty(AsynchAEMessage.IdleTime, iT ); // Send reply back to the client. Use internal (non-jms) transport transport.getUimaMessageDispatcher(anEndpoint.getEndpoint()).dispatch(message); } else { boolean sendReply = false; synchronized( cmOutstandingCASes ) { if ( cmOutstandingCASes.size() == 0) { inputCASReturned = true; sendReply = true; } else { // Change the state of the input CAS. Since the input CAS is not returned to the client // until all children of this CAS has been fully processed we keep the input in the cache. // The client will send Free CAS Notifications to release CASes produced here. When the // last child CAS is freed, the input CAS is allowed to be returned to the client. inputCASEntry.setPendingReply(true); } } if ( sendReply ) { // Return an input CAS to the client if there are no outstanding child CASes in play getOutputChannel().sendReply(aCasReferenceId, anEndpoint); } } // Remove input CAS state entry from the local cache if ( !isTopLevelComponent() ) { localCache.remove(aCasReferenceId); } } catch ( Throwable e) { e.printStackTrace(); processingFailed = true; ErrorContext errorContext = new ErrorContext(); errorContext.add(AsynchAEMessage.CasReference, aCasReferenceId); errorContext.add(AsynchAEMessage.Command, AsynchAEMessage.Process); errorContext.add(AsynchAEMessage.MessageType, AsynchAEMessage.Request); errorContext.add(AsynchAEMessage.Endpoint, anEndpoint); // Handle the exception. Pass reference to the PrimitiveController instance getErrorHandlerChain().handle(e, errorContext, this); } finally { dropCasStatistics(aCasReferenceId); if ( ae != null ) { try { aeInstancePool.checkin(ae); } catch( Exception e) { e.printStackTrace(); } } // drop the CAS if it has been successfully processed. If there was a failure, the Error Handler // will drop the CAS if ( isTopLevelComponent() && !processingFailed) { // Release CASes produced from the input CAS if the input CAS has been aborted if ( abortGeneratingCASes(aCasReferenceId) ) { if (UIMAFramework.getLogger(CLASS_NAME).isLoggable(Level.INFO)) { UIMAFramework.getLogger(CLASS_NAME).logrb(Level.INFO, CLASS_NAME.getName(), "process", UIMAEE_Constants.JMS_LOG_RESOURCE_BUNDLE, "UIMAEE_remove_cache_entry__INFO", new Object[] { getComponentName(), aCasReferenceId }); } getInProcessCache().releaseCASesProducedFromInputCAS(aCasReferenceId); } else if ( inputCASReturned ) { // Remove input CAS cache entry if the CAS has been sent to the client dropCAS(aCasReferenceId, true); localCache.dumpContents(); } } } } private void addConfigIntParameter( String aParamName, int aParamValue) { ConfigurationParameter cp = new ConfigurationParameter_impl(); cp.setMandatory(false); cp.setMultiValued(false); cp.setName(aParamName); cp.setType("Integer"); getAnalysisEngineMetadata().getConfigurationParameterDeclarations().addConfigurationParameter(cp); getAnalysisEngineMetadata().getConfigurationParameterSettings().setParameterValue(aParamName, aParamValue); } // Return metadata public void sendMetadata(Endpoint anEndpoint) throws AsynchAEException { addConfigIntParameter(AnalysisEngineController.AEInstanceCount, analysisEnginePoolSize); if ( getAnalysisEngineMetadata().getOperationalProperties().getOutputsNewCASes() ) { addConfigIntParameter(AnalysisEngineController.CasPoolSize, super.componentCasPoolSize); } super.sendMetadata(anEndpoint, getAnalysisEngineMetadata()); } private AnalysisEngineMetaData getAnalysisEngineMetadata() { return analysisEngineMetadata; } /** * Executes action on error. Primitive Controller allows two types of actions TERMINATE and DROPCAS. */ public void takeAction(String anAction, String anEndpointName, ErrorContext anErrorContext) { try { if (ErrorHandler.TERMINATE.equalsIgnoreCase(anAction) || ErrorHandler.DROPCAS.equalsIgnoreCase(anAction)) { super.handleAction(anAction, anEndpointName, anErrorContext); } } catch ( Exception e) { e.printStackTrace(); if (UIMAFramework.getLogger(CLASS_NAME).isLoggable(Level.WARNING)) { UIMAFramework.getLogger(CLASS_NAME).logrb(Level.WARNING, getClass().getName(), "takeAction", UIMAEE_Constants.JMS_LOG_RESOURCE_BUNDLE, "UIMAEE_exception__WARNING", new Object[] { e }); } } } public String getServiceEndpointName() { return getName(); } public synchronized ControllerLatch getControllerLatch() { return latch; } public boolean isPrimitive() { return true; } public Monitor getMonitor() { return super.monitor; } public void setMonitor(Monitor monitor) { this.monitor = monitor; } public void handleDelegateLifeCycleEvent( String anEndpoint, int aDelegateCount) { if ( aDelegateCount == 0 ) { // tbi } } protected String getNameFromMetadata() { return super.getMetaData().getName(); } public void setAnalysisEngineInstancePool( AnalysisEngineInstancePool aPool) { aeInstancePool = aPool; } public PrimitiveServiceInfo getServiceInfo() { if ( serviceInfo == null ) { serviceInfo = new PrimitiveServiceInfo(); } if ( isTopLevelComponent() && getInputChannel() != null ) { serviceInfo.setInputQueueName(getInputChannel().getServiceInfo().getInputQueueName()); serviceInfo.setBrokerURL(getInputChannel().getServiceInfo().getBrokerURL()); } serviceInfo.setState("Running"); if ( isCasMultiplier() ) { serviceInfo.setCASMultiplier(); } return serviceInfo; } public void stop() { System.out.println(">>>>> Stopping Controller:"+getComponentName()); super.stop(); stopInputChannel(); if ( aeInstancePool != null ) { try { aeInstancePool.destroy(); stopTransportLayer(); } catch( Exception e){ e.printStackTrace();} } if ( cmOutstandingCASes != null ) { cmOutstandingCASes.clear(); } if ( aeList != null ) { aeList.clear(); aeList = null; } System.out.println(">>>>> Done Stopping Controller:"+getComponentName()); } }
UIMA-1223 synchronize use of UIMAFramework.produceAnalysisEngine because it is not thread safe. git-svn-id: dd361d0afbe84f3eb97f7061549e905c2c5df34b@725312 13f79535-47bb-0310-9956-ffa450edef68
uima-as/uimaj-as-core/src/main/java/org/apache/uima/aae/controller/PrimitiveAnalysisEngineController_impl.java
UIMA-1223 synchronize use of UIMAFramework.produceAnalysisEngine because it is not thread safe.
<ide><path>ima-as/uimaj-as-core/src/main/java/org/apache/uima/aae/controller/PrimitiveAnalysisEngineController_impl.java <ide> throw new ResourceInitializationException(e); <ide> } <ide> <del> AnalysisEngine ae = UIMAFramework.produceAnalysisEngine(rSpecifier, paramsMap); <del> System.out.println(">>>>> Controller:"+getComponentName()+" Completed Initialization of New AE Instance In Thread::"+Thread.currentThread().getId()+" AE Instance Hashcode:"+ae.hashCode()); <ide> synchronized( mux ) { <add> AnalysisEngine ae = UIMAFramework.produceAnalysisEngine(rSpecifier, paramsMap); <add> System.out.println(">>>>> Controller:"+getComponentName()+" Completed Initialization of New AE Instance In Thread::"+Thread.currentThread().getId()+" AE Instance Hashcode:"+ae.hashCode()); <ide> if ( aeInstancePool == null ) { <ide> aeInstancePool = new AnalysisEngineInstancePoolWithThreadAffinity(analysisEnginePoolSize); <ide> }