lang
stringclasses 2
values | license
stringclasses 13
values | stderr
stringlengths 0
343
| commit
stringlengths 40
40
| returncode
int64 0
128
| repos
stringlengths 6
87.7k
| new_contents
stringlengths 0
6.23M
| new_file
stringlengths 3
311
| old_contents
stringlengths 0
6.23M
| message
stringlengths 6
9.1k
| old_file
stringlengths 3
311
| subject
stringlengths 0
4k
| git_diff
stringlengths 0
6.31M
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
Java | epl-1.0 | c7b6c322c84b140d2e550ec18836ea99287766df | 0 | opendaylight/yangtools,opendaylight/yangtools | /*
* Copyright (c) 2020 PANTHEON.tech, s.r.o. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
import org.opendaylight.yangtools.yang.xpath.api.YangXPathParserFactory;
module org.opendaylight.yangtools.yang.parser.rfc7950 {
// FIXME: audit these, potentially lowering them to their sole user if reasonable
exports org.opendaylight.yangtools.yang.parser.rfc7950.ir;
exports org.opendaylight.yangtools.yang.parser.rfc7950.reactor;
exports org.opendaylight.yangtools.yang.parser.rfc7950.repo;
uses YangXPathParserFactory;
requires transitive java.xml;
requires transitive com.google.common;
requires transitive org.opendaylight.yangtools.concepts;
requires transitive org.opendaylight.yangtools.yang.common;
requires transitive org.opendaylight.yangtools.yang.model.api;
requires transitive org.opendaylight.yangtools.yang.model.spi;
requires transitive org.opendaylight.yangtools.yang.parser.api;
requires transitive org.opendaylight.yangtools.yang.parser.reactor;
requires transitive org.opendaylight.yangtools.yang.parser.spi;
requires transitive org.opendaylight.yangtools.yang.repo.api;
requires transitive org.opendaylight.yangtools.yang.repo.spi;
requires transitive org.opendaylight.yangtools.yang.xpath.api;
requires org.antlr.antlr4.runtime;
requires org.opendaylight.yangtools.openconfig.model.api;
requires org.opendaylight.yangtools.yang.model.ri;
requires org.opendaylight.yangtools.util;
requires org.slf4j;
// Annotations
requires static transitive org.eclipse.jdt.annotation;
requires static com.github.spotbugs.annotations;
requires static org.checkerframework.checker.qual;
}
| parser/yang-parser-rfc7950/src/main/java/module-info.java | /*
* Copyright (c) 2020 PANTHEON.tech, s.r.o. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
module org.opendaylight.yangtools.yang.parser.rfc7950 {
// FIXME: audit these, potentially lowering them to their sole user if reasonable
exports org.opendaylight.yangtools.yang.parser.rfc7950.ir;
exports org.opendaylight.yangtools.yang.parser.rfc7950.namespace;
exports org.opendaylight.yangtools.yang.parser.rfc7950.reactor;
exports org.opendaylight.yangtools.yang.parser.rfc7950.repo;
exports org.opendaylight.yangtools.yang.parser.rfc7950.stmt;
uses org.opendaylight.yangtools.yang.xpath.api.YangXPathParserFactory;
requires transitive java.xml;
requires transitive com.google.common;
requires transitive org.opendaylight.yangtools.concepts;
requires transitive org.opendaylight.yangtools.yang.common;
requires transitive org.opendaylight.yangtools.yang.model.api;
requires transitive org.opendaylight.yangtools.yang.model.spi;
requires transitive org.opendaylight.yangtools.yang.parser.api;
requires transitive org.opendaylight.yangtools.yang.parser.reactor;
requires transitive org.opendaylight.yangtools.yang.parser.spi;
requires transitive org.opendaylight.yangtools.yang.repo.api;
requires transitive org.opendaylight.yangtools.yang.repo.spi;
requires transitive org.opendaylight.yangtools.yang.xpath.api;
requires org.antlr.antlr4.runtime;
requires org.opendaylight.yangtools.openconfig.model.api;
requires org.opendaylight.yangtools.yang.model.ri;
requires org.opendaylight.yangtools.util;
requires org.slf4j;
// Annotations
requires static transitive org.eclipse.jdt.annotation;
requires static com.github.spotbugs.annotations;
requires static org.checkerframework.checker.qual;
}
| Do not export yang.parser.rfc7950.{namespace,stmt}
These packages are not used anywhere in ODL proper, do not export them
to further isolate implementation internals.
Change-Id: Ic3a224eea07a49703fff9668ecb7b35e02b78611
Signed-off-by: Robert Varga <[email protected]>
| parser/yang-parser-rfc7950/src/main/java/module-info.java | Do not export yang.parser.rfc7950.{namespace,stmt} | <ide><path>arser/yang-parser-rfc7950/src/main/java/module-info.java
<ide> * terms of the Eclipse Public License v1.0 which accompanies this distribution,
<ide> * and is available at http://www.eclipse.org/legal/epl-v10.html
<ide> */
<add>import org.opendaylight.yangtools.yang.xpath.api.YangXPathParserFactory;
<add>
<ide> module org.opendaylight.yangtools.yang.parser.rfc7950 {
<ide> // FIXME: audit these, potentially lowering them to their sole user if reasonable
<ide> exports org.opendaylight.yangtools.yang.parser.rfc7950.ir;
<del> exports org.opendaylight.yangtools.yang.parser.rfc7950.namespace;
<ide> exports org.opendaylight.yangtools.yang.parser.rfc7950.reactor;
<ide> exports org.opendaylight.yangtools.yang.parser.rfc7950.repo;
<del> exports org.opendaylight.yangtools.yang.parser.rfc7950.stmt;
<ide>
<del> uses org.opendaylight.yangtools.yang.xpath.api.YangXPathParserFactory;
<add> uses YangXPathParserFactory;
<ide>
<ide> requires transitive java.xml;
<ide> requires transitive com.google.common; |
|
Java | bsd-3-clause | 1a3de308fd2f6510bedb8f5ac3b7c9fa6505d258 | 0 | bertleft/jmonkeyengine,bertleft/jmonkeyengine,bertleft/jmonkeyengine,bertleft/jmonkeyengine | /*
* Copyright (c) 2009-2015 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.bullet.objects;
import com.jme3.bullet.PhysicsSoftSpace;
import com.jme3.bullet.collision.PhysicsCollisionObject;
import com.jme3.bullet.objects.infos.SoftBodyWorldInfo;
import com.jme3.bullet.util.DebugMeshCallback;
import com.jme3.bullet.util.NativeMeshUtil;
import com.jme3.math.Quaternion;
import com.jme3.math.Transform;
import com.jme3.math.Vector3f;
import com.jme3.scene.Geometry;
import com.jme3.scene.Mesh;
import com.jme3.scene.Spatial;
import com.jme3.scene.VertexBuffer;
import com.jme3.scene.VertexBuffer.Type;
import com.jme3.scene.mesh.IndexBuffer;
import com.jme3.util.BufferUtils;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author dokthar
*/
public class PhysicsSoftBody extends PhysicsCollisionObject {
@Deprecated
public PhysicsSoftBody(Vector3f[] vertices, float[] masses) {
objectId = ctr_PhysicsSoftBody(vertices.length, vertices, masses);
postRebuild(false);
}
public PhysicsSoftBody() {
objectId = ctr_PhysicsSoftBody();
initDefault();
postRebuild(false);
}
public PhysicsSoftBody(Mesh triMesh) {
// must check if the mesh have %3 vertices
createFromTriMesh(triMesh);
}
// SoftBodies need to have a direct access to JME's Mesh buffer in order a have a more
// efficient way when updating the Mesh each frame
private final long createFromTriMesh(Mesh triMesh) {
IntBuffer indexBuffer = BufferUtils.createIntBuffer(triMesh.getTriangleCount() * 3);
FloatBuffer positionBuffer = triMesh.getFloatBuffer(Type.Position);
IndexBuffer indices = triMesh.getIndicesAsList();
int indicesLength = triMesh.getTriangleCount() * 3;
for (int i = 0; i < indicesLength; i++) { // done because mesh indexs can use short or i am wrong
indexBuffer.put(indices.get(i));
}
//Add
objectId = createFromTriMesh(indexBuffer, positionBuffer, triMesh.getTriangleCount(), false);
postRebuild(false);
return objectId;
}
private native long createFromTriMesh(IntBuffer triangles, FloatBuffer vertices, int numTriangles, boolean randomizeConstraints);
private native long ctr_PhysicsSoftBody();
private native long ctr_PhysicsSoftBody(int size, Vector3f[] vertices, float[] mass);
protected void rebuildFromTriMesh(Mesh mesh) {
// {mesh != null} => {old Native object is removed & destroyed; new Native object is created & added}
boolean wasInWorld = isInWorld();
preRebuild();
objectId = createFromTriMesh(mesh);
postRebuild(wasInWorld);
}
protected final void preRebuild() {
// {} = > {remove the body from the physics space and detroy the native object}
/* if (collisionShape instanceof MeshCollisionShape && mass != 0) {
throw new IllegalStateException("Dynamic rigidbody can not have mesh collision shape!");
}*/
if (objectId != 0) {
if (isInWorld()) {
PhysicsSoftSpace.getPhysicsSoftSpace().remove(this);
}
Logger.getLogger(this.getClass().getName()).log(Level.FINE, "Clearing RigidBody {0}", Long.toHexString(objectId));
finalizeNative(objectId);
}
}
protected final void postRebuild(boolean wasInWorld) {
// {} => {initUserPoint on the native object, if this wasInWorld add this into the physicsSpace}
initUserPointer();
if (wasInWorld) {
PhysicsSoftSpace.getPhysicsSoftSpace().add(this);
}
}
private void initDefault() {
initDefault(objectId);
}
private native void initDefault(long objectId);
public void setSoftBodyWorldInfo(SoftBodyWorldInfo worldinfo) {
setSoftBodyWorldInfo(objectId, worldinfo.getWorldInfoId());
}
private native void setSoftBodyWorldInfo(long objectId, long worldinfoId);
public SoftBodyWorldInfo getSoftBodyWorldInfo() {
long worldInfoId = getSoftBodyWorldInfo(objectId);
SoftBodyWorldInfo worldInfo = new SoftBodyWorldInfo(worldInfoId); // <-point on the same native object
return worldInfo;
}
private native long getSoftBodyWorldInfo(long objectId);
/* API */
// public PhysicsSoftBody(SoftBodyWorldInfo worldInfo, int node_count, Vector3f x[], btScalar* m);
// btSoftBody( btSoftBodyWorldInfo* worldInfo); done
// void initDefaults(); done
// btSoftBodyWorldInfo* getWorldInfo(); done
/* public boolean checkLink(int node0, int node1) {
}
public boolean checkLink(SoftBodyNode node0, SoftBodyNode node1) {
}
public boolean checkFace(int node0, int node1, int node2) {
}
public boolean checkFace(SoftBodyNode node0, SoftBodyNode node1, SoftBodyNode node2) { //<--- do not existe in bullet
}
*/
/* public void appendMaterial(Material material) {
appendMaterial(objectId, material);
}
private native void appendMaterial(long objectId, Material material);*/
/* Append anchor */
/* public void appendAnchor(int node, PhysicsRigidBody rigidBody, boolean collisionBetweenLinkedBodies, float influence) {
}
public void appendAnchor(int node, PhysicsRigidBody rigidBody, Vector3f localPivot, boolean collisionBetweenLinkedBodies, float influence) {
}*/
/* Append linear joint */
/*public void appendLinearJoint(const LJoint::Specs& specs,Cluster* body0,Body body1){
}
public void appendLinearJoint(const LJoint::Specs& specs,Body body=Body()) {
}
public void appendLinearJoint(const LJoint::Specs& specs,btSoftBody* body) {
}
*/
/* Append linear joint */
// public void appendAngularJoint(const AJoint::Specs& specs,Cluster* body0,Body body1);
// public void appendAngularJoint(const AJoint::Specs& specs,Body body=Body());
// public void appendAngularJoint(const AJoint::Specs& specs,btSoftBody* body);
/* Add force (or gravity) to the entire body */
public void addForce(Vector3f force) {
addForce(objectId, force);
}
private native void addForce(long objectId, Vector3f force);
/* Add force (or gravity) to a node of the body */
public void addForce(Vector3f force, int node) {
addForce(objectId, force, node);
}
private native void addForce(long objectId, Vector3f force, int node);
/* Add aero force to a node of the body */
public void addAeroForceToNode(Vector3f windVelocity, int nodeIndex) {
addAeroForceToNode(objectId, windVelocity, nodeIndex);
}
private native void addAeroForceToNode(long objectId, Vector3f windVelocity, int nodeIndex);
/* Add aero force to a face of the body */
public void addAeroForceToFace(Vector3f windVelocity, int faceIndex) {
addAeroForceToFace(objectId, windVelocity, faceIndex);
}
private native void addAeroForceToFace(long objectId, Vector3f windVelocity, int faceIndex);
/* Add velocity to the entire body */
public void addVelocity(Vector3f velocity) {
}
/* Set velocity for the entire body */
public void setVelocity(Vector3f velocity) {
}
/* Add velocity to a node of the body */
public void addVelocity(Vector3f velocity, int node) {
}
/* Set mass */
public void setMass(int node, float mass) {
setMass(objectId, node, mass);
}
private native void setMass(long objectId, int node, float mass);
/* Get mass */
public float getMass(int node) {
return getMass(objectId, node);
}
private native float getMass(long objectId, int node);
/* Get total mass */
public float getTotalMass() {
return getTotalMass(objectId);
}
private native float getTotalMass(long objectId);
/* Set total mass (weighted by previous masses) */
public void setTotalMass(float mass, boolean fromfaces) {
setTotalMass(objectId, mass, fromfaces);
}
public void setTotalMass(float mass) {
setTotalMass(mass, false);
}
private native void setTotalMass(long objectId, float mass, boolean fromFaces);
/* Set total density */
public void setTotalDensity(float density) {
setTotalDensity(objectId, density);
}
private native void setTotalDensity(long objectId, float density);
/* Set volume mass (using tetrahedrons) */
public void setVolumeMass(float mass) {
setVolumeMass(objectId, mass);
}
private native void setVolumeMass(long objectId, float mass);
/* Set volume density (using tetrahedrons) */
public void setVolumeDensity(float density) {
setVolumeDensity(objectId, density);
}
private native void setVolumeDensity(long objectId, float density);
/* Transform */
public void setPhysicsTransform(Transform trs) {
setPhysicsTransform(objectId, trs);
}
private native void setPhysicsTransform(long objectId, Transform trs);
public Transform getPhysicsTransform() {
Transform trs = new Transform();
getPhysicsTransform(objectId, trs);
return trs;
}
private native void getPhysicsTransform(long objectId, Transform trs);
/* Translate */
public void setPhysicsLocation(Vector3f vec) {
setPhysicsLocation(objectId, vec);
}
private native void setPhysicsLocation(long objectId, Vector3f vec);
public Vector3f getPhysicsLocation(Vector3f store) {
if (store == null) {
store = new Vector3f();
}
getPhysicsLocation(objectId, store);
return store;
}
public Vector3f getPhysicsLocation() {
return getPhysicsLocation(null);
}
private native void getPhysicsLocation(long objectId, Vector3f vec);
/* Rotate */
public void setPhysicsRotation(Quaternion rot) {
setPhysicsRotation(objectId, rot);
}
private native void setPhysicsRotation(long objectId, Quaternion rot);
public Quaternion getPhysicsRotation(Quaternion store) {
if (store == null) {
store = new Quaternion();
}
getPhysicsRotation(objectId, store);
return store;
}
public Quaternion getPhysicsRotation() {
return getPhysicsRotation(null);
}
private native void getPhysicsRotation(long objectId, Quaternion rot);
/* Scale */
public void setPhysicsScale(Vector3f scl) {
setPhysicsScale(objectId, scl);
}
private native void setPhysicsScale(long objectId, Vector3f scl);
public Vector3f getPhysicsScale() {
Vector3f scl = new Vector3f();
getPhysicsScale(objectId, scl);
return scl;
}
private native void getPhysicsScale(long objectId, Vector3f scl);
public float getRestLengthScale() {
return getRestLenghtScale(objectId);
}
/* Get link resting lengths scale */
private native float getRestLenghtScale(long objectId);
/* Scale resting length of all springs */
public void setRestLengthScale(float scale) {
setRestLenghtScale(objectId, scale);
}
private native void setRestLenghtScale(long objectId, float scale);
/* Set current state as pose */
public void setPose(boolean bvolume, boolean bframe) {
setPose(objectId, bvolume, bframe);
}
private native void setPose(long objectId, boolean bvolume, boolean bframe);
/* Set current link lengths as resting lengths */
public void resetLinkRestLengths() {
resetLinkRestLengths(objectId);
}
private native void resetLinkRestLengths(long objectId);
/* Return the volume */
public float getVolume() {
return getVolume(objectId);
}
private native float getVolume(long objectId);
/* Cluster count */
public int getClusterCount() {
return getClusterCount(objectId);
}
private native int getClusterCount(long objectId);
/* Cluster center of mass */
/*public static Vector3f clusterCom(const Cluster* cluster); */
public Vector3f getClusterCenterOfMass(int clusterId) {
Vector3f vec = new Vector3f();
getClusterCenterOfMass(objectId, clusterId, vec);
return vec;
}
private native void getClusterCenterOfMass(long objectId, int clusterId, Vector3f vec);
/* Cluster velocity at rpos */
/*public static Vector3f clusterVelocity(const Cluster* cluster,const btVector3& rpos);*/
/* Cluster impulse */
/*static void clusterVImpulse(Cluster* cluster,const btVector3& rpos,const btVector3& impulse);
static void clusterDImpulse(Cluster* cluster,const btVector3& rpos,const btVector3& impulse);
static void clusterImpulse(Cluster* cluster,const btVector3& rpos,const Impulse& impulse);
static void clusterVAImpulse(Cluster* cluster,const btVector3& impulse);
static void clusterDAImpulse(Cluster* cluster,const btVector3& impulse);
static void clusterAImpulse(Cluster* cluster,const Impulse& impulse);
static void clusterDCImpulse(Cluster* cluster,const btVector3& impulse);*/
/* Generate bending constraints based on distance in the adjency graph */
/*public int generateBendingConstraints( int distance, Material* mat=0){
}*/
/* Randomize constraints to reduce solver bias */
public void randomizeConstraints() {
randomizeConstraints(objectId);
}
private native void randomizeConstraints(long objectId);
/* Release clusters */
public void releaseCluster(int index) {
releaseCluster(objectId, index);
}
private native void releaseCluster(long objectId, int index);
public void releaseClusters() {
releaseClusters(objectId);
}
private native void releaseClusters(long objectId);
/* Generate clusters (K-mean) */
///generateClusters with k=0 will create a convex cluster for each tetrahedron or triangle
///otherwise an approximation will be used (better performance)
public int generateClusters(int k) {
return generateClusters(k, 8192);
}
public int generateClusters(int k, int maxiterations) {
return generateClusters(objectId, k, maxiterations);
}
private native int generateClusters(long objectId, int k, int maxiterations);
/* Refine */
/*public void refine(ImplicitFn* ifn,float accurary,boolean cut);*/
/* CutLink */
public boolean cutLink(int node0, int node1, float position) {
return false;
}
/*public boolean cutLink(Node* node0, Node* node1, float position){
}*/
///Ray casting using rayFrom and rayTo in worldspace, (not direction!)
/*public boolean rayTest(Vector3f rayFrom, Vector3f rayTo, sRayCast& results);*/
/* Solver presets */
/*public void setSolver(eSolverPresets::_ preset);*/
/* predictMotion */
public void predictMotion(float dt) {
predictMotion(objectId, dt);
}
private native void predictMotion(long objectId, float dt);
/* solveConstraints */
public void solveConstraints() {
solveConstraints(objectId);
}
private native void solveConstraints(long objectId);
/* staticSolve */
public void staticSolve(int iterations) {
staticSolve(objectId, iterations);
}
private native void staticSolve(long objectId, int iterations);
/* solveCommonConstraints */
/*public static void solveCommonConstraints(btSoftBody** bodies,int count,int iterations){
}*/
/* solveClusters */
/*public static void solveClusters(const btAlignedObjectArray<btSoftBody*>& bodies){
}*/
/* integrateMotion */
public void integrateMotion() {
integrateMotion(objectId);
}
private native void integrateMotion(long objectId);
/* defaultCollisionHandlers */
/*public void defaultCollisionHandler(const btCollisionObjectWrapper* pcoWrap){
}*/
public void defaultCollisionHandler(PhysicsSoftBody psb) {
defaultCollisionHandler(psb.objectId);
}
private native void defaultCollisionHandler(long objectId);
public boolean isInWorld() {
return isInWorld(objectId);
}
private native boolean isInWorld(long objectId);
/*====================*
Config access
*====================*/
//struct Config
// eAeroModel::_ aeromodel; // Aerodynamic model (default: V_Point)
// btScalar kVCF; // Velocities correction factor (Baumgarte)
public void setVelocitiesCorrectionFactor(float factor) {
setVelocitiesCorrectionFactor(objectId, factor);
}
private native void setVelocitiesCorrectionFactor(long bodyId, float factor);
public float getVelocitiesCorrectionFactor() {
return getVelocitiesCorrectionFactor(objectId);
}
private native float getVelocitiesCorrectionFactor(long bodyId);
// btScalar kDP; // Damping coefficient [0,1]
public void setDampingCoef(float coefficient) {
setDampingCoef(objectId, coefficient);
}
private native void setDampingCoef(long bodyId, float coefficient);
public float getDampingCoef() {
return getDampingCoef(objectId);
}
private native float getDampingCoef(long bodyId);
// btScalar kDG; // Drag coefficient [0,+inf]
public void setDragCoef(float coefficient) {
setDragCoef(objectId, coefficient);
}
private native void setDragCoef(long bodyId, float coefficient);
public float getDragCoef() {
return getDragCoef(objectId);
}
private native float getDragCoef(long bodyId);
// btScalar kLF; // Lift coefficient [0,+inf]
public void setLiftCoef(float coefficient) {
setLiftCoef(objectId, coefficient);
}
private native void setLiftCoef(long bodyId, float coefficient);
public float getLiftCoef() {
return getLiftCoef(objectId);
}
private native float getLiftCoef(long bodyId);
// btScalar kPR; // Pressure coefficient [-inf,+inf]
public void setPressureCoef(float coefficient) {
setPressureCoef(objectId, coefficient);
}
private native void setPressureCoef(long bodyId, float coefficient);
public float getPressureCoef() {
return getPressureCoef(objectId);
}
private native float getPressureCoef(long bodyId);
// btScalar kVC; // Volume conversation coefficient [0,+inf]
public void setVolumeConservationCoef(float coefficient) {
setVolumeConservationCoef(objectId, coefficient);
}
private native void setVolumeConservationCoef(long bodyId, float coefficient);
public float getVolumeConservationCoef() {
return getVolumeConservationCoef(objectId);
}
private native float getVolumeConservationCoef(long bodyId);
// -> btScalar kDF; // Dynamic friction coefficient [0,1]
/**
* set the Bullet kDF (aka Dynamic friction coefficient [0,1])
*
* @param coefficient
*/
public void setDynamicFrictionCoef(float coefficient) {
setDynamicFrictionCoef(objectId, coefficient);
}
private native void setDynamicFrictionCoef(long objectId, float coefficient);
public float getDynamicFrictionCoef() {
return getDynamicFrictionCoef(objectId);
}
private native float getDynamicFrictionCoef(long objectId);
// -> btScalar kMT; // Pose matching coefficient [0,1]
public void setPoseMatchingCoef(float coefficient) {
setPoseMatchingCoef(objectId, coefficient);
}
private native void setPoseMatchingCoef(long objectId, float coefficient);
public float getPoseMatchingCoef() {
return getPoseMatchingCoef(objectId);
}
private native float getPoseMatchingCoef(long bodyId);
// btScalar kCHR; // Rigid contacts hardness [0,1]
public void setRigidContactsHardness(float hardness) {
setRigidContactsHardness(objectId, hardness);
}
private native void setRigidContactsHardness(long bodyId, float hardness);
public float getRigidContactsHardness() {
return getRigidContactsHardness(objectId);
}
private native float getRigidContactsHardness(long bodyId);
// btScalar kKHR; // Kinetic contacts hardness [0,1]
public void setKineticContactsHardness(float hardness) {
setKineticContactsHardness(objectId, hardness);
}
private native void setKineticContactsHardness(long bodyId, float hardness);
public float getKineticContactsHardness() {
return getKineticContactsHardness(objectId);
}
private native float getKineticContactsHardness(long bodyId);
// btScalar kSHR; // Soft contacts hardness [0,1]
public void setSoftContactsHardness(float hardness) {
setSoftContactsHardness(objectId, hardness);
}
private native void setSoftContactsHardness(long bodyId, float hardness);
public float getSoftContactsHardness() {
return getSoftContactsHardness(objectId);
}
private native float getSoftContactsHardness(long bodyId);
// btScalar kAHR; // Anchors hardness [0,1]
public void setAnchorsHardness(float hardness) {
setAnchorsHardness(objectId, hardness);
}
private native void setAnchorsHardness(long bodyId, float hardness);
public float getAnchorsHardness() {
return getAnchorsHardness(objectId);
}
private native float getAnchorsHardness(long bodyId);
// btScalar kSRHR_CL; // Soft vs rigid hardness [0,1] (cluster only)
// btScalar kSKHR_CL; // Soft vs kinetic hardness [0,1] (cluster only)
// btScalar kSSHR_CL; // Soft vs soft hardness [0,1] (cluster only)
// btScalar kSR_SPLT_CL; // Soft vs rigid impulse split [0,1] (cluster only)
// btScalar kSK_SPLT_CL; // Soft vs rigid impulse split [0,1] (cluster only)
// btScalar kSS_SPLT_CL; // Soft vs rigid impulse split [0,1] (cluster only)
// btScalar maxvolume; // Maximum volume ratio for pose
public void setMaximumVolumeRatio(float ratio) {
setMaximumVolumeRatio(objectId, ratio);
}
private native void setMaximumVolumeRatio(long bodyId, float ratio);
public float getMaximumVolumeRatio() {
return getMaximumVolumeRatio(objectId);
}
private native float getMaximumVolumeRatio(long bodyId);
// btScalar timescale; // Time scale
public void setTimeScale(float scale) {
setTimeScale(objectId, scale);
}
private native void setTimeScale(long bodyId, float scale);
public float getTimeScale() {
return getTimeScale(objectId);
}
private native float getTimeScale(long bodyId);
// int viterations; // Velocities solver iterations
public void setVelocitiesIterations(int iterations) {
setVelocitiesIterations(objectId, iterations);
}
private native void setVelocitiesIterations(long objectId, int iteration);
public int getVelocitiesIterations() {
return getVelocitiesIterations(objectId);
}
private native int getVelocitiesIterations(long objectId);
// -> int piterations; // Positions solver iterations
public void setPositionIterations(int iterations) {
setPositionIterations(objectId, iterations);
}
private native void setPositionIterations(long objectId, int iteration);
public int getPositionIterations() {
return getPositionIterations(objectId);
}
private native int getPositionIterations(long objectId);
// int diterations; // Drift solver iterations
public void setDriftIterations(int iterations) {
setDriftIterations(objectId, iterations);
}
private native void setDriftIterations(long objectId, int iteration);
public int getDriftIterations() {
return getDriftIterations(objectId);
}
private native int getDriftIterations(long objectId);
// int citerations; // Cluster solver iterations
/* public void setClusterIterations(int iterations) {
setClusterIterations(objectId, iterations);
}
private native void setClusterIterations(long objectId, int iteration);
public int getClusterIterations() {
return getClusterIterations(objectId);
}
private native int getClusterIterations(long objectId);*/
// int collisions; // Collisions flags
// tVSolverArray m_vsequence; // Velocity solvers sequence
// tPSolverArray m_psequence; // Position solvers sequence
// tPSolverArray m_dsequence; // Drift solvers sequence
/*====================*
SoftBody to Mesh - UTILS
*====================*/
/*
Since bullet SoftBody don't use btCollisionShape, its not possible to use the DebugShapeFactory.
The following code is almost the same , but specially for SoftBody.
Theses methods are static (same as in DebugShapeFactory) so the code can be easily moved somewhere else.
*/
public static Geometry createDebugShape(PhysicsSoftBody softBody) {
if (softBody == null) {
return null;
}
Geometry debugShape = new Geometry();
debugShape.setMesh(getDebugMesh(softBody));
debugShape.updateModelBound();
debugShape.updateGeometricState();
return debugShape;
}
public static Mesh getDebugMesh(PhysicsSoftBody softBody) {
Mesh mesh = new Mesh();
mesh.setBuffer(Type.Position, 3, getVertices(softBody));
mesh.setBuffer(Type.Index, 3, getIndexes(softBody));
mesh.getFloatBuffer(Type.Position).clear();
return mesh;
}
private static FloatBuffer getVertices(PhysicsSoftBody softBody) {
DebugMeshCallback callback = new DebugMeshCallback();
getVertices(softBody.getObjectId(), callback);
return callback.getVertices();
}
private static native void getVertices(long bodyId, DebugMeshCallback buffer);
private static IntBuffer getIndexes(PhysicsSoftBody softBody) {
IntBuffer indexes = BufferUtils.createIntBuffer(getNumTriangle(softBody.getObjectId()) * 3);
getIndexes(softBody.getObjectId(), indexes);
return indexes;
}
private static native void getIndexes(long bodyId, IntBuffer buffer);
private static native int getNumTriangle(long bodyId);
public static void updateMesh(PhysicsSoftBody softBody, Mesh store, boolean updateNormals) {
FloatBuffer positionBuffer = store.getFloatBuffer(Type.Position);
FloatBuffer normalBuffer = store.getFloatBuffer(Type.Normal);
updateMesh(softBody.getObjectId(), positionBuffer, store.getVertexCount(), updateNormals, normalBuffer);
store.getBuffer(Type.Position).setUpdateNeeded();
}
private static native void updateMesh(long bodyId, FloatBuffer vertices, int numVertices, boolean updateNormals, FloatBuffer normals);
/*============*
* data Struct
*============*/
class Material {
private long materialId;
public Material(float linearStiffnessFactor, float angularStiffnessFactor, float volumeStiffnessFactor, int flags) {
this();
setLinearStiffnessFactor(materialId, linearStiffnessFactor);
setAngularStiffnessFactor(materialId, angularStiffnessFactor);
setVolumeStiffnessFactor(materialId, volumeStiffnessFactor);
}
private Material() {
this.materialId = createMaterial();
}
protected Material(long nativeId) {
this.materialId = nativeId;
}
@Override
public boolean equals(Object obj) {
if (obj.getClass() == Material.class) {
return this.materialId == ((Material) obj).materialId;
} else {
return false;
}
}
private native long createMaterial();
/**
* @return the linearStiffnessFactor
*/
public float getLinearStiffnessFactor() {
return getLinearStiffnessFactor(materialId);
}
private native float getLinearStiffnessFactor(long materialId);
/**
* @param linearStiffnessFactor the linearStiffnessFactor to set
*/
public void setLinearStiffnessFactor(float linearStiffnessFactor) {
setLinearStiffnessFactor(materialId, linearStiffnessFactor);
}
private native void setLinearStiffnessFactor(long materialId, float linearStiffnessFactor);
/**
* @return the angularStiffnessFactor
*/
public float getAngularStiffnessFactor() {
return getAngularStiffnessFactor(materialId);
}
private native float getAngularStiffnessFactor(long materialId);
/**
* @param angularStiffnessFactor the angularStiffnessFactor to set
*/
public void setAngularStiffnessFactor(float angularStiffnessFactor) {
setAngularStiffnessFactor(materialId, angularStiffnessFactor);
}
private native void setAngularStiffnessFactor(long materialId, float angularStiffnessFactor);
/**
* @return the volumeStiffnessFactor
*/
public float getVolumeStiffnessFactor() {
return getVolumeStiffnessFactor(materialId);
}
private native float getVolumeStiffnessFactor(long materialId);
/**
* @param volumeStiffnessFactor the volumeStiffnessFactor to set
*/
public void setVolumeStiffnessFactor(float volumeStiffnessFactor) {
setVolumeStiffnessFactor(materialId, volumeStiffnessFactor);
}
private native void setVolumeStiffnessFactor(long materialId, float volumeStiffnessFactor);
/**
* @return the flags
*/
public int getFlags() {
return getFlags(materialId);
}
private native int getFlags(long materialId);
/**
* @param flags the flags to set
*/
public void setFlags(int flags) {
setFlags(materialId, flags);
}
private native void setFlags(long materialId, int flags);
}
}
| jme3-bullet/src/main/java/com/jme3/bullet/objects/PhysicsSoftBody.java | /*
* Copyright (c) 2009-2015 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.bullet.objects;
import com.jme3.bullet.PhysicsSoftSpace;
import com.jme3.bullet.collision.PhysicsCollisionObject;
import com.jme3.bullet.objects.infos.SoftBodyWorldInfo;
import com.jme3.bullet.util.DebugMeshCallback;
import com.jme3.bullet.util.NativeMeshUtil;
import com.jme3.math.Quaternion;
import com.jme3.math.Transform;
import com.jme3.math.Vector3f;
import com.jme3.scene.Geometry;
import com.jme3.scene.Mesh;
import com.jme3.scene.Spatial;
import com.jme3.scene.VertexBuffer;
import com.jme3.scene.VertexBuffer.Type;
import com.jme3.scene.mesh.IndexBuffer;
import com.jme3.util.BufferUtils;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author dokthar
*/
public class PhysicsSoftBody extends PhysicsCollisionObject {
@Deprecated
public PhysicsSoftBody(Vector3f[] vertices, float[] masses) {
objectId = ctr_PhysicsSoftBody(vertices.length, vertices, masses);
postRebuild(false);
}
public PhysicsSoftBody() {
objectId = ctr_PhysicsSoftBody();
initDefault();
postRebuild(false);
}
public PhysicsSoftBody(Mesh triMesh) {
// must check if the mesh have %3 vertices
createFromTriMesh(triMesh);
}
// SoftBodies need to have a direct access to JME's Mesh buffer in order a have a more
// efficient way when updating the Mesh each frame
private final long createFromTriMesh(Mesh triMesh) {
IntBuffer indexBuffer = BufferUtils.createIntBuffer(triMesh.getTriangleCount() * 3);
FloatBuffer positionBuffer = triMesh.getFloatBuffer(Type.Position);
IndexBuffer indices = triMesh.getIndicesAsList();
int indicesLength = triMesh.getTriangleCount() * 3;
for (int i = 0; i < indicesLength; i++) { // done because mesh indexs can use short or i am wrong
indexBuffer.put(indices.get(i));
}
//Add
objectId = createFromTriMesh(indexBuffer, positionBuffer, triMesh.getTriangleCount(), false);
postRebuild(false);
return objectId;
}
private native long createFromTriMesh(IntBuffer triangles, FloatBuffer vertices, int numTriangles, boolean randomizeConstraints);
private native long ctr_PhysicsSoftBody();
private native long ctr_PhysicsSoftBody(int size, Vector3f[] vertices, float[] mass);
protected void rebuildFromTriMesh(Mesh mesh) {
// {mesh != null} => {old Native object is removed & destroyed; new Native object is created & added}
boolean wasInWorld = isInWorld();
preRebuild();
objectId = createFromTriMesh(mesh);
postRebuild(wasInWorld);
}
protected final void preRebuild() {
// {} = > {remove the body from the physics space and detroy the native object}
/* if (collisionShape instanceof MeshCollisionShape && mass != 0) {
throw new IllegalStateException("Dynamic rigidbody can not have mesh collision shape!");
}*/
if (objectId != 0) {
if (isInWorld()) {
PhysicsSoftSpace.getPhysicsSoftSpace().remove(this);
}
Logger.getLogger(this.getClass().getName()).log(Level.FINE, "Clearing RigidBody {0}", Long.toHexString(objectId));
finalizeNative(objectId);
}
}
protected final void postRebuild(boolean wasInWorld) {
// {} => {initUserPoint on the native object, if this wasInWorld add this into the physicsSpace}
initUserPointer();
if (wasInWorld) {
PhysicsSoftSpace.getPhysicsSoftSpace().add(this);
}
}
private void initDefault() {
initDefault(objectId);
}
private native void initDefault(long objectId);
public void setSoftBodyWorldInfo(SoftBodyWorldInfo worldinfo) {
setSoftBodyWorldInfo(objectId, worldinfo.getWorldInfoId());
}
private native void setSoftBodyWorldInfo(long objectId, long worldinfoId);
public SoftBodyWorldInfo getSoftBodyWorldInfo() {
long worldInfoId = getSoftBodyWorldInfo(objectId);
SoftBodyWorldInfo worldInfo = new SoftBodyWorldInfo(worldInfoId); // <-point on the same native object
return worldInfo;
}
private native long getSoftBodyWorldInfo(long objectId);
/* API */
// public PhysicsSoftBody(SoftBodyWorldInfo worldInfo, int node_count, Vector3f x[], btScalar* m);
// btSoftBody( btSoftBodyWorldInfo* worldInfo); done
// void initDefaults(); done
// btSoftBodyWorldInfo* getWorldInfo(); done
/* public boolean checkLink(int node0, int node1) {
}
public boolean checkLink(SoftBodyNode node0, SoftBodyNode node1) {
}
public boolean checkFace(int node0, int node1, int node2) {
}
public boolean checkFace(SoftBodyNode node0, SoftBodyNode node1, SoftBodyNode node2) { //<--- do not existe in bullet
}
*/
/* public void appendMaterial(SoftBodyMaterial material) {
appendMaterial(objectId, material);
}
private native void appendMaterial(long objectId, SoftBodyMaterial material);*/
/* Append anchor */
/* public void appendAnchor(int node, PhysicsRigidBody rigidBody, boolean collisionBetweenLinkedBodies, float influence) {
}
public void appendAnchor(int node, PhysicsRigidBody rigidBody, Vector3f localPivot, boolean collisionBetweenLinkedBodies, float influence) {
}*/
/* Append linear joint */
/*public void appendLinearJoint(const LJoint::Specs& specs,Cluster* body0,Body body1){
}
public void appendLinearJoint(const LJoint::Specs& specs,Body body=Body()) {
}
public void appendLinearJoint(const LJoint::Specs& specs,btSoftBody* body) {
}
*/
/* Append linear joint */
// public void appendAngularJoint(const AJoint::Specs& specs,Cluster* body0,Body body1);
// public void appendAngularJoint(const AJoint::Specs& specs,Body body=Body());
// public void appendAngularJoint(const AJoint::Specs& specs,btSoftBody* body);
/* Add force (or gravity) to the entire body */
public void addForce(Vector3f force) {
addForce(objectId, force);
}
private native void addForce(long objectId, Vector3f force);
/* Add force (or gravity) to a node of the body */
public void addForce(Vector3f force, int node) {
addForce(objectId, force, node);
}
private native void addForce(long objectId, Vector3f force, int node);
/* Add aero force to a node of the body */
public void addAeroForceToNode(Vector3f windVelocity, int nodeIndex) {
addAeroForceToNode(objectId, windVelocity, nodeIndex);
}
private native void addAeroForceToNode(long objectId, Vector3f windVelocity, int nodeIndex);
/* Add aero force to a face of the body */
public void addAeroForceToFace(Vector3f windVelocity, int faceIndex) {
addAeroForceToFace(objectId, windVelocity, faceIndex);
}
private native void addAeroForceToFace(long objectId, Vector3f windVelocity, int faceIndex);
/* Add velocity to the entire body */
public void addVelocity(Vector3f velocity) {
}
/* Set velocity for the entire body */
public void setVelocity(Vector3f velocity) {
}
/* Add velocity to a node of the body */
public void addVelocity(Vector3f velocity, int node) {
}
/* Set mass */
public void setMass(int node, float mass){
setMass(objectId, node, mass);
}
private native void setMass(long objectId, int node, float mass);
/* Get mass */
public float getMass(int node){
return getMass(objectId, node);
}
private native float getMass(long objectId, int node);
/* Get total mass */
public float getTotalMass(){
return getTotalMass(objectId);
}
private native float getTotalMass(long objectId);
/* Set total mass (weighted by previous masses) */
public void setTotalMass(float mass, boolean fromfaces){
setTotalMass(objectId, mass, fromfaces);
}
public void setTotalMass(float mass){
setTotalMass(mass, false);
}
private native void setTotalMass(long objectId, float mass, boolean fromFaces);
/* Set total density */
public void setTotalDensity(float density){
setTotalDensity(objectId, density);
}
private native void setTotalDensity(long objectId, float density);
/* Set volume mass (using tetrahedrons) */
public void setVolumeMass(float mass){
setVolumeMass(objectId, mass);
}
private native void setVolumeMass(long objectId, float mass);
/* Set volume density (using tetrahedrons) */
public void setVolumeDensity(float density){
setVolumeDensity(objectId, density);
}
private native void setVolumeDensity(long objectId, float density);
/* Transform */
public void setPhysicsTransform(Transform trs) {
setPhysicsTransform(objectId, trs);
}
private native void setPhysicsTransform(long objectId, Transform trs);
public Transform getPhysicsTransform() {
Transform trs = new Transform();
getPhysicsTransform(objectId, trs);
return trs;
}
private native void getPhysicsTransform(long objectId, Transform trs);
/* Translate */
public void setPhysicsLocation(Vector3f vec) {
setPhysicsLocation(objectId, vec);
}
private native void setPhysicsLocation(long objectId, Vector3f vec);
public Vector3f getPhysicsLocation(Vector3f store) {
if (store == null) {
store = new Vector3f();
}
getPhysicsLocation(objectId, store);
return store;
}
public Vector3f getPhysicsLocation() {
return getPhysicsLocation(null);
}
private native void getPhysicsLocation(long objectId, Vector3f vec);
/* Rotate */
public void setPhysicsRotation(Quaternion rot) {
setPhysicsRotation(objectId, rot);
}
private native void setPhysicsRotation(long objectId, Quaternion rot);
public Quaternion getPhysicsRotation(Quaternion store) {
if (store == null) {
store = new Quaternion();
}
getPhysicsRotation(objectId, store);
return store;
}
public Quaternion getPhysicsRotation() {
return getPhysicsRotation(null);
}
private native void getPhysicsRotation(long objectId, Quaternion rot);
/* Scale */
public void setPhysicsScale(Vector3f scl) {
setPhysicsScale(objectId, scl);
}
private native void setPhysicsScale(long objectId, Vector3f scl);
public Vector3f getPhysicsScale() {
Vector3f scl = new Vector3f();
getPhysicsScale(objectId, scl);
return scl;
}
private native void getPhysicsScale(long objectId, Vector3f scl);
public float getRestLengthScale() {
return getRestLenghtScale(objectId);
}
/* Get link resting lengths scale */
private native float getRestLenghtScale(long objectId);
/* Scale resting length of all springs */
public void setRestLengthScale(float scale) {
setRestLenghtScale(objectId, scale);
}
private native void setRestLenghtScale(long objectId, float scale);
/* Set current state as pose */
public void setPose(boolean bvolume, boolean bframe) {
setPose(objectId, bvolume, bframe);
}
private native void setPose(long objectId, boolean bvolume, boolean bframe);
/* Set current link lengths as resting lengths */
public void resetLinkRestLengths() {
resetLinkRestLengths(objectId);
}
private native void resetLinkRestLengths(long objectId);
/* Return the volume */
public float getVolume() {
return getVolume(objectId);
}
private native float getVolume(long objectId);
/* Cluster count */
public int getClusterCount() {
return getClusterCount(objectId);
}
private native int getClusterCount(long objectId);
/* Cluster center of mass */
/*public static Vector3f clusterCom(const Cluster* cluster); */
public Vector3f getClusterCenterOfMass(int clusterId) {
Vector3f vec = new Vector3f();
getClusterCenterOfMass(objectId, clusterId, vec);
return vec;
}
private native void getClusterCenterOfMass(long objectId, int clusterId, Vector3f vec);
/* Cluster velocity at rpos */
/*public static Vector3f clusterVelocity(const Cluster* cluster,const btVector3& rpos);*/
/* Cluster impulse */
/*static void clusterVImpulse(Cluster* cluster,const btVector3& rpos,const btVector3& impulse);
static void clusterDImpulse(Cluster* cluster,const btVector3& rpos,const btVector3& impulse);
static void clusterImpulse(Cluster* cluster,const btVector3& rpos,const Impulse& impulse);
static void clusterVAImpulse(Cluster* cluster,const btVector3& impulse);
static void clusterDAImpulse(Cluster* cluster,const btVector3& impulse);
static void clusterAImpulse(Cluster* cluster,const Impulse& impulse);
static void clusterDCImpulse(Cluster* cluster,const btVector3& impulse);*/
/* Generate bending constraints based on distance in the adjency graph */
/*public int generateBendingConstraints( int distance, Material* mat=0){
}*/
/* Randomize constraints to reduce solver bias */
public void randomizeConstraints() {
randomizeConstraints(objectId);
}
private native void randomizeConstraints(long objectId);
/* Release clusters */
public void releaseCluster(int index) {
releaseCluster(objectId, index);
}
private native void releaseCluster(long objectId, int index);
public void releaseClusters() {
releaseClusters(objectId);
}
private native void releaseClusters(long objectId);
/* Generate clusters (K-mean) */
///generateClusters with k=0 will create a convex cluster for each tetrahedron or triangle
///otherwise an approximation will be used (better performance)
public int generateClusters(int k) {
return generateClusters(k, 8192);
}
public int generateClusters(int k, int maxiterations) {
return generateClusters(objectId, k, maxiterations);
}
private native int generateClusters(long objectId, int k, int maxiterations);
/* Refine */
/*public void refine(ImplicitFn* ifn,float accurary,boolean cut);*/
/* CutLink */
public boolean cutLink(int node0, int node1, float position) {
return false;
}
/*public boolean cutLink(Node* node0, Node* node1, float position){
}*/
///Ray casting using rayFrom and rayTo in worldspace, (not direction!)
/*public boolean rayTest(Vector3f rayFrom, Vector3f rayTo, sRayCast& results);*/
/* Solver presets */
/*public void setSolver(eSolverPresets::_ preset);*/
/* predictMotion */
public void predictMotion(float dt) {
predictMotion(objectId, dt);
}
private native void predictMotion(long objectId, float dt);
/* solveConstraints */
public void solveConstraints() {
solveConstraints(objectId);
}
private native void solveConstraints(long objectId);
/* staticSolve */
public void staticSolve(int iterations) {
staticSolve(objectId, iterations);
}
private native void staticSolve(long objectId, int iterations);
/* solveCommonConstraints */
/*public static void solveCommonConstraints(btSoftBody** bodies,int count,int iterations){
}*/
/* solveClusters */
/*public static void solveClusters(const btAlignedObjectArray<btSoftBody*>& bodies){
}*/
/* integrateMotion */
public void integrateMotion() {
integrateMotion(objectId);
}
private native void integrateMotion(long objectId);
/* defaultCollisionHandlers */
/*public void defaultCollisionHandler(const btCollisionObjectWrapper* pcoWrap){
}*/
public void defaultCollisionHandler(PhysicsSoftBody psb) {
defaultCollisionHandler(psb.objectId);
}
private native void defaultCollisionHandler(long objectId);
public boolean isInWorld() {
return isInWorld(objectId);
}
private native boolean isInWorld(long objectId);
/*====================*
Config access
*====================*/
/*struct Config
{
eAeroModel::_ aeromodel; // Aerodynamic model (default: V_Point)
btScalar kVCF; // Velocities correction factor (Baumgarte)
btScalar kDP; // Damping coefficient [0,1]
btScalar kDG; // Drag coefficient [0,+inf]
btScalar kLF; // Lift coefficient [0,+inf]
btScalar kPR; // Pressure coefficient [-inf,+inf]
btScalar kVC; // Volume conversation coefficient [0,+inf]
btScalar kDF; // Dynamic friction coefficient [0,1]
btScalar kMT; // Pose matching coefficient [0,1]
btScalar kCHR; // Rigid contacts hardness [0,1]
btScalar kKHR; // Kinetic contacts hardness [0,1]
btScalar kSHR; // Soft contacts hardness [0,1]
btScalar kAHR; // Anchors hardness [0,1]
btScalar kSRHR_CL; // Soft vs rigid hardness [0,1] (cluster only)
btScalar kSKHR_CL; // Soft vs kinetic hardness [0,1] (cluster only)
btScalar kSSHR_CL; // Soft vs soft hardness [0,1] (cluster only)
btScalar kSR_SPLT_CL; // Soft vs rigid impulse split [0,1] (cluster only)
btScalar kSK_SPLT_CL; // Soft vs rigid impulse split [0,1] (cluster only)
btScalar kSS_SPLT_CL; // Soft vs rigid impulse split [0,1] (cluster only)
btScalar maxvolume; // Maximum volume ratio for pose
btScalar timescale; // Time scale
int viterations; // Velocities solver iterations
int piterations; // Positions solver iterations
int diterations; // Drift solver iterations
int citerations; // Cluster solver iterations
int collisions; // Collisions flags
tVSolverArray m_vsequence; // Velocity solvers sequence
tPSolverArray m_psequence; // Position solvers sequence
tPSolverArray m_dsequence; // Drift solvers sequence
};*/
/*btScalar kDF; // Dynamic friction coefficient [0,1]*/
public void setDynamicFriction(float coefficient){
setDynamicFriction(objectId, coefficient);
}
private native void setDynamicFriction(long objectId, float coefficient);
/*btScalar kMT; // Pose matching coefficient [0,1]*/
public void setPoseMatching(float coefficient){
setPoseMatching(objectId, coefficient);
}
private native void setPoseMatching(long objectId, float coefficient);
/*int piterations; // Positions solver iterations*/
public void setPositionSolver(int iterations){
setPositionSolver(objectId, iterations);
}
private native void setPositionSolver(long objectId, int iteration);
/*====================*
SoftBody to Mesh
*====================*/
/*
Since bullet SoftBody don't use btCollisionShape, its not possible to use the DebugShapeFactory.
The following code is almost the same , but specially for SoftBody.
Theses methods are static (same as in DebugShapeFactory) so the code can be easily moved somewhere else.
*/
public static Geometry createDebugShape(PhysicsSoftBody softBody) {
if (softBody == null) {
return null;
}
Geometry debugShape = new Geometry();
debugShape.setMesh(getDebugMesh(softBody));
debugShape.updateModelBound();
debugShape.updateGeometricState();
return debugShape;
}
public static Mesh getDebugMesh(PhysicsSoftBody softBody) {
Mesh mesh = new Mesh();
mesh.setBuffer(Type.Position, 3, getVertices(softBody));
mesh.setBuffer(Type.Index, 3, getIndexes(softBody));
mesh.getFloatBuffer(Type.Position).clear();
return mesh;
}
private static FloatBuffer getVertices(PhysicsSoftBody softBody) {
DebugMeshCallback callback = new DebugMeshCallback();
getVertices(softBody.getObjectId(), callback);
return callback.getVertices();
}
private static native void getVertices(long bodyId, DebugMeshCallback buffer);
private static IntBuffer getIndexes(PhysicsSoftBody softBody) {
IntBuffer indexes = BufferUtils.createIntBuffer(getNumTriangle(softBody.getObjectId()) * 3);
getIndexes(softBody.getObjectId(), indexes);
return indexes;
}
private static native void getIndexes(long bodyId, IntBuffer buffer);
private static native int getNumTriangle(long bodyId);
public static void updateMesh(PhysicsSoftBody softBody, Mesh store, boolean updateNormals) {
FloatBuffer positionBuffer = store.getFloatBuffer(Type.Position);
FloatBuffer normalBuffer = store.getFloatBuffer(Type.Normal);
updateMesh(softBody.getObjectId(), positionBuffer, store.getVertexCount(), updateNormals, normalBuffer);
store.getBuffer(Type.Position).setUpdateNeeded();
}
private static native void updateMesh(long bodyId, FloatBuffer vertices, int numVertices, boolean updateNormals, FloatBuffer normals);
/*============*
* data Struct
*============*/
class SoftBodyMaterial {
private float linearStiffnessFactor; // Linear stiffness coefficient [0,1]
private float angularStiffnessFactor; // Area/Angular stiffness coefficient [0,1]
private float volumeStiffnessFactor; // Volume stiffness coefficient [0,1]
private int flags; // Flags
public SoftBodyMaterial(float linearStiffnessFactor, float angularStiffnessFactor, float volumeStiffnessFactor, int flags) {
this.linearStiffnessFactor = linearStiffnessFactor;
this.angularStiffnessFactor = angularStiffnessFactor;
this.volumeStiffnessFactor = volumeStiffnessFactor;
this.flags = flags;
}
/**
* @return the linearStiffnessFactor
*/
public float getLinearStiffnessFactor() {
return linearStiffnessFactor;
}
/**
* @param linearStiffnessFactor the linearStiffnessFactor to set
*/
public void setLinearStiffnessFactor(float linearStiffnessFactor) {
this.linearStiffnessFactor = linearStiffnessFactor;
}
/**
* @return the angularStiffnessFactor
*/
public float getAngularStiffnessFactor() {
return angularStiffnessFactor;
}
/**
* @param angularStiffnessFactor the angularStiffnessFactor to set
*/
public void setAngularStiffnessFactor(float angularStiffnessFactor) {
this.angularStiffnessFactor = angularStiffnessFactor;
}
/**
* @return the volumeStiffnessFactor
*/
public float getVolumeStiffnessFactor() {
return volumeStiffnessFactor;
}
/**
* @param volumeStiffnessFactor the volumeStiffnessFactor to set
*/
public void setVolumeStiffnessFactor(float volumeStiffnessFactor) {
this.volumeStiffnessFactor = volumeStiffnessFactor;
}
/**
* @return the flags
*/
public int getFlags() {
return flags;
}
/**
* @param flags the flags to set
*/
public void setFlags(int flags) {
this.flags = flags;
}
}
}
| Bullet SoftBody : work on softBody's config access, jni left to do
| jme3-bullet/src/main/java/com/jme3/bullet/objects/PhysicsSoftBody.java | Bullet SoftBody : work on softBody's config access, jni left to do | <ide><path>me3-bullet/src/main/java/com/jme3/bullet/objects/PhysicsSoftBody.java
<ide>
<ide> }
<ide> */
<del> /* public void appendMaterial(SoftBodyMaterial material) {
<add> /* public void appendMaterial(Material material) {
<ide> appendMaterial(objectId, material);
<ide> }
<ide>
<del> private native void appendMaterial(long objectId, SoftBodyMaterial material);*/
<add> private native void appendMaterial(long objectId, Material material);*/
<ide>
<ide> /* Append anchor */
<ide> /* public void appendAnchor(int node, PhysicsRigidBody rigidBody, boolean collisionBetweenLinkedBodies, float influence) {
<ide> }
<ide>
<ide> /* Set mass */
<del> public void setMass(int node, float mass){
<add> public void setMass(int node, float mass) {
<ide> setMass(objectId, node, mass);
<ide> }
<del>
<add>
<ide> private native void setMass(long objectId, int node, float mass);
<del>
<add>
<ide> /* Get mass */
<del> public float getMass(int node){
<add> public float getMass(int node) {
<ide> return getMass(objectId, node);
<ide> }
<del>
<add>
<ide> private native float getMass(long objectId, int node);
<ide>
<ide> /* Get total mass */
<del> public float getTotalMass(){
<add> public float getTotalMass() {
<ide> return getTotalMass(objectId);
<ide> }
<del>
<add>
<ide> private native float getTotalMass(long objectId);
<ide>
<ide> /* Set total mass (weighted by previous masses) */
<del> public void setTotalMass(float mass, boolean fromfaces){
<add> public void setTotalMass(float mass, boolean fromfaces) {
<ide> setTotalMass(objectId, mass, fromfaces);
<ide> }
<del>
<del> public void setTotalMass(float mass){
<add>
<add> public void setTotalMass(float mass) {
<ide> setTotalMass(mass, false);
<ide> }
<del>
<add>
<ide> private native void setTotalMass(long objectId, float mass, boolean fromFaces);
<del>
<del>/* Set total density */
<del> public void setTotalDensity(float density){
<add>
<add> /* Set total density */
<add> public void setTotalDensity(float density) {
<ide> setTotalDensity(objectId, density);
<ide> }
<del>
<add>
<ide> private native void setTotalDensity(long objectId, float density);
<del>
<add>
<ide> /* Set volume mass (using tetrahedrons) */
<del> public void setVolumeMass(float mass){
<add> public void setVolumeMass(float mass) {
<ide> setVolumeMass(objectId, mass);
<ide> }
<del>
<add>
<ide> private native void setVolumeMass(long objectId, float mass);
<del>
<add>
<ide> /* Set volume density (using tetrahedrons) */
<del> public void setVolumeDensity(float density){
<add> public void setVolumeDensity(float density) {
<ide> setVolumeDensity(objectId, density);
<ide> }
<del>
<add>
<ide> private native void setVolumeDensity(long objectId, float density);
<ide>
<ide> /* Transform */
<ide> /*====================*
<ide> Config access
<ide> *====================*/
<del> /*struct Config
<del>{
<del>eAeroModel::_ aeromodel; // Aerodynamic model (default: V_Point)
<del>btScalar kVCF; // Velocities correction factor (Baumgarte)
<del>btScalar kDP; // Damping coefficient [0,1]
<del>btScalar kDG; // Drag coefficient [0,+inf]
<del>btScalar kLF; // Lift coefficient [0,+inf]
<del>btScalar kPR; // Pressure coefficient [-inf,+inf]
<del>btScalar kVC; // Volume conversation coefficient [0,+inf]
<del>btScalar kDF; // Dynamic friction coefficient [0,1]
<del>btScalar kMT; // Pose matching coefficient [0,1]
<del>btScalar kCHR; // Rigid contacts hardness [0,1]
<del>btScalar kKHR; // Kinetic contacts hardness [0,1]
<del>btScalar kSHR; // Soft contacts hardness [0,1]
<del>btScalar kAHR; // Anchors hardness [0,1]
<del>btScalar kSRHR_CL; // Soft vs rigid hardness [0,1] (cluster only)
<del>btScalar kSKHR_CL; // Soft vs kinetic hardness [0,1] (cluster only)
<del>btScalar kSSHR_CL; // Soft vs soft hardness [0,1] (cluster only)
<del>btScalar kSR_SPLT_CL; // Soft vs rigid impulse split [0,1] (cluster only)
<del>btScalar kSK_SPLT_CL; // Soft vs rigid impulse split [0,1] (cluster only)
<del>btScalar kSS_SPLT_CL; // Soft vs rigid impulse split [0,1] (cluster only)
<del>btScalar maxvolume; // Maximum volume ratio for pose
<del>btScalar timescale; // Time scale
<del>int viterations; // Velocities solver iterations
<del>int piterations; // Positions solver iterations
<del>int diterations; // Drift solver iterations
<del>int citerations; // Cluster solver iterations
<del>int collisions; // Collisions flags
<del>tVSolverArray m_vsequence; // Velocity solvers sequence
<del>tPSolverArray m_psequence; // Position solvers sequence
<del>tPSolverArray m_dsequence; // Drift solvers sequence
<del>};*/
<add> //struct Config
<add>// eAeroModel::_ aeromodel; // Aerodynamic model (default: V_Point)
<add>// btScalar kVCF; // Velocities correction factor (Baumgarte)
<add> public void setVelocitiesCorrectionFactor(float factor) {
<add> setVelocitiesCorrectionFactor(objectId, factor);
<add> }
<add>
<add> private native void setVelocitiesCorrectionFactor(long bodyId, float factor);
<add>
<add> public float getVelocitiesCorrectionFactor() {
<add> return getVelocitiesCorrectionFactor(objectId);
<add> }
<add>
<add> private native float getVelocitiesCorrectionFactor(long bodyId);
<add>
<add>// btScalar kDP; // Damping coefficient [0,1]
<add> public void setDampingCoef(float coefficient) {
<add> setDampingCoef(objectId, coefficient);
<add> }
<add>
<add> private native void setDampingCoef(long bodyId, float coefficient);
<add>
<add> public float getDampingCoef() {
<add> return getDampingCoef(objectId);
<add> }
<add>
<add> private native float getDampingCoef(long bodyId);
<add>
<add>// btScalar kDG; // Drag coefficient [0,+inf]
<add> public void setDragCoef(float coefficient) {
<add> setDragCoef(objectId, coefficient);
<add> }
<add>
<add> private native void setDragCoef(long bodyId, float coefficient);
<add>
<add> public float getDragCoef() {
<add> return getDragCoef(objectId);
<add> }
<add>
<add> private native float getDragCoef(long bodyId);
<add>
<add>// btScalar kLF; // Lift coefficient [0,+inf]
<add> public void setLiftCoef(float coefficient) {
<add> setLiftCoef(objectId, coefficient);
<add> }
<add>
<add> private native void setLiftCoef(long bodyId, float coefficient);
<add>
<add> public float getLiftCoef() {
<add> return getLiftCoef(objectId);
<add> }
<add>
<add> private native float getLiftCoef(long bodyId);
<add>
<add>// btScalar kPR; // Pressure coefficient [-inf,+inf]
<add> public void setPressureCoef(float coefficient) {
<add> setPressureCoef(objectId, coefficient);
<add> }
<add>
<add> private native void setPressureCoef(long bodyId, float coefficient);
<add>
<add> public float getPressureCoef() {
<add> return getPressureCoef(objectId);
<add> }
<add>
<add> private native float getPressureCoef(long bodyId);
<add>
<add>// btScalar kVC; // Volume conversation coefficient [0,+inf]
<add> public void setVolumeConservationCoef(float coefficient) {
<add> setVolumeConservationCoef(objectId, coefficient);
<add> }
<add>
<add> private native void setVolumeConservationCoef(long bodyId, float coefficient);
<add>
<add> public float getVolumeConservationCoef() {
<add> return getVolumeConservationCoef(objectId);
<add> }
<add>
<add> private native float getVolumeConservationCoef(long bodyId);
<add>
<add>// -> btScalar kDF; // Dynamic friction coefficient [0,1]
<add> /**
<add> * set the Bullet kDF (aka Dynamic friction coefficient [0,1])
<add> *
<add> * @param coefficient
<add> */
<add> public void setDynamicFrictionCoef(float coefficient) {
<add> setDynamicFrictionCoef(objectId, coefficient);
<add> }
<add>
<add> private native void setDynamicFrictionCoef(long objectId, float coefficient);
<add>
<add> public float getDynamicFrictionCoef() {
<add> return getDynamicFrictionCoef(objectId);
<add> }
<add>
<add> private native float getDynamicFrictionCoef(long objectId);
<add>
<add>// -> btScalar kMT; // Pose matching coefficient [0,1]
<add> public void setPoseMatchingCoef(float coefficient) {
<add> setPoseMatchingCoef(objectId, coefficient);
<add> }
<add>
<add> private native void setPoseMatchingCoef(long objectId, float coefficient);
<add>
<add> public float getPoseMatchingCoef() {
<add> return getPoseMatchingCoef(objectId);
<add> }
<add>
<add> private native float getPoseMatchingCoef(long bodyId);
<add>
<add>// btScalar kCHR; // Rigid contacts hardness [0,1]
<add> public void setRigidContactsHardness(float hardness) {
<add> setRigidContactsHardness(objectId, hardness);
<add> }
<add>
<add> private native void setRigidContactsHardness(long bodyId, float hardness);
<add>
<add> public float getRigidContactsHardness() {
<add> return getRigidContactsHardness(objectId);
<add> }
<add>
<add> private native float getRigidContactsHardness(long bodyId);
<add>
<add>// btScalar kKHR; // Kinetic contacts hardness [0,1]
<add> public void setKineticContactsHardness(float hardness) {
<add> setKineticContactsHardness(objectId, hardness);
<add> }
<add>
<add> private native void setKineticContactsHardness(long bodyId, float hardness);
<add>
<add> public float getKineticContactsHardness() {
<add> return getKineticContactsHardness(objectId);
<add> }
<add>
<add> private native float getKineticContactsHardness(long bodyId);
<add>
<add>// btScalar kSHR; // Soft contacts hardness [0,1]
<add> public void setSoftContactsHardness(float hardness) {
<add> setSoftContactsHardness(objectId, hardness);
<add> }
<add>
<add> private native void setSoftContactsHardness(long bodyId, float hardness);
<add>
<add> public float getSoftContactsHardness() {
<add> return getSoftContactsHardness(objectId);
<add> }
<add>
<add> private native float getSoftContactsHardness(long bodyId);
<add>
<add>// btScalar kAHR; // Anchors hardness [0,1]
<add> public void setAnchorsHardness(float hardness) {
<add> setAnchorsHardness(objectId, hardness);
<add> }
<add>
<add> private native void setAnchorsHardness(long bodyId, float hardness);
<add>
<add> public float getAnchorsHardness() {
<add> return getAnchorsHardness(objectId);
<add> }
<add>
<add> private native float getAnchorsHardness(long bodyId);
<add>
<add>// btScalar kSRHR_CL; // Soft vs rigid hardness [0,1] (cluster only)
<add>// btScalar kSKHR_CL; // Soft vs kinetic hardness [0,1] (cluster only)
<add>// btScalar kSSHR_CL; // Soft vs soft hardness [0,1] (cluster only)
<add>// btScalar kSR_SPLT_CL; // Soft vs rigid impulse split [0,1] (cluster only)
<add>// btScalar kSK_SPLT_CL; // Soft vs rigid impulse split [0,1] (cluster only)
<add>// btScalar kSS_SPLT_CL; // Soft vs rigid impulse split [0,1] (cluster only)
<add>// btScalar maxvolume; // Maximum volume ratio for pose
<add> public void setMaximumVolumeRatio(float ratio) {
<add> setMaximumVolumeRatio(objectId, ratio);
<add> }
<add>
<add> private native void setMaximumVolumeRatio(long bodyId, float ratio);
<add>
<add> public float getMaximumVolumeRatio() {
<add> return getMaximumVolumeRatio(objectId);
<add> }
<add>
<add> private native float getMaximumVolumeRatio(long bodyId);
<add>
<add>// btScalar timescale; // Time scale
<add> public void setTimeScale(float scale) {
<add> setTimeScale(objectId, scale);
<add> }
<add>
<add> private native void setTimeScale(long bodyId, float scale);
<add>
<add> public float getTimeScale() {
<add> return getTimeScale(objectId);
<add> }
<add>
<add> private native float getTimeScale(long bodyId);
<add>
<add>// int viterations; // Velocities solver iterations
<add> public void setVelocitiesIterations(int iterations) {
<add> setVelocitiesIterations(objectId, iterations);
<add> }
<add>
<add> private native void setVelocitiesIterations(long objectId, int iteration);
<add>
<add> public int getVelocitiesIterations() {
<add> return getVelocitiesIterations(objectId);
<add> }
<add>
<add> private native int getVelocitiesIterations(long objectId);
<add>
<add>// -> int piterations; // Positions solver iterations
<add> public void setPositionIterations(int iterations) {
<add> setPositionIterations(objectId, iterations);
<add> }
<add>
<add> private native void setPositionIterations(long objectId, int iteration);
<add>
<add> public int getPositionIterations() {
<add> return getPositionIterations(objectId);
<add> }
<add>
<add> private native int getPositionIterations(long objectId);
<add>
<add>// int diterations; // Drift solver iterations
<add> public void setDriftIterations(int iterations) {
<add> setDriftIterations(objectId, iterations);
<add> }
<add>
<add> private native void setDriftIterations(long objectId, int iteration);
<add>
<add> public int getDriftIterations() {
<add> return getDriftIterations(objectId);
<add> }
<add>
<add> private native int getDriftIterations(long objectId);
<add>
<add>// int citerations; // Cluster solver iterations
<add> /* public void setClusterIterations(int iterations) {
<add> setClusterIterations(objectId, iterations);
<add> }
<add>
<add> private native void setClusterIterations(long objectId, int iteration);
<add>
<add> public int getClusterIterations() {
<add> return getClusterIterations(objectId);
<add> }
<add>
<add> private native int getClusterIterations(long objectId);*/
<ide>
<del> /*btScalar kDF; // Dynamic friction coefficient [0,1]*/
<del> public void setDynamicFriction(float coefficient){
<del> setDynamicFriction(objectId, coefficient);
<del> }
<del>
<del> private native void setDynamicFriction(long objectId, float coefficient);
<del>
<del> /*btScalar kMT; // Pose matching coefficient [0,1]*/
<del> public void setPoseMatching(float coefficient){
<del> setPoseMatching(objectId, coefficient);
<del> }
<del>
<del> private native void setPoseMatching(long objectId, float coefficient);
<del>
<del> /*int piterations; // Positions solver iterations*/
<del> public void setPositionSolver(int iterations){
<del> setPositionSolver(objectId, iterations);
<del> }
<del>
<del> private native void setPositionSolver(long objectId, int iteration);
<del>
<add>// int collisions; // Collisions flags
<add>// tVSolverArray m_vsequence; // Velocity solvers sequence
<add>// tPSolverArray m_psequence; // Position solvers sequence
<add>// tPSolverArray m_dsequence; // Drift solvers sequence
<ide> /*====================*
<del> SoftBody to Mesh
<add> SoftBody to Mesh - UTILS
<ide> *====================*/
<ide> /*
<ide> Since bullet SoftBody don't use btCollisionShape, its not possible to use the DebugShapeFactory.
<ide> The following code is almost the same , but specially for SoftBody.
<ide> Theses methods are static (same as in DebugShapeFactory) so the code can be easily moved somewhere else.
<ide> */
<add>
<ide> public static Geometry createDebugShape(PhysicsSoftBody softBody) {
<ide> if (softBody == null) {
<ide> return null;
<ide> /*============*
<ide> * data Struct
<ide> *============*/
<del> class SoftBodyMaterial {
<del>
<del> private float linearStiffnessFactor; // Linear stiffness coefficient [0,1]
<del> private float angularStiffnessFactor; // Area/Angular stiffness coefficient [0,1]
<del> private float volumeStiffnessFactor; // Volume stiffness coefficient [0,1]
<del> private int flags; // Flags
<del>
<del> public SoftBodyMaterial(float linearStiffnessFactor, float angularStiffnessFactor, float volumeStiffnessFactor, int flags) {
<del> this.linearStiffnessFactor = linearStiffnessFactor;
<del> this.angularStiffnessFactor = angularStiffnessFactor;
<del> this.volumeStiffnessFactor = volumeStiffnessFactor;
<del> this.flags = flags;
<del> }
<add> class Material {
<add>
<add> private long materialId;
<add>
<add> public Material(float linearStiffnessFactor, float angularStiffnessFactor, float volumeStiffnessFactor, int flags) {
<add> this();
<add> setLinearStiffnessFactor(materialId, linearStiffnessFactor);
<add> setAngularStiffnessFactor(materialId, angularStiffnessFactor);
<add> setVolumeStiffnessFactor(materialId, volumeStiffnessFactor);
<add> }
<add>
<add> private Material() {
<add> this.materialId = createMaterial();
<add> }
<add>
<add> protected Material(long nativeId) {
<add> this.materialId = nativeId;
<add> }
<add>
<add> @Override
<add> public boolean equals(Object obj) {
<add> if (obj.getClass() == Material.class) {
<add> return this.materialId == ((Material) obj).materialId;
<add> } else {
<add> return false;
<add> }
<add> }
<add>
<add> private native long createMaterial();
<ide>
<ide> /**
<ide> * @return the linearStiffnessFactor
<ide> */
<ide> public float getLinearStiffnessFactor() {
<del> return linearStiffnessFactor;
<del> }
<add> return getLinearStiffnessFactor(materialId);
<add> }
<add>
<add> private native float getLinearStiffnessFactor(long materialId);
<ide>
<ide> /**
<ide> * @param linearStiffnessFactor the linearStiffnessFactor to set
<ide> */
<ide> public void setLinearStiffnessFactor(float linearStiffnessFactor) {
<del> this.linearStiffnessFactor = linearStiffnessFactor;
<del> }
<add> setLinearStiffnessFactor(materialId, linearStiffnessFactor);
<add> }
<add>
<add> private native void setLinearStiffnessFactor(long materialId, float linearStiffnessFactor);
<ide>
<ide> /**
<ide> * @return the angularStiffnessFactor
<ide> */
<ide> public float getAngularStiffnessFactor() {
<del> return angularStiffnessFactor;
<del> }
<add> return getAngularStiffnessFactor(materialId);
<add> }
<add>
<add> private native float getAngularStiffnessFactor(long materialId);
<ide>
<ide> /**
<ide> * @param angularStiffnessFactor the angularStiffnessFactor to set
<ide> */
<ide> public void setAngularStiffnessFactor(float angularStiffnessFactor) {
<del> this.angularStiffnessFactor = angularStiffnessFactor;
<del> }
<add> setAngularStiffnessFactor(materialId, angularStiffnessFactor);
<add> }
<add>
<add> private native void setAngularStiffnessFactor(long materialId, float angularStiffnessFactor);
<ide>
<ide> /**
<ide> * @return the volumeStiffnessFactor
<ide> */
<ide> public float getVolumeStiffnessFactor() {
<del> return volumeStiffnessFactor;
<del> }
<add> return getVolumeStiffnessFactor(materialId);
<add> }
<add>
<add> private native float getVolumeStiffnessFactor(long materialId);
<ide>
<ide> /**
<ide> * @param volumeStiffnessFactor the volumeStiffnessFactor to set
<ide> */
<ide> public void setVolumeStiffnessFactor(float volumeStiffnessFactor) {
<del> this.volumeStiffnessFactor = volumeStiffnessFactor;
<del> }
<add> setVolumeStiffnessFactor(materialId, volumeStiffnessFactor);
<add> }
<add>
<add> private native void setVolumeStiffnessFactor(long materialId, float volumeStiffnessFactor);
<ide>
<ide> /**
<ide> * @return the flags
<ide> */
<ide> public int getFlags() {
<del> return flags;
<del> }
<add> return getFlags(materialId);
<add> }
<add>
<add> private native int getFlags(long materialId);
<ide>
<ide> /**
<ide> * @param flags the flags to set
<ide> */
<ide> public void setFlags(int flags) {
<del> this.flags = flags;
<del> }
<add> setFlags(materialId, flags);
<add> }
<add>
<add> private native void setFlags(long materialId, int flags);
<ide>
<ide> }
<ide> } |
|
JavaScript | mit | d6aa43d90ed819b4bbe00840cdd98e90d2e6e490 | 0 | TheFellowshipOfTheCode/QuizziPedia,TheFellowshipOfTheCode/QuizziPedia | /*******************************************************************************
* Name: QuizziPedia::Back-End::App::Models::LangModel
* Description: scrivere una piccola descrizione della classe (riassunto da DDP).
* Relations with other classes:
* + NomeAltraClasse1
* + NomeAltraClasse2
* Creation data: 27-04-2016
* Author: Matteo Gnoato
********************************************************************************
* Updates history
*-------------------------------------------------------------------------------
* ID: QuizziPedia::Back-End::App::Model::LangModel_20160427
* Update data: 27-04-2016
* Description: Creata connessione con mongoose, creata la definizione dello schema
* Aggiunto metodo getVarlist.
* Autore: Matteo Gnoato
*-------------------------------------------------------------------------------
*******************************************************************************/
var mongoose = require('mongoose');
var langSchema = new mongoose.Schema({
lang: String,
variables: [String]
});
let langs = mongoose.model('Lang', langSchema );
langSchema.methods.getVarlist = function(lang, callback, errback){
if(lang === "ita"){
callback = langSchema.findOne({lang: ita});
}
else if(lang === "eng"){
callback = langSchema.findOne({lang: eng});
}
else{
errback; // quando è pronta la classe QuizziPediaError aggiungere qua
// l'errore di Lingua sconosciuta (1600)
}
}
module.exports = langs; | Back-End/App/Model/LangModel.js | var mongoose = require('mongoose');
var langSchema = new mongoose.Schema({
lang: String,
variables: [String]
});
module.exports = mongoose.model('Lang', langSchema); | Aggiunto metodo getVarlist su QuizziPedia::Back-End::App::Models::LangModel
| Back-End/App/Model/LangModel.js | Aggiunto metodo getVarlist su QuizziPedia::Back-End::App::Models::LangModel | <ide><path>ack-End/App/Model/LangModel.js
<add>/*******************************************************************************
<add> * Name: QuizziPedia::Back-End::App::Models::LangModel
<add> * Description: scrivere una piccola descrizione della classe (riassunto da DDP).
<add> * Relations with other classes:
<add> * + NomeAltraClasse1
<add> * + NomeAltraClasse2
<add> * Creation data: 27-04-2016
<add> * Author: Matteo Gnoato
<add> ********************************************************************************
<add> * Updates history
<add> *-------------------------------------------------------------------------------
<add> * ID: QuizziPedia::Back-End::App::Model::LangModel_20160427
<add> * Update data: 27-04-2016
<add> * Description: Creata connessione con mongoose, creata la definizione dello schema
<add> * Aggiunto metodo getVarlist.
<add> * Autore: Matteo Gnoato
<add> *-------------------------------------------------------------------------------
<add> *******************************************************************************/
<add>
<ide> var mongoose = require('mongoose');
<ide> var langSchema = new mongoose.Schema({
<ide> lang: String,
<ide> variables: [String]
<ide> });
<ide>
<del>module.exports = mongoose.model('Lang', langSchema);
<add>let langs = mongoose.model('Lang', langSchema );
<add>
<add>langSchema.methods.getVarlist = function(lang, callback, errback){
<add> if(lang === "ita"){
<add> callback = langSchema.findOne({lang: ita});
<add> }
<add> else if(lang === "eng"){
<add> callback = langSchema.findOne({lang: eng});
<add> }
<add> else{
<add> errback; // quando è pronta la classe QuizziPediaError aggiungere qua
<add> // l'errore di Lingua sconosciuta (1600)
<add> }
<add>}
<add>
<add>module.exports = langs; |
|
Java | lgpl-2.1 | abf28b359258685b276028efdb3d0f07753f3a36 | 0 | samskivert/samskivert,samskivert/samskivert | //
// $Id: MessageManager.java,v 1.11 2004/05/11 03:14:03 mdb Exp $
//
// samskivert library - useful routines for java programs
// Copyright (C) 2001 Michael Bayne
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.samskivert.servlet;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import com.samskivert.Log;
import com.samskivert.text.MessageUtil;
import com.samskivert.util.StringUtil;
/**
* The message manager handles the translation messages for a web
* application. The webapp should construct the message manager with the
* name of its message properties file and it can then make use of the
* message manager to generate locale specific messages for a request.
*/
public class MessageManager
{
/**
* Constructs a message manager with the specified bundle path. The
* message manager will be instantiating a <code>ResourceBundle</code>
* with the supplied path, so it should conform to the naming
* conventions defined by that class.
*
* @see java.util.ResourceBundle
*/
public MessageManager (String bundlePath)
{
// keep this for later
_bundlePath = bundlePath;
}
/**
* If the message manager is to be used in a multi-site environment,
* it can be configured to load site-specific message resources in
* addition to the default application message resources. It must be
* configured with the facilities to load site-specific resources by a
* call to this function.
*
* @param siteBundlePath the path to the site-specific message
* resources.
* @param siteLoader a site-specific resource loader, properly
* configured with a site identifier.
* @param siteIdent a site identifier that can be used to identify the
* site via which an http request was made.
*/
public void activateSiteSpecificMessages (String siteBundlePath,
SiteResourceLoader siteLoader,
SiteIdentifier siteIdent)
{
_siteBundlePath = siteBundlePath;
_siteLoader = siteLoader;
_siteIdent = siteIdent;
}
/**
* Return true if the specifed path exists in the resource bundle.
*/
public boolean exists (HttpServletRequest req, String path)
{
return (getMessage(req, path, false) != null);
}
/**
* Looks up the message with the specified path in the resource bundle
* most appropriate for the locales described as preferred by the
* request. Always reports missing paths.
*/
public String getMessage (HttpServletRequest req, String path)
{
return getMessage(req, path, true);
}
/**
* Looks up the message with the specified path in the resource bundle
* most appropriate for the locales described as preferred by the
* request, then substitutes the supplied arguments into that message
* using a <code>MessageFormat</code> object.
*
* @see java.text.MessageFormat
*/
public String getMessage (HttpServletRequest req, String path,
Object[] args)
{
String msg = getMessage(req, path, true);
// we may cache message formatters later, but for now just
// use the static convenience function
return MessageFormat.format(msg, args);
}
/**
* Looks up the message with the specified path in the resource bundle
* most appropriate for the locales described as preferred by the
* request. If requested it will log a missing path and return the
* path as the translation (which should make it obvious in the
* servlet that the translation is missing) otherwise it returns null.
*/
protected String getMessage (HttpServletRequest req, String path,
boolean reportMissing)
{
if (path == null) {
return "[null message key]";
}
// if the key is tainted, just strip the taint character
if (path.startsWith(MessageUtil.TAINT_CHAR)) {
return path.substring(1);
}
// attempt to determine whether or not this is a compound key
int tidx = path.indexOf("|");
if (tidx != -1) {
String key = path.substring(0, tidx);
String argstr = path.substring(tidx+1);
String[] args = StringUtil.split(argstr, "|");
// unescape and translate the arguments
for (int i = 0; i < args.length; i++) {
// if the argument is tainted, do no further translation
// (it might contain |s or other fun stuff)
if (args[i].startsWith(MessageUtil.TAINT_CHAR)) {
args[i] = MessageUtil.unescape(args[i].substring(1));
} else {
args[i] = getMessage(req, MessageUtil.unescape(args[i]));
}
}
return getMessage(req, key, args);
}
// load up the matching resource bundles (the array will contain
// the site-specific resources first and the application resources
// second); use the locale preferred by the client if possible
ResourceBundle[] bundles = resolveBundles(req);
if (bundles != null) {
int blength = bundles.length;
for (int i = 0; i < blength; i++) {
try {
if (bundles[i] != null) {
return bundles[i].getString(path);
}
} catch (MissingResourceException mre) {
// no complaints, just try the bundle in the enclosing
// scope
}
}
}
if (reportMissing) {
// if there's no translation for this path, complain about it
Log.warning("Missing translation message [path=" + path +
", url=" + req.getRequestURL() + "].");
return path;
}
return null;
}
/**
* Finds the closest matching resource bundle for the locales
* specified as preferred by the client in the supplied http request.
*/
protected ResourceBundle[] resolveBundles (HttpServletRequest req)
{
// first look to see if we've cached the bundles for this request
// in the request object
ResourceBundle[] bundles = (ResourceBundle[])
req.getAttribute(BUNDLE_CACHE_NAME);
if (bundles != null) {
return bundles;
}
// grab our site-specific class loader if we have one
ClassLoader siteLoader = null;
if (_siteLoader != null && _siteIdent != null) {
int siteId = _siteIdent.identifySite(req);
try {
siteLoader = _siteLoader.getSiteClassLoader(siteId);
} catch (IOException ioe) {
Log.warning("Unable to fetch site-specific classloader " +
"[siteId=" + siteId + ", error=" + ioe + "].");
}
}
// try looking up the appropriate bundles
bundles = new ResourceBundle[2];
// first from the site-specific classloader
if (siteLoader != null) {
bundles[0] = resolveBundle(req, _siteBundlePath, siteLoader);
}
// then from the default classloader
bundles[1] = resolveBundle(req, _bundlePath,
getClass().getClassLoader());
// if we found either or both bundles, cache 'em
if (bundles[0] != null || bundles[1] != null) {
req.setAttribute(BUNDLE_CACHE_NAME, bundles);
}
return bundles;
}
/**
* Resolves the default resource bundle based on the locale
* information provided in the supplied http request object.
*/
protected ResourceBundle resolveBundle (
HttpServletRequest req, String bundlePath, ClassLoader loader)
{
ResourceBundle bundle = null;
Enumeration locales = req.getLocales();
while (locales.hasMoreElements()) {
Locale locale = (Locale)locales.nextElement();
try {
// java caches resource bundles, so we don't need to
// reinvent the wheel here. however, java also falls back
// from a specific bundle to a more general one if it
// can't find a specific bundle. that's real nice of it,
// but we want first to see whether or not we have exact
// matches on any of the preferred locales specified by
// the client. if we don't, then we can rely on java's
// fallback mechanisms
bundle = ResourceBundle.getBundle(
bundlePath, locale, loader);
// if it's an exact match, off we go
if (bundle.getLocale().equals(locale)) {
break;
}
} catch (MissingResourceException mre) {
// no need to freak out quite yet, see if we have
// something for one of the other preferred locales
}
}
// if we were unable to find an exact match for any of the user's
// preferred locales, take their most preferred and let java
// perform it's fallback logic on that one
if (bundle == null) {
try {
bundle = ResourceBundle.getBundle(
bundlePath, req.getLocale(), loader);
} catch (MissingResourceException mre) {
// if we were unable even to find a default bundle, we've
// got real problems. time to freak out
Log.warning("Unable to resolve any message bundle " +
"[req=" + req.getRequestURI() +
", locale=" + req.getLocale() +
", bundlePath=" + bundlePath +
", classLoader=" + loader +
", siteBundlePath=" + _siteBundlePath +
", siteLoader=" + _siteLoader +
"].");
}
}
return bundle;
}
/** The path, relative to the classpath, to our resource bundles. */
protected String _bundlePath;
/** The path to the site-specific message bundles, fetched via the
* site-specific resource loader. */
protected String _siteBundlePath;
/** The resource loader with which to fetch our site-specific message
* bundles. */
protected SiteResourceLoader _siteLoader;
/** The site identifier we use to determine through which site a
* request was made. */
protected SiteIdentifier _siteIdent;
/** The attribute name that we use for caching resource bundles in
* request objects. */
protected static final String BUNDLE_CACHE_NAME =
"com.samskivert.servlet.MessageManager:CachedResourceBundle";
}
| projects/samskivert/src/java/com/samskivert/servlet/MessageManager.java | //
// $Id: MessageManager.java,v 1.11 2004/05/11 03:14:03 mdb Exp $
//
// samskivert library - useful routines for java programs
// Copyright (C) 2001 Michael Bayne
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.samskivert.servlet;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import com.samskivert.Log;
import com.samskivert.text.MessageUtil;
import com.samskivert.util.StringUtil;
/**
* The message manager handles the translation messages for a web
* application. The webapp should construct the message manager with the
* name of its message properties file and it can then make use of the
* message manager to generate locale specific messages for a request.
*/
public class MessageManager
{
/**
* Constructs a message manager with the specified bundle path. The
* message manager will be instantiating a <code>ResourceBundle</code>
* with the supplied path, so it should conform to the naming
* conventions defined by that class.
*
* @see java.util.ResourceBundle
*/
public MessageManager (String bundlePath)
{
// keep this for later
_bundlePath = bundlePath;
}
/**
* If the message manager is to be used in a multi-site environment,
* it can be configured to load site-specific message resources in
* addition to the default application message resources. It must be
* configured with the facilities to load site-specific resources by a
* call to this function.
*
* @param siteBundlePath the path to the site-specific message
* resources.
* @param siteLoader a site-specific resource loader, properly
* configured with a site identifier.
* @param siteIdent a site identifier that can be used to identify the
* site via which an http request was made.
*/
public void activateSiteSpecificMessages (String siteBundlePath,
SiteResourceLoader siteLoader,
SiteIdentifier siteIdent)
{
_siteBundlePath = siteBundlePath;
_siteLoader = siteLoader;
_siteIdent = siteIdent;
}
/**
* Return true if the specifed path exists in the resource bundle.
*/
public boolean exists (HttpServletRequest req, String path)
{
return (getMessage(req, path, false) != null);
}
/**
* Looks up the message with the specified path in the resource bundle
* most appropriate for the locales described as preferred by the
* request. Always reports missing paths.
*/
public String getMessage (HttpServletRequest req, String path)
{
return getMessage(req, path, true);
}
/**
* Looks up the message with the specified path in the resource bundle
* most appropriate for the locales described as preferred by the
* request, then substitutes the supplied arguments into that message
* using a <code>MessageFormat</code> object.
*
* @see java.text.MessageFormat
*/
public String getMessage (HttpServletRequest req, String path,
Object[] args)
{
String msg = getMessage(req, path, true);
// we may cache message formatters later, but for now just
// use the static convenience function
return MessageFormat.format(msg, args);
}
/**
* Looks up the message with the specified path in the resource bundle
* most appropriate for the locales described as preferred by the
* request. If requested it will log a missing path and return the
* path as the translation (which should make it obvious in the
* servlet that the translation is missing) otherwise it returns null.
*/
protected String getMessage (HttpServletRequest req, String path,
boolean reportMissing)
{
if (path == null) {
return "[null message key]";
}
// if the key is tainted, just strip the taint character
if (path.startsWith(MessageUtil.TAINT_CHAR)) {
return path.substring(1);
}
// attempt to determine whether or not this is a compound key
int tidx = path.indexOf("|");
if (tidx != -1) {
String key = path.substring(0, tidx);
String argstr = path.substring(tidx+1);
String[] args = StringUtil.split(argstr, "|");
// unescape and translate the arguments
for (int i = 0; i < args.length; i++) {
// if the argument is tainted, do no further translation
// (it might contain |s or other fun stuff)
if (args[i].startsWith(MessageUtil.TAINT_CHAR)) {
args[i] = MessageUtil.unescape(args[i].substring(1));
} else {
args[i] = getMessage(req, MessageUtil.unescape(args[i]));
}
}
return getMessage(req, key, args);
}
// load up the matching resource bundles (the array will contain
// the site-specific resources first and the application resources
// second); use the locale preferred by the client if possible
ResourceBundle[] bundles = resolveBundles(req);
if (bundles != null) {
int blength = bundles.length;
for (int i = 0; i < blength; i++) {
try {
if (bundles[i] != null) {
return bundles[i].getString(path);
}
} catch (MissingResourceException mre) {
// no complaints, just try the bundle in the enclosing
// scope
}
}
}
if (reportMissing) {
// if there's no translation for this path, complain about it
Log.warning("Missing translation message [path=" + path + "].");
return path;
}
return null;
}
/**
* Finds the closest matching resource bundle for the locales
* specified as preferred by the client in the supplied http request.
*/
protected ResourceBundle[] resolveBundles (HttpServletRequest req)
{
// first look to see if we've cached the bundles for this request
// in the request object
ResourceBundle[] bundles = (ResourceBundle[])
req.getAttribute(BUNDLE_CACHE_NAME);
if (bundles != null) {
return bundles;
}
// grab our site-specific class loader if we have one
ClassLoader siteLoader = null;
if (_siteLoader != null && _siteIdent != null) {
int siteId = _siteIdent.identifySite(req);
try {
siteLoader = _siteLoader.getSiteClassLoader(siteId);
} catch (IOException ioe) {
Log.warning("Unable to fetch site-specific classloader " +
"[siteId=" + siteId + ", error=" + ioe + "].");
}
}
// try looking up the appropriate bundles
bundles = new ResourceBundle[2];
// first from the site-specific classloader
if (siteLoader != null) {
bundles[0] = resolveBundle(req, _siteBundlePath, siteLoader);
}
// then from the default classloader
bundles[1] = resolveBundle(req, _bundlePath,
getClass().getClassLoader());
// if we found either or both bundles, cache 'em
if (bundles[0] != null || bundles[1] != null) {
req.setAttribute(BUNDLE_CACHE_NAME, bundles);
}
return bundles;
}
/**
* Resolves the default resource bundle based on the locale
* information provided in the supplied http request object.
*/
protected ResourceBundle resolveBundle (
HttpServletRequest req, String bundlePath, ClassLoader loader)
{
ResourceBundle bundle = null;
Enumeration locales = req.getLocales();
while (locales.hasMoreElements()) {
Locale locale = (Locale)locales.nextElement();
try {
// java caches resource bundles, so we don't need to
// reinvent the wheel here. however, java also falls back
// from a specific bundle to a more general one if it
// can't find a specific bundle. that's real nice of it,
// but we want first to see whether or not we have exact
// matches on any of the preferred locales specified by
// the client. if we don't, then we can rely on java's
// fallback mechanisms
bundle = ResourceBundle.getBundle(
bundlePath, locale, loader);
// if it's an exact match, off we go
if (bundle.getLocale().equals(locale)) {
break;
}
} catch (MissingResourceException mre) {
// no need to freak out quite yet, see if we have
// something for one of the other preferred locales
}
}
// if we were unable to find an exact match for any of the user's
// preferred locales, take their most preferred and let java
// perform it's fallback logic on that one
if (bundle == null) {
try {
bundle = ResourceBundle.getBundle(
bundlePath, req.getLocale(), loader);
} catch (MissingResourceException mre) {
// if we were unable even to find a default bundle, we've
// got real problems. time to freak out
Log.warning("Unable to resolve any message bundle " +
"[req=" + req.getRequestURI() +
", locale=" + req.getLocale() +
", bundlePath=" + bundlePath +
", classLoader=" + loader +
", siteBundlePath=" + _siteBundlePath +
", siteLoader=" + _siteLoader +
"].");
}
}
return bundle;
}
/** The path, relative to the classpath, to our resource bundles. */
protected String _bundlePath;
/** The path to the site-specific message bundles, fetched via the
* site-specific resource loader. */
protected String _siteBundlePath;
/** The resource loader with which to fetch our site-specific message
* bundles. */
protected SiteResourceLoader _siteLoader;
/** The site identifier we use to determine through which site a
* request was made. */
protected SiteIdentifier _siteIdent;
/** The attribute name that we use for caching resource bundles in
* request objects. */
protected static final String BUNDLE_CACHE_NAME =
"com.samskivert.servlet.MessageManager:CachedResourceBundle";
}
| Report the request URL when reporting a missing translation message.
git-svn-id: 64ebf368729f38804935acb7146e017e0f909c6b@1666 6335cc39-0255-0410-8fd6-9bcaacd3b74c
| projects/samskivert/src/java/com/samskivert/servlet/MessageManager.java | Report the request URL when reporting a missing translation message. | <ide><path>rojects/samskivert/src/java/com/samskivert/servlet/MessageManager.java
<ide>
<ide> if (reportMissing) {
<ide> // if there's no translation for this path, complain about it
<del> Log.warning("Missing translation message [path=" + path + "].");
<add> Log.warning("Missing translation message [path=" + path +
<add> ", url=" + req.getRequestURL() + "].");
<ide> return path;
<ide> }
<ide> |
|
Java | apache-2.0 | 5fe79786ecd08a47018244d45dcda70e06e87774 | 0 | dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android | package org.commcare.tasks;
import android.content.Context;
import android.os.AsyncTask;
import org.commcare.CommCareApplication;
import org.commcare.activities.SyncCapableCommCareActivity;
import org.commcare.logging.AndroidLogger;
import org.commcare.models.FormRecordProcessor;
import org.commcare.android.database.user.models.FormRecord;
import org.commcare.suite.model.Profile;
import org.commcare.tasks.templates.CommCareTask;
import org.commcare.tasks.templates.CommCareTaskConnector;
import org.commcare.utils.FormUploadResult;
import org.commcare.utils.FormUploadUtil;
import org.commcare.utils.SessionUnavailableException;
import org.commcare.views.notifications.NotificationMessageFactory;
import org.commcare.views.notifications.ProcessIssues;
import org.javarosa.core.model.User;
import org.javarosa.core.services.Logger;
import org.javarosa.xml.util.InvalidStructureException;
import org.javarosa.xml.util.UnfullfilledRequirementsException;
import org.xmlpull.v1.XmlPullParserException;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import javax.crypto.spec.SecretKeySpec;
/**
* @author ctsims
*/
public abstract class ProcessAndSendTask<R> extends CommCareTask<FormRecord, Long, FormUploadResult, R> implements DataSubmissionListener {
private Context c;
private String url;
private FormUploadResult[] results;
private final int sendTaskId;
public static final int PROCESSING_PHASE_ID = 8;
public static final int SEND_PHASE_ID = 9;
public static final int PROCESSING_PHASE_ID_NO_DIALOG = -8;
public static final int SEND_PHASE_ID_NO_DIALOG = -9;
public static final long PROGRESS_ALL_PROCESSED = 8;
public static final long SUBMISSION_BEGIN = 16;
public static final long SUBMISSION_START = 32;
public static final long SUBMISSION_NOTIFY = 64;
public static final long SUBMISSION_DONE = 128;
private static final long SUBMISSION_SUCCESS = 1;
private static final long SUBMISSION_FAIL = 0;
private FormSubmissionProgressBarListener progressBarListener;
private List<DataSubmissionListener> formSubmissionListeners;
private final FormRecordProcessor processor;
private static final int SUBMISSION_ATTEMPTS = 2;
private static final Queue<ProcessAndSendTask> processTasks = new LinkedList<>();
public ProcessAndSendTask(Context c, String url) {
this(c, url, true);
}
/**
* @param inSyncMode blocks the user with a sync dialog
*/
public ProcessAndSendTask(Context c, String url, boolean inSyncMode) {
this.c = c;
this.url = url;
this.processor = new FormRecordProcessor(c);
this.formSubmissionListeners = new ArrayList<>();
if (inSyncMode) {
this.sendTaskId = SEND_PHASE_ID;
this.taskId = PROCESSING_PHASE_ID;
} else {
this.sendTaskId = SEND_PHASE_ID_NO_DIALOG;
this.taskId = PROCESSING_PHASE_ID_NO_DIALOG;
}
}
@Override
protected FormUploadResult doTaskBackground(FormRecord... records) {
boolean needToSendLogs = false;
try {
results = new FormUploadResult[records.length];
for (int i = 0; i < records.length; ++i) {
//Assume failure
results[i] = FormUploadResult.FAILURE;
}
//The first thing we need to do is make sure everything is processed,
//we can't actually proceed before that.
try {
needToSendLogs = checkFormRecordStatus(records);
} catch (FileNotFoundException e) {
return FormUploadResult.PROGRESS_SDCARD_REMOVED;
} catch (TaskCancelledException e) {
return FormUploadResult.FAILURE;
}
this.publishProgress(PROGRESS_ALL_PROCESSED);
//Put us on the queue!
synchronized (processTasks) {
processTasks.add(this);
}
boolean needToRefresh;
try {
needToRefresh = blockUntilTopOfQueue();
} catch (TaskCancelledException e) {
return FormUploadResult.FAILURE;
}
if (needToRefresh) {
//There was another activity before this one. Refresh our models in case
//they were updated
for (int i = 0; i < records.length; ++i) {
int dbId = records[i].getID();
records[i] = processor.getRecord(dbId);
}
}
// Ok, all forms are now processed. Time to focus on sending
dispatchBeginSubmissionProcessToListeners(records.length);
sendForms(records);
return FormUploadResult.getWorstResult(results);
} catch (SessionUnavailableException sue) {
this.cancel(false);
return FormUploadResult.PROGRESS_LOGGED_OUT;
} finally {
this.endSubmissionProcess(
FormUploadResult.FULL_SUCCESS.equals(FormUploadResult.getWorstResult(results)));
synchronized (processTasks) {
processTasks.remove(this);
}
if (needToSendLogs) {
CommCareApplication.instance().notifyLogsPending();
}
}
}
private boolean checkFormRecordStatus(FormRecord[] records)
throws FileNotFoundException, TaskCancelledException {
boolean needToSendLogs = false;
processor.beginBulkSubmit();
for (int i = 0; i < records.length; ++i) {
if (isCancelled()) {
throw new TaskCancelledException();
}
FormRecord record = records[i];
//If the form is complete, but unprocessed, process it.
if (FormRecord.STATUS_COMPLETE.equals(record.getStatus())) {
try {
records[i] = processor.process(record);
} catch (InvalidStructureException e) {
CommCareApplication.notificationManager().reportNotificationMessage(NotificationMessageFactory.message(ProcessIssues.BadTransactions), true);
Logger.log(AndroidLogger.TYPE_ERROR_DESIGN, "Removing form record due to transaction data|" + getExceptionText(e));
FormRecordCleanupTask.wipeRecord(c, record);
needToSendLogs = true;
} catch (XmlPullParserException e) {
CommCareApplication.notificationManager().reportNotificationMessage(NotificationMessageFactory.message(ProcessIssues.BadTransactions), true);
Logger.log(AndroidLogger.TYPE_ERROR_DESIGN, "Removing form record due to bad xml|" + getExceptionText(e));
FormRecordCleanupTask.wipeRecord(c, record);
needToSendLogs = true;
} catch (UnfullfilledRequirementsException e) {
CommCareApplication.notificationManager().reportNotificationMessage(NotificationMessageFactory.message(ProcessIssues.BadTransactions), true);
Logger.log(AndroidLogger.TYPE_ERROR_DESIGN, "Removing form record due to bad requirements|" + getExceptionText(e));
FormRecordCleanupTask.wipeRecord(c, record);
needToSendLogs = true;
} catch (FileNotFoundException e) {
if (CommCareApplication.instance().isStorageAvailable()) {
//If storage is available generally, this is a bug in the app design
Logger.log(AndroidLogger.TYPE_ERROR_DESIGN, "Removing form record because file was missing|" + getExceptionText(e));
FormRecordCleanupTask.wipeRecord(c, record);
} else {
CommCareApplication.notificationManager().reportNotificationMessage(NotificationMessageFactory.message(ProcessIssues.StorageRemoved), true);
//Otherwise, the SD card just got removed, and we need to bail anyway.
throw e;
}
} catch (IOException e) {
Logger.log(AndroidLogger.TYPE_ERROR_WORKFLOW, "IO Issues processing a form. Tentatively not removing in case they are resolvable|" + getExceptionText(e));
}
}
}
processor.closeBulkSubmit();
return needToSendLogs;
}
private boolean blockUntilTopOfQueue() throws TaskCancelledException {
boolean needToRefresh = false;
while (true) {
//See if it's our turn to go
synchronized (processTasks) {
if (isCancelled()) {
processTasks.remove(this);
throw new TaskCancelledException();
}
//Are we at the head of the queue?
ProcessAndSendTask head = processTasks.peek();
if (head == this) {
break;
}
//Otherwise, is the head of the queue busted?
//*sigh*. Apparently Cancelled doesn't result in the task status being set
//to !Running for reasons which baffle me.
if (head.getStatus() != AsyncTask.Status.RUNNING || head.isCancelled()) {
//If so, get rid of it
processTasks.poll();
}
}
//If it's not yet quite our turn, take a nap
try {
needToRefresh = true;
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return needToRefresh;
}
private void sendForms(FormRecord[] records) {
for (int i = 0; i < records.length; ++i) {
//See whether we are OK to proceed based on the last form. We're now guaranteeing
//that forms are sent in order, so we won't proceed unless we succeed. We'll also permit
//proceeding if there was a local problem with a record, since we'll just move on from that
//processing.
if (i > 0 && !(results[i - 1] == FormUploadResult.FULL_SUCCESS || results[i - 1] == FormUploadResult.RECORD_FAILURE)) {
//Something went wrong with the last form, so we need to cancel this whole shebang
Logger.log(AndroidLogger.TYPE_WARNING_NETWORK, "Cancelling submission due to network errors. " + (i - 1) + " forms succesfully sent.");
break;
}
FormRecord record = records[i];
try {
//If it's unsent, go ahead and send it
if (FormRecord.STATUS_UNSENT.equals(record.getStatus())) {
File folder;
try {
folder = new File(record.getPath(c)).getCanonicalFile().getParentFile();
} catch (IOException e) {
Logger.log(AndroidLogger.TYPE_ERROR_WORKFLOW, "Bizarre. Exception just getting the file reference. Not removing." + getExceptionText(e));
continue;
}
//Good!
//Time to Send!
try {
User mUser = CommCareApplication.instance().getSession().getLoggedInUser();
int attemptsMade = 0;
logSubmissionAttempt(record);
while (attemptsMade < SUBMISSION_ATTEMPTS) {
if (attemptsMade > 0) {
Logger.log(AndroidLogger.TYPE_WARNING_NETWORK, "Retrying submission. " + (SUBMISSION_ATTEMPTS - attemptsMade) + " attempts remain");
}
results[i] = FormUploadUtil.sendInstance(i, folder, new SecretKeySpec(record.getAesKey(), "AES"), url, this, mUser);
if (results[i] == FormUploadResult.FULL_SUCCESS) {
logSubmissionSuccess(record);
break;
} else {
attemptsMade++;
}
}
if (results[i] == FormUploadResult.RECORD_FAILURE) {
//We tried to submit multiple times and there was a local problem (not a remote problem).
//This implies that something is wrong with the current record, and we need to quarantine it.
processor.updateRecordStatus(record, FormRecord.STATUS_LIMBO);
Logger.log(AndroidLogger.TYPE_ERROR_STORAGE, "Quarantined Form Record");
CommCareApplication.notificationManager().reportNotificationMessage(NotificationMessageFactory.message(ProcessIssues.RecordQuarantined), true);
}
} catch (FileNotFoundException e) {
if (CommCareApplication.instance().isStorageAvailable()) {
//If storage is available generally, this is a bug in the app design
// Log with two tags so we can track more easily
Logger.log(AndroidLogger.SOFT_ASSERT,
String.format("Removed form record with id %s because file was missing| %s",
record.getInstanceID(), getExceptionText(e)));
Logger.log(AndroidLogger.TYPE_FORM_SUBMISSION,
String.format("Removed form record with id %s because file was missing| %s",
record.getInstanceID(), getExceptionText(e)));
CommCareApplication.notificationManager().reportNotificationMessage(
NotificationMessageFactory.message(ProcessIssues.RecordFilesMissing), true);
FormRecordCleanupTask.wipeRecord(c, record);
} else {
//Otherwise, the SD card just got removed, and we need to bail anyway.
CommCareApplication.notificationManager().reportNotificationMessage(
NotificationMessageFactory.message(ProcessIssues.StorageRemoved), true);
break;
}
continue;
}
Profile p = CommCareApplication.instance().getCommCarePlatform().getCurrentProfile();
//Check for success
if (results[i] == FormUploadResult.FULL_SUCCESS) {
//Only delete if this device isn't set up to review.
if (p == null || !p.isFeatureActive(Profile.FEATURE_REVIEW)) {
FormRecordCleanupTask.wipeRecord(c, record);
} else {
//Otherwise save and move appropriately
processor.updateRecordStatus(record, FormRecord.STATUS_SAVED);
}
}
} else {
results[i] = FormUploadResult.FULL_SUCCESS;
}
} catch (SessionUnavailableException sue) {
throw sue;
} catch (Exception e) {
//Just try to skip for now. Hopefully this doesn't wreck the model :/
Logger.log(AndroidLogger.TYPE_ERROR_DESIGN, "Totally Unexpected Error during form submission" + getExceptionText(e));
}
}
}
private static void logSubmissionAttempt(FormRecord record) {
String attemptMesssage = String.format(
"Attempting to submit form with id %1$s and submission ordering number %2$s",
record.getInstanceID(),
record.getSubmissionOrderingNumber());
Logger.log(AndroidLogger.TYPE_FORM_SUBMISSION, attemptMesssage);
}
private static void logSubmissionSuccess(FormRecord record) {
String successMessage = String.format(
"Successfully submitted form with id %1$s and submission ordering number %2$s",
record.getInstanceID(),
record.getSubmissionOrderingNumber());
Logger.log(AndroidLogger.TYPE_FORM_SUBMISSION, successMessage);
}
public static int pending() {
synchronized (processTasks) {
return processTasks.size();
}
}
@Override
protected void onProgressUpdate(Long... values) {
if (values.length == 1 && values[0] == PROGRESS_ALL_PROCESSED) {
this.transitionPhase(sendTaskId);
}
super.onProgressUpdate(values);
if (values.length > 0) {
if (values[0] == SUBMISSION_BEGIN) {
dispatchBeginSubmissionProcessToListeners(values[1].intValue());
} else if (values[0] == SUBMISSION_START) {
int item = values[1].intValue();
long size = values[2];
dispatchStartSubmissionToListeners(item, size);
} else if (values[0] == SUBMISSION_NOTIFY) {
int item = values[1].intValue();
long progress = values[2];
dispatchNotifyProgressToListeners(item, progress);
} else if (values[0] == SUBMISSION_DONE) {
dispatchEndSubmissionProcessToListeners(values[1] == SUBMISSION_SUCCESS);
}
}
}
public void addProgressBarSubmissionListener(FormSubmissionProgressBarListener listener) {
this.progressBarListener = listener;
addSubmissionListener(listener);
}
public void addSubmissionListener(DataSubmissionListener submissionListener) {
formSubmissionListeners.add(submissionListener);
}
private void dispatchBeginSubmissionProcessToListeners(int totalItems) {
for (DataSubmissionListener listener : formSubmissionListeners) {
listener.beginSubmissionProcess(totalItems);
}
}
private void dispatchStartSubmissionToListeners(int itemNumber, long length) {
for (DataSubmissionListener listener : formSubmissionListeners) {
listener.startSubmission(itemNumber, length);
}
}
private void dispatchNotifyProgressToListeners(int itemNumber, long progress) {
for (DataSubmissionListener listener : formSubmissionListeners) {
listener.notifyProgress(itemNumber, progress);
}
}
private void dispatchEndSubmissionProcessToListeners(boolean success) {
for (DataSubmissionListener listener : formSubmissionListeners) {
listener.endSubmissionProcess(success);
}
}
@Override
protected void onPostExecute(FormUploadResult result) {
super.onPostExecute(result);
clearState();
}
private void clearState() {
c = null;
url = null;
results = null;
}
protected int getSuccessfulSends() {
int successes = 0;
for (FormUploadResult formResult : results) {
if (formResult != null && FormUploadResult.FULL_SUCCESS == formResult) {
successes++;
}
}
return successes;
}
//Wrappers for the internal stuff
@Override
public void beginSubmissionProcess(int totalItems) {
this.publishProgress(SUBMISSION_BEGIN, (long)totalItems);
}
@Override
public void startSubmission(int itemNumber, long sizeOfItem) {
this.publishProgress(SUBMISSION_START, (long)itemNumber, sizeOfItem);
}
@Override
public void notifyProgress(int itemNumber, long progress) {
this.publishProgress(SUBMISSION_NOTIFY, (long)itemNumber, progress);
}
@Override
public void endSubmissionProcess(boolean success) {
if (success) {
this.publishProgress(SUBMISSION_DONE, SUBMISSION_SUCCESS);
} else {
this.publishProgress(SUBMISSION_DONE, SUBMISSION_FAIL);
}
}
private String getExceptionText(Exception e) {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
e.printStackTrace(new PrintStream(bos));
return new String(bos.toByteArray());
} catch (Exception ex) {
return null;
}
}
@Override
protected void onCancelled() {
super.onCancelled();
dispatchEndSubmissionProcessToListeners(false);
CommCareApplication.notificationManager().reportNotificationMessage(NotificationMessageFactory.message(ProcessIssues.LoggedOut));
clearState();
}
@Override
public void connect(CommCareTaskConnector<R> connector) {
super.connect(connector);
if (progressBarListener != null) {
progressBarListener.attachToNewActivity(
(SyncCapableCommCareActivity)connector.getReceiver());
}
}
private static class TaskCancelledException extends Exception {
}
}
| app/src/org/commcare/tasks/ProcessAndSendTask.java | package org.commcare.tasks;
import android.content.Context;
import android.os.AsyncTask;
import org.commcare.CommCareApplication;
import org.commcare.activities.SyncCapableCommCareActivity;
import org.commcare.logging.AndroidLogger;
import org.commcare.models.FormRecordProcessor;
import org.commcare.android.database.user.models.FormRecord;
import org.commcare.suite.model.Profile;
import org.commcare.tasks.templates.CommCareTask;
import org.commcare.tasks.templates.CommCareTaskConnector;
import org.commcare.utils.FormUploadResult;
import org.commcare.utils.FormUploadUtil;
import org.commcare.utils.SessionUnavailableException;
import org.commcare.views.notifications.NotificationMessageFactory;
import org.commcare.views.notifications.ProcessIssues;
import org.javarosa.core.model.User;
import org.javarosa.core.services.Logger;
import org.javarosa.xml.util.InvalidStructureException;
import org.javarosa.xml.util.UnfullfilledRequirementsException;
import org.xmlpull.v1.XmlPullParserException;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import javax.crypto.spec.SecretKeySpec;
/**
* @author ctsims
*/
public abstract class ProcessAndSendTask<R> extends CommCareTask<FormRecord, Long, FormUploadResult, R> implements DataSubmissionListener {
private Context c;
private String url;
private FormUploadResult[] results;
private final int sendTaskId;
public static final int PROCESSING_PHASE_ID = 8;
public static final int SEND_PHASE_ID = 9;
public static final int PROCESSING_PHASE_ID_NO_DIALOG = -8;
public static final int SEND_PHASE_ID_NO_DIALOG = -9;
public static final long PROGRESS_ALL_PROCESSED = 8;
public static final long SUBMISSION_BEGIN = 16;
public static final long SUBMISSION_START = 32;
public static final long SUBMISSION_NOTIFY = 64;
public static final long SUBMISSION_DONE = 128;
private static final long SUBMISSION_SUCCESS = 1;
private static final long SUBMISSION_FAIL = 0;
private FormSubmissionProgressBarListener progressBarListener;
private List<DataSubmissionListener> formSubmissionListeners;
private final FormRecordProcessor processor;
private static final int SUBMISSION_ATTEMPTS = 2;
private static final Queue<ProcessAndSendTask> processTasks = new LinkedList<>();
public ProcessAndSendTask(Context c, String url) {
this(c, url, true);
}
/**
* @param inSyncMode blocks the user with a sync dialog
*/
public ProcessAndSendTask(Context c, String url, boolean inSyncMode) {
this.c = c;
this.url = url;
this.processor = new FormRecordProcessor(c);
this.formSubmissionListeners = new ArrayList<>();
if (inSyncMode) {
this.sendTaskId = SEND_PHASE_ID;
this.taskId = PROCESSING_PHASE_ID;
} else {
this.sendTaskId = SEND_PHASE_ID_NO_DIALOG;
this.taskId = PROCESSING_PHASE_ID_NO_DIALOG;
}
}
@Override
protected FormUploadResult doTaskBackground(FormRecord... records) {
boolean needToSendLogs = false;
try {
results = new FormUploadResult[records.length];
for (int i = 0; i < records.length; ++i) {
//Assume failure
results[i] = FormUploadResult.FAILURE;
}
//The first thing we need to do is make sure everything is processed,
//we can't actually proceed before that.
try {
needToSendLogs = checkFormRecordStatus(records);
} catch (FileNotFoundException e) {
return FormUploadResult.PROGRESS_SDCARD_REMOVED;
} catch (TaskCancelledException e) {
return FormUploadResult.FAILURE;
}
this.publishProgress(PROGRESS_ALL_PROCESSED);
//Put us on the queue!
synchronized (processTasks) {
processTasks.add(this);
}
boolean needToRefresh;
try {
needToRefresh = blockUntilTopOfQueue();
} catch (TaskCancelledException e) {
return FormUploadResult.FAILURE;
}
if (needToRefresh) {
//There was another activity before this one. Refresh our models in case
//they were updated
for (int i = 0; i < records.length; ++i) {
int dbId = records[i].getID();
records[i] = processor.getRecord(dbId);
}
}
// Ok, all forms are now processed. Time to focus on sending
dispatchBeginSubmissionProcessToListeners(records.length);
sendForms(records);
return FormUploadResult.getWorstResult(results);
} catch (SessionUnavailableException sue) {
this.cancel(false);
return FormUploadResult.PROGRESS_LOGGED_OUT;
} finally {
this.endSubmissionProcess(
FormUploadResult.FULL_SUCCESS.equals(FormUploadResult.getWorstResult(results)));
synchronized (processTasks) {
processTasks.remove(this);
}
if (needToSendLogs) {
CommCareApplication.instance().notifyLogsPending();
}
}
}
private boolean checkFormRecordStatus(FormRecord[] records)
throws FileNotFoundException, TaskCancelledException {
boolean needToSendLogs = false;
processor.beginBulkSubmit();
for (int i = 0; i < records.length; ++i) {
if (isCancelled()) {
throw new TaskCancelledException();
}
FormRecord record = records[i];
//If the form is complete, but unprocessed, process it.
if (FormRecord.STATUS_COMPLETE.equals(record.getStatus())) {
try {
records[i] = processor.process(record);
} catch (InvalidStructureException e) {
CommCareApplication.notificationManager().reportNotificationMessage(NotificationMessageFactory.message(ProcessIssues.BadTransactions), true);
Logger.log(AndroidLogger.TYPE_ERROR_DESIGN, "Removing form record due to transaction data|" + getExceptionText(e));
FormRecordCleanupTask.wipeRecord(c, record);
needToSendLogs = true;
} catch (XmlPullParserException e) {
CommCareApplication.notificationManager().reportNotificationMessage(NotificationMessageFactory.message(ProcessIssues.BadTransactions), true);
Logger.log(AndroidLogger.TYPE_ERROR_DESIGN, "Removing form record due to bad xml|" + getExceptionText(e));
FormRecordCleanupTask.wipeRecord(c, record);
needToSendLogs = true;
} catch (UnfullfilledRequirementsException e) {
CommCareApplication.notificationManager().reportNotificationMessage(NotificationMessageFactory.message(ProcessIssues.BadTransactions), true);
Logger.log(AndroidLogger.TYPE_ERROR_DESIGN, "Removing form record due to bad requirements|" + getExceptionText(e));
FormRecordCleanupTask.wipeRecord(c, record);
needToSendLogs = true;
} catch (FileNotFoundException e) {
if (CommCareApplication.instance().isStorageAvailable()) {
//If storage is available generally, this is a bug in the app design
Logger.log(AndroidLogger.TYPE_ERROR_DESIGN, "Removing form record because file was missing|" + getExceptionText(e));
FormRecordCleanupTask.wipeRecord(c, record);
} else {
CommCareApplication.notificationManager().reportNotificationMessage(NotificationMessageFactory.message(ProcessIssues.StorageRemoved), true);
//Otherwise, the SD card just got removed, and we need to bail anyway.
throw e;
}
} catch (IOException e) {
Logger.log(AndroidLogger.TYPE_ERROR_WORKFLOW, "IO Issues processing a form. Tentatively not removing in case they are resolvable|" + getExceptionText(e));
}
}
}
processor.closeBulkSubmit();
return needToSendLogs;
}
private boolean blockUntilTopOfQueue() throws TaskCancelledException {
boolean needToRefresh = false;
while (true) {
//See if it's our turn to go
synchronized (processTasks) {
if (isCancelled()) {
processTasks.remove(this);
throw new TaskCancelledException();
}
//Are we at the head of the queue?
ProcessAndSendTask head = processTasks.peek();
if (head == this) {
break;
}
//Otherwise, is the head of the queue busted?
//*sigh*. Apparently Cancelled doesn't result in the task status being set
//to !Running for reasons which baffle me.
if (head.getStatus() != AsyncTask.Status.RUNNING || head.isCancelled()) {
//If so, get rid of it
processTasks.poll();
}
}
//If it's not yet quite our turn, take a nap
try {
needToRefresh = true;
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return needToRefresh;
}
private void sendForms(FormRecord[] records) {
for (int i = 0; i < records.length; ++i) {
//See whether we are OK to proceed based on the last form. We're now guaranteeing
//that forms are sent in order, so we won't proceed unless we succeed. We'll also permit
//proceeding if there was a local problem with a record, since we'll just move on from that
//processing.
if (i > 0 && !(results[i - 1] == FormUploadResult.FULL_SUCCESS || results[i - 1] == FormUploadResult.RECORD_FAILURE)) {
//Something went wrong with the last form, so we need to cancel this whole shebang
Logger.log(AndroidLogger.TYPE_WARNING_NETWORK, "Cancelling submission due to network errors. " + (i - 1) + " forms succesfully sent.");
break;
}
FormRecord record = records[i];
try {
//If it's unsent, go ahead and send it
if (FormRecord.STATUS_UNSENT.equals(record.getStatus())) {
File folder;
try {
folder = new File(record.getPath(c)).getCanonicalFile().getParentFile();
} catch (IOException e) {
Logger.log(AndroidLogger.TYPE_ERROR_WORKFLOW, "Bizarre. Exception just getting the file reference. Not removing." + getExceptionText(e));
continue;
}
//Good!
//Time to Send!
try {
User mUser = CommCareApplication.instance().getSession().getLoggedInUser();
int attemptsMade = 0;
while (attemptsMade < SUBMISSION_ATTEMPTS) {
if (attemptsMade > 0) {
Logger.log(AndroidLogger.TYPE_WARNING_NETWORK, "Retrying submission. " + (SUBMISSION_ATTEMPTS - attemptsMade) + " attempts remain");
}
results[i] = FormUploadUtil.sendInstance(i, folder, new SecretKeySpec(record.getAesKey(), "AES"), url, this, mUser);
if (results[i] == FormUploadResult.FULL_SUCCESS) {
String submitLogMessage = String.format(
"Successfully submitted form with id %1$s and submission ordering number %2$s",
record.getInstanceID(),
record.getSubmissionOrderingNumber());
Logger.log(AndroidLogger.TYPE_FORM_SUBMISSION, submitLogMessage);
break;
} else {
attemptsMade++;
}
}
if (results[i] == FormUploadResult.RECORD_FAILURE) {
//We tried to submit multiple times and there was a local problem (not a remote problem).
//This implies that something is wrong with the current record, and we need to quarantine it.
processor.updateRecordStatus(record, FormRecord.STATUS_LIMBO);
Logger.log(AndroidLogger.TYPE_ERROR_STORAGE, "Quarantined Form Record");
CommCareApplication.notificationManager().reportNotificationMessage(NotificationMessageFactory.message(ProcessIssues.RecordQuarantined), true);
}
} catch (FileNotFoundException e) {
if (CommCareApplication.instance().isStorageAvailable()) {
//If storage is available generally, this is a bug in the app design
// Log with two tags so we can track more easily
Logger.log(AndroidLogger.SOFT_ASSERT,
String.format("Removed form record with id %s because file was missing| %s",
record.getInstanceID(), getExceptionText(e)));
Logger.log(AndroidLogger.TYPE_FORM_SUBMISSION,
String.format("Removed form record with id %s because file was missing| %s",
record.getInstanceID(), getExceptionText(e)));
CommCareApplication.notificationManager().reportNotificationMessage(
NotificationMessageFactory.message(ProcessIssues.RecordFilesMissing), true);
FormRecordCleanupTask.wipeRecord(c, record);
} else {
//Otherwise, the SD card just got removed, and we need to bail anyway.
CommCareApplication.notificationManager().reportNotificationMessage(
NotificationMessageFactory.message(ProcessIssues.StorageRemoved), true);
break;
}
continue;
}
Profile p = CommCareApplication.instance().getCommCarePlatform().getCurrentProfile();
//Check for success
if (results[i] == FormUploadResult.FULL_SUCCESS) {
//Only delete if this device isn't set up to review.
if (p == null || !p.isFeatureActive(Profile.FEATURE_REVIEW)) {
FormRecordCleanupTask.wipeRecord(c, record);
} else {
//Otherwise save and move appropriately
processor.updateRecordStatus(record, FormRecord.STATUS_SAVED);
}
}
} else {
results[i] = FormUploadResult.FULL_SUCCESS;
}
} catch (SessionUnavailableException sue) {
throw sue;
} catch (Exception e) {
//Just try to skip for now. Hopefully this doesn't wreck the model :/
Logger.log(AndroidLogger.TYPE_ERROR_DESIGN, "Totally Unexpected Error during form submission" + getExceptionText(e));
}
}
}
public static int pending() {
synchronized (processTasks) {
return processTasks.size();
}
}
@Override
protected void onProgressUpdate(Long... values) {
if (values.length == 1 && values[0] == PROGRESS_ALL_PROCESSED) {
this.transitionPhase(sendTaskId);
}
super.onProgressUpdate(values);
if (values.length > 0) {
if (values[0] == SUBMISSION_BEGIN) {
dispatchBeginSubmissionProcessToListeners(values[1].intValue());
} else if (values[0] == SUBMISSION_START) {
int item = values[1].intValue();
long size = values[2];
dispatchStartSubmissionToListeners(item, size);
} else if (values[0] == SUBMISSION_NOTIFY) {
int item = values[1].intValue();
long progress = values[2];
dispatchNotifyProgressToListeners(item, progress);
} else if (values[0] == SUBMISSION_DONE) {
dispatchEndSubmissionProcessToListeners(values[1] == SUBMISSION_SUCCESS);
}
}
}
public void addProgressBarSubmissionListener(FormSubmissionProgressBarListener listener) {
this.progressBarListener = listener;
addSubmissionListener(listener);
}
public void addSubmissionListener(DataSubmissionListener submissionListener) {
formSubmissionListeners.add(submissionListener);
}
private void dispatchBeginSubmissionProcessToListeners(int totalItems) {
for (DataSubmissionListener listener : formSubmissionListeners) {
listener.beginSubmissionProcess(totalItems);
}
}
private void dispatchStartSubmissionToListeners(int itemNumber, long length) {
for (DataSubmissionListener listener : formSubmissionListeners) {
listener.startSubmission(itemNumber, length);
}
}
private void dispatchNotifyProgressToListeners(int itemNumber, long progress) {
for (DataSubmissionListener listener : formSubmissionListeners) {
listener.notifyProgress(itemNumber, progress);
}
}
private void dispatchEndSubmissionProcessToListeners(boolean success) {
for (DataSubmissionListener listener : formSubmissionListeners) {
listener.endSubmissionProcess(success);
}
}
@Override
protected void onPostExecute(FormUploadResult result) {
super.onPostExecute(result);
clearState();
}
private void clearState() {
c = null;
url = null;
results = null;
}
protected int getSuccessfulSends() {
int successes = 0;
for (FormUploadResult formResult : results) {
if (formResult != null && FormUploadResult.FULL_SUCCESS == formResult) {
successes++;
}
}
return successes;
}
//Wrappers for the internal stuff
@Override
public void beginSubmissionProcess(int totalItems) {
this.publishProgress(SUBMISSION_BEGIN, (long)totalItems);
}
@Override
public void startSubmission(int itemNumber, long sizeOfItem) {
this.publishProgress(SUBMISSION_START, (long)itemNumber, sizeOfItem);
}
@Override
public void notifyProgress(int itemNumber, long progress) {
this.publishProgress(SUBMISSION_NOTIFY, (long)itemNumber, progress);
}
@Override
public void endSubmissionProcess(boolean success) {
if (success) {
this.publishProgress(SUBMISSION_DONE, SUBMISSION_SUCCESS);
} else {
this.publishProgress(SUBMISSION_DONE, SUBMISSION_FAIL);
}
}
private String getExceptionText(Exception e) {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
e.printStackTrace(new PrintStream(bos));
return new String(bos.toByteArray());
} catch (Exception ex) {
return null;
}
}
@Override
protected void onCancelled() {
super.onCancelled();
dispatchEndSubmissionProcessToListeners(false);
CommCareApplication.notificationManager().reportNotificationMessage(NotificationMessageFactory.message(ProcessIssues.LoggedOut));
clearState();
}
@Override
public void connect(CommCareTaskConnector<R> connector) {
super.connect(connector);
if (progressBarListener != null) {
progressBarListener.attachToNewActivity(
(SyncCapableCommCareActivity)connector.getReceiver());
}
}
private static class TaskCancelledException extends Exception {
}
}
| enhance logging
| app/src/org/commcare/tasks/ProcessAndSendTask.java | enhance logging | <ide><path>pp/src/org/commcare/tasks/ProcessAndSendTask.java
<ide> //Time to Send!
<ide> try {
<ide> User mUser = CommCareApplication.instance().getSession().getLoggedInUser();
<del>
<ide> int attemptsMade = 0;
<add> logSubmissionAttempt(record);
<ide> while (attemptsMade < SUBMISSION_ATTEMPTS) {
<ide> if (attemptsMade > 0) {
<ide> Logger.log(AndroidLogger.TYPE_WARNING_NETWORK, "Retrying submission. " + (SUBMISSION_ATTEMPTS - attemptsMade) + " attempts remain");
<ide> }
<ide> results[i] = FormUploadUtil.sendInstance(i, folder, new SecretKeySpec(record.getAesKey(), "AES"), url, this, mUser);
<ide> if (results[i] == FormUploadResult.FULL_SUCCESS) {
<del> String submitLogMessage = String.format(
<del> "Successfully submitted form with id %1$s and submission ordering number %2$s",
<del> record.getInstanceID(),
<del> record.getSubmissionOrderingNumber());
<del> Logger.log(AndroidLogger.TYPE_FORM_SUBMISSION, submitLogMessage);
<add> logSubmissionSuccess(record);
<ide> break;
<ide> } else {
<ide> attemptsMade++;
<ide> }
<ide> }
<ide>
<add> private static void logSubmissionAttempt(FormRecord record) {
<add> String attemptMesssage = String.format(
<add> "Attempting to submit form with id %1$s and submission ordering number %2$s",
<add> record.getInstanceID(),
<add> record.getSubmissionOrderingNumber());
<add> Logger.log(AndroidLogger.TYPE_FORM_SUBMISSION, attemptMesssage);
<add> }
<add>
<add> private static void logSubmissionSuccess(FormRecord record) {
<add> String successMessage = String.format(
<add> "Successfully submitted form with id %1$s and submission ordering number %2$s",
<add> record.getInstanceID(),
<add> record.getSubmissionOrderingNumber());
<add> Logger.log(AndroidLogger.TYPE_FORM_SUBMISSION, successMessage);
<add> }
<add>
<ide> public static int pending() {
<ide> synchronized (processTasks) {
<ide> return processTasks.size(); |
|
JavaScript | mit | c5fe2d44fb26859fc5b96ba5e2453455bc328f37 | 0 | TheOnlyArtz/may | /**
*@function {fetchSongData} fetching data from the video to play it
*@function {checkGuildVC} Check if the bot connects to a voice channel in the guild
*/
const fetchSongData = require('../functions/music/fetchSongData.js');
const checkGuildVC = require('../functions/music/checkGuildVC.js');
exports.run = async (client,msg,args) => {
let searchTerms = args.join(' ');
let videoId = await fetchSongData(client, msg, searchTerms);
await checkGuildVC(client, msg);
};
exports.help = {
category: 'music',
usage: '[Link or Term]',
description: 'Play music',
detail: 'Play music while you are in a voicechannel',
botPerm : ['SEND_MESSAGES', 'EMBED_LINKS', 'CONNECT', 'SPEAK', 'USE_VAD'],
authorPerm : [],
alias : [
'm p'
]
};
| commands/play.js | /**
*@function {fetchSongData} fetching data from the video to play it
*/
const fetchSongData = require('../functions/music/fetchSongData.js');
exports.run = async (client,msg,args) => {
let searchTerms = args.join(' ');
let videoId = await fetchSongData(client, msg, searchTerms);
if (videoId) {
if (!this.message.guild.voiceConnection) {
this.message.member.voiceChannel.join()
.then(async connection => {
logger.info(`Started to stream ${chalk.magenta(r.body.items[0].title)} for ${this.message.author.username}`);
play(connection, this.message);
});
}
} else {
return;
}
};
exports.help = {
category: 'music',
usage: '[Link or Term]',
description: 'Play music',
detail: 'Play music while you are in a voicechannel',
botPerm : ['SEND_MESSAGES', 'EMBED_LINKS', 'CONNECT', 'SPEAK', 'USE_VAD'],
authorPerm : [],
alias : [
'm p'
]
};
| Moved to new function
| commands/play.js | Moved to new function | <ide><path>ommands/play.js
<ide> /**
<ide> *@function {fetchSongData} fetching data from the video to play it
<add>*@function {checkGuildVC} Check if the bot connects to a voice channel in the guild
<ide> */
<add>
<ide> const fetchSongData = require('../functions/music/fetchSongData.js');
<add>const checkGuildVC = require('../functions/music/checkGuildVC.js');
<add>
<ide> exports.run = async (client,msg,args) => {
<ide> let searchTerms = args.join(' ');
<ide> let videoId = await fetchSongData(client, msg, searchTerms);
<del>
<del> if (videoId) {
<del> if (!this.message.guild.voiceConnection) {
<del> this.message.member.voiceChannel.join()
<del> .then(async connection => {
<del> logger.info(`Started to stream ${chalk.magenta(r.body.items[0].title)} for ${this.message.author.username}`);
<del> play(connection, this.message);
<del> });
<del> }
<del>
<del> } else {
<del> return;
<del> }
<add> await checkGuildVC(client, msg);
<ide> };
<ide>
<ide> exports.help = { |
|
Java | apache-2.0 | a77dfb0cbb7b2d0b04668c55568f60198c994f65 | 0 | krosenvold/AxonFramework,bojanv55/AxonFramework,AxonFramework/AxonFramework,adinath/AxonFramework,Cosium/AxonFramework | /*
* Copyright (c) 2010-2016. Axon Framework
* 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.axonframework.eventsourcing.eventstore;
import org.axonframework.eventsourcing.DomainEventMessage;
import org.axonframework.serialization.Serializer;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
/**
* Abstract base class of a serialized domain event. Fields in this class contain JPA annotations that direct JPA event
* storage engines how to store event entries.
*
* @author Rene de Waele
*/
@MappedSuperclass
public abstract class AbstractSequencedDomainEventEntry<T> extends AbstractDomainEventEntry<T> implements DomainEventData<T> {
@Id
@GeneratedValue
@SuppressWarnings("unused")
private long globalIndex;
/**
* Construct a new default domain event entry from a published domain event message to enable storing the event or
* sending it to a remote location. The event payload and metadata will be serialized to a byte array.
* <p>
* The given {@code serializer} will be used to serialize the payload and metadata in the given {@code
* eventMessage}. The type of the serialized data will be the same as the given {@code contentType}.
*
* @param eventMessage The event message to convert to a serialized event entry
* @param serializer The serializer to convert the event
* @param contentType The data type of the payload and metadata after serialization
*/
public AbstractSequencedDomainEventEntry(DomainEventMessage<?> eventMessage, Serializer serializer,
Class<T> contentType) {
super(eventMessage, serializer, contentType);
}
/**
* Default constructor required by JPA
*/
protected AbstractSequencedDomainEventEntry() {
}
}
| core/src/main/java/org/axonframework/eventsourcing/eventstore/AbstractSequencedDomainEventEntry.java | /*
* Copyright (c) 2010-2016. Axon Framework
* 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.axonframework.eventsourcing.eventstore;
import org.axonframework.eventsourcing.DomainEventMessage;
import org.axonframework.serialization.Serializer;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
/**
* Abstract base class of a serialized domain event. Fields in this class contain JPA annotations that direct JPA event
* storage engines how to store event entries.
*
* @author Rene de Waele
*/
@MappedSuperclass
public abstract class AbstractSequencedDomainEventEntry<T> extends AbstractDomainEventEntry<T> implements DomainEventData<T> {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@SuppressWarnings("unused")
private long globalIndex;
/**
* Construct a new default domain event entry from a published domain event message to enable storing the event or
* sending it to a remote location. The event payload and metadata will be serialized to a byte array.
* <p>
* The given {@code serializer} will be used to serialize the payload and metadata in the given {@code
* eventMessage}. The type of the serialized data will be the same as the given {@code contentType}.
*
* @param eventMessage The event message to convert to a serialized event entry
* @param serializer The serializer to convert the event
* @param contentType The data type of the payload and metadata after serialization
*/
public AbstractSequencedDomainEventEntry(DomainEventMessage<?> eventMessage, Serializer serializer,
Class<T> contentType) {
super(eventMessage, serializer, contentType);
}
/**
* Default constructor required by JPA
*/
protected AbstractSequencedDomainEventEntry() {
}
}
| Removed requirement for "identity" type auto generated ID
Instead, using "auto" (the default), since certain databases do not support 'identity' (such as Oracle)
| core/src/main/java/org/axonframework/eventsourcing/eventstore/AbstractSequencedDomainEventEntry.java | Removed requirement for "identity" type auto generated ID | <ide><path>ore/src/main/java/org/axonframework/eventsourcing/eventstore/AbstractSequencedDomainEventEntry.java
<ide> public abstract class AbstractSequencedDomainEventEntry<T> extends AbstractDomainEventEntry<T> implements DomainEventData<T> {
<ide>
<ide> @Id
<del> @GeneratedValue(strategy = GenerationType.IDENTITY)
<add> @GeneratedValue
<ide> @SuppressWarnings("unused")
<ide> private long globalIndex;
<ide> |
|
Java | apache-2.0 | 0a2a182806f3012cb31b0aea78ccf9526d61577f | 0 | akjava/gwt-three.js-test,akjava/gwt-three.js-test,akjava/gwt-three.js-test | /*
* gwt-wrap three.js
*
* Copyright (c) 2011 [email protected]
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.
based Three.js r45
https://github.com/mrdoob/three.js
The MIT License
Copyright (c) 2010-2011 three.js Authors. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package com.akjava.gwt.three.client.js.math;
import com.akjava.gwt.three.client.gwt.core.Intersect;
import com.akjava.gwt.three.client.js.core.Object3D;
import com.akjava.gwt.three.client.js.scenes.Scene;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArray;
public class Ray extends JavaScriptObject{
protected Ray(){}
public final native Vector3 getOrigin()/*-{
return this.origin;
}-*/;
public final native Vector3 getDirection()/*-{
return this.direction;
}-*/;
public final native Ray set(Vector3 origin,Vector3 direction)/*-{
return this.set(origin,direction);
}-*/;
public final native Ray copy(Ray ray)/*-{
return this.copy(ray);
}-*/;
public final native Vector3 at(double t,Vector3 optionalTarget)/*-{
return this.at(t,optionalTarget);
}-*/;
public final native Ray recast(double t)/*-{
return this.recast();
}-*/;
public final native Vector3 closestPointToPoint(Vector3 point,Vector3 optionalTarget)/*-{
return this.closestPointToPoint(point,optionalTarget);
}-*/;
public final native double distanceToPoint(Vector3 point)/*-{
return this.distanceToPoint(point);
}-*/;
public final native double distanceSqToSegment(Vector3 v0,Vector3 v1,Vector3 optionalPointOnRay,Vector3 optionalPointOnSegment)/*-{
return this.distanceSqToSegment(v0,v1,optionalPointOnRay,optionalPointOnSegment);
}-*/;
public final native boolean isIntersectionSphere(Sphere sphere)/*-{
return this.isIntersectionSphere(sphere);
}-*/;
public final native boolean isIntersectionPlane(Plane plane)/*-{
return this.isIntersectionPlane(plane);
}-*/;
public final native Double distanceToPlane(Plane plane)/*-{
return this.distanceToPlane(plane);
}-*/;
public final native Vector3 intersectPlane(Plane plane,Vector3 optionalTarget)/*-{
return this.intersectPlane(plane,optionalTarget);
}-*/;
public final native boolean isIntersectionBox(Box3 box)/*-{
return this.isIntersectionBox(box);
}-*/;
public final native Vector3 intersectBox(Box3 box,Vector3 optionalTarget)/*-{
return this.intersectBox(box,optionalTarget);
}-*/;
public final native Vector3 intersectTriangle(Vector3 a,Vector3 b,Vector3 c,boolean backfaceCulling,Vector3 optionalTarget)/*-{
return this.intersectTriangle();
}-*/;
public final native Ray applyMatrix4(Matrix4 matrix4)/*-{
return this.applyMatrix4(matrix4);
}-*/;
public final native boolean equals(Ray ray)/*-{
return this.equals(ray);
}-*/;
/**
* @deprecated?
*/
public final native JsArray<Intersect> intersectScene(Scene scene)/*-{
return this.intersectScene( scene );
}-*/;
/**
* @deprecated?
*/
public final native JsArray<Intersect> intersectObjects(JsArray<Object3D> objects)/*-{
return this.intersectObjects( objects );
}-*/;
/**
* @deprecated?
*/
public final native JsArray<Intersect> intersectObject(Object3D object)/*-{
return this.intersectObject( object );
}-*/;
public final native Vector3 intersectSphere (Sphere sphere,Vector3 optionalTarget)/*-{
return this.intersectSphere(sphere,optionalTarget);
}-*/;
public final native Ray clone()/*-{
return this.clone();
}-*/;
public final native double distanceSqToPoint(Vector3 point)/*-{
return this.distanceSqToPoint(point);
}-*/;
}
| src/com/akjava/gwt/three/client/js/math/Ray.java | /*
* gwt-wrap three.js
*
* Copyright (c) 2011 [email protected]
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.
based Three.js r45
https://github.com/mrdoob/three.js
The MIT License
Copyright (c) 2010-2011 three.js Authors. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package com.akjava.gwt.three.client.js.math;
import com.akjava.gwt.three.client.gwt.core.Intersect;
import com.akjava.gwt.three.client.js.core.Object3D;
import com.akjava.gwt.three.client.js.scenes.Scene;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArray;
public class Ray extends JavaScriptObject{
protected Ray(){}
public final native Vector3 getOrigin()/*-{
return this.origin;
}-*/;
public final native Vector3 getDirection()/*-{
return this.direction;
}-*/;
public final native Ray set(Vector3 origin,Vector3 direction)/*-{
return this.set(origin,direction);
}-*/;
public final native Ray copy(Ray ray)/*-{
return this.copy(ray);
}-*/;
public final native Vector3 at(double t,Vector3 optionalTarget)/*-{
return this.at(t,optionalTarget);
}-*/;
public final native Ray recast(double t)/*-{
return this.recast();
}-*/;
public final native Vector3 closestPointToPoint(Vector3 point,Vector3 optionalTarget)/*-{
return this.closestPointToPoint(point,optionalTarget);
}-*/;
public final native double distanceToPoint(Vector3 point)/*-{
return this.distanceToPoint(point);
}-*/;
public final native double distanceSqToSegment(Vector3 v0,Vector3 v1,Vector3 optionalPointOnRay,Vector3 optionalPointOnSegment)/*-{
return this.distanceSqToSegment(v0,v1,optionalPointOnRay,optionalPointOnSegment);
}-*/;
public final native boolean isIntersectionSphere(Sphere sphere)/*-{
return this.isIntersectionSphere(sphere);
}-*/;
public final native boolean isIntersectionPlane(Plane plane)/*-{
return this.isIntersectionPlane(plane);
}-*/;
public final native Double distanceToPlane(Plane plane)/*-{
return this.distanceToPlane(plane);
}-*/;
public final native Vector3 intersectPlane(Plane plane,Vector3 optionalTarget)/*-{
return this.intersectPlane(plane,optionalTarget);
}-*/;
public final native boolean isIntersectionBox(Box3 box)/*-{
return this.isIntersectionBox(box);
}-*/;
public final native Vector3 intersectBox(Box3 box,Vector3 optionalTarget)/*-{
return this.intersectBox(box,optionalTarget);
}-*/;
public final native Vector3 intersectTriangle(Vector3 a,Vector3 b,Vector3 c,boolean backfaceCulling,Vector3 optionalTarget)/*-{
return this.intersectTriangle();
}-*/;
public final native Ray applyMatrix4(Matrix4 matrix4)/*-{
return this.applyMatrix4(matrix4);
}-*/;
public final native boolean equals(Ray ray)/*-{
return this.equals(ray);
}-*/;
/**
* @deprecated?
*/
public final native JsArray<Intersect> intersectScene(Scene scene)/*-{
return this.intersectScene( scene );
}-*/;
/**
* @deprecated?
*/
public final native JsArray<Intersect> intersectObjects(JsArray<Object3D> objects)/*-{
return this.intersectObjects( objects );
}-*/;
/**
* @deprecated?
*/
public final native JsArray<Intersect> intersectObject(Object3D object)/*-{
return this.intersectObject( object );
}-*/;
public final native Vector3 intersectSphere (Sphere sphere,Vector3 optionalTarget)/*-{
return this.intersectSphere(sphere,optionalTarget);
}-*/;
public final native Ray clone()/*-{
return this.clone();
}-*/;
}
| for r72 add distanceSqToPoint | src/com/akjava/gwt/three/client/js/math/Ray.java | for r72 add distanceSqToPoint | <ide><path>rc/com/akjava/gwt/three/client/js/math/Ray.java
<ide> public final native Ray clone()/*-{
<ide> return this.clone();
<ide> }-*/;
<add>
<add>public final native double distanceSqToPoint(Vector3 point)/*-{
<add>return this.distanceSqToPoint(point);
<add>}-*/;
<ide> } |
|
Java | apache-2.0 | 59d033079c136d9add589175922bdb8e5b9c5106 | 0 | AlSidorenko/Junior | package ru.job4j.array;
/**
* Package for Array.
*
* @author Aleks Sidorenko (mailto:[email protected])
* @version $Id$
* @since 0.1
*/
public class BubbleSort {
/**
*Sort - array.
*@param array - source array.
*@return - sort array.
*/
public int[] sort(int[] array) {
for (int i = 1; i < array.length; i++) {
for (int j = array.length - 1; j >= i; j--) {
if (array[j - 1] > array[j]) {
int temp = array[j - 1];
array[j - 1] = array[j];
array[j] = temp;
}
}
}
return array;
}
} | chapter_001/src/main/java/ru/job4j/array/BubbleSort.java | package ru.job4j.array;
/**
* Package for Array.
*
* @author Aleks Sidorenko (mailto:[email protected])
* @version $Id$
* @since 0.1
*/
public class BubbleSort {
/**
*Sort - array.
*@param array - source array.
*@return - sort array.
*/
public int[] sort(int[] array) {
int t;
for (int i = 1; i < array.length; i++) {
for (int j = array.length - 1; j >= i; j--) {
if (array[j - 1] > array[j]) {
t = array[j - 1];
array[j - 1] = array[j];
array[j] = t;
}
}
}
return array;
}
} | task 195
| chapter_001/src/main/java/ru/job4j/array/BubbleSort.java | task 195 | <ide><path>hapter_001/src/main/java/ru/job4j/array/BubbleSort.java
<ide> *@return - sort array.
<ide> */
<ide> public int[] sort(int[] array) {
<del> int t;
<ide> for (int i = 1; i < array.length; i++) {
<ide> for (int j = array.length - 1; j >= i; j--) {
<ide> if (array[j - 1] > array[j]) {
<del> t = array[j - 1];
<add> int temp = array[j - 1];
<ide> array[j - 1] = array[j];
<del> array[j] = t;
<add> array[j] = temp;
<ide> }
<ide> }
<ide> } |
|
Java | apache-2.0 | 1a10a1356b2a44e526d18494afabff0b663afe29 | 0 | apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere | /*
* 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.shardingsphere.proxy.backend.text.distsql.ral.common.show.executor;
import org.apache.shardingsphere.infra.merge.result.MergedResult;
import org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.status.compute.ComputeNodeStatus;
import org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.status.compute.node.ComputeStatusNode;
import org.apache.shardingsphere.mode.manager.cluster.coordinator.utils.IpUtils;
import org.apache.shardingsphere.mode.metadata.persist.MetaDataPersistService;
import org.apache.shardingsphere.proxy.backend.context.ProxyContext;
import org.apache.shardingsphere.proxy.backend.response.header.query.impl.QueryHeader;
import org.apache.shardingsphere.sharding.merge.dal.common.MultipleLocalDataMergedResult;
import java.sql.Types;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Show instance executor.
*/
public final class ShowInstanceExecutor extends AbstractShowExecutor {
private static final String DELIMITER = "@";
private static final String ID = "instance_id";
private static final String STATUS = "status";
private static final String DISABLE = "disable";
private static final String ENABLE = "enable";
@Override
protected List<QueryHeader> createQueryHeaders() {
return Arrays.asList(
new QueryHeader("", "", ID, ID, Types.VARCHAR, "VARCHAR", 64, 0, false, false, false, false),
new QueryHeader("", "", STATUS, STATUS, Types.VARCHAR, "VARCHAR", 64, 0, false, false, false, false)
);
}
@Override
protected MergedResult createMergedResult() {
MetaDataPersistService persistService = ProxyContext.getInstance().getContextManager().getMetaDataContexts().getMetaDataPersistService().orElse(null);
if (null == persistService || null == persistService.getRepository()) {
return new MultipleLocalDataMergedResult(buildInstanceRows());
}
Collection<List<Object>> rows = buildInstanceRows(persistService, ENABLE);
Collection<List<Object>> disableInstanceIds = buildInstanceRows(persistService, DISABLE);
if (!disableInstanceIds.isEmpty()) {
rows.addAll(disableInstanceIds);
}
return new MultipleLocalDataMergedResult(rows);
}
private Collection<List<Object>> buildInstanceRows() {
List<List<Object>> rows = new LinkedList<>();
// TODO port is not saved in metadata, add port after saving
String instanceId = String.join(DELIMITER, IpUtils.getIp(), " ");
rows.add(buildRow(instanceId, ENABLE));
return rows;
}
private Collection<List<Object>> buildInstanceRows(final MetaDataPersistService persistService, final String status) {
String statusPath = ComputeStatusNode.getStatusPath(status.equals(ENABLE) ? ComputeNodeStatus.ONLINE : ComputeNodeStatus.CIRCUIT_BREAKER);
List<String> instanceIds = persistService.getRepository().getChildrenKeys(statusPath);
if (!instanceIds.isEmpty()) {
return instanceIds.stream().filter(Objects::nonNull).map(each -> buildRow(each, status)).collect(Collectors.toCollection(LinkedList::new));
}
return Collections.emptyList();
}
private List<Object> buildRow(final String instanceId, final String status) {
return Stream.of(instanceId, status).map(each -> (Object) each).collect(Collectors.toCollection(LinkedList::new));
}
}
| shardingsphere-proxy/shardingsphere-proxy-backend/src/main/java/org/apache/shardingsphere/proxy/backend/text/distsql/ral/common/show/executor/ShowInstanceExecutor.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.shardingsphere.proxy.backend.text.distsql.ral.common.show.executor;
import org.apache.shardingsphere.infra.merge.result.MergedResult;
import org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.status.compute.ComputeNodeStatus;
import org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.status.compute.node.ComputeStatusNode;
import org.apache.shardingsphere.mode.manager.cluster.coordinator.utils.IpUtils;
import org.apache.shardingsphere.mode.metadata.persist.MetaDataPersistService;
import org.apache.shardingsphere.proxy.backend.context.ProxyContext;
import org.apache.shardingsphere.proxy.backend.response.header.query.impl.QueryHeader;
import org.apache.shardingsphere.sharding.merge.dal.common.MultipleLocalDataMergedResult;
import java.sql.Types;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
/**
* Show instance executor.
*/
public final class ShowInstanceExecutor extends AbstractShowExecutor {
private static final String DELIMITER = "@";
private static final String IP = "ip";
private static final String PORT = "port";
private static final String STATUS = "status";
private static final String DISABLE = "disable";
private static final String ENABLE = "enable";
@Override
protected List<QueryHeader> createQueryHeaders() {
return Arrays.asList(
new QueryHeader("", "", IP, IP, Types.VARCHAR, "VARCHAR", 64, 0, false, false, false, false),
new QueryHeader("", "", PORT, PORT, Types.VARCHAR, "VARCHAR", 64, 0, false, false, false, false),
new QueryHeader("", "", STATUS, STATUS, Types.VARCHAR, "VARCHAR", 64, 0, false, false, false, false)
);
}
@Override
protected MergedResult createMergedResult() {
MetaDataPersistService persistService = ProxyContext.getInstance().getContextManager().getMetaDataContexts().getMetaDataPersistService().orElse(null);
if (null == persistService || null == persistService.getRepository()) {
return new MultipleLocalDataMergedResult(buildInstanceRows());
}
Collection<List<Object>> rows = buildInstanceRows(persistService, ENABLE);
Collection<List<Object>> disableInstanceIds = buildInstanceRows(persistService, DISABLE);
if (!disableInstanceIds.isEmpty()) {
rows.addAll(disableInstanceIds);
}
return new MultipleLocalDataMergedResult(rows);
}
private Collection<List<Object>> buildInstanceRows() {
List<List<Object>> rows = new LinkedList<>();
// TODO port is not saved in metadata, add port after saving
String instanceId = String.join(DELIMITER, IpUtils.getIp(), " ");
rows.add(buildRow(instanceId, ENABLE));
return rows;
}
private Collection<List<Object>> buildInstanceRows(final MetaDataPersistService persistService, final String status) {
String statusPath = ComputeStatusNode.getStatusPath(status.equals(ENABLE) ? ComputeNodeStatus.ONLINE : ComputeNodeStatus.CIRCUIT_BREAKER);
List<String> instanceIds = persistService.getRepository().getChildrenKeys(statusPath);
if (!instanceIds.isEmpty()) {
return instanceIds.stream().filter(Objects::nonNull).map(each -> buildRow(each, status)).collect(Collectors.toCollection(LinkedList::new));
}
return Collections.emptyList();
}
private List<Object> buildRow(final String instanceId, final String status) {
LinkedList<Object> result = Arrays.stream(instanceId.split(DELIMITER)).map(each -> (Object) each).collect(Collectors.toCollection(LinkedList::new));
result.add(status);
return result;
}
}
| [DistSQL] Adjust the display of the `show instance list` statement (#13787)
* Adjust display.
* Adjust display. | shardingsphere-proxy/shardingsphere-proxy-backend/src/main/java/org/apache/shardingsphere/proxy/backend/text/distsql/ral/common/show/executor/ShowInstanceExecutor.java | [DistSQL] Adjust the display of the `show instance list` statement (#13787) | <ide><path>hardingsphere-proxy/shardingsphere-proxy-backend/src/main/java/org/apache/shardingsphere/proxy/backend/text/distsql/ral/common/show/executor/ShowInstanceExecutor.java
<ide> import java.util.List;
<ide> import java.util.Objects;
<ide> import java.util.stream.Collectors;
<add>import java.util.stream.Stream;
<ide>
<ide> /**
<ide> * Show instance executor.
<ide>
<ide> private static final String DELIMITER = "@";
<ide>
<del> private static final String IP = "ip";
<del>
<del> private static final String PORT = "port";
<add> private static final String ID = "instance_id";
<ide>
<ide> private static final String STATUS = "status";
<ide>
<ide> @Override
<ide> protected List<QueryHeader> createQueryHeaders() {
<ide> return Arrays.asList(
<del> new QueryHeader("", "", IP, IP, Types.VARCHAR, "VARCHAR", 64, 0, false, false, false, false),
<del> new QueryHeader("", "", PORT, PORT, Types.VARCHAR, "VARCHAR", 64, 0, false, false, false, false),
<add> new QueryHeader("", "", ID, ID, Types.VARCHAR, "VARCHAR", 64, 0, false, false, false, false),
<ide> new QueryHeader("", "", STATUS, STATUS, Types.VARCHAR, "VARCHAR", 64, 0, false, false, false, false)
<ide> );
<ide> }
<ide> }
<ide>
<ide> private List<Object> buildRow(final String instanceId, final String status) {
<del> LinkedList<Object> result = Arrays.stream(instanceId.split(DELIMITER)).map(each -> (Object) each).collect(Collectors.toCollection(LinkedList::new));
<del> result.add(status);
<del> return result;
<add> return Stream.of(instanceId, status).map(each -> (Object) each).collect(Collectors.toCollection(LinkedList::new));
<ide> }
<ide> } |
|
JavaScript | mit | ca6b5f5c08b8aff1b7458756d3b39b20391ab564 | 0 | pdeffendol/foundation,socketz/foundation-multilevel-offcanvas,karland/foundation-sites,Iamronan/foundation,socketz/foundation-multilevel-offcanvas,socketz/foundation-multilevel-offcanvas,zurb/foundation-sites,ucla/foundation-sites,dragthor/foundation-sites,zurb/foundation,samuelmc/foundation-sites,dimamedia/foundation-6-sites-simple-scss-and-js,jaylensoeur/foundation-sites-6,andycochran/foundation-sites,jaylensoeur/foundation-sites-6,jaylensoeur/foundation-sites-6,atmmarketing/foundation-sites,Owlbertz/foundation,brettsmason/foundation-sites,brettsmason/foundation-sites,pdeffendol/foundation,atmmarketing/foundation-sites,jamesstoneco/foundation-sites,aoimedia/foundation,karland/foundation-sites,aoimedia/foundation,BerndtGroup/TBG-foundation-sites,IamManchanda/foundation-sites,getoutfitted/reaction-foundation-theme,colin-marshall/foundation-sites,jamesstoneco/foundation-sites,dimamedia/foundation-6-sites-simple-scss-and-js,andycochran/foundation-sites,Iamronan/foundation,ucla/foundation-sites,designerno1/foundation-sites,Owlbertz/foundation,Iamronan/foundation,getoutfitted/reaction-foundation-theme,BerndtGroup/TBG-foundation-sites,DaSchTour/foundation-sites,PassKitInc/foundation-sites,natewiebe13/foundation-sites,designerno1/foundation-sites,denisahac/foundation-sites,zurb/foundation-sites,brettsmason/foundation-sites,zurb/foundation,Owlbertz/foundation,natewiebe13/foundation-sites,jeromelebleu/foundation-sites,IamManchanda/foundation-sites,dragthor/foundation-sites,samuelmc/foundation-sites,zurb/foundation-sites,sethkane/foundation-sites,abdullahsalem/foundation-sites,abdullahsalem/foundation-sites,aoimedia/foundation,denisahac/foundation-sites,denisahac/foundation-sites,Owlbertz/foundation,getoutfitted/reaction-foundation-theme,colin-marshall/foundation-sites,designerno1/foundation-sites,atmmarketing/foundation-sites,sethkane/foundation-sites,PassKitInc/foundation-sites,ucla/foundation-sites,pdeffendol/foundation,zurb/foundation,pdeffendol/foundation,samuelmc/foundation-sites,dragthor/foundation-sites,IamManchanda/foundation-sites,PassKitInc/foundation-sites,colin-marshall/foundation-sites,andycochran/foundation-sites,DaSchTour/foundation-sites,jeromelebleu/foundation-sites,sethkane/foundation-sites,abdullahsalem/foundation-sites,natewiebe13/foundation-sites,BerndtGroup/TBG-foundation-sites,jeromelebleu/foundation-sites,karland/foundation-sites,jamesstoneco/foundation-sites | 'use strict';
/**
* DropdownMenu module.
* @module foundation.dropdown-menu
* @requires foundation.util.keyboard
* @requires foundation.util.box
* @requires foundation.util.nest
*/
export default class DropdownMenu {
/**
* Creates a new instance of DropdownMenu.
* @class
* @fires DropdownMenu#init
* @param {jQuery} element - jQuery object to make into a dropdown menu.
* @param {Object} options - Overrides to the default plugin settings.
*/
constructor(element, options) {
this.$element = element;
this.options = $.extend({}, DropdownMenu.defaults, this.$element.data(), options);
Foundation.Nest.Feather(this.$element, 'dropdown');
this._init();
Foundation.registerPlugin(this, 'DropdownMenu');
Foundation.Keyboard.register('DropdownMenu', {
'ENTER': 'open',
'SPACE': 'open',
'ARROW_RIGHT': 'next',
'ARROW_UP': 'up',
'ARROW_DOWN': 'down',
'ARROW_LEFT': 'previous',
'ESCAPE': 'close'
});
}
/**
* Initializes the plugin, and calls _prepareMenu
* @private
* @function
*/
_init() {
var subs = this.$element.find('li.is-dropdown-submenu-parent');
this.$element.children('.is-dropdown-submenu-parent').children('.is-dropdown-submenu').addClass('first-sub');
this.$menuItems = this.$element.find('[role="menuitem"]');
this.$tabs = this.$element.children('[role="menuitem"]');
this.isVert = this.$element.hasClass(this.options.verticalClass);
this.$tabs.find('ul.is-dropdown-submenu').addClass(this.options.verticalClass);
if (this.$element.hasClass(this.options.rightClass) || this.options.alignment === 'right' || Foundation.rtl()) {
this.options.alignment = 'right';
subs.addClass('is-left-arrow opens-left');
} else {
subs.addClass('is-right-arrow opens-right');
}
if (!this.isVert) {
this.$tabs.filter('.is-dropdown-submenu-parent').removeClass('is-right-arrow is-left-arrow opens-right opens-left')
.addClass('is-down-arrow');
}
this.changed = false;
this._events();
};
/**
* Adds event listeners to elements within the menu
* @private
* @function
*/
_events() {
var _this = this,
hasTouch = 'ontouchstart' in window || (typeof window.ontouchstart !== 'undefined'),
parClass = 'is-dropdown-submenu-parent';
if (this.options.clickOpen || hasTouch) {
this.$menuItems.on('click.zf.dropdownmenu touchstart.zf.dropdownmenu', function(e) {
var $elem = $(e.target).parentsUntil('ul', `.${parClass}`),
hasSub = $elem.hasClass(parClass),
hasClicked = $elem.attr('data-is-click') === 'true',
$sub = $elem.children('.is-dropdown-submenu');
if (hasSub) {
if (hasClicked) {
if (!_this.options.closeOnClick || (!_this.options.clickOpen && !hasTouch) || (_this.options.forceFollow && hasTouch)) { return; }
else {
e.stopImmediatePropagation();
e.preventDefault();
_this._hide($elem);
}
} else {
e.preventDefault();
e.stopImmediatePropagation();
_this._show($elem.children('.is-dropdown-submenu'));
$elem.add($elem.parentsUntil(_this.$element, `.${parClass}`)).attr('data-is-click', true);
}
} else { return; }
});
}
if (!this.options.disableHover) {
this.$menuItems.on('mouseenter.zf.dropdownmenu', function(e) {
e.stopImmediatePropagation();
var $elem = $(this),
hasSub = $elem.hasClass(parClass);
if (hasSub) {
clearTimeout(_this.delay);
_this.delay = setTimeout(function() {
_this._show($elem.children('.is-dropdown-submenu'));
}, _this.options.hoverDelay);
}
}).on('mouseleave.zf.dropdownmenu', function(e) {
var $elem = $(this),
hasSub = $elem.hasClass(parClass);
if (hasSub && _this.options.autoclose) {
if ($elem.attr('data-is-click') === 'true' && _this.options.clickOpen) { return false; }
clearTimeout(_this.delay);
_this.delay = setTimeout(function() {
_this._hide($elem);
}, _this.options.closingTime);
}
});
}
this.$menuItems.on('keydown.zf.dropdownmenu', function(e) {
var $element = $(e.target).parentsUntil('ul', '[role="menuitem"]'),
isTab = _this.$tabs.index($element) > -1,
$elements = isTab ? _this.$tabs : $element.siblings('li').add($element),
$prevElement,
$nextElement;
$elements.each(function(i) {
if ($(this).is($element)) {
$prevElement = $elements.eq(i-1);
$nextElement = $elements.eq(i+1);
return;
}
});
var nextSibling = function() {
if (!$element.is(':last-child')) $nextElement.children('a:first').focus();
}, prevSibling = function() {
$prevElement.children('a:first').focus();
}, openSub = function() {
var $sub = $element.children('ul.is-dropdown-submenu');
if ($sub.length) {
_this._show($sub);
$element.find('li > a:first').focus();
} else { return; }
}, closeSub = function() {
//if ($element.is(':first-child')) {
var close = $element.parent('ul').parent('li');
close.children('a:first').focus();
_this._hide(close);
//}
};
var functions = {
open: openSub,
close: function() {
_this._hide(_this.$element);
_this.$menuItems.find('a:first').focus(); // focus to first element
},
handled: function() {
e.preventDefault();
e.stopImmediatePropagation();
}
};
if (isTab) {
if (_this.vertical) { // vertical menu
if (_this.options.alignment === 'left') { // left aligned
$.extend(functions, {
down: nextSibling,
up: prevSibling,
next: openSub,
previous: closeSub
});
} else { // right aligned
$.extend(functions, {
down: nextSibling,
up: prevSibling,
next: closeSub,
previous: openSub
});
}
} else { // horizontal menu
$.extend(functions, {
next: nextSibling,
previous: prevSibling,
down: openSub,
up: closeSub
});
}
} else { // not tabs -> one sub
if (_this.options.alignment === 'left') { // left aligned
$.extend(functions, {
next: openSub,
previous: closeSub,
down: nextSibling,
up: prevSibling
});
} else { // right aligned
$.extend(functions, {
next: closeSub,
previous: openSub,
down: nextSibling,
up: prevSibling
});
}
}
Foundation.Keyboard.handleKey(e, 'DropdownMenu', functions);
});
}
/**
* Adds an event handler to the body to close any dropdowns on a click.
* @function
* @private
*/
_addBodyHandler() {
var $body = $(document.body),
_this = this;
$body.off('mouseup.zf.dropdownmenu touchend.zf.dropdownmenu')
.on('mouseup.zf.dropdownmenu touchend.zf.dropdownmenu', function(e) {
var $link = _this.$element.find(e.target);
if ($link.length) { return; }
_this._hide();
$body.off('mouseup.zf.dropdownmenu touchend.zf.dropdownmenu');
});
}
/**
* Opens a dropdown pane, and checks for collisions first.
* @param {jQuery} $sub - ul element that is a submenu to show
* @function
* @private
* @fires DropdownMenu#show
*/
_show($sub) {
var idx = this.$tabs.index(this.$tabs.filter(function(i, el) {
return $(el).find($sub).length > 0;
}));
var $sibs = $sub.parent('li.is-dropdown-submenu-parent').siblings('li.is-dropdown-submenu-parent');
this._hide($sibs, idx);
$sub.css('visibility', 'hidden').addClass('js-dropdown-active').attr({'aria-hidden': false})
.parent('li.is-dropdown-submenu-parent').addClass('is-active')
.attr({'aria-expanded': true});
var clear = Foundation.Box.ImNotTouchingYou($sub, null, true);
if (!clear) {
var oldClass = this.options.alignment === 'left' ? '-right' : '-left',
$parentLi = $sub.parent('.is-dropdown-submenu-parent');
$parentLi.removeClass(`opens${oldClass}`).addClass(`opens-${this.options.alignment}`);
clear = Foundation.Box.ImNotTouchingYou($sub, null, true);
if (!clear) {
$parentLi.removeClass(`opens-${this.options.alignment}`).addClass('opens-inner');
}
this.changed = true;
}
$sub.css('visibility', '');
if (this.options.closeOnClick) { this._addBodyHandler(); }
/**
* Fires when the new dropdown pane is visible.
* @event DropdownMenu#show
*/
this.$element.trigger('show.zf.dropdownmenu', [$sub]);
}
/**
* Hides a single, currently open dropdown pane, if passed a parameter, otherwise, hides everything.
* @function
* @param {jQuery} $elem - element with a submenu to hide
* @param {Number} idx - index of the $tabs collection to hide
* @private
*/
_hide($elem, idx) {
var $toClose;
if ($elem && $elem.length) {
$toClose = $elem;
} else if (idx !== undefined) {
$toClose = this.$tabs.not(function(i, el) {
return i === idx;
});
}
else {
$toClose = this.$element;
}
var somethingToClose = $toClose.hasClass('is-active') || $toClose.find('.is-active').length > 0;
if (somethingToClose) {
$toClose.find('li.is-active').add($toClose).attr({
'aria-expanded': false,
'data-is-click': false
}).removeClass('is-active');
$toClose.find('ul.js-dropdown-active').attr({
'aria-hidden': true
}).removeClass('js-dropdown-active');
if (this.changed || $toClose.find('opens-inner').length) {
var oldClass = this.options.alignment === 'left' ? 'right' : 'left';
$toClose.find('li.is-dropdown-submenu-parent').add($toClose)
.removeClass(`opens-inner opens-${this.options.alignment}`)
.addClass(`opens-${oldClass}`);
this.changed = false;
}
/**
* Fires when the open menus are closed.
* @event DropdownMenu#hide
*/
this.$element.trigger('hide.zf.dropdownmenu', [$toClose]);
}
}
/**
* Destroys the plugin.
* @function
*/
destroy() {
this.$menuItems.off('.zf.dropdownmenu').removeAttr('data-is-click')
.removeClass('is-right-arrow is-left-arrow is-down-arrow opens-right opens-left opens-inner');
$(document.body).off('.zf.dropdownmenu');
Foundation.Nest.Burn(this.$element, 'dropdown');
Foundation.unregisterPlugin(this);
}
}
/**
* Default settings for plugin
*/
DropdownMenu.defaults = {
/**
* Disallows hover events from opening submenus
* @option
* @example false
*/
disableHover: false,
/**
* Allow a submenu to automatically close on a mouseleave event, if not clicked open.
* @option
* @example true
*/
autoclose: true,
/**
* Amount of time to delay opening a submenu on hover event.
* @option
* @example 50
*/
hoverDelay: 50,
/**
* Allow a submenu to open/remain open on parent click event. Allows cursor to move away from menu.
* @option
* @example true
*/
clickOpen: false,
/**
* Amount of time to delay closing a submenu on a mouseleave event.
* @option
* @example 500
*/
closingTime: 500,
/**
* Position of the menu relative to what direction the submenus should open. Handled by JS.
* @option
* @example 'left'
*/
alignment: 'left',
/**
* Allow clicks on the body to close any open submenus.
* @option
* @example true
*/
closeOnClick: true,
/**
* Class applied to vertical oriented menus, Foundation default is `vertical`. Update this if using your own class.
* @option
* @example 'vertical'
*/
verticalClass: 'vertical',
/**
* Class applied to right-side oriented menus, Foundation default is `align-right`. Update this if using your own class.
* @option
* @example 'align-right'
*/
rightClass: 'align-right',
/**
* Boolean to force overide the clicking of links to perform default action, on second touch event for mobile.
* @option
* @example false
*/
forceFollow: true
};
// Window exports
if (window.Foundation) {
window.Foundation.plugin(DropdownMenu, 'DropdownMenu');
}
| js/foundation.dropdownMenu.js | /**
* DropdownMenu module.
* @module foundation.dropdown-menu
* @requires foundation.util.keyboard
* @requires foundation.util.box
* @requires foundation.util.nest
*/
!function($, Foundation){
'use strict';
/**
* Creates a new instance of DropdownMenu.
* @class
* @fires DropdownMenu#init
* @param {jQuery} element - jQuery object to make into a dropdown menu.
* @param {Object} options - Overrides to the default plugin settings.
*/
function DropdownMenu(element, options){
this.$element = element;
this.options = $.extend({}, DropdownMenu.defaults, this.$element.data(), options);
Foundation.Nest.Feather(this.$element, 'dropdown');
this._init();
Foundation.registerPlugin(this, 'DropdownMenu');
Foundation.Keyboard.register('DropdownMenu', {
'ENTER': 'open',
'SPACE': 'open',
'ARROW_RIGHT': 'next',
'ARROW_UP': 'up',
'ARROW_DOWN': 'down',
'ARROW_LEFT': 'previous',
'ESCAPE': 'close'
});
}
/**
* Default settings for plugin
*/
DropdownMenu.defaults = {
/**
* Disallows hover events from opening submenus
* @option
* @example false
*/
disableHover: false,
/**
* Allow a submenu to automatically close on a mouseleave event, if not clicked open.
* @option
* @example true
*/
autoclose: true,
/**
* Amount of time to delay opening a submenu on hover event.
* @option
* @example 50
*/
hoverDelay: 50,
/**
* Allow a submenu to open/remain open on parent click event. Allows cursor to move away from menu.
* @option
* @example true
*/
clickOpen: false,
/**
* Amount of time to delay closing a submenu on a mouseleave event.
* @option
* @example 500
*/
closingTime: 500,
/**
* Position of the menu relative to what direction the submenus should open. Handled by JS.
* @option
* @example 'left'
*/
alignment: 'left',
/**
* Allow clicks on the body to close any open submenus.
* @option
* @example true
*/
closeOnClick: true,
/**
* Class applied to vertical oriented menus, Foundation default is `vertical`. Update this if using your own class.
* @option
* @example 'vertical'
*/
verticalClass: 'vertical',
/**
* Class applied to right-side oriented menus, Foundation default is `align-right`. Update this if using your own class.
* @option
* @example 'align-right'
*/
rightClass: 'align-right',
/**
* Boolean to force overide the clicking of links to perform default action, on second touch event for mobile.
* @option
* @example false
*/
forceFollow: true
};
/**
* Initializes the plugin, and calls _prepareMenu
* @private
* @function
*/
DropdownMenu.prototype._init = function(){
var subs = this.$element.find('li.is-dropdown-submenu-parent');
this.$element.children('.is-dropdown-submenu-parent').children('.is-dropdown-submenu').addClass('first-sub');
this.$menuItems = this.$element.find('[role="menuitem"]');
this.$tabs = this.$element.children('[role="menuitem"]');
this.isVert = this.$element.hasClass(this.options.verticalClass);
this.$tabs.find('ul.is-dropdown-submenu').addClass(this.options.verticalClass);
if(this.$element.hasClass(this.options.rightClass) || this.options.alignment === 'right' || Foundation.rtl()){
this.options.alignment = 'right';
subs.addClass('is-left-arrow opens-left');
}else{
subs.addClass('is-right-arrow opens-right');
}
if(!this.isVert){
this.$tabs.filter('.is-dropdown-submenu-parent').removeClass('is-right-arrow is-left-arrow opens-right opens-left')
.addClass('is-down-arrow');
}
this.changed = false;
this._events();
};
/**
* Adds event listeners to elements within the menu
* @private
* @function
*/
DropdownMenu.prototype._events = function(){
var _this = this,
hasTouch = 'ontouchstart' in window || (typeof window.ontouchstart !== 'undefined'),
parClass = 'is-dropdown-submenu-parent';
if(this.options.clickOpen || hasTouch){
this.$menuItems.on('click.zf.dropdownmenu touchstart.zf.dropdownmenu', function(e){
var $elem = $(e.target).parentsUntil('ul', `.${parClass}`),
hasSub = $elem.hasClass(parClass),
hasClicked = $elem.attr('data-is-click') === 'true',
$sub = $elem.children('.is-dropdown-submenu');
if(hasSub){
if(hasClicked){
if(!_this.options.closeOnClick || (!_this.options.clickOpen && !hasTouch) || (_this.options.forceFollow && hasTouch)){ return; }
else{
e.stopImmediatePropagation();
e.preventDefault();
_this._hide($elem);
}
}else{
e.preventDefault();
e.stopImmediatePropagation();
_this._show($elem.children('.is-dropdown-submenu'));
$elem.add($elem.parentsUntil(_this.$element, `.${parClass}`)).attr('data-is-click', true);
}
}else{ return; }
});
}
if(!this.options.disableHover){
this.$menuItems.on('mouseenter.zf.dropdownmenu', function(e){
e.stopImmediatePropagation();
var $elem = $(this),
hasSub = $elem.hasClass(parClass);
if(hasSub){
clearTimeout(_this.delay);
_this.delay = setTimeout(function(){
_this._show($elem.children('.is-dropdown-submenu'));
}, _this.options.hoverDelay);
}
}).on('mouseleave.zf.dropdownmenu', function(e){
var $elem = $(this),
hasSub = $elem.hasClass(parClass);
if(hasSub && _this.options.autoclose){
if($elem.attr('data-is-click') === 'true' && _this.options.clickOpen){ return false; }
clearTimeout(_this.delay);
_this.delay = setTimeout(function(){
_this._hide($elem);
}, _this.options.closingTime);
}
});
}
this.$menuItems.on('keydown.zf.dropdownmenu', function(e){
var $element = $(e.target).parentsUntil('ul', '[role="menuitem"]'),
isTab = _this.$tabs.index($element) > -1,
$elements = isTab ? _this.$tabs : $element.siblings('li').add($element),
$prevElement,
$nextElement;
$elements.each(function(i) {
if ($(this).is($element)) {
$prevElement = $elements.eq(i-1);
$nextElement = $elements.eq(i+1);
return;
}
});
var nextSibling = function() {
if (!$element.is(':last-child')) $nextElement.children('a:first').focus();
}, prevSibling = function() {
$prevElement.children('a:first').focus();
}, openSub = function() {
var $sub = $element.children('ul.is-dropdown-submenu');
if($sub.length){
_this._show($sub);
$element.find('li > a:first').focus();
}else{ return; }
}, closeSub = function() {
//if ($element.is(':first-child')) {
var close = $element.parent('ul').parent('li');
close.children('a:first').focus();
_this._hide(close);
//}
};
var functions = {
open: openSub,
close: function() {
_this._hide(_this.$element);
_this.$menuItems.find('a:first').focus(); // focus to first element
},
handled: function() {
e.preventDefault();
e.stopImmediatePropagation();
}
};
if (isTab) {
if (_this.vertical) { // vertical menu
if (_this.options.alignment === 'left') { // left aligned
$.extend(functions, {
down: nextSibling,
up: prevSibling,
next: openSub,
previous: closeSub
});
} else { // right aligned
$.extend(functions, {
down: nextSibling,
up: prevSibling,
next: closeSub,
previous: openSub
});
}
} else { // horizontal menu
$.extend(functions, {
next: nextSibling,
previous: prevSibling,
down: openSub,
up: closeSub
});
}
} else { // not tabs -> one sub
if (_this.options.alignment === 'left') { // left aligned
$.extend(functions, {
next: openSub,
previous: closeSub,
down: nextSibling,
up: prevSibling
});
} else { // right aligned
$.extend(functions, {
next: closeSub,
previous: openSub,
down: nextSibling,
up: prevSibling
});
}
}
Foundation.Keyboard.handleKey(e, 'DropdownMenu', functions);
});
};
/**
* Adds an event handler to the body to close any dropdowns on a click.
* @function
* @private
*/
DropdownMenu.prototype._addBodyHandler = function(){
var $body = $(document.body),
_this = this;
$body.off('mouseup.zf.dropdownmenu touchend.zf.dropdownmenu')
.on('mouseup.zf.dropdownmenu touchend.zf.dropdownmenu', function(e){
var $link = _this.$element.find(e.target);
if($link.length){ return; }
_this._hide();
$body.off('mouseup.zf.dropdownmenu touchend.zf.dropdownmenu');
});
};
/**
* Opens a dropdown pane, and checks for collisions first.
* @param {jQuery} $sub - ul element that is a submenu to show
* @function
* @private
* @fires DropdownMenu#show
*/
DropdownMenu.prototype._show = function($sub){
var idx = this.$tabs.index(this.$tabs.filter(function(i, el){
return $(el).find($sub).length > 0;
}));
var $sibs = $sub.parent('li.is-dropdown-submenu-parent').siblings('li.is-dropdown-submenu-parent');
this._hide($sibs, idx);
$sub.css('visibility', 'hidden').addClass('js-dropdown-active').attr({'aria-hidden': false})
.parent('li.is-dropdown-submenu-parent').addClass('is-active')
.attr({'aria-expanded': true});
var clear = Foundation.Box.ImNotTouchingYou($sub, null, true);
if(!clear){
var oldClass = this.options.alignment === 'left' ? '-right' : '-left',
$parentLi = $sub.parent('.is-dropdown-submenu-parent');
$parentLi.removeClass(`opens${oldClass}`).addClass(`opens-${this.options.alignment}`);
clear = Foundation.Box.ImNotTouchingYou($sub, null, true);
if(!clear){
$parentLi.removeClass(`opens-${this.options.alignment}`).addClass('opens-inner');
}
this.changed = true;
}
$sub.css('visibility', '');
if(this.options.closeOnClick){ this._addBodyHandler(); }
/**
* Fires when the new dropdown pane is visible.
* @event DropdownMenu#show
*/
this.$element.trigger('show.zf.dropdownmenu', [$sub]);
};
/**
* Hides a single, currently open dropdown pane, if passed a parameter, otherwise, hides everything.
* @function
* @param {jQuery} $elem - element with a submenu to hide
* @param {Number} idx - index of the $tabs collection to hide
* @private
*/
DropdownMenu.prototype._hide = function($elem, idx){
var $toClose;
if($elem && $elem.length){
$toClose = $elem;
}else if(idx !== undefined){
$toClose = this.$tabs.not(function(i, el){
return i === idx;
});
}
else{
$toClose = this.$element;
}
var somethingToClose = $toClose.hasClass('is-active') || $toClose.find('.is-active').length > 0;
if(somethingToClose){
$toClose.find('li.is-active').add($toClose).attr({
'aria-expanded': false,
'data-is-click': false
}).removeClass('is-active');
$toClose.find('ul.js-dropdown-active').attr({
'aria-hidden': true
}).removeClass('js-dropdown-active');
if(this.changed || $toClose.find('opens-inner').length){
var oldClass = this.options.alignment === 'left' ? 'right' : 'left';
$toClose.find('li.is-dropdown-submenu-parent').add($toClose)
.removeClass(`opens-inner opens-${this.options.alignment}`)
.addClass(`opens-${oldClass}`);
this.changed = false;
}
/**
* Fires when the open menus are closed.
* @event DropdownMenu#hide
*/
this.$element.trigger('hide.zf.dropdownmenu', [$toClose]);
}
};
/**
* Destroys the plugin.
* @function
*/
DropdownMenu.prototype.destroy = function(){
this.$menuItems.off('.zf.dropdownmenu').removeAttr('data-is-click')
.removeClass('is-right-arrow is-left-arrow is-down-arrow opens-right opens-left opens-inner');
$(document.body).off('.zf.dropdownmenu');
Foundation.Nest.Burn(this.$element, 'dropdown');
Foundation.unregisterPlugin(this);
};
Foundation.plugin(DropdownMenu, 'DropdownMenu');
}(jQuery, window.Foundation);
| Convert dropdown menu to ES6 class
| js/foundation.dropdownMenu.js | Convert dropdown menu to ES6 class | <ide><path>s/foundation.dropdownMenu.js
<add>'use strict';
<add>
<ide> /**
<ide> * DropdownMenu module.
<ide> * @module foundation.dropdown-menu
<ide> * @requires foundation.util.box
<ide> * @requires foundation.util.nest
<ide> */
<del>!function($, Foundation){
<del> 'use strict';
<del>
<add>
<add>export default class DropdownMenu {
<ide> /**
<ide> * Creates a new instance of DropdownMenu.
<ide> * @class
<ide> * @param {jQuery} element - jQuery object to make into a dropdown menu.
<ide> * @param {Object} options - Overrides to the default plugin settings.
<ide> */
<del> function DropdownMenu(element, options){
<add> constructor(element, options) {
<ide> this.$element = element;
<ide> this.options = $.extend({}, DropdownMenu.defaults, this.$element.data(), options);
<ide>
<ide> }
<ide>
<ide> /**
<del> * Default settings for plugin
<del> */
<del> DropdownMenu.defaults = {
<del> /**
<del> * Disallows hover events from opening submenus
<del> * @option
<del> * @example false
<del> */
<del> disableHover: false,
<del> /**
<del> * Allow a submenu to automatically close on a mouseleave event, if not clicked open.
<del> * @option
<del> * @example true
<del> */
<del> autoclose: true,
<del> /**
<del> * Amount of time to delay opening a submenu on hover event.
<del> * @option
<del> * @example 50
<del> */
<del> hoverDelay: 50,
<del> /**
<del> * Allow a submenu to open/remain open on parent click event. Allows cursor to move away from menu.
<del> * @option
<del> * @example true
<del> */
<del> clickOpen: false,
<del> /**
<del> * Amount of time to delay closing a submenu on a mouseleave event.
<del> * @option
<del> * @example 500
<del> */
<del>
<del> closingTime: 500,
<del> /**
<del> * Position of the menu relative to what direction the submenus should open. Handled by JS.
<del> * @option
<del> * @example 'left'
<del> */
<del> alignment: 'left',
<del> /**
<del> * Allow clicks on the body to close any open submenus.
<del> * @option
<del> * @example true
<del> */
<del> closeOnClick: true,
<del> /**
<del> * Class applied to vertical oriented menus, Foundation default is `vertical`. Update this if using your own class.
<del> * @option
<del> * @example 'vertical'
<del> */
<del> verticalClass: 'vertical',
<del> /**
<del> * Class applied to right-side oriented menus, Foundation default is `align-right`. Update this if using your own class.
<del> * @option
<del> * @example 'align-right'
<del> */
<del> rightClass: 'align-right',
<del> /**
<del> * Boolean to force overide the clicking of links to perform default action, on second touch event for mobile.
<del> * @option
<del> * @example false
<del> */
<del> forceFollow: true
<del> };
<del> /**
<ide> * Initializes the plugin, and calls _prepareMenu
<ide> * @private
<ide> * @function
<ide> */
<del> DropdownMenu.prototype._init = function(){
<add> _init() {
<ide> var subs = this.$element.find('li.is-dropdown-submenu-parent');
<ide> this.$element.children('.is-dropdown-submenu-parent').children('.is-dropdown-submenu').addClass('first-sub');
<ide>
<ide> this.isVert = this.$element.hasClass(this.options.verticalClass);
<ide> this.$tabs.find('ul.is-dropdown-submenu').addClass(this.options.verticalClass);
<ide>
<del> if(this.$element.hasClass(this.options.rightClass) || this.options.alignment === 'right' || Foundation.rtl()){
<add> if (this.$element.hasClass(this.options.rightClass) || this.options.alignment === 'right' || Foundation.rtl()) {
<ide> this.options.alignment = 'right';
<ide> subs.addClass('is-left-arrow opens-left');
<del> }else{
<add> } else {
<ide> subs.addClass('is-right-arrow opens-right');
<ide> }
<del> if(!this.isVert){
<add> if (!this.isVert) {
<ide> this.$tabs.filter('.is-dropdown-submenu-parent').removeClass('is-right-arrow is-left-arrow opens-right opens-left')
<ide> .addClass('is-down-arrow');
<ide> }
<ide> * @private
<ide> * @function
<ide> */
<del> DropdownMenu.prototype._events = function(){
<add> _events() {
<ide> var _this = this,
<ide> hasTouch = 'ontouchstart' in window || (typeof window.ontouchstart !== 'undefined'),
<ide> parClass = 'is-dropdown-submenu-parent';
<ide>
<del> if(this.options.clickOpen || hasTouch){
<del> this.$menuItems.on('click.zf.dropdownmenu touchstart.zf.dropdownmenu', function(e){
<add> if (this.options.clickOpen || hasTouch) {
<add> this.$menuItems.on('click.zf.dropdownmenu touchstart.zf.dropdownmenu', function(e) {
<ide> var $elem = $(e.target).parentsUntil('ul', `.${parClass}`),
<ide> hasSub = $elem.hasClass(parClass),
<ide> hasClicked = $elem.attr('data-is-click') === 'true',
<ide> $sub = $elem.children('.is-dropdown-submenu');
<ide>
<del> if(hasSub){
<del> if(hasClicked){
<del> if(!_this.options.closeOnClick || (!_this.options.clickOpen && !hasTouch) || (_this.options.forceFollow && hasTouch)){ return; }
<del> else{
<add> if (hasSub) {
<add> if (hasClicked) {
<add> if (!_this.options.closeOnClick || (!_this.options.clickOpen && !hasTouch) || (_this.options.forceFollow && hasTouch)) { return; }
<add> else {
<ide> e.stopImmediatePropagation();
<ide> e.preventDefault();
<ide> _this._hide($elem);
<ide> }
<del> }else{
<add> } else {
<ide> e.preventDefault();
<ide> e.stopImmediatePropagation();
<ide> _this._show($elem.children('.is-dropdown-submenu'));
<ide> $elem.add($elem.parentsUntil(_this.$element, `.${parClass}`)).attr('data-is-click', true);
<ide> }
<del> }else{ return; }
<add> } else { return; }
<ide> });
<ide> }
<ide>
<del> if(!this.options.disableHover){
<del> this.$menuItems.on('mouseenter.zf.dropdownmenu', function(e){
<add> if (!this.options.disableHover) {
<add> this.$menuItems.on('mouseenter.zf.dropdownmenu', function(e) {
<ide> e.stopImmediatePropagation();
<ide> var $elem = $(this),
<ide> hasSub = $elem.hasClass(parClass);
<ide>
<del> if(hasSub){
<add> if (hasSub) {
<ide> clearTimeout(_this.delay);
<del> _this.delay = setTimeout(function(){
<add> _this.delay = setTimeout(function() {
<ide> _this._show($elem.children('.is-dropdown-submenu'));
<ide> }, _this.options.hoverDelay);
<ide> }
<del> }).on('mouseleave.zf.dropdownmenu', function(e){
<add> }).on('mouseleave.zf.dropdownmenu', function(e) {
<ide> var $elem = $(this),
<ide> hasSub = $elem.hasClass(parClass);
<del> if(hasSub && _this.options.autoclose){
<del> if($elem.attr('data-is-click') === 'true' && _this.options.clickOpen){ return false; }
<add> if (hasSub && _this.options.autoclose) {
<add> if ($elem.attr('data-is-click') === 'true' && _this.options.clickOpen) { return false; }
<ide>
<ide> clearTimeout(_this.delay);
<del> _this.delay = setTimeout(function(){
<add> _this.delay = setTimeout(function() {
<ide> _this._hide($elem);
<ide> }, _this.options.closingTime);
<ide> }
<ide> });
<ide> }
<del> this.$menuItems.on('keydown.zf.dropdownmenu', function(e){
<add> this.$menuItems.on('keydown.zf.dropdownmenu', function(e) {
<ide> var $element = $(e.target).parentsUntil('ul', '[role="menuitem"]'),
<ide> isTab = _this.$tabs.index($element) > -1,
<ide> $elements = isTab ? _this.$tabs : $element.siblings('li').add($element),
<ide> $prevElement.children('a:first').focus();
<ide> }, openSub = function() {
<ide> var $sub = $element.children('ul.is-dropdown-submenu');
<del> if($sub.length){
<add> if ($sub.length) {
<ide> _this._show($sub);
<ide> $element.find('li > a:first').focus();
<del> }else{ return; }
<add> } else { return; }
<ide> }, closeSub = function() {
<ide> //if ($element.is(':first-child')) {
<ide> var close = $element.parent('ul').parent('li');
<ide> Foundation.Keyboard.handleKey(e, 'DropdownMenu', functions);
<ide>
<ide> });
<del> };
<add> }
<add>
<ide> /**
<ide> * Adds an event handler to the body to close any dropdowns on a click.
<ide> * @function
<ide> * @private
<ide> */
<del> DropdownMenu.prototype._addBodyHandler = function(){
<add> _addBodyHandler() {
<ide> var $body = $(document.body),
<ide> _this = this;
<ide> $body.off('mouseup.zf.dropdownmenu touchend.zf.dropdownmenu')
<del> .on('mouseup.zf.dropdownmenu touchend.zf.dropdownmenu', function(e){
<add> .on('mouseup.zf.dropdownmenu touchend.zf.dropdownmenu', function(e) {
<ide> var $link = _this.$element.find(e.target);
<del> if($link.length){ return; }
<add> if ($link.length) { return; }
<ide>
<ide> _this._hide();
<ide> $body.off('mouseup.zf.dropdownmenu touchend.zf.dropdownmenu');
<ide> });
<del> };
<add> }
<add>
<ide> /**
<ide> * Opens a dropdown pane, and checks for collisions first.
<ide> * @param {jQuery} $sub - ul element that is a submenu to show
<ide> * @private
<ide> * @fires DropdownMenu#show
<ide> */
<del> DropdownMenu.prototype._show = function($sub){
<del> var idx = this.$tabs.index(this.$tabs.filter(function(i, el){
<add> _show($sub) {
<add> var idx = this.$tabs.index(this.$tabs.filter(function(i, el) {
<ide> return $(el).find($sub).length > 0;
<ide> }));
<ide> var $sibs = $sub.parent('li.is-dropdown-submenu-parent').siblings('li.is-dropdown-submenu-parent');
<ide> .parent('li.is-dropdown-submenu-parent').addClass('is-active')
<ide> .attr({'aria-expanded': true});
<ide> var clear = Foundation.Box.ImNotTouchingYou($sub, null, true);
<del> if(!clear){
<add> if (!clear) {
<ide> var oldClass = this.options.alignment === 'left' ? '-right' : '-left',
<ide> $parentLi = $sub.parent('.is-dropdown-submenu-parent');
<ide> $parentLi.removeClass(`opens${oldClass}`).addClass(`opens-${this.options.alignment}`);
<ide> clear = Foundation.Box.ImNotTouchingYou($sub, null, true);
<del> if(!clear){
<add> if (!clear) {
<ide> $parentLi.removeClass(`opens-${this.options.alignment}`).addClass('opens-inner');
<ide> }
<ide> this.changed = true;
<ide> }
<ide> $sub.css('visibility', '');
<del> if(this.options.closeOnClick){ this._addBodyHandler(); }
<add> if (this.options.closeOnClick) { this._addBodyHandler(); }
<ide> /**
<ide> * Fires when the new dropdown pane is visible.
<ide> * @event DropdownMenu#show
<ide> */
<ide> this.$element.trigger('show.zf.dropdownmenu', [$sub]);
<del> };
<add> }
<add>
<ide> /**
<ide> * Hides a single, currently open dropdown pane, if passed a parameter, otherwise, hides everything.
<ide> * @function
<ide> * @param {Number} idx - index of the $tabs collection to hide
<ide> * @private
<ide> */
<del> DropdownMenu.prototype._hide = function($elem, idx){
<add> _hide($elem, idx) {
<ide> var $toClose;
<del> if($elem && $elem.length){
<add> if ($elem && $elem.length) {
<ide> $toClose = $elem;
<del> }else if(idx !== undefined){
<del> $toClose = this.$tabs.not(function(i, el){
<add> } else if (idx !== undefined) {
<add> $toClose = this.$tabs.not(function(i, el) {
<ide> return i === idx;
<ide> });
<ide> }
<del> else{
<add> else {
<ide> $toClose = this.$element;
<ide> }
<ide> var somethingToClose = $toClose.hasClass('is-active') || $toClose.find('.is-active').length > 0;
<ide>
<del> if(somethingToClose){
<add> if (somethingToClose) {
<ide> $toClose.find('li.is-active').add($toClose).attr({
<ide> 'aria-expanded': false,
<ide> 'data-is-click': false
<ide> 'aria-hidden': true
<ide> }).removeClass('js-dropdown-active');
<ide>
<del> if(this.changed || $toClose.find('opens-inner').length){
<add> if (this.changed || $toClose.find('opens-inner').length) {
<ide> var oldClass = this.options.alignment === 'left' ? 'right' : 'left';
<ide> $toClose.find('li.is-dropdown-submenu-parent').add($toClose)
<ide> .removeClass(`opens-inner opens-${this.options.alignment}`)
<ide> */
<ide> this.$element.trigger('hide.zf.dropdownmenu', [$toClose]);
<ide> }
<del> };
<add> }
<add>
<ide> /**
<ide> * Destroys the plugin.
<ide> * @function
<ide> */
<del> DropdownMenu.prototype.destroy = function(){
<add> destroy() {
<ide> this.$menuItems.off('.zf.dropdownmenu').removeAttr('data-is-click')
<ide> .removeClass('is-right-arrow is-left-arrow is-down-arrow opens-right opens-left opens-inner');
<ide> $(document.body).off('.zf.dropdownmenu');
<ide> Foundation.Nest.Burn(this.$element, 'dropdown');
<ide> Foundation.unregisterPlugin(this);
<del> };
<del>
<del> Foundation.plugin(DropdownMenu, 'DropdownMenu');
<del>}(jQuery, window.Foundation);
<add> }
<add>}
<add>
<add>/**
<add> * Default settings for plugin
<add> */
<add>DropdownMenu.defaults = {
<add> /**
<add> * Disallows hover events from opening submenus
<add> * @option
<add> * @example false
<add> */
<add> disableHover: false,
<add> /**
<add> * Allow a submenu to automatically close on a mouseleave event, if not clicked open.
<add> * @option
<add> * @example true
<add> */
<add> autoclose: true,
<add> /**
<add> * Amount of time to delay opening a submenu on hover event.
<add> * @option
<add> * @example 50
<add> */
<add> hoverDelay: 50,
<add> /**
<add> * Allow a submenu to open/remain open on parent click event. Allows cursor to move away from menu.
<add> * @option
<add> * @example true
<add> */
<add> clickOpen: false,
<add> /**
<add> * Amount of time to delay closing a submenu on a mouseleave event.
<add> * @option
<add> * @example 500
<add> */
<add>
<add> closingTime: 500,
<add> /**
<add> * Position of the menu relative to what direction the submenus should open. Handled by JS.
<add> * @option
<add> * @example 'left'
<add> */
<add> alignment: 'left',
<add> /**
<add> * Allow clicks on the body to close any open submenus.
<add> * @option
<add> * @example true
<add> */
<add> closeOnClick: true,
<add> /**
<add> * Class applied to vertical oriented menus, Foundation default is `vertical`. Update this if using your own class.
<add> * @option
<add> * @example 'vertical'
<add> */
<add> verticalClass: 'vertical',
<add> /**
<add> * Class applied to right-side oriented menus, Foundation default is `align-right`. Update this if using your own class.
<add> * @option
<add> * @example 'align-right'
<add> */
<add> rightClass: 'align-right',
<add> /**
<add> * Boolean to force overide the clicking of links to perform default action, on second touch event for mobile.
<add> * @option
<add> * @example false
<add> */
<add> forceFollow: true
<add>};
<add>
<add>// Window exports
<add>if (window.Foundation) {
<add> window.Foundation.plugin(DropdownMenu, 'DropdownMenu');
<add>} |
|
Java | epl-1.0 | df6183a971c5d784dddbb8dd37df00638e29b82b | 0 | debrief/debrief,debrief/debrief,debrief/debrief,debrief/debrief,debrief/debrief,debrief/debrief | /*
* Debrief - the Open Source Maritime Analysis Application
* http://debrief.info
*
* (C) 2000-2014, PlanetMayo Ltd
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the Eclipse Public License v1.0
* (http://www.eclipse.org/legal/epl-v10.html)
*
* 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.
*/
package org.mwc.debrief.core.ContextOperations;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.operations.IUndoableOperation;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.mwc.cmap.core.CorePlugin;
import org.mwc.cmap.core.operations.CMAPOperation;
import org.mwc.cmap.core.property_support.RightClickSupport.RightClickContextItemGenerator;
import Debrief.Wrappers.FixWrapper;
import Debrief.Wrappers.TrackWrapper;
import Debrief.Wrappers.Track.TrackSegment;
import Debrief.Wrappers.Track.TrackWrapper_Support;
import Debrief.Wrappers.Track.TrackWrapper_Support.SegmentList;
import MWC.Algorithms.Conversions;
import MWC.GUI.Editable;
import MWC.GUI.Layer;
import MWC.GUI.Layers;
import MWC.GenericData.HiResDate;
import MWC.GenericData.WorldLocation;
import MWC.TacticalData.Fix;
import junit.framework.TestCase;
/**
* @author ian.mayo
*/
public class SplitTracksIntoLegs implements RightClickContextItemGenerator
{
private static class SplitTracksOperation extends CMAPOperation
{
/**
* the parent to update on completion
*/
private final Layers _layers;
private final List<TrackWrapper> _tracks;
private final Long _period;
private final HashMap<TrackWrapper, List<TrackSegment>> _trackChanges;
public SplitTracksOperation(final String title, final Layers theLayers,
final List<TrackWrapper> tracks, final Long period)
{
super(title);
_layers = theLayers;
_tracks = tracks;
_period = period;
_trackChanges = new HashMap<TrackWrapper, List<TrackSegment>>();
}
@Override
public boolean canRedo()
{
return true;
}
@Override
public boolean canUndo()
{
return true;
}
@Override
public IStatus execute(final IProgressMonitor monitor,
final IAdaptable info) throws ExecutionException
{
boolean modified = false;
_trackChanges.clear();
// loop through the tracks
for (final TrackWrapper track : _tracks)
{
final List<TrackSegment> newSegments = TrackWrapper_Support
.splitTrackAtJumps(track, _period);
modified = modified || !newSegments.isEmpty();
_trackChanges.put(track, newSegments);
}
// did anything get changed
if (modified)
{
fireModified();
}
return Status.OK_STATUS;
}
private void fireModified()
{
_layers.fireExtended();
}
@Override
public IStatus undo(final IProgressMonitor monitor, final IAdaptable info)
throws ExecutionException
{
int numChanges = 0;
// ok, merge the segments
for (final TrackWrapper track : _trackChanges.keySet())
{
final List<TrackSegment> splits = _trackChanges.get(track);
final TrackSegment target = splits.get(0);
final SegmentList existingSegments = track.getSegments();
int ctr = 0;
for (final TrackSegment segment : splits)
{
if (segment != target)
{
// check this is an existing segment for this track
// if we've performed several split/merge operations
// the list may now be out of sync
if (existingSegments.contains(segment))
{
// remove the segment
track.removeElement(segment);
final Enumeration<Editable> fixes = segment.elements();
while (fixes.hasMoreElements())
{
final FixWrapper fix = (FixWrapper) fixes.nextElement();
target.addFix(fix);
}
ctr++;
}
}
}
numChanges += ctr;
}
final boolean modified = numChanges > 0;
// did anything get changed
if (modified)
{
fireModified();
}
return Status.OK_STATUS;
}
}
public static class TestSplittingTracks extends TestCase
{
private static FixWrapper getFix(final long dtg, final double course,
final double speed)
{
final Fix theFix = new Fix(new HiResDate(dtg), new WorldLocation(2, 2, 2),
course, Conversions.Kts2Yps(speed));
final FixWrapper res = new FixWrapper(theFix);
return res;
}
private static TrackWrapper getOne()
{
final TrackWrapper tOne = new TrackWrapper();
tOne.setName("t-1");
tOne.addFix(getFix(1000, 22, 33));
tOne.addFix(getFix(2000, 22, 33));
tOne.addFix(getFix(2100, 22, 33));
tOne.addFix(getFix(4000, 22, 33));
tOne.addFix(getFix(5000, 22, 33));
tOne.addFix(getFix(6000, 22, 33));
tOne.addFix(getFix(7000, 22, 33));
tOne.addFix(getFix(8000, 22, 33));
tOne.addFix(getFix(9000, 22, 33));
tOne.addFix(getFix(10000, 22, 33));
tOne.addFix(getFix(11100, 22, 33));
tOne.addFix(getFix(12000, 22, 33));
tOne.addFix(getFix(13000, 22, 33));
tOne.addFix(getFix(14000, 22, 33));
return tOne;
}
private static TrackWrapper getTwo()
{
final TrackWrapper tTwo = new TrackWrapper();
tTwo.setName("t-2");
tTwo.addFix(getFix(1000, 22, 33));
tTwo.addFix(getFix(2000, 22, 33));
tTwo.addFix(getFix(2100, 22, 33));
tTwo.addFix(getFix(4000, 22, 33));
tTwo.addFix(getFix(5000, 22, 33));
tTwo.addFix(getFix(8000, 22, 33));
tTwo.addFix(getFix(9000, 22, 33));
tTwo.addFix(getFix(10000, 22, 33));
tTwo.addFix(getFix(11100, 22, 33));
tTwo.addFix(getFix(12000, 22, 33));
tTwo.addFix(getFix(13000, 22, 33));
tTwo.addFix(getFix(14000, 22, 33));
return tTwo;
}
public void testSplitOperation() throws ExecutionException
{
final TrackWrapper tOne = getOne();
final TrackWrapper tTwo = getTwo();
final Layers layers = new Layers();
layers.addThisLayer(tOne);
layers.addThisLayer(tTwo);
final List<TrackWrapper> tracks = new ArrayList<TrackWrapper>();
tracks.add(tOne);
tracks.add(tTwo);
final SplitTracksOperation oper = new SplitTracksOperation("Split tracks",
layers, tracks, 1000L);
assertEquals("just one leg", 1, tOne.getSegments().size());
assertEquals("just one leg", 1, tTwo.getSegments().size());
assertEquals("correct positions", 14, tOne.numFixes());
assertEquals("correct positions", 12, tTwo.numFixes());
oper.execute(null, null);
// check the contents of the operation
final HashMap<TrackWrapper, List<TrackSegment>> map = oper._trackChanges;
assertEquals("two tracks", 2, map.keySet().size());
assertEquals("more leg", 3, tOne.getSegments().size());
assertEquals("more legs", 4, tTwo.getSegments().size());
assertEquals("correct positions", 14, tOne.numFixes());
assertEquals("correct positions", 12, tTwo.numFixes());
oper.undo(null, null);
assertEquals("just one leg", 1, tOne.getSegments().size());
assertEquals("just one leg", 1, tTwo.getSegments().size());
assertEquals("correct positions", 14, tOne.numFixes());
assertEquals("correct positions", 12, tTwo.numFixes());
}
}
@Override
public void generate(final IMenuManager parent, final Layers theLayers,
final Layer[] parentLayers, final Editable[] subjects)
{
boolean goForIt = true;
final List<TrackWrapper> tracks = new ArrayList<TrackWrapper>();
// we're only going to work with one or more items
if (subjects.length > 0)
{
// are they tracks?
for (int i = 0; i < subjects.length; i++)
{
final Editable thisE = subjects[i];
if (thisE instanceof TrackWrapper)
{
goForIt = true;
tracks.add((TrackWrapper) thisE);
}
else
{
goForIt = false;
}
}
}
// check we got more than one to group
if (tracks.size() < 1)
goForIt = false;
// ok, is it worth going for?
if (goForIt)
{
// right,stick in a separator
parent.add(new Separator());
final String msg = tracks.size() > 1 ? "tracks" : "track";
final String fullMsg = "Split " + msg + " into segments on gaps over...";
final MenuManager listing = new MenuManager(fullMsg);
final HashMap<Long, String> choices = new HashMap<Long, String>();
choices.put(60 * 1000L, "1 Minute");
choices.put(60 * 60 * 1000L, "1 Hour");
choices.put(24 * 60 * 60 * 1000L, "1 Day");
choices.put(7 * 24 * 60 * 60 * 1000L, "1 Week");
for (final Long period : choices.keySet())
{
// get the time period
final String label = choices.get(period);
// create this operation
final Action doMerge = new Action(label)
{
@Override
public void run()
{
final IUndoableOperation theAction = new SplitTracksOperation(
"Split tracks at jumps over " + label, theLayers, tracks,
period);
CorePlugin.run(theAction);
}
};
listing.add(doMerge);
}
parent.add(listing);
}
}
}
| org.mwc.debrief.core/src/org/mwc/debrief/core/ContextOperations/SplitTracksIntoLegs.java | /*
* Debrief - the Open Source Maritime Analysis Application
* http://debrief.info
*
* (C) 2000-2014, PlanetMayo Ltd
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the Eclipse Public License v1.0
* (http://www.eclipse.org/legal/epl-v10.html)
*
* 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.
*/
package org.mwc.debrief.core.ContextOperations;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.operations.IUndoableOperation;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.mwc.cmap.core.CorePlugin;
import org.mwc.cmap.core.operations.CMAPOperation;
import org.mwc.cmap.core.property_support.RightClickSupport.RightClickContextItemGenerator;
import Debrief.Wrappers.FixWrapper;
import Debrief.Wrappers.TrackWrapper;
import Debrief.Wrappers.Track.TrackSegment;
import Debrief.Wrappers.Track.TrackWrapper_Support;
import MWC.Algorithms.Conversions;
import MWC.GUI.Editable;
import MWC.GUI.Layer;
import MWC.GUI.Layers;
import MWC.GenericData.HiResDate;
import MWC.GenericData.WorldLocation;
import MWC.TacticalData.Fix;
import junit.framework.TestCase;
/**
* @author ian.mayo
*/
public class SplitTracksIntoLegs implements RightClickContextItemGenerator
{
private static class SplitTracksOperation extends CMAPOperation
{
/**
* the parent to update on completion
*/
private final Layers _layers;
private final List<TrackWrapper> _tracks;
private final Long _period;
private final HashMap<TrackWrapper, List<TrackSegment>> _trackChanges;
public SplitTracksOperation(final String title, final Layers theLayers,
final List<TrackWrapper> tracks, final Long period)
{
super(title);
_layers = theLayers;
_tracks = tracks;
_period = period;
_trackChanges = new HashMap<TrackWrapper, List<TrackSegment>>();
}
@Override
public boolean canRedo()
{
return true;
}
@Override
public boolean canUndo()
{
return true;
}
@Override
public IStatus execute(final IProgressMonitor monitor,
final IAdaptable info) throws ExecutionException
{
boolean modified = false;
_trackChanges.clear();
// loop through the tracks
for (final TrackWrapper track : _tracks)
{
final List<TrackSegment> newSegments = TrackWrapper_Support
.splitTrackAtJumps(track, _period);
modified = modified || !newSegments.isEmpty();
_trackChanges.put(track, newSegments);
}
// did anything get changed
if (modified)
{
fireModified();
}
return Status.OK_STATUS;
}
private void fireModified()
{
_layers.fireExtended();
}
@Override
public IStatus undo(final IProgressMonitor monitor, final IAdaptable info)
throws ExecutionException
{
int numChanges = 0;
// ok, merge the segments
for (final TrackWrapper track : _trackChanges.keySet())
{
final List<TrackSegment> splits = _trackChanges.get(track);
final TrackSegment target = splits.get(0);
int ctr = 0;
for (final TrackSegment segment : splits)
{
if (segment != target)
{
// remove the segment
track.removeElement(segment);
final Enumeration<Editable> fixes = segment.elements();
while (fixes.hasMoreElements())
{
final FixWrapper fix = (FixWrapper) fixes.nextElement();
target.addFix(fix);
}
ctr++;
}
}
numChanges += ctr;
}
final boolean modified = numChanges > 0;
// did anything get changed
if (modified)
{
fireModified();
}
return Status.OK_STATUS;
}
}
public static class TestSplittingTracks extends TestCase
{
private static FixWrapper getFix(final long dtg, final double course,
final double speed)
{
final Fix theFix = new Fix(new HiResDate(dtg), new WorldLocation(2, 2, 2),
course, Conversions.Kts2Yps(speed));
final FixWrapper res = new FixWrapper(theFix);
return res;
}
private static TrackWrapper getOne()
{
final TrackWrapper tOne = new TrackWrapper();
tOne.setName("t-1");
tOne.addFix(getFix(1000, 22, 33));
tOne.addFix(getFix(2000, 22, 33));
tOne.addFix(getFix(2100, 22, 33));
tOne.addFix(getFix(4000, 22, 33));
tOne.addFix(getFix(5000, 22, 33));
tOne.addFix(getFix(6000, 22, 33));
tOne.addFix(getFix(7000, 22, 33));
tOne.addFix(getFix(8000, 22, 33));
tOne.addFix(getFix(9000, 22, 33));
tOne.addFix(getFix(10000, 22, 33));
tOne.addFix(getFix(11100, 22, 33));
tOne.addFix(getFix(12000, 22, 33));
tOne.addFix(getFix(13000, 22, 33));
tOne.addFix(getFix(14000, 22, 33));
return tOne;
}
private static TrackWrapper getTwo()
{
final TrackWrapper tTwo = new TrackWrapper();
tTwo.setName("t-2");
tTwo.addFix(getFix(1000, 22, 33));
tTwo.addFix(getFix(2000, 22, 33));
tTwo.addFix(getFix(2100, 22, 33));
tTwo.addFix(getFix(4000, 22, 33));
tTwo.addFix(getFix(5000, 22, 33));
tTwo.addFix(getFix(8000, 22, 33));
tTwo.addFix(getFix(9000, 22, 33));
tTwo.addFix(getFix(10000, 22, 33));
tTwo.addFix(getFix(11100, 22, 33));
tTwo.addFix(getFix(12000, 22, 33));
tTwo.addFix(getFix(13000, 22, 33));
tTwo.addFix(getFix(14000, 22, 33));
return tTwo;
}
public void testSplitOperation() throws ExecutionException
{
final TrackWrapper tOne = getOne();
final TrackWrapper tTwo = getTwo();
final Layers layers = new Layers();
layers.addThisLayer(tOne);
layers.addThisLayer(tTwo);
final List<TrackWrapper> tracks = new ArrayList<TrackWrapper>();
tracks.add(tOne);
tracks.add(tTwo);
final SplitTracksOperation oper = new SplitTracksOperation("Split tracks",
layers, tracks, 1000L);
assertEquals("just one leg", 1, tOne.getSegments().size());
assertEquals("just one leg", 1, tTwo.getSegments().size());
assertEquals("correct positions", 14, tOne.numFixes());
assertEquals("correct positions", 12, tTwo.numFixes());
oper.execute(null, null);
// check the contents of the operation
final HashMap<TrackWrapper, List<TrackSegment>> map = oper._trackChanges;
assertEquals("two tracks", 2, map.keySet().size());
assertEquals("more leg", 3, tOne.getSegments().size());
assertEquals("more legs", 4, tTwo.getSegments().size());
assertEquals("correct positions", 14, tOne.numFixes());
assertEquals("correct positions", 12, tTwo.numFixes());
oper.undo(null, null);
assertEquals("just one leg", 1, tOne.getSegments().size());
assertEquals("just one leg", 1, tTwo.getSegments().size());
assertEquals("correct positions", 14, tOne.numFixes());
assertEquals("correct positions", 12, tTwo.numFixes());
}
}
@Override
public void generate(final IMenuManager parent, final Layers theLayers,
final Layer[] parentLayers, final Editable[] subjects)
{
boolean goForIt = true;
final List<TrackWrapper> tracks = new ArrayList<TrackWrapper>();
// we're only going to work with one or more items
if (subjects.length > 0)
{
// are they tracks?
for (int i = 0; i < subjects.length; i++)
{
final Editable thisE = subjects[i];
if (thisE instanceof TrackWrapper)
{
goForIt = true;
tracks.add((TrackWrapper) thisE);
}
else
{
goForIt = false;
}
}
}
// check we got more than one to group
if (tracks.size() < 1)
goForIt = false;
// ok, is it worth going for?
if (goForIt)
{
// right,stick in a separator
parent.add(new Separator());
final String msg = tracks.size() > 1 ? "tracks" : "track";
final String fullMsg = "Split " + msg + " into segments on gaps over...";
final MenuManager listing = new MenuManager(fullMsg);
final HashMap<Long, String> choices = new HashMap<Long, String>();
choices.put(60 * 1000L, "1 Minute");
choices.put(60 * 60 * 1000L, "1 Hour");
choices.put(24 * 60 * 60 * 1000L, "1 Day");
choices.put(7 * 24 * 60 * 60 * 1000L, "1 Week");
for (final Long period : choices.keySet())
{
// get the time period
final String label = choices.get(period);
// create this operation
final Action doMerge = new Action(label)
{
@Override
public void run()
{
final IUndoableOperation theAction = new SplitTracksOperation(
"Split tracks at jumps over " + label, theLayers, tracks,
period);
CorePlugin.run(theAction);
}
};
listing.add(doMerge);
}
parent.add(listing);
}
}
}
| Avoid warnings when undoing split tracks
| org.mwc.debrief.core/src/org/mwc/debrief/core/ContextOperations/SplitTracksIntoLegs.java | Avoid warnings when undoing split tracks | <ide><path>rg.mwc.debrief.core/src/org/mwc/debrief/core/ContextOperations/SplitTracksIntoLegs.java
<ide> import Debrief.Wrappers.TrackWrapper;
<ide> import Debrief.Wrappers.Track.TrackSegment;
<ide> import Debrief.Wrappers.Track.TrackWrapper_Support;
<add>import Debrief.Wrappers.Track.TrackWrapper_Support.SegmentList;
<ide> import MWC.Algorithms.Conversions;
<ide> import MWC.GUI.Editable;
<ide> import MWC.GUI.Layer;
<ide>
<ide> final TrackSegment target = splits.get(0);
<ide>
<add> final SegmentList existingSegments = track.getSegments();
<add>
<ide> int ctr = 0;
<ide> for (final TrackSegment segment : splits)
<ide> {
<ide> if (segment != target)
<ide> {
<del> // remove the segment
<del> track.removeElement(segment);
<del>
<del> final Enumeration<Editable> fixes = segment.elements();
<del> while (fixes.hasMoreElements())
<add> // check this is an existing segment for this track
<add> // if we've performed several split/merge operations
<add> // the list may now be out of sync
<add> if (existingSegments.contains(segment))
<ide> {
<del> final FixWrapper fix = (FixWrapper) fixes.nextElement();
<del> target.addFix(fix);
<add> // remove the segment
<add> track.removeElement(segment);
<add>
<add> final Enumeration<Editable> fixes = segment.elements();
<add> while (fixes.hasMoreElements())
<add> {
<add> final FixWrapper fix = (FixWrapper) fixes.nextElement();
<add> target.addFix(fix);
<add> }
<add> ctr++;
<ide> }
<del> ctr++;
<ide> }
<ide> }
<ide> |
|
JavaScript | mit | cd568ccccb22c72b499b7e25de823c7363a618c8 | 0 | itgfirm/safe-food,itgfirm/safe-food,itgfirm/safe-food | // Karma configuration
// http://karma-runner.github.io/0.10/config/configuration-file.html
module.exports = function(config) {
config.set({
// base path, that will be used to resolve files and exclude
basePath: '../../',
// testing framework to use (jasmine/mocha/qunit/...)
frameworks: ['jasmine', 'requirejs'],
// list of files / patterns to load in the browser
files: [
'client/test/test-main.js',
{pattern: 'client/**/*.js', included: false}
],
// list of files / patterns to exclude
exclude: [
'client/scripts/main.js',
'client/vendor/**/*_spec.js'
],
// web server port
port: 8080,
// level of logging
// possible values:
// LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel: config.LOG_INFO,
reporters: ['dots'],
// enable / disable watching file and executing
// tests whenever any file changes
autoWatch: false,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers: ['PhantomJS'],
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: false
});
};
| client/test/karma.conf.js | // Karma configuration
// http://karma-runner.github.io/0.10/config/configuration-file.html
module.exports = function(config) {
config.set({
// base path, that will be used to resolve files and exclude
basePath: '../../',
// testing framework to use (jasmine/mocha/qunit/...)
frameworks: ['jasmine', "requirejs"],
// list of files / patterns to load in the browser
files: [
'client/test/test-main.js',
{pattern: 'client/**/*.js', included: false}
],
// list of files / patterns to exclude
exclude: [
'client/scripts/main.js',
'client/vendor/**/*_spec.js'
],
// web server port
port: 8080,
// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel: config.LOG_INFO,
reporters: ['dots'],
// enable / disable watching file and executing tests whenever any file changes
autoWatch: false,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers: ['PhantomJS'],
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: false
});
};
| cleaned up a bit of lint in the karma config
| client/test/karma.conf.js | cleaned up a bit of lint in the karma config | <ide><path>lient/test/karma.conf.js
<ide> basePath: '../../',
<ide>
<ide> // testing framework to use (jasmine/mocha/qunit/...)
<del> frameworks: ['jasmine', "requirejs"],
<add> frameworks: ['jasmine', 'requirejs'],
<ide>
<ide> // list of files / patterns to load in the browser
<ide> files: [
<ide> port: 8080,
<ide>
<ide> // level of logging
<del> // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
<add> // possible values:
<add> // LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
<ide> logLevel: config.LOG_INFO,
<ide>
<ide> reporters: ['dots'],
<ide>
<del> // enable / disable watching file and executing tests whenever any file changes
<add> // enable / disable watching file and executing
<add> // tests whenever any file changes
<ide> autoWatch: false,
<ide>
<ide> |
|
Java | apache-2.0 | 9918198dfcffa69a82d3f7cda3d1313b36708f52 | 0 | bibliolabs/rome,rometools/rome,rometools/rome,bibliolabs/rome | /*
* ConverterForOPML10.java
*
* Created on April 25, 2006, 1:26 AM
*
* 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.sun.syndication.feed.synd.impl;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Stack;
import java.util.logging.Logger;
import com.sun.syndication.feed.WireFeed;
import com.sun.syndication.feed.opml.Attribute;
import com.sun.syndication.feed.opml.Opml;
import com.sun.syndication.feed.opml.Outline;
import com.sun.syndication.feed.synd.Converter;
import com.sun.syndication.feed.synd.SyndCategory;
import com.sun.syndication.feed.synd.SyndCategoryImpl;
import com.sun.syndication.feed.synd.SyndContent;
import com.sun.syndication.feed.synd.SyndContentImpl;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndEntryImpl;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.feed.synd.SyndLink;
import com.sun.syndication.feed.synd.SyndLinkImpl;
import com.sun.syndication.feed.synd.SyndPerson;
import com.sun.syndication.feed.synd.SyndPersonImpl;
/**
*
* @author cooper
*/
public class ConverterForOPML10 implements Converter {
private static final Logger LOG = Logger.getLogger(ConverterForOPML10.class.getName().toString());
public static final String URI_TREE = "urn:rome.tree";
public static final String URI_ATTRIBUTE = "urn:rome.attribute#";
/** Creates a new instance of ConverterForOPML10 */
public ConverterForOPML10() {
super();
}
protected void addOwner(final Opml opml, final SyndFeed syndFeed) {
if (opml.getOwnerEmail() != null || opml.getOwnerName() != null) {
final List<SyndPerson> authors = new ArrayList<SyndPerson>();
final SyndPerson person = new SyndPersonImpl();
person.setEmail(opml.getOwnerEmail());
person.setName(opml.getOwnerName());
authors.add(person);
syndFeed.setAuthors(authors);
}
}
/**
* Makes a deep copy/conversion of the values of a real feed into a SyndFeedImpl.
* <p>
* It assumes the given SyndFeedImpl has no properties set.
* <p>
*
* @param feed real feed to copy/convert.
* @param syndFeed the SyndFeedImpl that will contain the copied/converted values of the real feed.
*/
@Override
public void copyInto(final WireFeed feed, final SyndFeed syndFeed) {
final Opml opml = (Opml) feed;
syndFeed.setTitle(opml.getTitle());
addOwner(opml, syndFeed);
syndFeed.setPublishedDate(opml.getModified() != null ? opml.getModified() : opml.getCreated());
syndFeed.setFeedType(opml.getFeedType());
syndFeed.setModules(opml.getModules());
syndFeed.setFeedType(getType());
createEntries(new TreeContext(), syndFeed.getEntries(), opml.getOutlines());
}
protected void createEntries(final TreeContext context, final List<SyndEntry> allEntries, final List<Outline> outlines) {
final List<Outline> so = Collections.synchronizedList(outlines);
for (int i = 0; i < so.size(); i++) {
createEntry(context, allEntries, so.get(i));
}
}
protected SyndEntry createEntry(final TreeContext context, final List<SyndEntry> allEntries, final Outline outline) {
final SyndEntry entry = new SyndEntryImpl();
if (outline.getType() != null && outline.getType().equals("rss")) {
entry.setLink(outline.getHtmlUrl() != null ? outline.getHtmlUrl() : outline.getXmlUrl());
} else if (outline.getType() != null && outline.getType().equals("link")) {
entry.setLink(outline.getUrl());
}
if (outline.getHtmlUrl() != null) {
final SyndLink link = new SyndLinkImpl();
link.setRel("alternate");
link.setType("text/html");
link.setHref(outline.getHtmlUrl());
entry.getLinks().add(link);
entry.setLink(outline.getHtmlUrl());
}
if (outline.getXmlUrl() != null && outline.getType() != null && outline.getType().equalsIgnoreCase("rss")) {
final SyndLink link = new SyndLinkImpl();
link.setRel("alternate");
link.setType("application/rss+xml");
link.setHref(outline.getXmlUrl());
entry.getLinks().add(link);
if (entry.getLink() == null) {
entry.setLink(outline.getXmlUrl());
}
}
if (outline.getXmlUrl() != null && outline.getType() != null && outline.getType().equalsIgnoreCase("atom")) {
final SyndLink link = new SyndLinkImpl();
link.setRel("alternate");
link.setType("application/atom+xml");
link.setHref(outline.getXmlUrl());
entry.getLinks().add(link);
if (entry.getLink() == null) {
entry.setLink(outline.getXmlUrl());
}
}
if (outline.getType() != null && outline.getType().equals("rss")) {
entry.setTitle(outline.getTitle());
} else {
entry.setTitle(outline.getText());
}
if (outline.getText() == null && entry.getTitle() != null) {
final SyndContent c = new SyndContentImpl();
c.setValue(outline.getText());
entry.setDescription(c);
}
entry.setPublishedDate(outline.getCreated());
final String nodeName = "node." + outline.hashCode();
final SyndCategory cat = new TreeCategoryImpl();
cat.setTaxonomyUri(URI_TREE);
cat.setName(nodeName);
entry.getCategories().add(cat);
if (!context.isEmpty()) {
final Integer parent = context.peek();
final SyndCategory pcat = new TreeCategoryImpl();
pcat.setTaxonomyUri(URI_TREE);
pcat.setName("parent." + parent);
entry.getCategories().add(pcat);
}
final List<Attribute> attributes = Collections.synchronizedList(outline.getAttributes());
for (int i = 0; i < attributes.size(); i++) {
final Attribute a = attributes.get(i);
final SyndCategory acat = new SyndCategoryImpl();
acat.setName(a.getValue());
acat.setTaxonomyUri(URI_ATTRIBUTE + a.getName());
entry.getCategories().add(acat);
}
entry.setModules(outline.getModules());
allEntries.add(entry);
context.push(new Integer(outline.hashCode()));
createEntries(context, allEntries, outline.getChildren());
context.pop();
return entry;
}
/**
* Creates real feed with a deep copy/conversion of the values of a SyndFeedImpl.
* <p>
*
* @param syndFeed SyndFeedImpl to copy/convert value from.
* @return a real feed with copied/converted values of the SyndFeedImpl.
*
*/
@Override
public WireFeed createRealFeed(final SyndFeed syndFeed) {
final List<SyndEntry> entries = Collections.synchronizedList(syndFeed.getEntries());
final HashMap<String, Outline> entriesByNode = new HashMap<String, Outline>();
final ArrayList<OutlineHolder> doAfterPass = new ArrayList<OutlineHolder>(); // this will hold entries that we can't parent the first time.
final ArrayList<Outline> root = new ArrayList<Outline>(); // this holds root level outlines;
for (int i = 0; i < entries.size(); i++) {
final SyndEntry entry = entries.get(i);
final Outline o = new Outline();
final List<SyndCategory> cats = Collections.synchronizedList(entry.getCategories());
boolean parentFound = false;
final StringBuffer category = new StringBuffer();
for (int j = 0; j < cats.size(); j++) {
final SyndCategory cat = cats.get(j);
if (cat.getTaxonomyUri() != null && cat.getTaxonomyUri().equals(URI_TREE)) {
final String nodeVal = cat.getName().substring(cat.getName().lastIndexOf("."), cat.getName().length());
if (cat.getName().startsWith("node.")) {
entriesByNode.put(nodeVal, o);
} else if (cat.getName().startsWith("parent.")) {
parentFound = true;
final Outline parent = entriesByNode.get(nodeVal);
if (parent != null) {
parent.getChildren().add(o);
} else {
doAfterPass.add(new OutlineHolder(o, nodeVal));
}
}
} else if (cat.getTaxonomyUri() != null && cat.getTaxonomyUri().startsWith(URI_ATTRIBUTE)) {
final String name = cat.getTaxonomyUri().substring(cat.getTaxonomyUri().indexOf("#") + 1, cat.getTaxonomyUri().length());
o.getAttributes().add(new Attribute(name, cat.getName()));
} else {
if (category.length() > 0) {
category.append(", ");
}
category.append(cat.getName());
}
}
if (!parentFound) {
root.add(o);
}
if (category.length() > 0) {
o.getAttributes().add(new Attribute("category", category.toString()));
}
final List<SyndLink> links = Collections.synchronizedList(entry.getLinks());
// final String entryLink = entry.getLink();
for (int j = 0; j < links.size(); j++) {
final SyndLink link = links.get(j);
// if(link.getHref().equals(entryLink)) {
if (link.getType() != null && link.getRel() != null && link.getRel().equals("alternate")
&& (link.getType().equals("application/rss+xml") || link.getType().equals("application/atom+xml"))) {
o.setType("rss");
if (o.getXmlUrl() == null) {
o.getAttributes().add(new Attribute("xmlUrl", link.getHref()));
}
} else if (link.getType() != null && link.getType().equals("text/html")) {
if (o.getHtmlUrl() == null) {
o.getAttributes().add(new Attribute("htmlUrl", link.getHref()));
}
} else {
o.setType(link.getType());
}
// }
}
if (o.getType() == null || o.getType().equals("link")) {
o.setText(entry.getTitle());
} else {
o.setTitle(entry.getTitle());
}
if (o.getText() == null && entry.getDescription() != null) {
o.setText(entry.getDescription().getValue());
}
}
// Do back and parenting for things we missed.
for (int i = 0; i < doAfterPass.size(); i++) {
final OutlineHolder o = doAfterPass.get(i);
final Outline parent = entriesByNode.get(o.parent);
if (parent == null) {
root.add(o.outline);
LOG.warning("Unable to find parent node :" + o.parent);
} else {
parent.getChildren().add(o.outline);
}
}
final Opml opml = new Opml();
opml.setFeedType(getType());
opml.setCreated(syndFeed.getPublishedDate());
opml.setTitle(syndFeed.getTitle());
final List<SyndPerson> authors = Collections.synchronizedList(syndFeed.getAuthors());
for (int i = 0; i < authors.size(); i++) {
final SyndPerson p = authors.get(i);
if (syndFeed.getAuthor() == null || syndFeed.getAuthor().equals(p.getName())) {
opml.setOwnerName(p.getName());
opml.setOwnerEmail(p.getEmail());
opml.setOwnerId(p.getUri());
}
}
opml.setOutlines(root);
return opml;
}
/**
* Returns the type (version) of the real feed this converter handles.
* <p>
*
* @return the real feed type.
* @see WireFeed for details on the format of this string.
* <p>
*/
@Override
public String getType() {
return "opml_1.0";
}
private static class OutlineHolder {
Outline outline;
String parent;
public OutlineHolder(final Outline outline, final String parent) {
this.outline = outline;
this.parent = parent;
}
}
private static class TreeContext extends Stack<Integer> {
private static final long serialVersionUID = 1L;
TreeContext() {
super();
}
}
}
| src/main/java/com/sun/syndication/feed/synd/impl/ConverterForOPML10.java | /*
* ConverterForOPML10.java
*
* Created on April 25, 2006, 1:26 AM
*
* 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.sun.syndication.feed.synd.impl;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Stack;
import java.util.logging.Logger;
import com.sun.syndication.feed.WireFeed;
import com.sun.syndication.feed.opml.Attribute;
import com.sun.syndication.feed.opml.Opml;
import com.sun.syndication.feed.opml.Outline;
import com.sun.syndication.feed.synd.Converter;
import com.sun.syndication.feed.synd.SyndCategory;
import com.sun.syndication.feed.synd.SyndCategoryImpl;
import com.sun.syndication.feed.synd.SyndContent;
import com.sun.syndication.feed.synd.SyndContentImpl;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndEntryImpl;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.feed.synd.SyndLink;
import com.sun.syndication.feed.synd.SyndLinkImpl;
import com.sun.syndication.feed.synd.SyndPerson;
import com.sun.syndication.feed.synd.SyndPersonImpl;
/**
*
* @author cooper
*/
public class ConverterForOPML10 implements Converter {
private static final Logger LOG = Logger.getLogger(ConverterForOPML10.class.getName().toString());
public static final String URI_TREE = "urn:rome.tree";
public static final String URI_ATTRIBUTE = "urn:rome.attribute#";
/** Creates a new instance of ConverterForOPML10 */
public ConverterForOPML10() {
super();
}
protected void addOwner(final Opml opml, final SyndFeed syndFeed) {
if (opml.getOwnerEmail() != null || opml.getOwnerName() != null) {
final List<SyndPerson> authors = new ArrayList<SyndPerson>();
final SyndPerson person = new SyndPersonImpl();
person.setEmail(opml.getOwnerEmail());
person.setName(opml.getOwnerName());
authors.add(person);
syndFeed.setAuthors(authors);
}
}
/**
* Makes a deep copy/conversion of the values of a real feed into a SyndFeedImpl.
* <p>
* It assumes the given SyndFeedImpl has no properties set.
* <p>
*
* @param feed real feed to copy/convert.
* @param syndFeed the SyndFeedImpl that will contain the copied/converted values of the real feed.
*/
@Override
public void copyInto(final WireFeed feed, final SyndFeed syndFeed) {
final Opml opml = (Opml) feed;
syndFeed.setTitle(opml.getTitle());
addOwner(opml, syndFeed);
syndFeed.setPublishedDate(opml.getModified() != null ? opml.getModified() : opml.getCreated());
syndFeed.setFeedType(opml.getFeedType());
syndFeed.setModules(opml.getModules());
syndFeed.setFeedType(getType());
createEntries(new TreeContext(), syndFeed.getEntries(), opml.getOutlines());
}
protected void createEntries(final TreeContext context, final List<SyndEntry> allEntries, final List<Outline> outlines) {
final List<Outline> so = Collections.synchronizedList(outlines);
for (int i = 0; i < so.size(); i++) {
createEntry(context, allEntries, so.get(i));
}
}
protected SyndEntry createEntry(final TreeContext context, final List<SyndEntry> allEntries, final Outline outline) {
final SyndEntry entry = new SyndEntryImpl();
if (outline.getType() != null && outline.getType().equals("rss")) {
entry.setLink(outline.getHtmlUrl() != null ? outline.getHtmlUrl() : outline.getXmlUrl());
} else if (outline.getType() != null && outline.getType().equals("link")) {
entry.setLink(outline.getUrl());
}
if (outline.getHtmlUrl() != null) {
final SyndLink link = new SyndLinkImpl();
link.setRel("alternate");
link.setType("text/html");
link.setHref(outline.getHtmlUrl());
entry.getLinks().add(link);
entry.setLink(outline.getHtmlUrl());
}
if (outline.getXmlUrl() != null && outline.getType() != null && outline.getType().equalsIgnoreCase("rss")) {
final SyndLink link = new SyndLinkImpl();
link.setRel("alternate");
link.setType("application/rss+xml");
link.setHref(outline.getXmlUrl());
entry.getLinks().add(link);
if (entry.getLink() == null) {
entry.setLink(outline.getXmlUrl());
}
}
if (outline.getXmlUrl() != null && outline.getType() != null && outline.getType().equalsIgnoreCase("atom")) {
final SyndLink link = new SyndLinkImpl();
link.setRel("alternate");
link.setType("application/atom+xml");
link.setHref(outline.getXmlUrl());
entry.getLinks().add(link);
if (entry.getLink() == null) {
entry.setLink(outline.getXmlUrl());
}
}
if (outline.getType() != null && outline.getType().equals("rss")) {
entry.setTitle(outline.getTitle());
} else {
entry.setTitle(outline.getText());
}
if (outline.getText() == null && entry.getTitle() != null) {
final SyndContent c = new SyndContentImpl();
c.setValue(outline.getText());
entry.setDescription(c);
}
entry.setPublishedDate(outline.getCreated());
final String nodeName = "node." + outline.hashCode();
final SyndCategory cat = new TreeCategoryImpl();
cat.setTaxonomyUri(URI_TREE);
cat.setName(nodeName);
entry.getCategories().add(cat);
if (context.size() > 0) {
final Integer parent = context.peek();
final SyndCategory pcat = new TreeCategoryImpl();
pcat.setTaxonomyUri(URI_TREE);
pcat.setName("parent." + parent);
entry.getCategories().add(pcat);
}
final List<Attribute> attributes = Collections.synchronizedList(outline.getAttributes());
for (int i = 0; i < attributes.size(); i++) {
final Attribute a = attributes.get(i);
final SyndCategory acat = new SyndCategoryImpl();
acat.setName(a.getValue());
acat.setTaxonomyUri(URI_ATTRIBUTE + a.getName());
entry.getCategories().add(acat);
}
entry.setModules(outline.getModules());
allEntries.add(entry);
context.push(new Integer(outline.hashCode()));
createEntries(context, allEntries, outline.getChildren());
context.pop();
return entry;
}
/**
* Creates real feed with a deep copy/conversion of the values of a SyndFeedImpl.
* <p>
*
* @param syndFeed SyndFeedImpl to copy/convert value from.
* @return a real feed with copied/converted values of the SyndFeedImpl.
*
*/
@Override
public WireFeed createRealFeed(final SyndFeed syndFeed) {
final List<SyndEntry> entries = Collections.synchronizedList(syndFeed.getEntries());
final HashMap<String, Outline> entriesByNode = new HashMap<String, Outline>();
final ArrayList<OutlineHolder> doAfterPass = new ArrayList<OutlineHolder>(); // this will hold entries that we can't parent the first time.
final ArrayList<Outline> root = new ArrayList<Outline>(); // this holds root level outlines;
for (int i = 0; i < entries.size(); i++) {
final SyndEntry entry = entries.get(i);
final Outline o = new Outline();
final List<SyndCategory> cats = Collections.synchronizedList(entry.getCategories());
boolean parentFound = false;
final StringBuffer category = new StringBuffer();
for (int j = 0; j < cats.size(); j++) {
final SyndCategory cat = cats.get(j);
if (cat.getTaxonomyUri() != null && cat.getTaxonomyUri().equals(URI_TREE)) {
final String nodeVal = cat.getName().substring(cat.getName().lastIndexOf("."), cat.getName().length());
if (cat.getName().startsWith("node.")) {
entriesByNode.put(nodeVal, o);
} else if (cat.getName().startsWith("parent.")) {
parentFound = true;
final Outline parent = entriesByNode.get(nodeVal);
if (parent != null) {
parent.getChildren().add(o);
} else {
doAfterPass.add(new OutlineHolder(o, nodeVal));
}
}
} else if (cat.getTaxonomyUri() != null && cat.getTaxonomyUri().startsWith(URI_ATTRIBUTE)) {
final String name = cat.getTaxonomyUri().substring(cat.getTaxonomyUri().indexOf("#") + 1, cat.getTaxonomyUri().length());
o.getAttributes().add(new Attribute(name, cat.getName()));
} else {
if (category.length() > 0) {
category.append(", ");
}
category.append(cat.getName());
}
}
if (!parentFound) {
root.add(o);
}
if (category.length() > 0) {
o.getAttributes().add(new Attribute("category", category.toString()));
}
final List<SyndLink> links = Collections.synchronizedList(entry.getLinks());
// final String entryLink = entry.getLink();
for (int j = 0; j < links.size(); j++) {
final SyndLink link = links.get(j);
// if(link.getHref().equals(entryLink)) {
if (link.getType() != null && link.getRel() != null && link.getRel().equals("alternate")
&& (link.getType().equals("application/rss+xml") || link.getType().equals("application/atom+xml"))) {
o.setType("rss");
if (o.getXmlUrl() == null) {
o.getAttributes().add(new Attribute("xmlUrl", link.getHref()));
}
} else if (link.getType() != null && link.getType().equals("text/html")) {
if (o.getHtmlUrl() == null) {
o.getAttributes().add(new Attribute("htmlUrl", link.getHref()));
}
} else {
o.setType(link.getType());
}
// }
}
if (o.getType() == null || o.getType().equals("link")) {
o.setText(entry.getTitle());
} else {
o.setTitle(entry.getTitle());
}
if (o.getText() == null && entry.getDescription() != null) {
o.setText(entry.getDescription().getValue());
}
}
// Do back and parenting for things we missed.
for (int i = 0; i < doAfterPass.size(); i++) {
final OutlineHolder o = doAfterPass.get(i);
final Outline parent = entriesByNode.get(o.parent);
if (parent == null) {
root.add(o.outline);
LOG.warning("Unable to find parent node :" + o.parent);
} else {
parent.getChildren().add(o.outline);
}
}
final Opml opml = new Opml();
opml.setFeedType(getType());
opml.setCreated(syndFeed.getPublishedDate());
opml.setTitle(syndFeed.getTitle());
final List<SyndPerson> authors = Collections.synchronizedList(syndFeed.getAuthors());
for (int i = 0; i < authors.size(); i++) {
final SyndPerson p = authors.get(i);
if (syndFeed.getAuthor() == null || syndFeed.getAuthor().equals(p.getName())) {
opml.setOwnerName(p.getName());
opml.setOwnerEmail(p.getEmail());
opml.setOwnerId(p.getUri());
}
}
opml.setOutlines(root);
return opml;
}
/**
* Returns the type (version) of the real feed this converter handles.
* <p>
*
* @return the real feed type.
* @see WireFeed for details on the format of this string.
* <p>
*/
@Override
public String getType() {
return "opml_1.0";
}
private static class OutlineHolder {
Outline outline;
String parent;
public OutlineHolder(final Outline outline, final String parent) {
this.outline = outline;
this.parent = parent;
}
}
private static class TreeContext extends Stack<Integer> {
private static final long serialVersionUID = 1L;
TreeContext() {
super();
}
}
}
| Replaced Collection.size() > 0 through !Collection.isEmpty() | src/main/java/com/sun/syndication/feed/synd/impl/ConverterForOPML10.java | Replaced Collection.size() > 0 through !Collection.isEmpty() | <ide><path>rc/main/java/com/sun/syndication/feed/synd/impl/ConverterForOPML10.java
<ide> cat.setName(nodeName);
<ide> entry.getCategories().add(cat);
<ide>
<del> if (context.size() > 0) {
<add> if (!context.isEmpty()) {
<ide> final Integer parent = context.peek();
<ide> final SyndCategory pcat = new TreeCategoryImpl();
<ide> pcat.setTaxonomyUri(URI_TREE); |
|
Java | mit | ee978cd6a32a79556bf268523ab7132650462378 | 0 | bcgit/bc-java,bcgit/bc-java,bcgit/bc-java | package org.bouncycastle.crypto.engines;
import org.bouncycastle.crypto.BlockCipher;
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.DataLengthException;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.util.Arrays;
import org.bouncycastle.util.Pack;
/*
* Reference implementation of DSTU7624 national Ukrainian standard of block encryption.
* Thanks to Roman Oliynikov' native C implementation:
* https://github.com/Roman-Oliynikov/Kalyna-reference
*
* DSTU7564 is very similar to AES but with some security improvements in key schedule algorithm
* and supports different block and key lengths (128/256/512 bits).
*/
public class DSTU7624Engine
implements BlockCipher
{
private static final int BITS_IN_WORD = 64;
private static final int BITS_IN_BYTE = 8;
private static final int BITS_IN_LONG = 64;
private static final int REDUCTION_POLYNOMIAL = 0x011d; /* x^8 + x^4 + x^3 + x^2 + 1 */
private long[] internalState;
private long[] workingKey;
private long[][] roundKeys;
/* Number of 64-bit words in block */
private int wordsInBlock;
/* Number of 64-bit words in key */
private int wordsInKey;
/* Number of encryption rounds depending on key length */
private static final int ROUNDS_128 = 10;
private static final int ROUNDS_256 = 14;
private static final int ROUNDS_512 = 18;
private int roundsAmount;
private boolean forEncryption;
private byte[] internalStateBytes;
private byte[] tempInternalStateBytes;
public DSTU7624Engine(int blockBitLength)
throws IllegalArgumentException
{
/* DSTU7624 supports 128 | 256 | 512 key/block sizes */
if (blockBitLength != 128 && blockBitLength != 256 && blockBitLength != 512)
{
throw new IllegalArgumentException("unsupported block length: only 128/256/512 are allowed");
}
wordsInBlock = blockBitLength / BITS_IN_WORD;
internalState = new long[wordsInBlock];
internalStateBytes = new byte[internalState.length * BITS_IN_LONG / BITS_IN_BYTE];
tempInternalStateBytes = new byte[internalState.length * BITS_IN_LONG / BITS_IN_BYTE];
}
public void init(boolean forEncryption, CipherParameters params)
throws IllegalArgumentException
{
if (params instanceof KeyParameter)
{
this.forEncryption = forEncryption;
byte[] keyBytes = ((KeyParameter)params).getKey();
int keyBitLength = keyBytes.length * BITS_IN_BYTE;
int blockBitLength = wordsInBlock * BITS_IN_WORD;
if (keyBitLength != 128 && keyBitLength != 256 && keyBitLength != 512)
{
throw new IllegalArgumentException("unsupported key length: only 128/256/512 are allowed");
}
/* Limitations on key lengths depending on block lengths. See table 6.1 in standard */
if (blockBitLength == 128)
{
if (keyBitLength == 512)
{
throw new IllegalArgumentException("Unsupported key length");
}
}
if (blockBitLength == 256)
{
if (keyBitLength == 128)
{
throw new IllegalArgumentException("Unsupported key length");
}
}
if (blockBitLength == 512)
{
if (keyBitLength != 512)
{
throw new IllegalArgumentException("Unsupported key length");
}
}
switch (keyBitLength)
{
case 128:
roundsAmount = ROUNDS_128;
break;
case 256:
roundsAmount = ROUNDS_256;
break;
case 512:
roundsAmount = ROUNDS_512;
break;
}
wordsInKey = keyBitLength / BITS_IN_WORD;
/* +1 round key as defined in standard */
roundKeys = new long[roundsAmount + 1][];
for (int roundKeyIndex = 0; roundKeyIndex < roundKeys.length; roundKeyIndex++)
{
roundKeys[roundKeyIndex] = new long[wordsInBlock];
}
workingKey = new long[wordsInKey];
if (keyBytes.length != wordsInKey * BITS_IN_WORD / BITS_IN_BYTE)
{
throw new IllegalArgumentException("Invalid key parameter passed to DSTU7624Engine init");
}
/* Unpack encryption key bytes to words */
Pack.littleEndianToLong(keyBytes, 0, workingKey);
long[] tempKeys = new long[wordsInBlock];
/* KSA in DSTU7624 is strengthened to mitigate known weaknesses in AES KSA (eprint.iacr.org/2012/260.pdf) */
workingKeyExpandKT(workingKey, tempKeys);
workingKeyExpandEven(workingKey, tempKeys);
workingKeyExpandOdd();
}
else
{
throw new IllegalArgumentException("Invalid parameter passed to DSTU7624Engine init");
}
}
public String getAlgorithmName()
{
return "DSTU7624";
}
public int getBlockSize()
{
return wordsInBlock * BITS_IN_WORD / BITS_IN_BYTE;
}
public int processBlock(byte[] in, int inOff, byte[] out, int outOff)
throws DataLengthException, IllegalStateException
{
if (workingKey == null)
{
throw new IllegalStateException("DSTU7624 engine not initialised");
}
if (inOff + getBlockSize() > in.length)
{
throw new DataLengthException("Input buffer too short");
}
if (outOff + getBlockSize() > out.length)
{
throw new DataLengthException("Output buffer too short");
}
if (forEncryption)
{
int round = 0;
/* Unpack */
Pack.littleEndianToLong(in, inOff, internalState);
/* Encrypt */
for (int wordIndex = 0; wordIndex < wordsInBlock; wordIndex++)
{
internalState[wordIndex] += roundKeys[round][wordIndex];
}
for (round = 1; round < roundsAmount; round++)
{
SubBytes();
ShiftRows();
MixColumns(mdsMatrix); // equals to multiplication on matrix
for (int wordIndex = 0; wordIndex < wordsInBlock; wordIndex++)
{
internalState[wordIndex] ^= roundKeys[round][wordIndex];
}
}
SubBytes();
ShiftRows();
MixColumns(mdsMatrix); // equals to multiplication on matrix
for (int wordIndex = 0; wordIndex < wordsInBlock; wordIndex++)
{
internalState[wordIndex] += roundKeys[roundsAmount][wordIndex];
}
/* Pack */
Pack.longToLittleEndian(internalState, out, outOff);
}
else
{
int round = roundsAmount;
/* Unpack */
Pack.littleEndianToLong(in, inOff, internalState);
/* Decrypt */
for (int wordIndex = 0; wordIndex < wordsInBlock; wordIndex++)
{
internalState[wordIndex] -= roundKeys[round][wordIndex];
}
for (round = roundsAmount - 1; round > 0; round--)
{
MixColumns(mdsInvMatrix); // equals to multiplication on matrix
InvShiftRows();
InvSubBytes();
for (int wordIndex = 0; wordIndex < wordsInBlock; wordIndex++)
{
internalState[wordIndex] ^= roundKeys[round][wordIndex];
}
}
MixColumns(mdsInvMatrix); // equals to multiplication on matrix
InvShiftRows();
InvSubBytes();
for (int wordIndex = 0; wordIndex < wordsInBlock; wordIndex++)
{
internalState[wordIndex] -= roundKeys[0][wordIndex];
}
/* Pack */
Pack.longToLittleEndian(internalState, out, outOff);
}
return getBlockSize();
}
public void reset()
{
Arrays.fill(internalState, 0);
Arrays.fill(internalStateBytes, (byte)0x00);
Arrays.fill(tempInternalStateBytes, (byte)0x00);
}
private void workingKeyExpandKT(long[] workingKey, long[] tempKeys)
{
long[] k0 = new long[wordsInBlock];
long[] k1 = new long[wordsInBlock];
internalState = new long[wordsInBlock];
internalState[0] += wordsInBlock + wordsInKey + 1;
if (wordsInBlock == wordsInKey)
{
System.arraycopy(workingKey, 0, k0, 0, k0.length);
System.arraycopy(workingKey, 0, k1, 0, k1.length);
}
else
{
System.arraycopy(workingKey, 0, k0, 0, wordsInBlock);
System.arraycopy(workingKey, wordsInBlock, k1, 0, wordsInBlock);
}
for (int wordIndex = 0; wordIndex < internalState.length; wordIndex++)
{
internalState[wordIndex] += k0[wordIndex];
}
SubBytes();
ShiftRows();
MixColumns(mdsMatrix); // equals to multiplication on matrix
for (int wordIndex = 0; wordIndex < internalState.length; wordIndex++)
{
internalState[wordIndex] ^= k1[wordIndex];
}
SubBytes();
ShiftRows();
MixColumns(mdsMatrix); // equals to multiplication on matrix
for (int wordIndex = 0; wordIndex < internalState.length; wordIndex++)
{
internalState[wordIndex] += k0[wordIndex];
}
SubBytes();
ShiftRows();
MixColumns(mdsMatrix); // equals to multiplication on matrix
System.arraycopy(internalState, 0, tempKeys, 0, wordsInBlock);
}
private void workingKeyExpandEven(long[] workingKey, long[] tempKey)
{
long[] initialData = new long[wordsInKey];
long[] tempRoundKey = new long[wordsInBlock];
long[] tmv = new long[wordsInBlock];
int round = 0;
System.arraycopy(workingKey, 0, initialData, 0, wordsInKey);
for (int wordIndex = 0; wordIndex < wordsInBlock; wordIndex++)
{
tmv[wordIndex] = 0x0001000100010001L;
}
while (true)
{
System.arraycopy(tempKey, 0, internalState, 0, wordsInBlock);
for (int wordIndex = 0; wordIndex < wordsInBlock; wordIndex++)
{
internalState[wordIndex] += tmv[wordIndex];
}
System.arraycopy(internalState, 0, tempRoundKey, 0, wordsInBlock);
System.arraycopy(initialData, 0, internalState, 0, wordsInBlock);
for (int wordIndex = 0; wordIndex < wordsInBlock; wordIndex++)
{
internalState[wordIndex] += tempRoundKey[wordIndex];
}
SubBytes();
ShiftRows();
MixColumns(mdsMatrix); // equals to multiplication on matrix
for (int wordIndex = 0; wordIndex < wordsInBlock; wordIndex++)
{
internalState[wordIndex] ^= tempRoundKey[wordIndex];
}
SubBytes();
ShiftRows();
MixColumns(mdsMatrix); // equals to multiplication on matrix
for (int wordIndex = 0; wordIndex < wordsInBlock; wordIndex++)
{
internalState[wordIndex] += tempRoundKey[wordIndex];
}
System.arraycopy(internalState, 0, roundKeys[round], 0, wordsInBlock);
if (roundsAmount == round)
{
break;
}
if (wordsInBlock != wordsInKey)
{
round += 2;
ShiftLeft(tmv);
System.arraycopy(tempKey, 0, internalState, 0, wordsInBlock);
for (int wordIndex = 0; wordIndex < wordsInBlock; wordIndex++)
{
internalState[wordIndex] += tmv[wordIndex];
}
System.arraycopy(internalState, 0, tempRoundKey, 0, wordsInBlock);
System.arraycopy(initialData, wordsInBlock, internalState, 0, wordsInBlock);
for (int wordIndex = 0; wordIndex < wordsInBlock; wordIndex++)
{
internalState[wordIndex] += tempRoundKey[wordIndex];
}
SubBytes();
ShiftRows();
MixColumns(mdsMatrix); // equals to multiplication on matrix
for (int wordIndex = 0; wordIndex < wordsInBlock; wordIndex++)
{
internalState[wordIndex] ^= tempRoundKey[wordIndex];
}
SubBytes();
ShiftRows();
MixColumns(mdsMatrix); // equals to multiplication on matrix
for (int wordIndex = 0; wordIndex < wordsInBlock; wordIndex++)
{
internalState[wordIndex] += tempRoundKey[wordIndex];
}
System.arraycopy(internalState, 0, roundKeys[round], 0, wordsInBlock);
if (roundsAmount == round)
{
break;
}
}
round += 2;
ShiftLeft(tmv);
long temp = initialData[0];
System.arraycopy(initialData, 1, initialData, 0, initialData.length - 1);
initialData[initialData.length - 1] = temp;
}
}
private void workingKeyExpandOdd()
{
for (int roundIndex = 1; roundIndex < roundsAmount; roundIndex += 2)
{
System.arraycopy(roundKeys[roundIndex - 1], 0, roundKeys[roundIndex], 0, wordsInBlock);
RotateLeft(roundKeys[roundIndex]);
}
}
private void SubBytes()
{
for (int i = 0; i < wordsInBlock; i++)
{
internalState[i] = sboxesForEncryption[0][(int)(internalState[i] & 0x00000000000000FFL)] & 0x00000000000000FFL |
(long)sboxesForEncryption[1][(int)((internalState[i] & 0x000000000000FF00L) >>> 8)] << 8 & 0x000000000000FF00L |
(long)sboxesForEncryption[2][(int)((internalState[i] & 0x0000000000FF0000L) >>> 16)] << 16 & 0x0000000000FF0000L |
(long)sboxesForEncryption[3][(int)((internalState[i] & 0x00000000FF000000L) >>> 24)] << 24 & 0x00000000FF000000L |
(long)sboxesForEncryption[0][(int)((internalState[i] & 0x000000FF00000000L) >>> 32)] << 32 & 0x000000FF00000000L |
(long)sboxesForEncryption[1][(int)((internalState[i] & 0x0000FF0000000000L) >>> 40)] << 40 & 0x0000FF0000000000L |
(long)sboxesForEncryption[2][(int)((internalState[i] & 0x00FF000000000000L) >>> 48)] << 48 & 0x00FF000000000000L |
(long)sboxesForEncryption[3][(int)((internalState[i] & 0xFF00000000000000L) >>> 56)] << 56 & 0xFF00000000000000L;
}
}
private void InvSubBytes()
{
for (int i = 0; i < wordsInBlock; i++)
{
internalState[i] = sboxesForDecryption[0][(int)(internalState[i] & 0x00000000000000FFL)] & 0x00000000000000FFL |
(long)sboxesForDecryption[1][(int)((internalState[i] & 0x000000000000FF00L) >>> 8)] << 8 & 0x000000000000FF00L |
(long)sboxesForDecryption[2][(int)((internalState[i] & 0x0000000000FF0000L) >>> 16)] << 16 & 0x0000000000FF0000L |
(long)sboxesForDecryption[3][(int)((internalState[i] & 0x00000000FF000000L) >>> 24)] << 24 & 0x00000000FF000000L |
(long)sboxesForDecryption[0][(int)((internalState[i] & 0x000000FF00000000L) >>> 32)] << 32 & 0x000000FF00000000L |
(long)sboxesForDecryption[1][(int)((internalState[i] & 0x0000FF0000000000L) >>> 40)] << 40 & 0x0000FF0000000000L |
(long)sboxesForDecryption[2][(int)((internalState[i] & 0x00FF000000000000L) >>> 48)] << 48 & 0x00FF000000000000L |
(long)sboxesForDecryption[3][(int)((internalState[i] & 0xFF00000000000000L) >>> 56)] << 56 & 0xFF00000000000000L;
}
}
private void ShiftRows()
{
int row, col;
int shift = -1;
Pack.longToLittleEndian(internalState, internalStateBytes, 0);
for (row = 0; row < BITS_IN_LONG / BITS_IN_BYTE; row++)
{
if (row % (BITS_IN_LONG / BITS_IN_BYTE / wordsInBlock) == 0)
{
shift += 1;
}
for (col = 0; col < wordsInBlock; col++)
{
tempInternalStateBytes[row + ((col + shift) % wordsInBlock) * BITS_IN_LONG / BITS_IN_BYTE] = internalStateBytes[row + col * BITS_IN_LONG / BITS_IN_BYTE];
}
}
Pack.littleEndianToLong(tempInternalStateBytes, 0, internalState);
}
private void InvShiftRows()
{
int row, col;
int shift = -1;
Pack.longToLittleEndian(internalState, internalStateBytes, 0);
for (row = 0; row < BITS_IN_LONG / BITS_IN_BYTE; row++)
{
if (row % (BITS_IN_LONG / BITS_IN_BYTE / wordsInBlock) == 0)
{
shift += 1;
}
for (col = 0; col < wordsInBlock; col++)
{
tempInternalStateBytes[row + col * BITS_IN_LONG / BITS_IN_BYTE] = internalStateBytes[row + ((col + shift) % wordsInBlock) * BITS_IN_LONG / BITS_IN_BYTE];
}
}
Pack.littleEndianToLong(tempInternalStateBytes, 0, internalState);
}
private void MixColumns(byte[][] matrix)
{
int col, row, b;
byte product;
long result;
Pack.longToLittleEndian(internalState, internalStateBytes, 0);
long shift;
for (col = 0; col < wordsInBlock; ++col)
{
result = 0;
shift = 0xFF00000000000000L;
for (row = BITS_IN_LONG / BITS_IN_BYTE - 1; row >= 0; --row)
{
product = 0;
for (b = BITS_IN_LONG / BITS_IN_BYTE - 1; b >= 0; --b)
{
product ^= MultiplyGF(internalStateBytes[b + col * BITS_IN_LONG / BITS_IN_BYTE], matrix[row][b]);
}
result |= ((long)product << (row * BITS_IN_LONG / BITS_IN_BYTE) & shift);
shift >>>= 8;
}
internalState[col] = result;
}
}
private byte MultiplyGF(byte x, byte y)
{
byte r = 0;
int hbit;
for (int i = 0; i < BITS_IN_BYTE; i++)
{
if ((y & 0x01) == 1)
{
r ^= x;
}
hbit = x & 0x80;
x <<= 1;
if (hbit == 0x80)
{
x = (byte)((int)x ^ REDUCTION_POLYNOMIAL);
}
y >>= 1;
}
return r;
}
private void ShiftLeft(long[] value)
{
for (int i = 0; i < value.length; i++)
{
value[i] <<= 1;
}
//reversing state
for (int i = 0; i < value.length / 2; i++)
{
long temp = value[i];
value[i] = value[value.length - i - 1];
value[value.length - i - 1] = temp;
}
}
private void RotateLeft(long[] value)
{
int rotateBytesLength = 2 * value.length + 3;
int bytesLength = value.length * (BITS_IN_WORD / BITS_IN_BYTE);
byte[] bytes = new byte[value.length * BITS_IN_LONG / BITS_IN_BYTE];
Pack.longToLittleEndian(value, bytes, 0);
byte[] buffer = new byte[rotateBytesLength];
System.arraycopy(bytes, 0, buffer, 0, rotateBytesLength);
System.arraycopy(bytes, rotateBytesLength, bytes, 0, bytesLength - rotateBytesLength);
System.arraycopy(buffer, 0, bytes, bytesLength - rotateBytesLength, rotateBytesLength);
Pack.littleEndianToLong(bytes, 0, value);
}
//region MATRICES AND S-BOXES
private byte[][] mdsMatrix =
{
new byte[]{(byte)0x01, (byte)0x01, (byte)0x05, (byte)0x01, (byte)0x08, (byte)0x06, (byte)0x07, (byte)0x04},
new byte[]{(byte)0x04, (byte)0x01, (byte)0x01, (byte)0x05, (byte)0x01, (byte)0x08, (byte)0x06, (byte)0x07},
new byte[]{(byte)0x07, (byte)0x04, (byte)0x01, (byte)0x01, (byte)0x05, (byte)0x01, (byte)0x08, (byte)0x06},
new byte[]{(byte)0x06, (byte)0x07, (byte)0x04, (byte)0x01, (byte)0x01, (byte)0x05, (byte)0x01, (byte)0x08},
new byte[]{(byte)0x08, (byte)0x06, (byte)0x07, (byte)0x04, (byte)0x01, (byte)0x01, (byte)0x05, (byte)0x01},
new byte[]{(byte)0x01, (byte)0x08, (byte)0x06, (byte)0x07, (byte)0x04, (byte)0x01, (byte)0x01, (byte)0x05},
new byte[]{(byte)0x05, (byte)0x01, (byte)0x08, (byte)0x06, (byte)0x07, (byte)0x04, (byte)0x01, (byte)0x01},
new byte[]{(byte)0x01, (byte)0x05, (byte)0x01, (byte)0x08, (byte)0x06, (byte)0x07, (byte)0x04, (byte)0x01}
};
private byte[][] mdsInvMatrix =
{
new byte[]{(byte)0xAD, (byte)0x95, (byte)0x76, (byte)0xA8, (byte)0x2F, (byte)0x49, (byte)0xD7, (byte)0xCA},
new byte[]{(byte)0xCA, (byte)0xAD, (byte)0x95, (byte)0x76, (byte)0xA8, (byte)0x2F, (byte)0x49, (byte)0xD7},
new byte[]{(byte)0xD7, (byte)0xCA, (byte)0xAD, (byte)0x95, (byte)0x76, (byte)0xA8, (byte)0x2F, (byte)0x49},
new byte[]{(byte)0x49, (byte)0xD7, (byte)0xCA, (byte)0xAD, (byte)0x95, (byte)0x76, (byte)0xA8, (byte)0x2F},
new byte[]{(byte)0x2F, (byte)0x49, (byte)0xD7, (byte)0xCA, (byte)0xAD, (byte)0x95, (byte)0x76, (byte)0xA8},
new byte[]{(byte)0xA8, (byte)0x2F, (byte)0x49, (byte)0xD7, (byte)0xCA, (byte)0xAD, (byte)0x95, (byte)0x76},
new byte[]{(byte)0x76, (byte)0xA8, (byte)0x2F, (byte)0x49, (byte)0xD7, (byte)0xCA, (byte)0xAD, (byte)0x95},
new byte[]{(byte)0x95, (byte)0x76, (byte)0xA8, (byte)0x2F, (byte)0x49, (byte)0xD7, (byte)0xCA, (byte)0xAD}
};
private byte[][] sboxesForEncryption =
{
new byte[]
{
(byte)0xa8, (byte)0x43, (byte)0x5f, (byte)0x06, (byte)0x6b, (byte)0x75, (byte)0x6c, (byte)0x59,
(byte)0x71, (byte)0xdf, (byte)0x87, (byte)0x95, (byte)0x17, (byte)0xf0, (byte)0xd8, (byte)0x09,
(byte)0x6d, (byte)0xf3, (byte)0x1d, (byte)0xcb, (byte)0xc9, (byte)0x4d, (byte)0x2c, (byte)0xaf,
(byte)0x79, (byte)0xe0, (byte)0x97, (byte)0xfd, (byte)0x6f, (byte)0x4b, (byte)0x45, (byte)0x39,
(byte)0x3e, (byte)0xdd, (byte)0xa3, (byte)0x4f, (byte)0xb4, (byte)0xb6, (byte)0x9a, (byte)0x0e,
(byte)0x1f, (byte)0xbf, (byte)0x15, (byte)0xe1, (byte)0x49, (byte)0xd2, (byte)0x93, (byte)0xc6,
(byte)0x92, (byte)0x72, (byte)0x9e, (byte)0x61, (byte)0xd1, (byte)0x63, (byte)0xfa, (byte)0xee,
(byte)0xf4, (byte)0x19, (byte)0xd5, (byte)0xad, (byte)0x58, (byte)0xa4, (byte)0xbb, (byte)0xa1,
(byte)0xdc, (byte)0xf2, (byte)0x83, (byte)0x37, (byte)0x42, (byte)0xe4, (byte)0x7a, (byte)0x32,
(byte)0x9c, (byte)0xcc, (byte)0xab, (byte)0x4a, (byte)0x8f, (byte)0x6e, (byte)0x04, (byte)0x27,
(byte)0x2e, (byte)0xe7, (byte)0xe2, (byte)0x5a, (byte)0x96, (byte)0x16, (byte)0x23, (byte)0x2b,
(byte)0xc2, (byte)0x65, (byte)0x66, (byte)0x0f, (byte)0xbc, (byte)0xa9, (byte)0x47, (byte)0x41,
(byte)0x34, (byte)0x48, (byte)0xfc, (byte)0xb7, (byte)0x6a, (byte)0x88, (byte)0xa5, (byte)0x53,
(byte)0x86, (byte)0xf9, (byte)0x5b, (byte)0xdb, (byte)0x38, (byte)0x7b, (byte)0xc3, (byte)0x1e,
(byte)0x22, (byte)0x33, (byte)0x24, (byte)0x28, (byte)0x36, (byte)0xc7, (byte)0xb2, (byte)0x3b,
(byte)0x8e, (byte)0x77, (byte)0xba, (byte)0xf5, (byte)0x14, (byte)0x9f, (byte)0x08, (byte)0x55,
(byte)0x9b, (byte)0x4c, (byte)0xfe, (byte)0x60, (byte)0x5c, (byte)0xda, (byte)0x18, (byte)0x46,
(byte)0xcd, (byte)0x7d, (byte)0x21, (byte)0xb0, (byte)0x3f, (byte)0x1b, (byte)0x89, (byte)0xff,
(byte)0xeb, (byte)0x84, (byte)0x69, (byte)0x3a, (byte)0x9d, (byte)0xd7, (byte)0xd3, (byte)0x70,
(byte)0x67, (byte)0x40, (byte)0xb5, (byte)0xde, (byte)0x5d, (byte)0x30, (byte)0x91, (byte)0xb1,
(byte)0x78, (byte)0x11, (byte)0x01, (byte)0xe5, (byte)0x00, (byte)0x68, (byte)0x98, (byte)0xa0,
(byte)0xc5, (byte)0x02, (byte)0xa6, (byte)0x74, (byte)0x2d, (byte)0x0b, (byte)0xa2, (byte)0x76,
(byte)0xb3, (byte)0xbe, (byte)0xce, (byte)0xbd, (byte)0xae, (byte)0xe9, (byte)0x8a, (byte)0x31,
(byte)0x1c, (byte)0xec, (byte)0xf1, (byte)0x99, (byte)0x94, (byte)0xaa, (byte)0xf6, (byte)0x26,
(byte)0x2f, (byte)0xef, (byte)0xe8, (byte)0x8c, (byte)0x35, (byte)0x03, (byte)0xd4, (byte)0x7f,
(byte)0xfb, (byte)0x05, (byte)0xc1, (byte)0x5e, (byte)0x90, (byte)0x20, (byte)0x3d, (byte)0x82,
(byte)0xf7, (byte)0xea, (byte)0x0a, (byte)0x0d, (byte)0x7e, (byte)0xf8, (byte)0x50, (byte)0x1a,
(byte)0xc4, (byte)0x07, (byte)0x57, (byte)0xb8, (byte)0x3c, (byte)0x62, (byte)0xe3, (byte)0xc8,
(byte)0xac, (byte)0x52, (byte)0x64, (byte)0x10, (byte)0xd0, (byte)0xd9, (byte)0x13, (byte)0x0c,
(byte)0x12, (byte)0x29, (byte)0x51, (byte)0xb9, (byte)0xcf, (byte)0xd6, (byte)0x73, (byte)0x8d,
(byte)0x81, (byte)0x54, (byte)0xc0, (byte)0xed, (byte)0x4e, (byte)0x44, (byte)0xa7, (byte)0x2a,
(byte)0x85, (byte)0x25, (byte)0xe6, (byte)0xca, (byte)0x7c, (byte)0x8b, (byte)0x56, (byte)0x80
},
new byte[]
{
(byte)0xce, (byte)0xbb, (byte)0xeb, (byte)0x92, (byte)0xea, (byte)0xcb, (byte)0x13, (byte)0xc1,
(byte)0xe9, (byte)0x3a, (byte)0xd6, (byte)0xb2, (byte)0xd2, (byte)0x90, (byte)0x17, (byte)0xf8,
(byte)0x42, (byte)0x15, (byte)0x56, (byte)0xb4, (byte)0x65, (byte)0x1c, (byte)0x88, (byte)0x43,
(byte)0xc5, (byte)0x5c, (byte)0x36, (byte)0xba, (byte)0xf5, (byte)0x57, (byte)0x67, (byte)0x8d,
(byte)0x31, (byte)0xf6, (byte)0x64, (byte)0x58, (byte)0x9e, (byte)0xf4, (byte)0x22, (byte)0xaa,
(byte)0x75, (byte)0x0f, (byte)0x02, (byte)0xb1, (byte)0xdf, (byte)0x6d, (byte)0x73, (byte)0x4d,
(byte)0x7c, (byte)0x26, (byte)0x2e, (byte)0xf7, (byte)0x08, (byte)0x5d, (byte)0x44, (byte)0x3e,
(byte)0x9f, (byte)0x14, (byte)0xc8, (byte)0xae, (byte)0x54, (byte)0x10, (byte)0xd8, (byte)0xbc,
(byte)0x1a, (byte)0x6b, (byte)0x69, (byte)0xf3, (byte)0xbd, (byte)0x33, (byte)0xab, (byte)0xfa,
(byte)0xd1, (byte)0x9b, (byte)0x68, (byte)0x4e, (byte)0x16, (byte)0x95, (byte)0x91, (byte)0xee,
(byte)0x4c, (byte)0x63, (byte)0x8e, (byte)0x5b, (byte)0xcc, (byte)0x3c, (byte)0x19, (byte)0xa1,
(byte)0x81, (byte)0x49, (byte)0x7b, (byte)0xd9, (byte)0x6f, (byte)0x37, (byte)0x60, (byte)0xca,
(byte)0xe7, (byte)0x2b, (byte)0x48, (byte)0xfd, (byte)0x96, (byte)0x45, (byte)0xfc, (byte)0x41,
(byte)0x12, (byte)0x0d, (byte)0x79, (byte)0xe5, (byte)0x89, (byte)0x8c, (byte)0xe3, (byte)0x20,
(byte)0x30, (byte)0xdc, (byte)0xb7, (byte)0x6c, (byte)0x4a, (byte)0xb5, (byte)0x3f, (byte)0x97,
(byte)0xd4, (byte)0x62, (byte)0x2d, (byte)0x06, (byte)0xa4, (byte)0xa5, (byte)0x83, (byte)0x5f,
(byte)0x2a, (byte)0xda, (byte)0xc9, (byte)0x00, (byte)0x7e, (byte)0xa2, (byte)0x55, (byte)0xbf,
(byte)0x11, (byte)0xd5, (byte)0x9c, (byte)0xcf, (byte)0x0e, (byte)0x0a, (byte)0x3d, (byte)0x51,
(byte)0x7d, (byte)0x93, (byte)0x1b, (byte)0xfe, (byte)0xc4, (byte)0x47, (byte)0x09, (byte)0x86,
(byte)0x0b, (byte)0x8f, (byte)0x9d, (byte)0x6a, (byte)0x07, (byte)0xb9, (byte)0xb0, (byte)0x98,
(byte)0x18, (byte)0x32, (byte)0x71, (byte)0x4b, (byte)0xef, (byte)0x3b, (byte)0x70, (byte)0xa0,
(byte)0xe4, (byte)0x40, (byte)0xff, (byte)0xc3, (byte)0xa9, (byte)0xe6, (byte)0x78, (byte)0xf9,
(byte)0x8b, (byte)0x46, (byte)0x80, (byte)0x1e, (byte)0x38, (byte)0xe1, (byte)0xb8, (byte)0xa8,
(byte)0xe0, (byte)0x0c, (byte)0x23, (byte)0x76, (byte)0x1d, (byte)0x25, (byte)0x24, (byte)0x05,
(byte)0xf1, (byte)0x6e, (byte)0x94, (byte)0x28, (byte)0x9a, (byte)0x84, (byte)0xe8, (byte)0xa3,
(byte)0x4f, (byte)0x77, (byte)0xd3, (byte)0x85, (byte)0xe2, (byte)0x52, (byte)0xf2, (byte)0x82,
(byte)0x50, (byte)0x7a, (byte)0x2f, (byte)0x74, (byte)0x53, (byte)0xb3, (byte)0x61, (byte)0xaf,
(byte)0x39, (byte)0x35, (byte)0xde, (byte)0xcd, (byte)0x1f, (byte)0x99, (byte)0xac, (byte)0xad,
(byte)0x72, (byte)0x2c, (byte)0xdd, (byte)0xd0, (byte)0x87, (byte)0xbe, (byte)0x5e, (byte)0xa6,
(byte)0xec, (byte)0x04, (byte)0xc6, (byte)0x03, (byte)0x34, (byte)0xfb, (byte)0xdb, (byte)0x59,
(byte)0xb6, (byte)0xc2, (byte)0x01, (byte)0xf0, (byte)0x5a, (byte)0xed, (byte)0xa7, (byte)0x66,
(byte)0x21, (byte)0x7f, (byte)0x8a, (byte)0x27, (byte)0xc7, (byte)0xc0, (byte)0x29, (byte)0xd7
},
new byte[]
{
(byte)0x93, (byte)0xd9, (byte)0x9a, (byte)0xb5, (byte)0x98, (byte)0x22, (byte)0x45, (byte)0xfc,
(byte)0xba, (byte)0x6a, (byte)0xdf, (byte)0x02, (byte)0x9f, (byte)0xdc, (byte)0x51, (byte)0x59,
(byte)0x4a, (byte)0x17, (byte)0x2b, (byte)0xc2, (byte)0x94, (byte)0xf4, (byte)0xbb, (byte)0xa3,
(byte)0x62, (byte)0xe4, (byte)0x71, (byte)0xd4, (byte)0xcd, (byte)0x70, (byte)0x16, (byte)0xe1,
(byte)0x49, (byte)0x3c, (byte)0xc0, (byte)0xd8, (byte)0x5c, (byte)0x9b, (byte)0xad, (byte)0x85,
(byte)0x53, (byte)0xa1, (byte)0x7a, (byte)0xc8, (byte)0x2d, (byte)0xe0, (byte)0xd1, (byte)0x72,
(byte)0xa6, (byte)0x2c, (byte)0xc4, (byte)0xe3, (byte)0x76, (byte)0x78, (byte)0xb7, (byte)0xb4,
(byte)0x09, (byte)0x3b, (byte)0x0e, (byte)0x41, (byte)0x4c, (byte)0xde, (byte)0xb2, (byte)0x90,
(byte)0x25, (byte)0xa5, (byte)0xd7, (byte)0x03, (byte)0x11, (byte)0x00, (byte)0xc3, (byte)0x2e,
(byte)0x92, (byte)0xef, (byte)0x4e, (byte)0x12, (byte)0x9d, (byte)0x7d, (byte)0xcb, (byte)0x35,
(byte)0x10, (byte)0xd5, (byte)0x4f, (byte)0x9e, (byte)0x4d, (byte)0xa9, (byte)0x55, (byte)0xc6,
(byte)0xd0, (byte)0x7b, (byte)0x18, (byte)0x97, (byte)0xd3, (byte)0x36, (byte)0xe6, (byte)0x48,
(byte)0x56, (byte)0x81, (byte)0x8f, (byte)0x77, (byte)0xcc, (byte)0x9c, (byte)0xb9, (byte)0xe2,
(byte)0xac, (byte)0xb8, (byte)0x2f, (byte)0x15, (byte)0xa4, (byte)0x7c, (byte)0xda, (byte)0x38,
(byte)0x1e, (byte)0x0b, (byte)0x05, (byte)0xd6, (byte)0x14, (byte)0x6e, (byte)0x6c, (byte)0x7e,
(byte)0x66, (byte)0xfd, (byte)0xb1, (byte)0xe5, (byte)0x60, (byte)0xaf, (byte)0x5e, (byte)0x33,
(byte)0x87, (byte)0xc9, (byte)0xf0, (byte)0x5d, (byte)0x6d, (byte)0x3f, (byte)0x88, (byte)0x8d,
(byte)0xc7, (byte)0xf7, (byte)0x1d, (byte)0xe9, (byte)0xec, (byte)0xed, (byte)0x80, (byte)0x29,
(byte)0x27, (byte)0xcf, (byte)0x99, (byte)0xa8, (byte)0x50, (byte)0x0f, (byte)0x37, (byte)0x24,
(byte)0x28, (byte)0x30, (byte)0x95, (byte)0xd2, (byte)0x3e, (byte)0x5b, (byte)0x40, (byte)0x83,
(byte)0xb3, (byte)0x69, (byte)0x57, (byte)0x1f, (byte)0x07, (byte)0x1c, (byte)0x8a, (byte)0xbc,
(byte)0x20, (byte)0xeb, (byte)0xce, (byte)0x8e, (byte)0xab, (byte)0xee, (byte)0x31, (byte)0xa2,
(byte)0x73, (byte)0xf9, (byte)0xca, (byte)0x3a, (byte)0x1a, (byte)0xfb, (byte)0x0d, (byte)0xc1,
(byte)0xfe, (byte)0xfa, (byte)0xf2, (byte)0x6f, (byte)0xbd, (byte)0x96, (byte)0xdd, (byte)0x43,
(byte)0x52, (byte)0xb6, (byte)0x08, (byte)0xf3, (byte)0xae, (byte)0xbe, (byte)0x19, (byte)0x89,
(byte)0x32, (byte)0x26, (byte)0xb0, (byte)0xea, (byte)0x4b, (byte)0x64, (byte)0x84, (byte)0x82,
(byte)0x6b, (byte)0xf5, (byte)0x79, (byte)0xbf, (byte)0x01, (byte)0x5f, (byte)0x75, (byte)0x63,
(byte)0x1b, (byte)0x23, (byte)0x3d, (byte)0x68, (byte)0x2a, (byte)0x65, (byte)0xe8, (byte)0x91,
(byte)0xf6, (byte)0xff, (byte)0x13, (byte)0x58, (byte)0xf1, (byte)0x47, (byte)0x0a, (byte)0x7f,
(byte)0xc5, (byte)0xa7, (byte)0xe7, (byte)0x61, (byte)0x5a, (byte)0x06, (byte)0x46, (byte)0x44,
(byte)0x42, (byte)0x04, (byte)0xa0, (byte)0xdb, (byte)0x39, (byte)0x86, (byte)0x54, (byte)0xaa,
(byte)0x8c, (byte)0x34, (byte)0x21, (byte)0x8b, (byte)0xf8, (byte)0x0c, (byte)0x74, (byte)0x67
},
new byte[]
{
(byte)0x68, (byte)0x8d, (byte)0xca, (byte)0x4d, (byte)0x73, (byte)0x4b, (byte)0x4e, (byte)0x2a,
(byte)0xd4, (byte)0x52, (byte)0x26, (byte)0xb3, (byte)0x54, (byte)0x1e, (byte)0x19, (byte)0x1f,
(byte)0x22, (byte)0x03, (byte)0x46, (byte)0x3d, (byte)0x2d, (byte)0x4a, (byte)0x53, (byte)0x83,
(byte)0x13, (byte)0x8a, (byte)0xb7, (byte)0xd5, (byte)0x25, (byte)0x79, (byte)0xf5, (byte)0xbd,
(byte)0x58, (byte)0x2f, (byte)0x0d, (byte)0x02, (byte)0xed, (byte)0x51, (byte)0x9e, (byte)0x11,
(byte)0xf2, (byte)0x3e, (byte)0x55, (byte)0x5e, (byte)0xd1, (byte)0x16, (byte)0x3c, (byte)0x66,
(byte)0x70, (byte)0x5d, (byte)0xf3, (byte)0x45, (byte)0x40, (byte)0xcc, (byte)0xe8, (byte)0x94,
(byte)0x56, (byte)0x08, (byte)0xce, (byte)0x1a, (byte)0x3a, (byte)0xd2, (byte)0xe1, (byte)0xdf,
(byte)0xb5, (byte)0x38, (byte)0x6e, (byte)0x0e, (byte)0xe5, (byte)0xf4, (byte)0xf9, (byte)0x86,
(byte)0xe9, (byte)0x4f, (byte)0xd6, (byte)0x85, (byte)0x23, (byte)0xcf, (byte)0x32, (byte)0x99,
(byte)0x31, (byte)0x14, (byte)0xae, (byte)0xee, (byte)0xc8, (byte)0x48, (byte)0xd3, (byte)0x30,
(byte)0xa1, (byte)0x92, (byte)0x41, (byte)0xb1, (byte)0x18, (byte)0xc4, (byte)0x2c, (byte)0x71,
(byte)0x72, (byte)0x44, (byte)0x15, (byte)0xfd, (byte)0x37, (byte)0xbe, (byte)0x5f, (byte)0xaa,
(byte)0x9b, (byte)0x88, (byte)0xd8, (byte)0xab, (byte)0x89, (byte)0x9c, (byte)0xfa, (byte)0x60,
(byte)0xea, (byte)0xbc, (byte)0x62, (byte)0x0c, (byte)0x24, (byte)0xa6, (byte)0xa8, (byte)0xec,
(byte)0x67, (byte)0x20, (byte)0xdb, (byte)0x7c, (byte)0x28, (byte)0xdd, (byte)0xac, (byte)0x5b,
(byte)0x34, (byte)0x7e, (byte)0x10, (byte)0xf1, (byte)0x7b, (byte)0x8f, (byte)0x63, (byte)0xa0,
(byte)0x05, (byte)0x9a, (byte)0x43, (byte)0x77, (byte)0x21, (byte)0xbf, (byte)0x27, (byte)0x09,
(byte)0xc3, (byte)0x9f, (byte)0xb6, (byte)0xd7, (byte)0x29, (byte)0xc2, (byte)0xeb, (byte)0xc0,
(byte)0xa4, (byte)0x8b, (byte)0x8c, (byte)0x1d, (byte)0xfb, (byte)0xff, (byte)0xc1, (byte)0xb2,
(byte)0x97, (byte)0x2e, (byte)0xf8, (byte)0x65, (byte)0xf6, (byte)0x75, (byte)0x07, (byte)0x04,
(byte)0x49, (byte)0x33, (byte)0xe4, (byte)0xd9, (byte)0xb9, (byte)0xd0, (byte)0x42, (byte)0xc7,
(byte)0x6c, (byte)0x90, (byte)0x00, (byte)0x8e, (byte)0x6f, (byte)0x50, (byte)0x01, (byte)0xc5,
(byte)0xda, (byte)0x47, (byte)0x3f, (byte)0xcd, (byte)0x69, (byte)0xa2, (byte)0xe2, (byte)0x7a,
(byte)0xa7, (byte)0xc6, (byte)0x93, (byte)0x0f, (byte)0x0a, (byte)0x06, (byte)0xe6, (byte)0x2b,
(byte)0x96, (byte)0xa3, (byte)0x1c, (byte)0xaf, (byte)0x6a, (byte)0x12, (byte)0x84, (byte)0x39,
(byte)0xe7, (byte)0xb0, (byte)0x82, (byte)0xf7, (byte)0xfe, (byte)0x9d, (byte)0x87, (byte)0x5c,
(byte)0x81, (byte)0x35, (byte)0xde, (byte)0xb4, (byte)0xa5, (byte)0xfc, (byte)0x80, (byte)0xef,
(byte)0xcb, (byte)0xbb, (byte)0x6b, (byte)0x76, (byte)0xba, (byte)0x5a, (byte)0x7d, (byte)0x78,
(byte)0x0b, (byte)0x95, (byte)0xe3, (byte)0xad, (byte)0x74, (byte)0x98, (byte)0x3b, (byte)0x36,
(byte)0x64, (byte)0x6d, (byte)0xdc, (byte)0xf0, (byte)0x59, (byte)0xa9, (byte)0x4c, (byte)0x17,
(byte)0x7f, (byte)0x91, (byte)0xb8, (byte)0xc9, (byte)0x57, (byte)0x1b, (byte)0xe0, (byte)0x61
}
};
private byte[][] sboxesForDecryption =
{
new byte[]
{
(byte)0xa4, (byte)0xa2, (byte)0xa9, (byte)0xc5, (byte)0x4e, (byte)0xc9, (byte)0x03, (byte)0xd9,
(byte)0x7e, (byte)0x0f, (byte)0xd2, (byte)0xad, (byte)0xe7, (byte)0xd3, (byte)0x27, (byte)0x5b,
(byte)0xe3, (byte)0xa1, (byte)0xe8, (byte)0xe6, (byte)0x7c, (byte)0x2a, (byte)0x55, (byte)0x0c,
(byte)0x86, (byte)0x39, (byte)0xd7, (byte)0x8d, (byte)0xb8, (byte)0x12, (byte)0x6f, (byte)0x28,
(byte)0xcd, (byte)0x8a, (byte)0x70, (byte)0x56, (byte)0x72, (byte)0xf9, (byte)0xbf, (byte)0x4f,
(byte)0x73, (byte)0xe9, (byte)0xf7, (byte)0x57, (byte)0x16, (byte)0xac, (byte)0x50, (byte)0xc0,
(byte)0x9d, (byte)0xb7, (byte)0x47, (byte)0x71, (byte)0x60, (byte)0xc4, (byte)0x74, (byte)0x43,
(byte)0x6c, (byte)0x1f, (byte)0x93, (byte)0x77, (byte)0xdc, (byte)0xce, (byte)0x20, (byte)0x8c,
(byte)0x99, (byte)0x5f, (byte)0x44, (byte)0x01, (byte)0xf5, (byte)0x1e, (byte)0x87, (byte)0x5e,
(byte)0x61, (byte)0x2c, (byte)0x4b, (byte)0x1d, (byte)0x81, (byte)0x15, (byte)0xf4, (byte)0x23,
(byte)0xd6, (byte)0xea, (byte)0xe1, (byte)0x67, (byte)0xf1, (byte)0x7f, (byte)0xfe, (byte)0xda,
(byte)0x3c, (byte)0x07, (byte)0x53, (byte)0x6a, (byte)0x84, (byte)0x9c, (byte)0xcb, (byte)0x02,
(byte)0x83, (byte)0x33, (byte)0xdd, (byte)0x35, (byte)0xe2, (byte)0x59, (byte)0x5a, (byte)0x98,
(byte)0xa5, (byte)0x92, (byte)0x64, (byte)0x04, (byte)0x06, (byte)0x10, (byte)0x4d, (byte)0x1c,
(byte)0x97, (byte)0x08, (byte)0x31, (byte)0xee, (byte)0xab, (byte)0x05, (byte)0xaf, (byte)0x79,
(byte)0xa0, (byte)0x18, (byte)0x46, (byte)0x6d, (byte)0xfc, (byte)0x89, (byte)0xd4, (byte)0xc7,
(byte)0xff, (byte)0xf0, (byte)0xcf, (byte)0x42, (byte)0x91, (byte)0xf8, (byte)0x68, (byte)0x0a,
(byte)0x65, (byte)0x8e, (byte)0xb6, (byte)0xfd, (byte)0xc3, (byte)0xef, (byte)0x78, (byte)0x4c,
(byte)0xcc, (byte)0x9e, (byte)0x30, (byte)0x2e, (byte)0xbc, (byte)0x0b, (byte)0x54, (byte)0x1a,
(byte)0xa6, (byte)0xbb, (byte)0x26, (byte)0x80, (byte)0x48, (byte)0x94, (byte)0x32, (byte)0x7d,
(byte)0xa7, (byte)0x3f, (byte)0xae, (byte)0x22, (byte)0x3d, (byte)0x66, (byte)0xaa, (byte)0xf6,
(byte)0x00, (byte)0x5d, (byte)0xbd, (byte)0x4a, (byte)0xe0, (byte)0x3b, (byte)0xb4, (byte)0x17,
(byte)0x8b, (byte)0x9f, (byte)0x76, (byte)0xb0, (byte)0x24, (byte)0x9a, (byte)0x25, (byte)0x63,
(byte)0xdb, (byte)0xeb, (byte)0x7a, (byte)0x3e, (byte)0x5c, (byte)0xb3, (byte)0xb1, (byte)0x29,
(byte)0xf2, (byte)0xca, (byte)0x58, (byte)0x6e, (byte)0xd8, (byte)0xa8, (byte)0x2f, (byte)0x75,
(byte)0xdf, (byte)0x14, (byte)0xfb, (byte)0x13, (byte)0x49, (byte)0x88, (byte)0xb2, (byte)0xec,
(byte)0xe4, (byte)0x34, (byte)0x2d, (byte)0x96, (byte)0xc6, (byte)0x3a, (byte)0xed, (byte)0x95,
(byte)0x0e, (byte)0xe5, (byte)0x85, (byte)0x6b, (byte)0x40, (byte)0x21, (byte)0x9b, (byte)0x09,
(byte)0x19, (byte)0x2b, (byte)0x52, (byte)0xde, (byte)0x45, (byte)0xa3, (byte)0xfa, (byte)0x51,
(byte)0xc2, (byte)0xb5, (byte)0xd1, (byte)0x90, (byte)0xb9, (byte)0xf3, (byte)0x37, (byte)0xc1,
(byte)0x0d, (byte)0xba, (byte)0x41, (byte)0x11, (byte)0x38, (byte)0x7b, (byte)0xbe, (byte)0xd0,
(byte)0xd5, (byte)0x69, (byte)0x36, (byte)0xc8, (byte)0x62, (byte)0x1b, (byte)0x82, (byte)0x8f
},
new byte[]
{
(byte)0x83, (byte)0xf2, (byte)0x2a, (byte)0xeb, (byte)0xe9, (byte)0xbf, (byte)0x7b, (byte)0x9c,
(byte)0x34, (byte)0x96, (byte)0x8d, (byte)0x98, (byte)0xb9, (byte)0x69, (byte)0x8c, (byte)0x29,
(byte)0x3d, (byte)0x88, (byte)0x68, (byte)0x06, (byte)0x39, (byte)0x11, (byte)0x4c, (byte)0x0e,
(byte)0xa0, (byte)0x56, (byte)0x40, (byte)0x92, (byte)0x15, (byte)0xbc, (byte)0xb3, (byte)0xdc,
(byte)0x6f, (byte)0xf8, (byte)0x26, (byte)0xba, (byte)0xbe, (byte)0xbd, (byte)0x31, (byte)0xfb,
(byte)0xc3, (byte)0xfe, (byte)0x80, (byte)0x61, (byte)0xe1, (byte)0x7a, (byte)0x32, (byte)0xd2,
(byte)0x70, (byte)0x20, (byte)0xa1, (byte)0x45, (byte)0xec, (byte)0xd9, (byte)0x1a, (byte)0x5d,
(byte)0xb4, (byte)0xd8, (byte)0x09, (byte)0xa5, (byte)0x55, (byte)0x8e, (byte)0x37, (byte)0x76,
(byte)0xa9, (byte)0x67, (byte)0x10, (byte)0x17, (byte)0x36, (byte)0x65, (byte)0xb1, (byte)0x95,
(byte)0x62, (byte)0x59, (byte)0x74, (byte)0xa3, (byte)0x50, (byte)0x2f, (byte)0x4b, (byte)0xc8,
(byte)0xd0, (byte)0x8f, (byte)0xcd, (byte)0xd4, (byte)0x3c, (byte)0x86, (byte)0x12, (byte)0x1d,
(byte)0x23, (byte)0xef, (byte)0xf4, (byte)0x53, (byte)0x19, (byte)0x35, (byte)0xe6, (byte)0x7f,
(byte)0x5e, (byte)0xd6, (byte)0x79, (byte)0x51, (byte)0x22, (byte)0x14, (byte)0xf7, (byte)0x1e,
(byte)0x4a, (byte)0x42, (byte)0x9b, (byte)0x41, (byte)0x73, (byte)0x2d, (byte)0xc1, (byte)0x5c,
(byte)0xa6, (byte)0xa2, (byte)0xe0, (byte)0x2e, (byte)0xd3, (byte)0x28, (byte)0xbb, (byte)0xc9,
(byte)0xae, (byte)0x6a, (byte)0xd1, (byte)0x5a, (byte)0x30, (byte)0x90, (byte)0x84, (byte)0xf9,
(byte)0xb2, (byte)0x58, (byte)0xcf, (byte)0x7e, (byte)0xc5, (byte)0xcb, (byte)0x97, (byte)0xe4,
(byte)0x16, (byte)0x6c, (byte)0xfa, (byte)0xb0, (byte)0x6d, (byte)0x1f, (byte)0x52, (byte)0x99,
(byte)0x0d, (byte)0x4e, (byte)0x03, (byte)0x91, (byte)0xc2, (byte)0x4d, (byte)0x64, (byte)0x77,
(byte)0x9f, (byte)0xdd, (byte)0xc4, (byte)0x49, (byte)0x8a, (byte)0x9a, (byte)0x24, (byte)0x38,
(byte)0xa7, (byte)0x57, (byte)0x85, (byte)0xc7, (byte)0x7c, (byte)0x7d, (byte)0xe7, (byte)0xf6,
(byte)0xb7, (byte)0xac, (byte)0x27, (byte)0x46, (byte)0xde, (byte)0xdf, (byte)0x3b, (byte)0xd7,
(byte)0x9e, (byte)0x2b, (byte)0x0b, (byte)0xd5, (byte)0x13, (byte)0x75, (byte)0xf0, (byte)0x72,
(byte)0xb6, (byte)0x9d, (byte)0x1b, (byte)0x01, (byte)0x3f, (byte)0x44, (byte)0xe5, (byte)0x87,
(byte)0xfd, (byte)0x07, (byte)0xf1, (byte)0xab, (byte)0x94, (byte)0x18, (byte)0xea, (byte)0xfc,
(byte)0x3a, (byte)0x82, (byte)0x5f, (byte)0x05, (byte)0x54, (byte)0xdb, (byte)0x00, (byte)0x8b,
(byte)0xe3, (byte)0x48, (byte)0x0c, (byte)0xca, (byte)0x78, (byte)0x89, (byte)0x0a, (byte)0xff,
(byte)0x3e, (byte)0x5b, (byte)0x81, (byte)0xee, (byte)0x71, (byte)0xe2, (byte)0xda, (byte)0x2c,
(byte)0xb8, (byte)0xb5, (byte)0xcc, (byte)0x6e, (byte)0xa8, (byte)0x6b, (byte)0xad, (byte)0x60,
(byte)0xc6, (byte)0x08, (byte)0x04, (byte)0x02, (byte)0xe8, (byte)0xf5, (byte)0x4f, (byte)0xa4,
(byte)0xf3, (byte)0xc0, (byte)0xce, (byte)0x43, (byte)0x25, (byte)0x1c, (byte)0x21, (byte)0x33,
(byte)0x0f, (byte)0xaf, (byte)0x47, (byte)0xed, (byte)0x66, (byte)0x63, (byte)0x93, (byte)0xaa
},
new byte[]
{
(byte)0x45, (byte)0xd4, (byte)0x0b, (byte)0x43, (byte)0xf1, (byte)0x72, (byte)0xed, (byte)0xa4,
(byte)0xc2, (byte)0x38, (byte)0xe6, (byte)0x71, (byte)0xfd, (byte)0xb6, (byte)0x3a, (byte)0x95,
(byte)0x50, (byte)0x44, (byte)0x4b, (byte)0xe2, (byte)0x74, (byte)0x6b, (byte)0x1e, (byte)0x11,
(byte)0x5a, (byte)0xc6, (byte)0xb4, (byte)0xd8, (byte)0xa5, (byte)0x8a, (byte)0x70, (byte)0xa3,
(byte)0xa8, (byte)0xfa, (byte)0x05, (byte)0xd9, (byte)0x97, (byte)0x40, (byte)0xc9, (byte)0x90,
(byte)0x98, (byte)0x8f, (byte)0xdc, (byte)0x12, (byte)0x31, (byte)0x2c, (byte)0x47, (byte)0x6a,
(byte)0x99, (byte)0xae, (byte)0xc8, (byte)0x7f, (byte)0xf9, (byte)0x4f, (byte)0x5d, (byte)0x96,
(byte)0x6f, (byte)0xf4, (byte)0xb3, (byte)0x39, (byte)0x21, (byte)0xda, (byte)0x9c, (byte)0x85,
(byte)0x9e, (byte)0x3b, (byte)0xf0, (byte)0xbf, (byte)0xef, (byte)0x06, (byte)0xee, (byte)0xe5,
(byte)0x5f, (byte)0x20, (byte)0x10, (byte)0xcc, (byte)0x3c, (byte)0x54, (byte)0x4a, (byte)0x52,
(byte)0x94, (byte)0x0e, (byte)0xc0, (byte)0x28, (byte)0xf6, (byte)0x56, (byte)0x60, (byte)0xa2,
(byte)0xe3, (byte)0x0f, (byte)0xec, (byte)0x9d, (byte)0x24, (byte)0x83, (byte)0x7e, (byte)0xd5,
(byte)0x7c, (byte)0xeb, (byte)0x18, (byte)0xd7, (byte)0xcd, (byte)0xdd, (byte)0x78, (byte)0xff,
(byte)0xdb, (byte)0xa1, (byte)0x09, (byte)0xd0, (byte)0x76, (byte)0x84, (byte)0x75, (byte)0xbb,
(byte)0x1d, (byte)0x1a, (byte)0x2f, (byte)0xb0, (byte)0xfe, (byte)0xd6, (byte)0x34, (byte)0x63,
(byte)0x35, (byte)0xd2, (byte)0x2a, (byte)0x59, (byte)0x6d, (byte)0x4d, (byte)0x77, (byte)0xe7,
(byte)0x8e, (byte)0x61, (byte)0xcf, (byte)0x9f, (byte)0xce, (byte)0x27, (byte)0xf5, (byte)0x80,
(byte)0x86, (byte)0xc7, (byte)0xa6, (byte)0xfb, (byte)0xf8, (byte)0x87, (byte)0xab, (byte)0x62,
(byte)0x3f, (byte)0xdf, (byte)0x48, (byte)0x00, (byte)0x14, (byte)0x9a, (byte)0xbd, (byte)0x5b,
(byte)0x04, (byte)0x92, (byte)0x02, (byte)0x25, (byte)0x65, (byte)0x4c, (byte)0x53, (byte)0x0c,
(byte)0xf2, (byte)0x29, (byte)0xaf, (byte)0x17, (byte)0x6c, (byte)0x41, (byte)0x30, (byte)0xe9,
(byte)0x93, (byte)0x55, (byte)0xf7, (byte)0xac, (byte)0x68, (byte)0x26, (byte)0xc4, (byte)0x7d,
(byte)0xca, (byte)0x7a, (byte)0x3e, (byte)0xa0, (byte)0x37, (byte)0x03, (byte)0xc1, (byte)0x36,
(byte)0x69, (byte)0x66, (byte)0x08, (byte)0x16, (byte)0xa7, (byte)0xbc, (byte)0xc5, (byte)0xd3,
(byte)0x22, (byte)0xb7, (byte)0x13, (byte)0x46, (byte)0x32, (byte)0xe8, (byte)0x57, (byte)0x88,
(byte)0x2b, (byte)0x81, (byte)0xb2, (byte)0x4e, (byte)0x64, (byte)0x1c, (byte)0xaa, (byte)0x91,
(byte)0x58, (byte)0x2e, (byte)0x9b, (byte)0x5c, (byte)0x1b, (byte)0x51, (byte)0x73, (byte)0x42,
(byte)0x23, (byte)0x01, (byte)0x6e, (byte)0xf3, (byte)0x0d, (byte)0xbe, (byte)0x3d, (byte)0x0a,
(byte)0x2d, (byte)0x1f, (byte)0x67, (byte)0x33, (byte)0x19, (byte)0x7b, (byte)0x5e, (byte)0xea,
(byte)0xde, (byte)0x8b, (byte)0xcb, (byte)0xa9, (byte)0x8c, (byte)0x8d, (byte)0xad, (byte)0x49,
(byte)0x82, (byte)0xe4, (byte)0xba, (byte)0xc3, (byte)0x15, (byte)0xd1, (byte)0xe0, (byte)0x89,
(byte)0xfc, (byte)0xb1, (byte)0xb9, (byte)0xb5, (byte)0x07, (byte)0x79, (byte)0xb8, (byte)0xe1
},
new byte[]
{
(byte)0xb2, (byte)0xb6, (byte)0x23, (byte)0x11, (byte)0xa7, (byte)0x88, (byte)0xc5, (byte)0xa6,
(byte)0x39, (byte)0x8f, (byte)0xc4, (byte)0xe8, (byte)0x73, (byte)0x22, (byte)0x43, (byte)0xc3,
(byte)0x82, (byte)0x27, (byte)0xcd, (byte)0x18, (byte)0x51, (byte)0x62, (byte)0x2d, (byte)0xf7,
(byte)0x5c, (byte)0x0e, (byte)0x3b, (byte)0xfd, (byte)0xca, (byte)0x9b, (byte)0x0d, (byte)0x0f,
(byte)0x79, (byte)0x8c, (byte)0x10, (byte)0x4c, (byte)0x74, (byte)0x1c, (byte)0x0a, (byte)0x8e,
(byte)0x7c, (byte)0x94, (byte)0x07, (byte)0xc7, (byte)0x5e, (byte)0x14, (byte)0xa1, (byte)0x21,
(byte)0x57, (byte)0x50, (byte)0x4e, (byte)0xa9, (byte)0x80, (byte)0xd9, (byte)0xef, (byte)0x64,
(byte)0x41, (byte)0xcf, (byte)0x3c, (byte)0xee, (byte)0x2e, (byte)0x13, (byte)0x29, (byte)0xba,
(byte)0x34, (byte)0x5a, (byte)0xae, (byte)0x8a, (byte)0x61, (byte)0x33, (byte)0x12, (byte)0xb9,
(byte)0x55, (byte)0xa8, (byte)0x15, (byte)0x05, (byte)0xf6, (byte)0x03, (byte)0x06, (byte)0x49,
(byte)0xb5, (byte)0x25, (byte)0x09, (byte)0x16, (byte)0x0c, (byte)0x2a, (byte)0x38, (byte)0xfc,
(byte)0x20, (byte)0xf4, (byte)0xe5, (byte)0x7f, (byte)0xd7, (byte)0x31, (byte)0x2b, (byte)0x66,
(byte)0x6f, (byte)0xff, (byte)0x72, (byte)0x86, (byte)0xf0, (byte)0xa3, (byte)0x2f, (byte)0x78,
(byte)0x00, (byte)0xbc, (byte)0xcc, (byte)0xe2, (byte)0xb0, (byte)0xf1, (byte)0x42, (byte)0xb4,
(byte)0x30, (byte)0x5f, (byte)0x60, (byte)0x04, (byte)0xec, (byte)0xa5, (byte)0xe3, (byte)0x8b,
(byte)0xe7, (byte)0x1d, (byte)0xbf, (byte)0x84, (byte)0x7b, (byte)0xe6, (byte)0x81, (byte)0xf8,
(byte)0xde, (byte)0xd8, (byte)0xd2, (byte)0x17, (byte)0xce, (byte)0x4b, (byte)0x47, (byte)0xd6,
(byte)0x69, (byte)0x6c, (byte)0x19, (byte)0x99, (byte)0x9a, (byte)0x01, (byte)0xb3, (byte)0x85,
(byte)0xb1, (byte)0xf9, (byte)0x59, (byte)0xc2, (byte)0x37, (byte)0xe9, (byte)0xc8, (byte)0xa0,
(byte)0xed, (byte)0x4f, (byte)0x89, (byte)0x68, (byte)0x6d, (byte)0xd5, (byte)0x26, (byte)0x91,
(byte)0x87, (byte)0x58, (byte)0xbd, (byte)0xc9, (byte)0x98, (byte)0xdc, (byte)0x75, (byte)0xc0,
(byte)0x76, (byte)0xf5, (byte)0x67, (byte)0x6b, (byte)0x7e, (byte)0xeb, (byte)0x52, (byte)0xcb,
(byte)0xd1, (byte)0x5b, (byte)0x9f, (byte)0x0b, (byte)0xdb, (byte)0x40, (byte)0x92, (byte)0x1a,
(byte)0xfa, (byte)0xac, (byte)0xe4, (byte)0xe1, (byte)0x71, (byte)0x1f, (byte)0x65, (byte)0x8d,
(byte)0x97, (byte)0x9e, (byte)0x95, (byte)0x90, (byte)0x5d, (byte)0xb7, (byte)0xc1, (byte)0xaf,
(byte)0x54, (byte)0xfb, (byte)0x02, (byte)0xe0, (byte)0x35, (byte)0xbb, (byte)0x3a, (byte)0x4d,
(byte)0xad, (byte)0x2c, (byte)0x3d, (byte)0x56, (byte)0x08, (byte)0x1b, (byte)0x4a, (byte)0x93,
(byte)0x6a, (byte)0xab, (byte)0xb8, (byte)0x7a, (byte)0xf2, (byte)0x7d, (byte)0xda, (byte)0x3f,
(byte)0xfe, (byte)0x3e, (byte)0xbe, (byte)0xea, (byte)0xaa, (byte)0x44, (byte)0xc6, (byte)0xd0,
(byte)0x36, (byte)0x48, (byte)0x70, (byte)0x96, (byte)0x77, (byte)0x24, (byte)0x53, (byte)0xdf,
(byte)0xf3, (byte)0x83, (byte)0x28, (byte)0x32, (byte)0x45, (byte)0x1e, (byte)0xa4, (byte)0xd3,
(byte)0xa2, (byte)0x46, (byte)0x6e, (byte)0x9c, (byte)0xdd, (byte)0x63, (byte)0xd4, (byte)0x9d
}
};
//endregion
}
| core/src/main/java/org/bouncycastle/crypto/engines/DSTU7624Engine.java | package org.bouncycastle.crypto.engines;
import org.bouncycastle.crypto.BlockCipher;
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.DataLengthException;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.util.Arrays;
import org.bouncycastle.util.Pack;
/*
* Reference implementation of DSTU7624 national Ukrainian standard of block encryption.
* Thanks to Roman Oliynikov' native C implementation:
* https://github.com/Roman-Oliynikov/Kalyna-reference
*
* DSTU7564 is very similar to AES but with some security improvements in key shedule algorithm
* and supports different block and key lengths (128/256/512 bits).
*/
public class DSTU7624Engine
implements BlockCipher {
private static final int BITS_IN_WORD = 64;
private static final int BITS_IN_BYTE = 8;
private static final int BITS_IN_LONG = 64;
private static final int REDUCTION_POLYNOMIAL = 0x011d; /* x^8 + x^4 + x^3 + x^2 + 1 */
private long [] internalState;
private long [] workingKey;
private long [][] roundKeys;
/* Number of 64-bit words in block */
private int wordsInBlock;
/* Number of 64-bit words in key */
private int wordsInKey;
/* Number of encryption rounds depending on key length */
private static int ROUNDS_128 = 10;
private static int ROUNDS_256 = 14;
private static int ROUNDS_512 = 18;
private int roundsAmount;
private boolean forEncryption;
private byte[] internalStateBytes;
private byte[] tempInternalStateBytes;
public DSTU7624Engine(int blockBitLength) throws IllegalArgumentException
{
/* DSTU7624 supports 128 | 256 | 512 key/block sizes */
if (blockBitLength != 128 && blockBitLength != 256 && blockBitLength != 512)
{
throw new IllegalArgumentException("unsupported block length: only 128/256/512 are allowed");
}
wordsInBlock = blockBitLength / BITS_IN_WORD;
internalState = new long[wordsInBlock];
internalStateBytes = new byte[internalState.length * BITS_IN_LONG / BITS_IN_BYTE];
tempInternalStateBytes = new byte[internalState.length * BITS_IN_LONG / BITS_IN_BYTE];
}
public void init(boolean forEncryption, CipherParameters params) throws IllegalArgumentException
{
if (params instanceof KeyParameter)
{
this.forEncryption = forEncryption;
byte[] keyBytes = ((KeyParameter)params).getKey();
int keyBitLength = keyBytes.length * BITS_IN_BYTE;
int blockBitLength = wordsInBlock * BITS_IN_WORD;
if (keyBitLength != 128 && keyBitLength != 256 && keyBitLength != 512)
{
throw new IllegalArgumentException("unsupported key length: only 128/256/512 are allowed");
}
/* Limitations on key lengths depending on block lengths. See table 6.1 in standard */
if (blockBitLength == 128)
{
if (keyBitLength == 512)
{
throw new IllegalArgumentException("Unsupported key length");
}
}
if (blockBitLength == 256)
{
if (keyBitLength == 128)
{
throw new IllegalArgumentException("Unsupported key length");
}
}
if (blockBitLength == 512)
{
if (keyBitLength != 512)
{
throw new IllegalArgumentException("Unsupported key length");
}
}
switch (keyBitLength)
{
case 128: roundsAmount = ROUNDS_128;
break;
case 256: roundsAmount = ROUNDS_256;
break;
case 512: roundsAmount = ROUNDS_512;
break;
}
wordsInKey = keyBitLength / BITS_IN_WORD;
/* +1 round key as defined in standard */
roundKeys = new long[roundsAmount + 1][];
for (int roundKeyIndex = 0; roundKeyIndex < roundKeys.length; roundKeyIndex++)
{
roundKeys[roundKeyIndex] = new long[wordsInBlock];
}
workingKey = new long[wordsInKey];
if (keyBytes.length != wordsInKey * BITS_IN_WORD / BITS_IN_BYTE)
{
throw new IllegalArgumentException("Invalid key parameter passed to DSTU7624Engine init");
}
/* Unpack encryption key bytes to words */
Pack.littleEndianToLong(keyBytes, 0, workingKey);
long[] tempKeys = new long[wordsInBlock];
/* KSA in DSTU7624 is strengthened to mitigate known weaknesses in AES KSA (eprint.iacr.org/2012/260.pdf) */
workingKeyExpandKT(workingKey, tempKeys);
workingKeyExpandEven(workingKey, tempKeys);
workingKeyExpandOdd();
}
else
{
throw new IllegalArgumentException("Invalid parameter passed to DSTU7624Engine init");
}
}
public String getAlgorithmName()
{
return "DSTU7624";
}
public int getBlockSize()
{
return wordsInBlock * BITS_IN_WORD / BITS_IN_BYTE;
}
public int processBlock(byte[] in, int inOff, byte[] out, int outOff) throws DataLengthException, IllegalStateException
{
if (workingKey == null) {
throw new IllegalStateException("DSTU7624 engine not initialised");
}
if (inOff + getBlockSize() > in.length) {
throw new DataLengthException("Input buffer too short");
}
if (outOff + getBlockSize() > out.length) {
throw new DataLengthException("Output buffer too short");
}
if (forEncryption){
int round = 0;
/* Unpack */
Pack.littleEndianToLong(in, inOff, internalState);
/* Encrypt */
for (int wordIndex = 0; wordIndex < wordsInBlock; wordIndex++){
internalState[wordIndex] += roundKeys[round][wordIndex];
}
for (round = 1; round < roundsAmount; round++){
SubBytes();
ShiftRows();
MixColumns(mdsMatrix); // equals to multiplication on matrix
for (int wordIndex = 0; wordIndex < wordsInBlock; wordIndex++){
internalState[wordIndex] ^= roundKeys[round][wordIndex];
}
}
SubBytes();
ShiftRows();
MixColumns(mdsMatrix); // equals to multiplication on matrix
for (int wordIndex = 0; wordIndex < wordsInBlock; wordIndex++){
internalState[wordIndex] += roundKeys[roundsAmount][wordIndex];
}
/* Pack */
Pack.longToLittleEndian(internalState, out, outOff);
}
else {
int round = roundsAmount;
/* Unpack */
Pack.littleEndianToLong(in, inOff, internalState);
/* Decrypt */
for (int wordIndex = 0; wordIndex < wordsInBlock; wordIndex++){
internalState[wordIndex] -= roundKeys[round][wordIndex];
}
for (round = roundsAmount - 1; round > 0; round--){
MixColumns(mdsInvMatrix); // equals to multiplication on matrix
InvShiftRows();
InvSubBytes();
for (int wordIndex = 0; wordIndex < wordsInBlock; wordIndex++){
internalState[wordIndex] ^= roundKeys[round][wordIndex];
}
}
MixColumns(mdsInvMatrix); // equals to multiplication on matrix
InvShiftRows();
InvSubBytes();
for (int wordIndex = 0; wordIndex < wordsInBlock; wordIndex++){
internalState[wordIndex] -= roundKeys[0][wordIndex];
}
/* Pack */
Pack.longToLittleEndian(internalState, out, outOff);
}
return getBlockSize();
}
public void reset()
{
Arrays.fill(internalState, 0);
Arrays.fill(internalStateBytes, (byte)0x00);
Arrays.fill(tempInternalStateBytes, (byte)0x00);
}
public void workingKeyExpandKT(long[] workingKey, long[] tempKeys)
{
long[] k0 = new long[wordsInBlock];
long[] k1 = new long[wordsInBlock];
internalState = new long[wordsInBlock];
internalState[0] += wordsInBlock + wordsInKey + 1;
if(wordsInBlock == wordsInKey)
{
System.arraycopy(workingKey, 0, k0, 0, k0.length);
System.arraycopy(workingKey, 0, k1, 0, k1.length);
}
else
{
System.arraycopy(workingKey, 0, k0, 0, wordsInBlock);
System.arraycopy(workingKey, wordsInBlock, k1, 0, wordsInBlock);
}
for (int wordIndex = 0; wordIndex < internalState.length; wordIndex++)
{
internalState[wordIndex] += k0[wordIndex];
}
SubBytes();
ShiftRows();
MixColumns(mdsMatrix); // equals to multiplication on matrix
for (int wordIndex = 0; wordIndex < internalState.length; wordIndex++)
{
internalState[wordIndex] ^= k1[wordIndex];
}
SubBytes();
ShiftRows();
MixColumns(mdsMatrix); // equals to multiplication on matrix
for (int wordIndex = 0; wordIndex < internalState.length; wordIndex++)
{
internalState[wordIndex] += k0[wordIndex];
}
SubBytes();
ShiftRows();
MixColumns(mdsMatrix); // equals to multiplication on matrix
System.arraycopy(internalState, 0, tempKeys, 0, wordsInBlock);
}
public void workingKeyExpandEven(long[] workingKey, long[] tempKey)
{
long[] initialData = new long[wordsInKey];
long[] tempRoundKey = new long[wordsInBlock];
long[] tmv = new long[wordsInBlock];
int round = 0;
System.arraycopy(workingKey, 0, initialData, 0, wordsInKey);
for (int wordIndex = 0; wordIndex < wordsInBlock; wordIndex++)
{
tmv[wordIndex] = 0x0001000100010001L;
}
while(true)
{
System.arraycopy(tempKey, 0, internalState, 0, wordsInBlock);
for (int wordIndex = 0; wordIndex < wordsInBlock; wordIndex++) {
internalState[wordIndex] += tmv[wordIndex];
}
System.arraycopy(internalState, 0, tempRoundKey, 0, wordsInBlock);
System.arraycopy(initialData, 0, internalState, 0, wordsInBlock);
for (int wordIndex = 0; wordIndex < wordsInBlock; wordIndex++) {
internalState[wordIndex] += tempRoundKey[wordIndex];
}
SubBytes();
ShiftRows();
MixColumns(mdsMatrix); // equals to multiplication on matrix
for (int wordIndex = 0; wordIndex < wordsInBlock; wordIndex++) {
internalState[wordIndex] ^= tempRoundKey[wordIndex];
}
SubBytes();
ShiftRows();
MixColumns(mdsMatrix); // equals to multiplication on matrix
for (int wordIndex = 0; wordIndex < wordsInBlock; wordIndex++) {
internalState[wordIndex] += tempRoundKey[wordIndex];
}
System.arraycopy(internalState, 0, roundKeys[round], 0, wordsInBlock);
if (roundsAmount == round)
{
break;
}
if (wordsInBlock != wordsInKey)
{
round += 2;
ShiftLeft(tmv);
System.arraycopy(tempKey, 0, internalState,0, wordsInBlock);
for (int wordIndex = 0; wordIndex < wordsInBlock; wordIndex++) {
internalState[wordIndex] += tmv[wordIndex];
}
System.arraycopy(internalState, 0, tempRoundKey, 0, wordsInBlock);
System.arraycopy(initialData, wordsInBlock, internalState, 0, wordsInBlock);
for (int wordIndex = 0; wordIndex < wordsInBlock; wordIndex++) {
internalState[wordIndex] += tempRoundKey[wordIndex];
}
SubBytes();
ShiftRows();
MixColumns(mdsMatrix); // equals to multiplication on matrix
for (int wordIndex = 0; wordIndex < wordsInBlock; wordIndex++) {
internalState[wordIndex] ^= tempRoundKey[wordIndex];
}
SubBytes();
ShiftRows();
MixColumns(mdsMatrix); // equals to multiplication on matrix
for (int wordIndex = 0; wordIndex < wordsInBlock; wordIndex++) {
internalState[wordIndex] += tempRoundKey[wordIndex];
}
System.arraycopy(internalState, 0, roundKeys[round], 0, wordsInBlock);
if (roundsAmount == round)
{
break;
}
}
round += 2;
ShiftLeft(tmv);
long temp = initialData[0];
System.arraycopy(initialData, 1, initialData, 0, initialData.length - 1);
initialData[initialData.length - 1] = temp;
}
}
public void workingKeyExpandOdd()
{
for (int roundIndex = 1; roundIndex < roundsAmount; roundIndex += 2)
{
System.arraycopy(roundKeys[roundIndex - 1], 0, roundKeys[roundIndex], 0, wordsInBlock);
RotateLeft(roundKeys[roundIndex]);
}
}
private void SubBytes()
{
for (int i = 0; i < wordsInBlock; i++) {
internalState[i] = sboxesForEncryption[0][(int) (internalState[i] & 0x00000000000000FFL)] & 0x00000000000000FFL |
(long) sboxesForEncryption[1][(int) ((internalState[i] & 0x000000000000FF00L) >>> 8)] << 8 & 0x000000000000FF00L |
(long) sboxesForEncryption[2][(int) ((internalState[i] & 0x0000000000FF0000L) >>> 16)] << 16 & 0x0000000000FF0000L |
(long) sboxesForEncryption[3][(int) ((internalState[i] & 0x00000000FF000000L) >>> 24)] << 24 & 0x00000000FF000000L |
(long) sboxesForEncryption[0][(int) ((internalState[i] & 0x000000FF00000000L) >>> 32)] << 32 & 0x000000FF00000000L |
(long) sboxesForEncryption[1][(int) ((internalState[i] & 0x0000FF0000000000L) >>> 40)] << 40 & 0x0000FF0000000000L |
(long) sboxesForEncryption[2][(int) ((internalState[i] & 0x00FF000000000000L) >>> 48)] << 48 & 0x00FF000000000000L |
(long) sboxesForEncryption[3][(int) ((internalState[i] & 0xFF00000000000000L) >>> 56)] << 56 & 0xFF00000000000000L;
}
}
private void InvSubBytes()
{
for (int i = 0; i < wordsInBlock; i++)
{
internalState[i] = sboxesForDecryption[0][(int) (internalState[i] & 0x00000000000000FFL)] & 0x00000000000000FFL |
(long) sboxesForDecryption[1][(int) ((internalState[i] & 0x000000000000FF00L) >>> 8)] << 8 & 0x000000000000FF00L |
(long) sboxesForDecryption[2][(int) ((internalState[i] & 0x0000000000FF0000L) >>> 16)] << 16 & 0x0000000000FF0000L |
(long) sboxesForDecryption[3][(int) ((internalState[i] & 0x00000000FF000000L) >>> 24)] << 24 & 0x00000000FF000000L |
(long) sboxesForDecryption[0][(int) ((internalState[i] & 0x000000FF00000000L) >>> 32)] << 32 & 0x000000FF00000000L |
(long) sboxesForDecryption[1][(int) ((internalState[i] & 0x0000FF0000000000L) >>> 40)] << 40 & 0x0000FF0000000000L |
(long) sboxesForDecryption[2][(int) ((internalState[i] & 0x00FF000000000000L) >>> 48)] << 48 & 0x00FF000000000000L |
(long) sboxesForDecryption[3][(int) ((internalState[i] & 0xFF00000000000000L) >>> 56)] << 56 & 0xFF00000000000000L;
}
}
private void ShiftRows()
{
int row, col;
int shift = -1;
Pack.longToLittleEndian(internalState, internalStateBytes, 0);
for (row = 0; row < BITS_IN_LONG / BITS_IN_BYTE; row++)
{
if (row % (BITS_IN_LONG / BITS_IN_BYTE / wordsInBlock) == 0)
{
shift += 1;
}
for (col = 0; col < wordsInBlock; col++)
{
tempInternalStateBytes[row + ((col + shift) % wordsInBlock) * BITS_IN_LONG / BITS_IN_BYTE] = internalStateBytes[row + col * BITS_IN_LONG / BITS_IN_BYTE];
}
}
Pack.littleEndianToLong(tempInternalStateBytes, 0, internalState);
}
private void InvShiftRows()
{
int row, col;
int shift = -1;
Pack.longToLittleEndian(internalState, internalStateBytes, 0);
for (row = 0; row < BITS_IN_LONG / BITS_IN_BYTE; row++){
if (row % (BITS_IN_LONG / BITS_IN_BYTE / wordsInBlock) == 0) {
shift += 1;
}
for (col = 0; col < wordsInBlock; col++)
{
tempInternalStateBytes[row + col * BITS_IN_LONG / BITS_IN_BYTE] = internalStateBytes[row + ((col + shift) % wordsInBlock) * BITS_IN_LONG / BITS_IN_BYTE];
}
}
Pack.littleEndianToLong(tempInternalStateBytes, 0, internalState);
}
private void MixColumns(byte[][] matrix)
{
int col, row, b;
byte product;
long result;
Pack.longToLittleEndian(internalState, internalStateBytes, 0);
long shift;
for (col = 0; col < wordsInBlock; ++col)
{
result = 0;
shift = 0xFF00000000000000L;
for (row = BITS_IN_LONG / BITS_IN_BYTE - 1; row >= 0; --row)
{
product = 0;
for (b = BITS_IN_LONG / BITS_IN_BYTE - 1; b >= 0; --b) {
product ^= MultiplyGF(internalStateBytes[b + col * BITS_IN_LONG / BITS_IN_BYTE], matrix[row][b]);
}
result |= ((long)product << (row * BITS_IN_LONG / BITS_IN_BYTE) & shift);
shift >>>= 8;
}
internalState[col] = result;
}
}
private byte MultiplyGF(byte x, byte y)
{
byte r = 0;
int hbit;
for (int i = 0; i < BITS_IN_BYTE; i++)
{
if ((y & 0x01) == 1)
{
r ^= x;
}
hbit = x & 0x80;
x <<= 1;
if (hbit == 0x80)
{
x = (byte)((int)x ^ REDUCTION_POLYNOMIAL);
}
y >>= 1;
}
return r;
}
private void ShiftLeft(long[] value)
{
for (int i = 0; i < value.length; i++)
{
value[i] <<= 1;
}
//reversing state
for(int i = 0; i < value.length / 2; i++)
{
long temp = value[i];
value[i] = value[value.length - i - 1];
value[value.length - i - 1] = temp;
}
}
private void RotateLeft(long[] value)
{
int rotateBytesLength = 2 * value.length + 3;
int bytesLength = value.length * (BITS_IN_WORD / BITS_IN_BYTE);
byte[] bytes = new byte[value.length * BITS_IN_LONG / BITS_IN_BYTE];
Pack.longToLittleEndian(value, bytes, 0);
byte[] buffer = new byte[rotateBytesLength];
System.arraycopy(bytes, 0, buffer, 0, rotateBytesLength);
System.arraycopy(bytes, rotateBytesLength, bytes, 0, bytesLength - rotateBytesLength);
System.arraycopy(buffer, 0, bytes, bytesLength - rotateBytesLength, rotateBytesLength);
Pack.littleEndianToLong(bytes, 0, value);
}
//region MATRICES AND S-BOXES
private byte[][] mdsMatrix =
{
new byte[] { (byte)0x01, (byte)0x01, (byte)0x05, (byte)0x01, (byte)0x08, (byte)0x06, (byte)0x07, (byte)0x04 },
new byte[] { (byte)0x04, (byte)0x01, (byte)0x01, (byte)0x05, (byte)0x01, (byte)0x08, (byte)0x06, (byte)0x07 },
new byte[] { (byte)0x07, (byte)0x04, (byte)0x01, (byte)0x01, (byte)0x05, (byte)0x01, (byte)0x08, (byte)0x06 },
new byte[] { (byte)0x06, (byte)0x07, (byte)0x04, (byte)0x01, (byte)0x01, (byte)0x05, (byte)0x01, (byte)0x08 },
new byte[] { (byte)0x08, (byte)0x06, (byte)0x07, (byte)0x04, (byte)0x01, (byte)0x01, (byte)0x05, (byte)0x01 },
new byte[] { (byte)0x01, (byte)0x08, (byte)0x06, (byte)0x07, (byte)0x04, (byte)0x01, (byte)0x01, (byte)0x05 },
new byte[] { (byte)0x05, (byte)0x01, (byte)0x08, (byte)0x06, (byte)0x07, (byte)0x04, (byte)0x01, (byte)0x01 },
new byte[] { (byte)0x01, (byte)0x05, (byte)0x01, (byte)0x08, (byte)0x06, (byte)0x07, (byte)0x04, (byte)0x01 }
};
private byte[][] mdsInvMatrix =
{
new byte[] { (byte)0xAD, (byte)0x95, (byte)0x76, (byte)0xA8, (byte)0x2F, (byte)0x49, (byte)0xD7, (byte)0xCA },
new byte[] { (byte)0xCA, (byte)0xAD, (byte)0x95, (byte)0x76, (byte)0xA8, (byte)0x2F, (byte)0x49, (byte)0xD7 },
new byte[] { (byte)0xD7, (byte)0xCA, (byte)0xAD, (byte)0x95, (byte)0x76, (byte)0xA8, (byte)0x2F, (byte)0x49 },
new byte[] { (byte)0x49, (byte)0xD7, (byte)0xCA, (byte)0xAD, (byte)0x95, (byte)0x76, (byte)0xA8, (byte)0x2F },
new byte[] { (byte)0x2F, (byte)0x49, (byte)0xD7, (byte)0xCA, (byte)0xAD, (byte)0x95, (byte)0x76, (byte)0xA8 },
new byte[] { (byte)0xA8, (byte)0x2F, (byte)0x49, (byte)0xD7, (byte)0xCA, (byte)0xAD, (byte)0x95, (byte)0x76 },
new byte[] { (byte)0x76, (byte)0xA8, (byte)0x2F, (byte)0x49, (byte)0xD7, (byte)0xCA, (byte)0xAD, (byte)0x95 },
new byte[] { (byte)0x95, (byte)0x76, (byte)0xA8, (byte)0x2F, (byte)0x49, (byte)0xD7, (byte)0xCA, (byte)0xAD }
};
private byte[][] sboxesForEncryption =
{
new byte[]
{
(byte)0xa8, (byte)0x43, (byte)0x5f, (byte)0x06, (byte)0x6b, (byte)0x75, (byte)0x6c, (byte)0x59,
(byte)0x71, (byte)0xdf, (byte)0x87, (byte)0x95, (byte)0x17, (byte)0xf0, (byte)0xd8, (byte)0x09,
(byte)0x6d, (byte)0xf3, (byte)0x1d, (byte)0xcb, (byte)0xc9, (byte)0x4d, (byte)0x2c, (byte)0xaf,
(byte)0x79, (byte)0xe0, (byte)0x97, (byte)0xfd, (byte)0x6f, (byte)0x4b, (byte)0x45, (byte)0x39,
(byte)0x3e, (byte)0xdd, (byte)0xa3, (byte)0x4f, (byte)0xb4, (byte)0xb6, (byte)0x9a, (byte)0x0e,
(byte)0x1f, (byte)0xbf, (byte)0x15, (byte)0xe1, (byte)0x49, (byte)0xd2, (byte)0x93, (byte)0xc6,
(byte)0x92, (byte)0x72, (byte)0x9e, (byte)0x61, (byte)0xd1, (byte)0x63, (byte)0xfa, (byte)0xee,
(byte)0xf4, (byte)0x19, (byte)0xd5, (byte)0xad, (byte)0x58, (byte)0xa4, (byte)0xbb, (byte)0xa1,
(byte)0xdc, (byte)0xf2, (byte)0x83, (byte)0x37, (byte)0x42, (byte)0xe4, (byte)0x7a, (byte)0x32,
(byte)0x9c, (byte)0xcc, (byte)0xab, (byte)0x4a, (byte)0x8f, (byte)0x6e, (byte)0x04, (byte)0x27,
(byte)0x2e, (byte)0xe7, (byte)0xe2, (byte)0x5a, (byte)0x96, (byte)0x16, (byte)0x23, (byte)0x2b,
(byte)0xc2, (byte)0x65, (byte)0x66, (byte)0x0f, (byte)0xbc, (byte)0xa9, (byte)0x47, (byte)0x41,
(byte)0x34, (byte)0x48, (byte)0xfc, (byte)0xb7, (byte)0x6a, (byte)0x88, (byte)0xa5, (byte)0x53,
(byte)0x86, (byte)0xf9, (byte)0x5b, (byte)0xdb, (byte)0x38, (byte)0x7b, (byte)0xc3, (byte)0x1e,
(byte)0x22, (byte)0x33, (byte)0x24, (byte)0x28, (byte)0x36, (byte)0xc7, (byte)0xb2, (byte)0x3b,
(byte)0x8e, (byte)0x77, (byte)0xba, (byte)0xf5, (byte)0x14, (byte)0x9f, (byte)0x08, (byte)0x55,
(byte)0x9b, (byte)0x4c, (byte)0xfe, (byte)0x60, (byte)0x5c, (byte)0xda, (byte)0x18, (byte)0x46,
(byte)0xcd, (byte)0x7d, (byte)0x21, (byte)0xb0, (byte)0x3f, (byte)0x1b, (byte)0x89, (byte)0xff,
(byte)0xeb, (byte)0x84, (byte)0x69, (byte)0x3a, (byte)0x9d, (byte)0xd7, (byte)0xd3, (byte)0x70,
(byte)0x67, (byte)0x40, (byte)0xb5, (byte)0xde, (byte)0x5d, (byte)0x30, (byte)0x91, (byte)0xb1,
(byte)0x78, (byte)0x11, (byte)0x01, (byte)0xe5, (byte)0x00, (byte)0x68, (byte)0x98, (byte)0xa0,
(byte)0xc5, (byte)0x02, (byte)0xa6, (byte)0x74, (byte)0x2d, (byte)0x0b, (byte)0xa2, (byte)0x76,
(byte)0xb3, (byte)0xbe, (byte)0xce, (byte)0xbd, (byte)0xae, (byte)0xe9, (byte)0x8a, (byte)0x31,
(byte)0x1c, (byte)0xec, (byte)0xf1, (byte)0x99, (byte)0x94, (byte)0xaa, (byte)0xf6, (byte)0x26,
(byte)0x2f, (byte)0xef, (byte)0xe8, (byte)0x8c, (byte)0x35, (byte)0x03, (byte)0xd4, (byte)0x7f,
(byte)0xfb, (byte)0x05, (byte)0xc1, (byte)0x5e, (byte)0x90, (byte)0x20, (byte)0x3d, (byte)0x82,
(byte)0xf7, (byte)0xea, (byte)0x0a, (byte)0x0d, (byte)0x7e, (byte)0xf8, (byte)0x50, (byte)0x1a,
(byte)0xc4, (byte)0x07, (byte)0x57, (byte)0xb8, (byte)0x3c, (byte)0x62, (byte)0xe3, (byte)0xc8,
(byte)0xac, (byte)0x52, (byte)0x64, (byte)0x10, (byte)0xd0, (byte)0xd9, (byte)0x13, (byte)0x0c,
(byte)0x12, (byte)0x29, (byte)0x51, (byte)0xb9, (byte)0xcf, (byte)0xd6, (byte)0x73, (byte)0x8d,
(byte)0x81, (byte)0x54, (byte)0xc0, (byte)0xed, (byte)0x4e, (byte)0x44, (byte)0xa7, (byte)0x2a,
(byte)0x85, (byte)0x25, (byte)0xe6, (byte)0xca, (byte)0x7c, (byte)0x8b, (byte)0x56, (byte)0x80
},
new byte[]
{
(byte)0xce, (byte)0xbb, (byte)0xeb, (byte)0x92, (byte)0xea, (byte)0xcb, (byte)0x13, (byte)0xc1,
(byte)0xe9, (byte)0x3a, (byte)0xd6, (byte)0xb2, (byte)0xd2, (byte)0x90, (byte)0x17, (byte)0xf8,
(byte)0x42, (byte)0x15, (byte)0x56, (byte)0xb4, (byte)0x65, (byte)0x1c, (byte)0x88, (byte)0x43,
(byte)0xc5, (byte)0x5c, (byte)0x36, (byte)0xba, (byte)0xf5, (byte)0x57, (byte)0x67, (byte)0x8d,
(byte)0x31, (byte)0xf6, (byte)0x64, (byte)0x58, (byte)0x9e, (byte)0xf4, (byte)0x22, (byte)0xaa,
(byte)0x75, (byte)0x0f, (byte)0x02, (byte)0xb1, (byte)0xdf, (byte)0x6d, (byte)0x73, (byte)0x4d,
(byte)0x7c, (byte)0x26, (byte)0x2e, (byte)0xf7, (byte)0x08, (byte)0x5d, (byte)0x44, (byte)0x3e,
(byte)0x9f, (byte)0x14, (byte)0xc8, (byte)0xae, (byte)0x54, (byte)0x10, (byte)0xd8, (byte)0xbc,
(byte)0x1a, (byte)0x6b, (byte)0x69, (byte)0xf3, (byte)0xbd, (byte)0x33, (byte)0xab, (byte)0xfa,
(byte)0xd1, (byte)0x9b, (byte)0x68, (byte)0x4e, (byte)0x16, (byte)0x95, (byte)0x91, (byte)0xee,
(byte)0x4c, (byte)0x63, (byte)0x8e, (byte)0x5b, (byte)0xcc, (byte)0x3c, (byte)0x19, (byte)0xa1,
(byte)0x81, (byte)0x49, (byte)0x7b, (byte)0xd9, (byte)0x6f, (byte)0x37, (byte)0x60, (byte)0xca,
(byte)0xe7, (byte)0x2b, (byte)0x48, (byte)0xfd, (byte)0x96, (byte)0x45, (byte)0xfc, (byte)0x41,
(byte)0x12, (byte)0x0d, (byte)0x79, (byte)0xe5, (byte)0x89, (byte)0x8c, (byte)0xe3, (byte)0x20,
(byte)0x30, (byte)0xdc, (byte)0xb7, (byte)0x6c, (byte)0x4a, (byte)0xb5, (byte)0x3f, (byte)0x97,
(byte)0xd4, (byte)0x62, (byte)0x2d, (byte)0x06, (byte)0xa4, (byte)0xa5, (byte)0x83, (byte)0x5f,
(byte)0x2a, (byte)0xda, (byte)0xc9, (byte)0x00, (byte)0x7e, (byte)0xa2, (byte)0x55, (byte)0xbf,
(byte)0x11, (byte)0xd5, (byte)0x9c, (byte)0xcf, (byte)0x0e, (byte)0x0a, (byte)0x3d, (byte)0x51,
(byte)0x7d, (byte)0x93, (byte)0x1b, (byte)0xfe, (byte)0xc4, (byte)0x47, (byte)0x09, (byte)0x86,
(byte)0x0b, (byte)0x8f, (byte)0x9d, (byte)0x6a, (byte)0x07, (byte)0xb9, (byte)0xb0, (byte)0x98,
(byte)0x18, (byte)0x32, (byte)0x71, (byte)0x4b, (byte)0xef, (byte)0x3b, (byte)0x70, (byte)0xa0,
(byte)0xe4, (byte)0x40, (byte)0xff, (byte)0xc3, (byte)0xa9, (byte)0xe6, (byte)0x78, (byte)0xf9,
(byte)0x8b, (byte)0x46, (byte)0x80, (byte)0x1e, (byte)0x38, (byte)0xe1, (byte)0xb8, (byte)0xa8,
(byte)0xe0, (byte)0x0c, (byte)0x23, (byte)0x76, (byte)0x1d, (byte)0x25, (byte)0x24, (byte)0x05,
(byte)0xf1, (byte)0x6e, (byte)0x94, (byte)0x28, (byte)0x9a, (byte)0x84, (byte)0xe8, (byte)0xa3,
(byte)0x4f, (byte)0x77, (byte)0xd3, (byte)0x85, (byte)0xe2, (byte)0x52, (byte)0xf2, (byte)0x82,
(byte)0x50, (byte)0x7a, (byte)0x2f, (byte)0x74, (byte)0x53, (byte)0xb3, (byte)0x61, (byte)0xaf,
(byte)0x39, (byte)0x35, (byte)0xde, (byte)0xcd, (byte)0x1f, (byte)0x99, (byte)0xac, (byte)0xad,
(byte)0x72, (byte)0x2c, (byte)0xdd, (byte)0xd0, (byte)0x87, (byte)0xbe, (byte)0x5e, (byte)0xa6,
(byte)0xec, (byte)0x04, (byte)0xc6, (byte)0x03, (byte)0x34, (byte)0xfb, (byte)0xdb, (byte)0x59,
(byte)0xb6, (byte)0xc2, (byte)0x01, (byte)0xf0, (byte)0x5a, (byte)0xed, (byte)0xa7, (byte)0x66,
(byte)0x21, (byte)0x7f, (byte)0x8a, (byte)0x27, (byte)0xc7, (byte)0xc0, (byte)0x29, (byte)0xd7
},
new byte[]
{
(byte)0x93, (byte)0xd9, (byte)0x9a, (byte)0xb5, (byte)0x98, (byte)0x22, (byte)0x45, (byte)0xfc,
(byte)0xba, (byte)0x6a, (byte)0xdf, (byte)0x02, (byte)0x9f, (byte)0xdc, (byte)0x51, (byte)0x59,
(byte)0x4a, (byte)0x17, (byte)0x2b, (byte)0xc2, (byte)0x94, (byte)0xf4, (byte)0xbb, (byte)0xa3,
(byte)0x62, (byte)0xe4, (byte)0x71, (byte)0xd4, (byte)0xcd, (byte)0x70, (byte)0x16, (byte)0xe1,
(byte)0x49, (byte)0x3c, (byte)0xc0, (byte)0xd8, (byte)0x5c, (byte)0x9b, (byte)0xad, (byte)0x85,
(byte)0x53, (byte)0xa1, (byte)0x7a, (byte)0xc8, (byte)0x2d, (byte)0xe0, (byte)0xd1, (byte)0x72,
(byte)0xa6, (byte)0x2c, (byte)0xc4, (byte)0xe3, (byte)0x76, (byte)0x78, (byte)0xb7, (byte)0xb4,
(byte)0x09, (byte)0x3b, (byte)0x0e, (byte)0x41, (byte)0x4c, (byte)0xde, (byte)0xb2, (byte)0x90,
(byte)0x25, (byte)0xa5, (byte)0xd7, (byte)0x03, (byte)0x11, (byte)0x00, (byte)0xc3, (byte)0x2e,
(byte)0x92, (byte)0xef, (byte)0x4e, (byte)0x12, (byte)0x9d, (byte)0x7d, (byte)0xcb, (byte)0x35,
(byte)0x10, (byte)0xd5, (byte)0x4f, (byte)0x9e, (byte)0x4d, (byte)0xa9, (byte)0x55, (byte)0xc6,
(byte)0xd0, (byte)0x7b, (byte)0x18, (byte)0x97, (byte)0xd3, (byte)0x36, (byte)0xe6, (byte)0x48,
(byte)0x56, (byte)0x81, (byte)0x8f, (byte)0x77, (byte)0xcc, (byte)0x9c, (byte)0xb9, (byte)0xe2,
(byte)0xac, (byte)0xb8, (byte)0x2f, (byte)0x15, (byte)0xa4, (byte)0x7c, (byte)0xda, (byte)0x38,
(byte)0x1e, (byte)0x0b, (byte)0x05, (byte)0xd6, (byte)0x14, (byte)0x6e, (byte)0x6c, (byte)0x7e,
(byte)0x66, (byte)0xfd, (byte)0xb1, (byte)0xe5, (byte)0x60, (byte)0xaf, (byte)0x5e, (byte)0x33,
(byte)0x87, (byte)0xc9, (byte)0xf0, (byte)0x5d, (byte)0x6d, (byte)0x3f, (byte)0x88, (byte)0x8d,
(byte)0xc7, (byte)0xf7, (byte)0x1d, (byte)0xe9, (byte)0xec, (byte)0xed, (byte)0x80, (byte)0x29,
(byte)0x27, (byte)0xcf, (byte)0x99, (byte)0xa8, (byte)0x50, (byte)0x0f, (byte)0x37, (byte)0x24,
(byte)0x28, (byte)0x30, (byte)0x95, (byte)0xd2, (byte)0x3e, (byte)0x5b, (byte)0x40, (byte)0x83,
(byte)0xb3, (byte)0x69, (byte)0x57, (byte)0x1f, (byte)0x07, (byte)0x1c, (byte)0x8a, (byte)0xbc,
(byte)0x20, (byte)0xeb, (byte)0xce, (byte)0x8e, (byte)0xab, (byte)0xee, (byte)0x31, (byte)0xa2,
(byte)0x73, (byte)0xf9, (byte)0xca, (byte)0x3a, (byte)0x1a, (byte)0xfb, (byte)0x0d, (byte)0xc1,
(byte)0xfe, (byte)0xfa, (byte)0xf2, (byte)0x6f, (byte)0xbd, (byte)0x96, (byte)0xdd, (byte)0x43,
(byte)0x52, (byte)0xb6, (byte)0x08, (byte)0xf3, (byte)0xae, (byte)0xbe, (byte)0x19, (byte)0x89,
(byte)0x32, (byte)0x26, (byte)0xb0, (byte)0xea, (byte)0x4b, (byte)0x64, (byte)0x84, (byte)0x82,
(byte)0x6b, (byte)0xf5, (byte)0x79, (byte)0xbf, (byte)0x01, (byte)0x5f, (byte)0x75, (byte)0x63,
(byte)0x1b, (byte)0x23, (byte)0x3d, (byte)0x68, (byte)0x2a, (byte)0x65, (byte)0xe8, (byte)0x91,
(byte)0xf6, (byte)0xff, (byte)0x13, (byte)0x58, (byte)0xf1, (byte)0x47, (byte)0x0a, (byte)0x7f,
(byte)0xc5, (byte)0xa7, (byte)0xe7, (byte)0x61, (byte)0x5a, (byte)0x06, (byte)0x46, (byte)0x44,
(byte)0x42, (byte)0x04, (byte)0xa0, (byte)0xdb, (byte)0x39, (byte)0x86, (byte)0x54, (byte)0xaa,
(byte)0x8c, (byte)0x34, (byte)0x21, (byte)0x8b, (byte)0xf8, (byte)0x0c, (byte)0x74, (byte)0x67
},
new byte[]
{
(byte)0x68, (byte)0x8d, (byte)0xca, (byte)0x4d, (byte)0x73, (byte)0x4b, (byte)0x4e, (byte)0x2a,
(byte)0xd4, (byte)0x52, (byte)0x26, (byte)0xb3, (byte)0x54, (byte)0x1e, (byte)0x19, (byte)0x1f,
(byte)0x22, (byte)0x03, (byte)0x46, (byte)0x3d, (byte)0x2d, (byte)0x4a, (byte)0x53, (byte)0x83,
(byte)0x13, (byte)0x8a, (byte)0xb7, (byte)0xd5, (byte)0x25, (byte)0x79, (byte)0xf5, (byte)0xbd,
(byte)0x58, (byte)0x2f, (byte)0x0d, (byte)0x02, (byte)0xed, (byte)0x51, (byte)0x9e, (byte)0x11,
(byte)0xf2, (byte)0x3e, (byte)0x55, (byte)0x5e, (byte)0xd1, (byte)0x16, (byte)0x3c, (byte)0x66,
(byte)0x70, (byte)0x5d, (byte)0xf3, (byte)0x45, (byte)0x40, (byte)0xcc, (byte)0xe8, (byte)0x94,
(byte)0x56, (byte)0x08, (byte)0xce, (byte)0x1a, (byte)0x3a, (byte)0xd2, (byte)0xe1,(byte)0xdf,
(byte)0xb5, (byte)0x38, (byte)0x6e, (byte)0x0e, (byte)0xe5, (byte)0xf4, (byte)0xf9, (byte)0x86,
(byte)0xe9, (byte)0x4f, (byte)0xd6, (byte)0x85, (byte)0x23, (byte)0xcf, (byte)0x32, (byte)0x99,
(byte)0x31, (byte)0x14, (byte)0xae, (byte)0xee, (byte)0xc8, (byte)0x48, (byte)0xd3, (byte)0x30,
(byte)0xa1, (byte)0x92, (byte)0x41, (byte)0xb1, (byte)0x18, (byte)0xc4, (byte)0x2c, (byte)0x71,
(byte)0x72, (byte)0x44, (byte)0x15, (byte)0xfd, (byte)0x37, (byte)0xbe, (byte)0x5f, (byte)0xaa,
(byte)0x9b, (byte)0x88, (byte)0xd8, (byte)0xab, (byte)0x89, (byte)0x9c, (byte)0xfa, (byte)0x60,
(byte)0xea, (byte)0xbc, (byte)0x62, (byte)0x0c, (byte)0x24, (byte)0xa6, (byte)0xa8, (byte)0xec,
(byte)0x67, (byte)0x20, (byte)0xdb, (byte)0x7c, (byte)0x28, (byte)0xdd, (byte)0xac, (byte)0x5b,
(byte)0x34, (byte)0x7e, (byte)0x10, (byte)0xf1, (byte)0x7b, (byte)0x8f, (byte)0x63, (byte)0xa0,
(byte)0x05, (byte)0x9a, (byte)0x43, (byte)0x77, (byte)0x21, (byte)0xbf, (byte)0x27, (byte)0x09,
(byte)0xc3, (byte)0x9f, (byte)0xb6, (byte)0xd7, (byte)0x29, (byte)0xc2, (byte)0xeb, (byte)0xc0,
(byte)0xa4, (byte)0x8b, (byte)0x8c, (byte)0x1d, (byte)0xfb, (byte)0xff, (byte)0xc1, (byte)0xb2,
(byte)0x97, (byte)0x2e, (byte)0xf8, (byte)0x65, (byte)0xf6, (byte)0x75, (byte)0x07, (byte)0x04,
(byte)0x49, (byte)0x33, (byte)0xe4, (byte)0xd9, (byte)0xb9, (byte)0xd0, (byte)0x42, (byte)0xc7,
(byte)0x6c, (byte)0x90, (byte)0x00, (byte)0x8e, (byte)0x6f, (byte)0x50, (byte)0x01, (byte)0xc5,
(byte)0xda, (byte)0x47, (byte)0x3f, (byte)0xcd, (byte)0x69, (byte)0xa2, (byte)0xe2, (byte)0x7a,
(byte)0xa7, (byte)0xc6, (byte)0x93, (byte)0x0f, (byte)0x0a, (byte)0x06, (byte)0xe6, (byte)0x2b,
(byte)0x96, (byte)0xa3, (byte)0x1c, (byte)0xaf, (byte)0x6a, (byte)0x12, (byte)0x84, (byte)0x39,
(byte)0xe7, (byte)0xb0, (byte)0x82, (byte)0xf7, (byte)0xfe, (byte)0x9d, (byte)0x87, (byte)0x5c,
(byte)0x81, (byte)0x35, (byte)0xde, (byte)0xb4, (byte)0xa5, (byte)0xfc, (byte)0x80, (byte)0xef,
(byte)0xcb, (byte)0xbb, (byte)0x6b, (byte)0x76, (byte)0xba, (byte)0x5a, (byte)0x7d, (byte)0x78,
(byte)0x0b, (byte)0x95, (byte)0xe3, (byte)0xad, (byte)0x74, (byte)0x98, (byte)0x3b, (byte)0x36,
(byte)0x64, (byte)0x6d, (byte)0xdc, (byte)0xf0, (byte)0x59, (byte)0xa9, (byte)0x4c, (byte)0x17,
(byte)0x7f, (byte)0x91, (byte)0xb8, (byte)0xc9, (byte)0x57, (byte)0x1b, (byte)0xe0, (byte)0x61
}
};
private byte[][] sboxesForDecryption =
{
new byte[]
{
(byte)0xa4, (byte)0xa2, (byte)0xa9, (byte)0xc5, (byte)0x4e, (byte)0xc9, (byte)0x03, (byte)0xd9,
(byte)0x7e, (byte)0x0f, (byte)0xd2, (byte)0xad, (byte)0xe7, (byte)0xd3, (byte)0x27, (byte)0x5b,
(byte)0xe3, (byte)0xa1, (byte)0xe8, (byte)0xe6, (byte)0x7c, (byte)0x2a, (byte)0x55, (byte)0x0c,
(byte)0x86, (byte)0x39, (byte)0xd7, (byte)0x8d, (byte)0xb8, (byte)0x12, (byte)0x6f, (byte)0x28,
(byte)0xcd, (byte)0x8a, (byte)0x70, (byte)0x56, (byte)0x72, (byte)0xf9, (byte)0xbf, (byte)0x4f,
(byte)0x73, (byte)0xe9, (byte)0xf7, (byte)0x57, (byte)0x16, (byte)0xac, (byte)0x50, (byte)0xc0,
(byte)0x9d, (byte)0xb7, (byte)0x47, (byte)0x71, (byte)0x60, (byte)0xc4, (byte)0x74, (byte)0x43,
(byte)0x6c, (byte)0x1f, (byte)0x93, (byte)0x77, (byte)0xdc, (byte)0xce, (byte)0x20, (byte)0x8c,
(byte)0x99, (byte)0x5f, (byte)0x44, (byte)0x01, (byte)0xf5, (byte)0x1e, (byte)0x87, (byte)0x5e,
(byte)0x61, (byte)0x2c, (byte)0x4b, (byte)0x1d, (byte)0x81, (byte)0x15, (byte)0xf4, (byte)0x23,
(byte)0xd6, (byte)0xea, (byte)0xe1, (byte)0x67, (byte)0xf1, (byte)0x7f, (byte)0xfe, (byte)0xda,
(byte)0x3c, (byte)0x07, (byte)0x53, (byte)0x6a, (byte)0x84, (byte)0x9c, (byte)0xcb, (byte)0x02,
(byte)0x83, (byte)0x33, (byte)0xdd, (byte)0x35, (byte)0xe2, (byte)0x59, (byte)0x5a, (byte)0x98,
(byte)0xa5, (byte)0x92, (byte)0x64, (byte)0x04, (byte)0x06, (byte)0x10, (byte)0x4d, (byte)0x1c,
(byte)0x97, (byte)0x08, (byte)0x31, (byte)0xee, (byte)0xab, (byte)0x05, (byte)0xaf, (byte)0x79,
(byte)0xa0, (byte)0x18, (byte)0x46, (byte)0x6d, (byte)0xfc, (byte)0x89, (byte)0xd4, (byte)0xc7,
(byte)0xff, (byte)0xf0, (byte)0xcf, (byte)0x42, (byte)0x91, (byte)0xf8, (byte)0x68, (byte)0x0a,
(byte)0x65, (byte)0x8e, (byte)0xb6, (byte)0xfd, (byte)0xc3, (byte)0xef, (byte)0x78, (byte)0x4c,
(byte)0xcc, (byte)0x9e, (byte)0x30, (byte)0x2e, (byte)0xbc, (byte)0x0b, (byte)0x54, (byte)0x1a,
(byte)0xa6, (byte)0xbb, (byte)0x26, (byte)0x80, (byte)0x48, (byte)0x94, (byte)0x32, (byte)0x7d,
(byte)0xa7, (byte)0x3f, (byte)0xae, (byte)0x22, (byte)0x3d, (byte)0x66, (byte)0xaa, (byte)0xf6,
(byte)0x00, (byte)0x5d, (byte)0xbd, (byte)0x4a, (byte)0xe0, (byte)0x3b, (byte)0xb4, (byte)0x17,
(byte)0x8b, (byte)0x9f, (byte)0x76, (byte)0xb0, (byte)0x24, (byte)0x9a, (byte)0x25, (byte)0x63,
(byte)0xdb, (byte)0xeb, (byte)0x7a, (byte)0x3e, (byte)0x5c, (byte)0xb3, (byte)0xb1, (byte)0x29,
(byte)0xf2, (byte)0xca, (byte)0x58, (byte)0x6e, (byte)0xd8, (byte)0xa8, (byte)0x2f, (byte)0x75,
(byte)0xdf, (byte)0x14, (byte)0xfb, (byte)0x13, (byte)0x49, (byte)0x88, (byte)0xb2, (byte)0xec,
(byte)0xe4, (byte)0x34, (byte)0x2d, (byte)0x96, (byte)0xc6, (byte)0x3a, (byte)0xed, (byte)0x95,
(byte)0x0e, (byte)0xe5, (byte)0x85, (byte)0x6b, (byte)0x40, (byte)0x21, (byte)0x9b, (byte)0x09,
(byte)0x19, (byte)0x2b, (byte)0x52, (byte)0xde, (byte)0x45, (byte)0xa3, (byte)0xfa, (byte)0x51,
(byte)0xc2, (byte)0xb5, (byte)0xd1, (byte)0x90, (byte)0xb9, (byte)0xf3, (byte)0x37, (byte)0xc1,
(byte)0x0d, (byte)0xba, (byte)0x41, (byte)0x11, (byte)0x38, (byte)0x7b, (byte)0xbe, (byte)0xd0,
(byte)0xd5, (byte)0x69, (byte)0x36, (byte)0xc8, (byte)0x62, (byte)0x1b, (byte)0x82, (byte)0x8f
},
new byte[]
{
(byte)0x83, (byte)0xf2, (byte)0x2a, (byte)0xeb, (byte)0xe9, (byte)0xbf, (byte)0x7b, (byte)0x9c,
(byte)0x34, (byte)0x96, (byte)0x8d, (byte)0x98, (byte)0xb9, (byte)0x69, (byte)0x8c, (byte)0x29,
(byte)0x3d, (byte)0x88, (byte)0x68, (byte)0x06, (byte)0x39, (byte)0x11, (byte)0x4c, (byte)0x0e,
(byte)0xa0, (byte)0x56, (byte)0x40, (byte)0x92, (byte)0x15, (byte)0xbc, (byte)0xb3, (byte)0xdc,
(byte)0x6f, (byte)0xf8, (byte)0x26, (byte)0xba, (byte)0xbe, (byte)0xbd, (byte)0x31, (byte)0xfb,
(byte)0xc3, (byte)0xfe, (byte)0x80, (byte)0x61, (byte)0xe1, (byte)0x7a, (byte)0x32, (byte)0xd2,
(byte)0x70, (byte)0x20, (byte)0xa1, (byte)0x45, (byte)0xec, (byte)0xd9, (byte)0x1a, (byte)0x5d,
(byte)0xb4, (byte)0xd8, (byte)0x09, (byte)0xa5, (byte)0x55, (byte)0x8e, (byte)0x37, (byte)0x76,
(byte)0xa9, (byte)0x67, (byte)0x10, (byte)0x17, (byte)0x36, (byte)0x65, (byte)0xb1, (byte)0x95,
(byte)0x62, (byte)0x59, (byte)0x74, (byte)0xa3, (byte)0x50, (byte)0x2f, (byte)0x4b, (byte)0xc8,
(byte)0xd0, (byte)0x8f, (byte)0xcd, (byte)0xd4, (byte)0x3c, (byte)0x86, (byte)0x12, (byte)0x1d,
(byte)0x23, (byte)0xef, (byte)0xf4, (byte)0x53, (byte)0x19, (byte)0x35, (byte)0xe6, (byte)0x7f,
(byte)0x5e, (byte)0xd6, (byte)0x79, (byte)0x51, (byte)0x22, (byte)0x14, (byte)0xf7, (byte)0x1e,
(byte)0x4a, (byte)0x42, (byte)0x9b, (byte)0x41, (byte)0x73, (byte)0x2d, (byte)0xc1, (byte)0x5c,
(byte)0xa6, (byte)0xa2, (byte)0xe0, (byte)0x2e, (byte)0xd3, (byte)0x28, (byte)0xbb, (byte)0xc9,
(byte)0xae, (byte)0x6a, (byte)0xd1, (byte)0x5a, (byte)0x30, (byte)0x90, (byte)0x84, (byte)0xf9,
(byte)0xb2, (byte)0x58, (byte)0xcf, (byte)0x7e, (byte)0xc5, (byte)0xcb, (byte)0x97, (byte)0xe4,
(byte)0x16, (byte)0x6c, (byte)0xfa, (byte)0xb0, (byte)0x6d, (byte)0x1f, (byte)0x52, (byte)0x99,
(byte)0x0d, (byte)0x4e, (byte)0x03, (byte)0x91, (byte)0xc2, (byte)0x4d, (byte)0x64, (byte)0x77,
(byte)0x9f, (byte)0xdd, (byte)0xc4, (byte)0x49, (byte)0x8a, (byte)0x9a, (byte)0x24, (byte)0x38,
(byte)0xa7, (byte)0x57, (byte)0x85, (byte)0xc7, (byte)0x7c, (byte)0x7d, (byte)0xe7, (byte)0xf6,
(byte)0xb7, (byte)0xac, (byte)0x27, (byte)0x46, (byte)0xde, (byte)0xdf, (byte)0x3b, (byte)0xd7,
(byte)0x9e, (byte)0x2b, (byte)0x0b, (byte)0xd5, (byte)0x13, (byte)0x75, (byte)0xf0, (byte)0x72,
(byte)0xb6, (byte)0x9d, (byte)0x1b, (byte)0x01, (byte)0x3f, (byte)0x44, (byte)0xe5, (byte)0x87,
(byte)0xfd, (byte)0x07, (byte)0xf1, (byte)0xab, (byte)0x94, (byte)0x18, (byte)0xea, (byte)0xfc,
(byte)0x3a, (byte)0x82, (byte)0x5f, (byte)0x05, (byte)0x54, (byte)0xdb, (byte)0x00, (byte)0x8b,
(byte)0xe3, (byte)0x48, (byte)0x0c, (byte)0xca, (byte)0x78, (byte)0x89, (byte)0x0a, (byte)0xff,
(byte)0x3e, (byte)0x5b, (byte)0x81, (byte)0xee, (byte)0x71, (byte)0xe2, (byte)0xda, (byte)0x2c,
(byte)0xb8, (byte)0xb5, (byte)0xcc, (byte)0x6e, (byte)0xa8, (byte)0x6b, (byte)0xad, (byte)0x60,
(byte)0xc6, (byte)0x08, (byte)0x04, (byte)0x02, (byte)0xe8, (byte)0xf5, (byte)0x4f, (byte)0xa4,
(byte)0xf3, (byte)0xc0, (byte)0xce, (byte)0x43, (byte)0x25, (byte)0x1c, (byte)0x21, (byte)0x33,
(byte)0x0f, (byte)0xaf, (byte)0x47, (byte)0xed, (byte)0x66, (byte)0x63, (byte)0x93, (byte)0xaa
},
new byte[]
{
(byte)0x45, (byte)0xd4, (byte)0x0b, (byte)0x43, (byte)0xf1, (byte)0x72, (byte)0xed, (byte)0xa4,
(byte)0xc2, (byte)0x38, (byte)0xe6, (byte)0x71, (byte)0xfd, (byte)0xb6, (byte)0x3a, (byte)0x95,
(byte)0x50, (byte)0x44, (byte)0x4b, (byte)0xe2, (byte)0x74, (byte)0x6b, (byte)0x1e, (byte)0x11,
(byte)0x5a, (byte)0xc6, (byte)0xb4, (byte)0xd8, (byte)0xa5, (byte)0x8a, (byte)0x70, (byte)0xa3,
(byte)0xa8, (byte)0xfa, (byte)0x05, (byte)0xd9, (byte)0x97, (byte)0x40, (byte)0xc9, (byte)0x90,
(byte)0x98, (byte)0x8f, (byte)0xdc, (byte)0x12, (byte)0x31, (byte)0x2c, (byte)0x47, (byte)0x6a,
(byte)0x99, (byte)0xae, (byte)0xc8, (byte)0x7f, (byte)0xf9, (byte)0x4f, (byte)0x5d, (byte)0x96,
(byte)0x6f, (byte)0xf4, (byte)0xb3, (byte)0x39, (byte)0x21, (byte)0xda, (byte)0x9c, (byte)0x85,
(byte)0x9e, (byte)0x3b, (byte)0xf0, (byte)0xbf, (byte)0xef, (byte)0x06, (byte)0xee, (byte)0xe5,
(byte)0x5f, (byte)0x20, (byte)0x10, (byte)0xcc, (byte)0x3c, (byte)0x54, (byte)0x4a, (byte)0x52,
(byte)0x94, (byte)0x0e, (byte)0xc0, (byte)0x28, (byte)0xf6, (byte)0x56, (byte)0x60, (byte)0xa2,
(byte)0xe3, (byte)0x0f, (byte)0xec, (byte)0x9d, (byte)0x24, (byte)0x83, (byte)0x7e, (byte)0xd5,
(byte)0x7c, (byte)0xeb, (byte)0x18, (byte)0xd7, (byte)0xcd, (byte)0xdd, (byte)0x78, (byte)0xff,
(byte)0xdb, (byte)0xa1, (byte)0x09, (byte)0xd0, (byte)0x76, (byte)0x84, (byte)0x75, (byte)0xbb,
(byte)0x1d, (byte)0x1a, (byte)0x2f, (byte)0xb0, (byte)0xfe, (byte)0xd6, (byte)0x34, (byte)0x63,
(byte)0x35, (byte)0xd2, (byte)0x2a, (byte)0x59, (byte)0x6d, (byte)0x4d, (byte)0x77, (byte)0xe7,
(byte)0x8e, (byte)0x61, (byte)0xcf, (byte)0x9f, (byte)0xce, (byte)0x27, (byte)0xf5, (byte)0x80,
(byte)0x86, (byte)0xc7, (byte)0xa6, (byte)0xfb, (byte)0xf8, (byte)0x87, (byte)0xab, (byte)0x62,
(byte)0x3f, (byte)0xdf, (byte)0x48, (byte)0x00, (byte)0x14, (byte)0x9a, (byte)0xbd, (byte)0x5b,
(byte)0x04, (byte)0x92, (byte)0x02, (byte)0x25, (byte)0x65, (byte)0x4c, (byte)0x53, (byte)0x0c,
(byte)0xf2, (byte)0x29, (byte)0xaf, (byte)0x17, (byte)0x6c, (byte)0x41, (byte)0x30, (byte)0xe9,
(byte)0x93, (byte)0x55, (byte)0xf7, (byte)0xac, (byte)0x68, (byte)0x26, (byte)0xc4, (byte)0x7d,
(byte)0xca, (byte)0x7a, (byte)0x3e, (byte)0xa0, (byte)0x37, (byte)0x03, (byte)0xc1, (byte)0x36,
(byte)0x69, (byte)0x66, (byte)0x08, (byte)0x16, (byte)0xa7, (byte)0xbc, (byte)0xc5, (byte)0xd3,
(byte)0x22, (byte)0xb7, (byte)0x13, (byte)0x46, (byte)0x32, (byte)0xe8, (byte)0x57, (byte)0x88,
(byte)0x2b, (byte)0x81, (byte)0xb2, (byte)0x4e, (byte)0x64, (byte)0x1c, (byte)0xaa, (byte)0x91,
(byte)0x58, (byte)0x2e, (byte)0x9b, (byte)0x5c, (byte)0x1b, (byte)0x51, (byte)0x73, (byte)0x42,
(byte)0x23, (byte)0x01, (byte)0x6e, (byte)0xf3, (byte)0x0d, (byte)0xbe, (byte)0x3d, (byte)0x0a,
(byte)0x2d, (byte)0x1f, (byte)0x67, (byte)0x33, (byte)0x19, (byte)0x7b, (byte)0x5e, (byte)0xea,
(byte)0xde, (byte)0x8b, (byte)0xcb, (byte)0xa9, (byte)0x8c, (byte)0x8d, (byte)0xad, (byte)0x49,
(byte)0x82, (byte)0xe4, (byte)0xba, (byte)0xc3, (byte)0x15, (byte)0xd1, (byte)0xe0, (byte)0x89,
(byte)0xfc, (byte)0xb1, (byte)0xb9, (byte)0xb5, (byte)0x07, (byte)0x79, (byte)0xb8, (byte)0xe1
},
new byte[]
{
(byte)0xb2, (byte)0xb6, (byte)0x23, (byte)0x11, (byte)0xa7, (byte)0x88, (byte)0xc5, (byte)0xa6,
(byte)0x39, (byte)0x8f, (byte)0xc4, (byte)0xe8, (byte)0x73, (byte)0x22, (byte)0x43, (byte)0xc3,
(byte)0x82, (byte)0x27, (byte)0xcd, (byte)0x18, (byte)0x51, (byte)0x62, (byte)0x2d, (byte)0xf7,
(byte)0x5c, (byte)0x0e, (byte)0x3b, (byte)0xfd, (byte)0xca, (byte)0x9b, (byte)0x0d, (byte)0x0f,
(byte)0x79, (byte)0x8c, (byte)0x10, (byte)0x4c, (byte)0x74, (byte)0x1c, (byte)0x0a, (byte)0x8e,
(byte)0x7c, (byte)0x94, (byte)0x07, (byte)0xc7, (byte)0x5e, (byte)0x14, (byte)0xa1, (byte)0x21,
(byte)0x57, (byte)0x50, (byte)0x4e, (byte)0xa9, (byte)0x80, (byte)0xd9, (byte)0xef, (byte)0x64,
(byte)0x41, (byte)0xcf, (byte)0x3c, (byte)0xee, (byte)0x2e, (byte)0x13, (byte)0x29, (byte)0xba,
(byte)0x34, (byte)0x5a, (byte)0xae, (byte)0x8a, (byte)0x61, (byte)0x33, (byte)0x12, (byte)0xb9,
(byte)0x55, (byte)0xa8, (byte)0x15, (byte)0x05, (byte)0xf6, (byte)0x03, (byte)0x06, (byte)0x49,
(byte)0xb5, (byte)0x25, (byte)0x09, (byte)0x16, (byte)0x0c, (byte)0x2a, (byte)0x38, (byte)0xfc,
(byte)0x20, (byte)0xf4, (byte)0xe5, (byte)0x7f, (byte)0xd7, (byte)0x31, (byte)0x2b, (byte)0x66,
(byte)0x6f, (byte)0xff, (byte)0x72, (byte)0x86, (byte)0xf0, (byte)0xa3, (byte)0x2f, (byte)0x78,
(byte)0x00, (byte)0xbc, (byte)0xcc, (byte)0xe2, (byte)0xb0, (byte)0xf1, (byte)0x42, (byte)0xb4,
(byte)0x30, (byte)0x5f, (byte)0x60, (byte)0x04, (byte)0xec, (byte)0xa5, (byte)0xe3, (byte)0x8b,
(byte)0xe7, (byte)0x1d, (byte)0xbf, (byte)0x84, (byte)0x7b, (byte)0xe6, (byte)0x81, (byte)0xf8,
(byte)0xde, (byte)0xd8, (byte)0xd2, (byte)0x17, (byte)0xce, (byte)0x4b, (byte)0x47, (byte)0xd6,
(byte)0x69, (byte)0x6c, (byte)0x19, (byte)0x99, (byte)0x9a, (byte)0x01, (byte)0xb3, (byte)0x85,
(byte)0xb1, (byte)0xf9, (byte)0x59, (byte)0xc2, (byte)0x37, (byte)0xe9, (byte)0xc8, (byte)0xa0,
(byte)0xed, (byte)0x4f, (byte)0x89, (byte)0x68, (byte)0x6d, (byte)0xd5, (byte)0x26, (byte)0x91,
(byte)0x87, (byte)0x58, (byte)0xbd, (byte)0xc9, (byte)0x98, (byte)0xdc, (byte)0x75, (byte)0xc0,
(byte)0x76, (byte)0xf5, (byte)0x67, (byte)0x6b, (byte)0x7e, (byte)0xeb, (byte)0x52, (byte)0xcb,
(byte)0xd1, (byte)0x5b, (byte)0x9f, (byte)0x0b, (byte)0xdb, (byte)0x40, (byte)0x92, (byte)0x1a,
(byte)0xfa, (byte)0xac, (byte)0xe4, (byte)0xe1, (byte)0x71, (byte)0x1f, (byte)0x65, (byte)0x8d,
(byte)0x97, (byte)0x9e, (byte)0x95, (byte)0x90, (byte)0x5d, (byte)0xb7, (byte)0xc1, (byte)0xaf,
(byte)0x54, (byte)0xfb, (byte)0x02, (byte)0xe0, (byte)0x35, (byte)0xbb, (byte)0x3a, (byte)0x4d,
(byte)0xad, (byte)0x2c, (byte)0x3d, (byte)0x56, (byte)0x08, (byte)0x1b, (byte)0x4a, (byte)0x93,
(byte)0x6a, (byte)0xab, (byte)0xb8, (byte)0x7a, (byte)0xf2, (byte)0x7d, (byte)0xda, (byte)0x3f,
(byte)0xfe, (byte)0x3e, (byte)0xbe, (byte)0xea, (byte)0xaa, (byte)0x44, (byte)0xc6, (byte)0xd0,
(byte)0x36, (byte)0x48, (byte)0x70, (byte)0x96, (byte)0x77, (byte)0x24, (byte)0x53, (byte)0xdf,
(byte)0xf3, (byte)0x83, (byte)0x28, (byte)0x32, (byte)0x45, (byte)0x1e, (byte)0xa4, (byte)0xd3,
(byte)0xa2, (byte)0x46, (byte)0x6e, (byte)0x9c, (byte)0xdd, (byte)0x63, (byte)0xd4, (byte)0x9d
}
};
//endregion
}
| fixed method exposure, made constants final
| core/src/main/java/org/bouncycastle/crypto/engines/DSTU7624Engine.java | fixed method exposure, made constants final | <ide><path>ore/src/main/java/org/bouncycastle/crypto/engines/DSTU7624Engine.java
<ide> * Thanks to Roman Oliynikov' native C implementation:
<ide> * https://github.com/Roman-Oliynikov/Kalyna-reference
<ide> *
<del>* DSTU7564 is very similar to AES but with some security improvements in key shedule algorithm
<add>* DSTU7564 is very similar to AES but with some security improvements in key schedule algorithm
<ide> * and supports different block and key lengths (128/256/512 bits).
<ide> */
<ide> public class DSTU7624Engine
<del> implements BlockCipher {
<add> implements BlockCipher
<add>{
<ide>
<ide> private static final int BITS_IN_WORD = 64;
<ide> private static final int BITS_IN_BYTE = 8;
<ide> private static final int BITS_IN_LONG = 64;
<del>
<add>
<ide> private static final int REDUCTION_POLYNOMIAL = 0x011d; /* x^8 + x^4 + x^3 + x^2 + 1 */
<ide>
<del> private long [] internalState;
<del> private long [] workingKey;
<del> private long [][] roundKeys;
<add> private long[] internalState;
<add> private long[] workingKey;
<add> private long[][] roundKeys;
<ide>
<ide> /* Number of 64-bit words in block */
<ide> private int wordsInBlock;
<ide> private int wordsInKey;
<ide>
<ide> /* Number of encryption rounds depending on key length */
<del> private static int ROUNDS_128 = 10;
<del> private static int ROUNDS_256 = 14;
<del> private static int ROUNDS_512 = 18;
<add> private static final int ROUNDS_128 = 10;
<add> private static final int ROUNDS_256 = 14;
<add> private static final int ROUNDS_512 = 18;
<ide>
<ide> private int roundsAmount;
<ide>
<ide> private byte[] internalStateBytes;
<ide> private byte[] tempInternalStateBytes;
<ide>
<del> public DSTU7624Engine(int blockBitLength) throws IllegalArgumentException
<add> public DSTU7624Engine(int blockBitLength)
<add> throws IllegalArgumentException
<ide> {
<ide> /* DSTU7624 supports 128 | 256 | 512 key/block sizes */
<ide> if (blockBitLength != 128 && blockBitLength != 256 && blockBitLength != 512)
<ide> tempInternalStateBytes = new byte[internalState.length * BITS_IN_LONG / BITS_IN_BYTE];
<ide> }
<ide>
<del> public void init(boolean forEncryption, CipherParameters params) throws IllegalArgumentException
<add> public void init(boolean forEncryption, CipherParameters params)
<add> throws IllegalArgumentException
<ide> {
<ide> if (params instanceof KeyParameter)
<ide> {
<ide>
<ide> switch (keyBitLength)
<ide> {
<del> case 128: roundsAmount = ROUNDS_128;
<del> break;
<del> case 256: roundsAmount = ROUNDS_256;
<del> break;
<del> case 512: roundsAmount = ROUNDS_512;
<del> break;
<add> case 128:
<add> roundsAmount = ROUNDS_128;
<add> break;
<add> case 256:
<add> roundsAmount = ROUNDS_256;
<add> break;
<add> case 512:
<add> roundsAmount = ROUNDS_512;
<add> break;
<ide> }
<ide>
<ide> wordsInKey = keyBitLength / BITS_IN_WORD;
<ide> return wordsInBlock * BITS_IN_WORD / BITS_IN_BYTE;
<ide> }
<ide>
<del> public int processBlock(byte[] in, int inOff, byte[] out, int outOff) throws DataLengthException, IllegalStateException
<del> {
<del> if (workingKey == null) {
<add> public int processBlock(byte[] in, int inOff, byte[] out, int outOff)
<add> throws DataLengthException, IllegalStateException
<add> {
<add> if (workingKey == null)
<add> {
<ide> throw new IllegalStateException("DSTU7624 engine not initialised");
<ide> }
<ide>
<del> if (inOff + getBlockSize() > in.length) {
<add> if (inOff + getBlockSize() > in.length)
<add> {
<ide> throw new DataLengthException("Input buffer too short");
<ide> }
<ide>
<del> if (outOff + getBlockSize() > out.length) {
<add> if (outOff + getBlockSize() > out.length)
<add> {
<ide> throw new DataLengthException("Output buffer too short");
<ide> }
<ide>
<ide>
<del> if (forEncryption){
<add> if (forEncryption)
<add> {
<ide> int round = 0;
<ide>
<ide> /* Unpack */
<ide> Pack.littleEndianToLong(in, inOff, internalState);
<ide>
<ide> /* Encrypt */
<del> for (int wordIndex = 0; wordIndex < wordsInBlock; wordIndex++){
<add> for (int wordIndex = 0; wordIndex < wordsInBlock; wordIndex++)
<add> {
<ide> internalState[wordIndex] += roundKeys[round][wordIndex];
<ide> }
<ide>
<del> for (round = 1; round < roundsAmount; round++){
<add> for (round = 1; round < roundsAmount; round++)
<add> {
<ide> SubBytes();
<ide> ShiftRows();
<ide> MixColumns(mdsMatrix); // equals to multiplication on matrix
<ide>
<del> for (int wordIndex = 0; wordIndex < wordsInBlock; wordIndex++){
<add> for (int wordIndex = 0; wordIndex < wordsInBlock; wordIndex++)
<add> {
<ide> internalState[wordIndex] ^= roundKeys[round][wordIndex];
<ide> }
<ide> }
<ide> ShiftRows();
<ide> MixColumns(mdsMatrix); // equals to multiplication on matrix
<ide>
<del> for (int wordIndex = 0; wordIndex < wordsInBlock; wordIndex++){
<add> for (int wordIndex = 0; wordIndex < wordsInBlock; wordIndex++)
<add> {
<ide> internalState[wordIndex] += roundKeys[roundsAmount][wordIndex];
<ide> }
<ide>
<ide> Pack.longToLittleEndian(internalState, out, outOff);
<ide>
<ide> }
<del> else {
<add> else
<add> {
<ide> int round = roundsAmount;
<ide>
<ide> /* Unpack */
<ide> Pack.littleEndianToLong(in, inOff, internalState);
<ide>
<ide> /* Decrypt */
<del> for (int wordIndex = 0; wordIndex < wordsInBlock; wordIndex++){
<add> for (int wordIndex = 0; wordIndex < wordsInBlock; wordIndex++)
<add> {
<ide> internalState[wordIndex] -= roundKeys[round][wordIndex];
<ide> }
<ide>
<del> for (round = roundsAmount - 1; round > 0; round--){
<add> for (round = roundsAmount - 1; round > 0; round--)
<add> {
<ide> MixColumns(mdsInvMatrix); // equals to multiplication on matrix
<ide> InvShiftRows();
<ide> InvSubBytes();
<ide>
<del> for (int wordIndex = 0; wordIndex < wordsInBlock; wordIndex++){
<add> for (int wordIndex = 0; wordIndex < wordsInBlock; wordIndex++)
<add> {
<ide> internalState[wordIndex] ^= roundKeys[round][wordIndex];
<ide> }
<ide> }
<ide> InvShiftRows();
<ide> InvSubBytes();
<ide>
<del> for (int wordIndex = 0; wordIndex < wordsInBlock; wordIndex++){
<add> for (int wordIndex = 0; wordIndex < wordsInBlock; wordIndex++)
<add> {
<ide> internalState[wordIndex] -= roundKeys[0][wordIndex];
<ide> }
<ide>
<ide> }
<ide>
<ide>
<del>
<del> public void workingKeyExpandKT(long[] workingKey, long[] tempKeys)
<add> private void workingKeyExpandKT(long[] workingKey, long[] tempKeys)
<ide> {
<ide> long[] k0 = new long[wordsInBlock];
<ide> long[] k1 = new long[wordsInBlock];
<ide> internalState = new long[wordsInBlock];
<ide> internalState[0] += wordsInBlock + wordsInKey + 1;
<ide>
<del> if(wordsInBlock == wordsInKey)
<add> if (wordsInBlock == wordsInKey)
<ide> {
<ide> System.arraycopy(workingKey, 0, k0, 0, k0.length);
<ide> System.arraycopy(workingKey, 0, k1, 0, k1.length);
<ide> System.arraycopy(internalState, 0, tempKeys, 0, wordsInBlock);
<ide> }
<ide>
<del> public void workingKeyExpandEven(long[] workingKey, long[] tempKey)
<add> private void workingKeyExpandEven(long[] workingKey, long[] tempKey)
<ide> {
<ide> long[] initialData = new long[wordsInKey];
<ide> long[] tempRoundKey = new long[wordsInBlock];
<ide> tmv[wordIndex] = 0x0001000100010001L;
<ide> }
<ide>
<del> while(true)
<add> while (true)
<ide> {
<ide> System.arraycopy(tempKey, 0, internalState, 0, wordsInBlock);
<ide>
<del> for (int wordIndex = 0; wordIndex < wordsInBlock; wordIndex++) {
<add> for (int wordIndex = 0; wordIndex < wordsInBlock; wordIndex++)
<add> {
<ide> internalState[wordIndex] += tmv[wordIndex];
<ide> }
<ide>
<ide> System.arraycopy(internalState, 0, tempRoundKey, 0, wordsInBlock);
<ide> System.arraycopy(initialData, 0, internalState, 0, wordsInBlock);
<ide>
<del> for (int wordIndex = 0; wordIndex < wordsInBlock; wordIndex++) {
<add> for (int wordIndex = 0; wordIndex < wordsInBlock; wordIndex++)
<add> {
<ide> internalState[wordIndex] += tempRoundKey[wordIndex];
<ide> }
<ide>
<ide> ShiftRows();
<ide> MixColumns(mdsMatrix); // equals to multiplication on matrix
<ide>
<del> for (int wordIndex = 0; wordIndex < wordsInBlock; wordIndex++) {
<add> for (int wordIndex = 0; wordIndex < wordsInBlock; wordIndex++)
<add> {
<ide> internalState[wordIndex] ^= tempRoundKey[wordIndex];
<ide> }
<ide>
<ide> ShiftRows();
<ide> MixColumns(mdsMatrix); // equals to multiplication on matrix
<ide>
<del> for (int wordIndex = 0; wordIndex < wordsInBlock; wordIndex++) {
<add> for (int wordIndex = 0; wordIndex < wordsInBlock; wordIndex++)
<add> {
<ide> internalState[wordIndex] += tempRoundKey[wordIndex];
<ide> }
<ide>
<ide> {
<ide> round += 2;
<ide> ShiftLeft(tmv);
<del> System.arraycopy(tempKey, 0, internalState,0, wordsInBlock);
<del>
<del> for (int wordIndex = 0; wordIndex < wordsInBlock; wordIndex++) {
<add> System.arraycopy(tempKey, 0, internalState, 0, wordsInBlock);
<add>
<add> for (int wordIndex = 0; wordIndex < wordsInBlock; wordIndex++)
<add> {
<ide> internalState[wordIndex] += tmv[wordIndex];
<ide> }
<ide>
<ide> System.arraycopy(internalState, 0, tempRoundKey, 0, wordsInBlock);
<ide> System.arraycopy(initialData, wordsInBlock, internalState, 0, wordsInBlock);
<ide>
<del> for (int wordIndex = 0; wordIndex < wordsInBlock; wordIndex++) {
<add> for (int wordIndex = 0; wordIndex < wordsInBlock; wordIndex++)
<add> {
<ide> internalState[wordIndex] += tempRoundKey[wordIndex];
<ide> }
<ide>
<ide> ShiftRows();
<ide> MixColumns(mdsMatrix); // equals to multiplication on matrix
<ide>
<del> for (int wordIndex = 0; wordIndex < wordsInBlock; wordIndex++) {
<add> for (int wordIndex = 0; wordIndex < wordsInBlock; wordIndex++)
<add> {
<ide> internalState[wordIndex] ^= tempRoundKey[wordIndex];
<ide> }
<ide>
<ide> ShiftRows();
<ide> MixColumns(mdsMatrix); // equals to multiplication on matrix
<ide>
<del> for (int wordIndex = 0; wordIndex < wordsInBlock; wordIndex++) {
<add> for (int wordIndex = 0; wordIndex < wordsInBlock; wordIndex++)
<add> {
<ide> internalState[wordIndex] += tempRoundKey[wordIndex];
<ide> }
<ide>
<ide> }
<ide> }
<ide>
<del> public void workingKeyExpandOdd()
<add> private void workingKeyExpandOdd()
<ide> {
<ide> for (int roundIndex = 1; roundIndex < roundsAmount; roundIndex += 2)
<ide> {
<ide> }
<ide>
<ide>
<del>
<ide> private void SubBytes()
<ide> {
<del> for (int i = 0; i < wordsInBlock; i++) {
<del> internalState[i] = sboxesForEncryption[0][(int) (internalState[i] & 0x00000000000000FFL)] & 0x00000000000000FFL |
<del> (long) sboxesForEncryption[1][(int) ((internalState[i] & 0x000000000000FF00L) >>> 8)] << 8 & 0x000000000000FF00L |
<del> (long) sboxesForEncryption[2][(int) ((internalState[i] & 0x0000000000FF0000L) >>> 16)] << 16 & 0x0000000000FF0000L |
<del> (long) sboxesForEncryption[3][(int) ((internalState[i] & 0x00000000FF000000L) >>> 24)] << 24 & 0x00000000FF000000L |
<del> (long) sboxesForEncryption[0][(int) ((internalState[i] & 0x000000FF00000000L) >>> 32)] << 32 & 0x000000FF00000000L |
<del> (long) sboxesForEncryption[1][(int) ((internalState[i] & 0x0000FF0000000000L) >>> 40)] << 40 & 0x0000FF0000000000L |
<del> (long) sboxesForEncryption[2][(int) ((internalState[i] & 0x00FF000000000000L) >>> 48)] << 48 & 0x00FF000000000000L |
<del> (long) sboxesForEncryption[3][(int) ((internalState[i] & 0xFF00000000000000L) >>> 56)] << 56 & 0xFF00000000000000L;
<add> for (int i = 0; i < wordsInBlock; i++)
<add> {
<add> internalState[i] = sboxesForEncryption[0][(int)(internalState[i] & 0x00000000000000FFL)] & 0x00000000000000FFL |
<add> (long)sboxesForEncryption[1][(int)((internalState[i] & 0x000000000000FF00L) >>> 8)] << 8 & 0x000000000000FF00L |
<add> (long)sboxesForEncryption[2][(int)((internalState[i] & 0x0000000000FF0000L) >>> 16)] << 16 & 0x0000000000FF0000L |
<add> (long)sboxesForEncryption[3][(int)((internalState[i] & 0x00000000FF000000L) >>> 24)] << 24 & 0x00000000FF000000L |
<add> (long)sboxesForEncryption[0][(int)((internalState[i] & 0x000000FF00000000L) >>> 32)] << 32 & 0x000000FF00000000L |
<add> (long)sboxesForEncryption[1][(int)((internalState[i] & 0x0000FF0000000000L) >>> 40)] << 40 & 0x0000FF0000000000L |
<add> (long)sboxesForEncryption[2][(int)((internalState[i] & 0x00FF000000000000L) >>> 48)] << 48 & 0x00FF000000000000L |
<add> (long)sboxesForEncryption[3][(int)((internalState[i] & 0xFF00000000000000L) >>> 56)] << 56 & 0xFF00000000000000L;
<ide> }
<ide> }
<ide>
<ide> {
<ide> for (int i = 0; i < wordsInBlock; i++)
<ide> {
<del> internalState[i] = sboxesForDecryption[0][(int) (internalState[i] & 0x00000000000000FFL)] & 0x00000000000000FFL |
<del> (long) sboxesForDecryption[1][(int) ((internalState[i] & 0x000000000000FF00L) >>> 8)] << 8 & 0x000000000000FF00L |
<del> (long) sboxesForDecryption[2][(int) ((internalState[i] & 0x0000000000FF0000L) >>> 16)] << 16 & 0x0000000000FF0000L |
<del> (long) sboxesForDecryption[3][(int) ((internalState[i] & 0x00000000FF000000L) >>> 24)] << 24 & 0x00000000FF000000L |
<del> (long) sboxesForDecryption[0][(int) ((internalState[i] & 0x000000FF00000000L) >>> 32)] << 32 & 0x000000FF00000000L |
<del> (long) sboxesForDecryption[1][(int) ((internalState[i] & 0x0000FF0000000000L) >>> 40)] << 40 & 0x0000FF0000000000L |
<del> (long) sboxesForDecryption[2][(int) ((internalState[i] & 0x00FF000000000000L) >>> 48)] << 48 & 0x00FF000000000000L |
<del> (long) sboxesForDecryption[3][(int) ((internalState[i] & 0xFF00000000000000L) >>> 56)] << 56 & 0xFF00000000000000L;
<add> internalState[i] = sboxesForDecryption[0][(int)(internalState[i] & 0x00000000000000FFL)] & 0x00000000000000FFL |
<add> (long)sboxesForDecryption[1][(int)((internalState[i] & 0x000000000000FF00L) >>> 8)] << 8 & 0x000000000000FF00L |
<add> (long)sboxesForDecryption[2][(int)((internalState[i] & 0x0000000000FF0000L) >>> 16)] << 16 & 0x0000000000FF0000L |
<add> (long)sboxesForDecryption[3][(int)((internalState[i] & 0x00000000FF000000L) >>> 24)] << 24 & 0x00000000FF000000L |
<add> (long)sboxesForDecryption[0][(int)((internalState[i] & 0x000000FF00000000L) >>> 32)] << 32 & 0x000000FF00000000L |
<add> (long)sboxesForDecryption[1][(int)((internalState[i] & 0x0000FF0000000000L) >>> 40)] << 40 & 0x0000FF0000000000L |
<add> (long)sboxesForDecryption[2][(int)((internalState[i] & 0x00FF000000000000L) >>> 48)] << 48 & 0x00FF000000000000L |
<add> (long)sboxesForDecryption[3][(int)((internalState[i] & 0xFF00000000000000L) >>> 56)] << 56 & 0xFF00000000000000L;
<ide> }
<ide> }
<ide>
<ide>
<ide> Pack.longToLittleEndian(internalState, internalStateBytes, 0);
<ide>
<del> for (row = 0; row < BITS_IN_LONG / BITS_IN_BYTE; row++){
<del> if (row % (BITS_IN_LONG / BITS_IN_BYTE / wordsInBlock) == 0) {
<add> for (row = 0; row < BITS_IN_LONG / BITS_IN_BYTE; row++)
<add> {
<add> if (row % (BITS_IN_LONG / BITS_IN_BYTE / wordsInBlock) == 0)
<add> {
<ide> shift += 1;
<ide> }
<ide> for (col = 0; col < wordsInBlock; col++)
<ide> for (row = BITS_IN_LONG / BITS_IN_BYTE - 1; row >= 0; --row)
<ide> {
<ide> product = 0;
<del> for (b = BITS_IN_LONG / BITS_IN_BYTE - 1; b >= 0; --b) {
<add> for (b = BITS_IN_LONG / BITS_IN_BYTE - 1; b >= 0; --b)
<add> {
<ide> product ^= MultiplyGF(internalStateBytes[b + col * BITS_IN_LONG / BITS_IN_BYTE], matrix[row][b]);
<ide> }
<ide>
<ide> value[i] <<= 1;
<ide> }
<ide> //reversing state
<del> for(int i = 0; i < value.length / 2; i++)
<add> for (int i = 0; i < value.length / 2; i++)
<ide> {
<ide> long temp = value[i];
<ide> value[i] = value[value.length - i - 1];
<ide> }
<ide>
<ide>
<del>
<del>//region MATRICES AND S-BOXES
<add> //region MATRICES AND S-BOXES
<ide> private byte[][] mdsMatrix =
<del> {
<del> new byte[] { (byte)0x01, (byte)0x01, (byte)0x05, (byte)0x01, (byte)0x08, (byte)0x06, (byte)0x07, (byte)0x04 },
<del> new byte[] { (byte)0x04, (byte)0x01, (byte)0x01, (byte)0x05, (byte)0x01, (byte)0x08, (byte)0x06, (byte)0x07 },
<del> new byte[] { (byte)0x07, (byte)0x04, (byte)0x01, (byte)0x01, (byte)0x05, (byte)0x01, (byte)0x08, (byte)0x06 },
<del> new byte[] { (byte)0x06, (byte)0x07, (byte)0x04, (byte)0x01, (byte)0x01, (byte)0x05, (byte)0x01, (byte)0x08 },
<del> new byte[] { (byte)0x08, (byte)0x06, (byte)0x07, (byte)0x04, (byte)0x01, (byte)0x01, (byte)0x05, (byte)0x01 },
<del> new byte[] { (byte)0x01, (byte)0x08, (byte)0x06, (byte)0x07, (byte)0x04, (byte)0x01, (byte)0x01, (byte)0x05 },
<del> new byte[] { (byte)0x05, (byte)0x01, (byte)0x08, (byte)0x06, (byte)0x07, (byte)0x04, (byte)0x01, (byte)0x01 },
<del> new byte[] { (byte)0x01, (byte)0x05, (byte)0x01, (byte)0x08, (byte)0x06, (byte)0x07, (byte)0x04, (byte)0x01 }
<del> };
<add> {
<add> new byte[]{(byte)0x01, (byte)0x01, (byte)0x05, (byte)0x01, (byte)0x08, (byte)0x06, (byte)0x07, (byte)0x04},
<add> new byte[]{(byte)0x04, (byte)0x01, (byte)0x01, (byte)0x05, (byte)0x01, (byte)0x08, (byte)0x06, (byte)0x07},
<add> new byte[]{(byte)0x07, (byte)0x04, (byte)0x01, (byte)0x01, (byte)0x05, (byte)0x01, (byte)0x08, (byte)0x06},
<add> new byte[]{(byte)0x06, (byte)0x07, (byte)0x04, (byte)0x01, (byte)0x01, (byte)0x05, (byte)0x01, (byte)0x08},
<add> new byte[]{(byte)0x08, (byte)0x06, (byte)0x07, (byte)0x04, (byte)0x01, (byte)0x01, (byte)0x05, (byte)0x01},
<add> new byte[]{(byte)0x01, (byte)0x08, (byte)0x06, (byte)0x07, (byte)0x04, (byte)0x01, (byte)0x01, (byte)0x05},
<add> new byte[]{(byte)0x05, (byte)0x01, (byte)0x08, (byte)0x06, (byte)0x07, (byte)0x04, (byte)0x01, (byte)0x01},
<add> new byte[]{(byte)0x01, (byte)0x05, (byte)0x01, (byte)0x08, (byte)0x06, (byte)0x07, (byte)0x04, (byte)0x01}
<add> };
<ide>
<ide> private byte[][] mdsInvMatrix =
<del> {
<del> new byte[] { (byte)0xAD, (byte)0x95, (byte)0x76, (byte)0xA8, (byte)0x2F, (byte)0x49, (byte)0xD7, (byte)0xCA },
<del> new byte[] { (byte)0xCA, (byte)0xAD, (byte)0x95, (byte)0x76, (byte)0xA8, (byte)0x2F, (byte)0x49, (byte)0xD7 },
<del> new byte[] { (byte)0xD7, (byte)0xCA, (byte)0xAD, (byte)0x95, (byte)0x76, (byte)0xA8, (byte)0x2F, (byte)0x49 },
<del> new byte[] { (byte)0x49, (byte)0xD7, (byte)0xCA, (byte)0xAD, (byte)0x95, (byte)0x76, (byte)0xA8, (byte)0x2F },
<del> new byte[] { (byte)0x2F, (byte)0x49, (byte)0xD7, (byte)0xCA, (byte)0xAD, (byte)0x95, (byte)0x76, (byte)0xA8 },
<del> new byte[] { (byte)0xA8, (byte)0x2F, (byte)0x49, (byte)0xD7, (byte)0xCA, (byte)0xAD, (byte)0x95, (byte)0x76 },
<del> new byte[] { (byte)0x76, (byte)0xA8, (byte)0x2F, (byte)0x49, (byte)0xD7, (byte)0xCA, (byte)0xAD, (byte)0x95 },
<del> new byte[] { (byte)0x95, (byte)0x76, (byte)0xA8, (byte)0x2F, (byte)0x49, (byte)0xD7, (byte)0xCA, (byte)0xAD }
<del> };
<add> {
<add> new byte[]{(byte)0xAD, (byte)0x95, (byte)0x76, (byte)0xA8, (byte)0x2F, (byte)0x49, (byte)0xD7, (byte)0xCA},
<add> new byte[]{(byte)0xCA, (byte)0xAD, (byte)0x95, (byte)0x76, (byte)0xA8, (byte)0x2F, (byte)0x49, (byte)0xD7},
<add> new byte[]{(byte)0xD7, (byte)0xCA, (byte)0xAD, (byte)0x95, (byte)0x76, (byte)0xA8, (byte)0x2F, (byte)0x49},
<add> new byte[]{(byte)0x49, (byte)0xD7, (byte)0xCA, (byte)0xAD, (byte)0x95, (byte)0x76, (byte)0xA8, (byte)0x2F},
<add> new byte[]{(byte)0x2F, (byte)0x49, (byte)0xD7, (byte)0xCA, (byte)0xAD, (byte)0x95, (byte)0x76, (byte)0xA8},
<add> new byte[]{(byte)0xA8, (byte)0x2F, (byte)0x49, (byte)0xD7, (byte)0xCA, (byte)0xAD, (byte)0x95, (byte)0x76},
<add> new byte[]{(byte)0x76, (byte)0xA8, (byte)0x2F, (byte)0x49, (byte)0xD7, (byte)0xCA, (byte)0xAD, (byte)0x95},
<add> new byte[]{(byte)0x95, (byte)0x76, (byte)0xA8, (byte)0x2F, (byte)0x49, (byte)0xD7, (byte)0xCA, (byte)0xAD}
<add> };
<ide>
<ide>
<ide> private byte[][] sboxesForEncryption =
<del> {
<del> new byte[]
<del> {
<del> (byte)0xa8, (byte)0x43, (byte)0x5f, (byte)0x06, (byte)0x6b, (byte)0x75, (byte)0x6c, (byte)0x59,
<del> (byte)0x71, (byte)0xdf, (byte)0x87, (byte)0x95, (byte)0x17, (byte)0xf0, (byte)0xd8, (byte)0x09,
<del> (byte)0x6d, (byte)0xf3, (byte)0x1d, (byte)0xcb, (byte)0xc9, (byte)0x4d, (byte)0x2c, (byte)0xaf,
<del> (byte)0x79, (byte)0xe0, (byte)0x97, (byte)0xfd, (byte)0x6f, (byte)0x4b, (byte)0x45, (byte)0x39,
<del> (byte)0x3e, (byte)0xdd, (byte)0xa3, (byte)0x4f, (byte)0xb4, (byte)0xb6, (byte)0x9a, (byte)0x0e,
<del> (byte)0x1f, (byte)0xbf, (byte)0x15, (byte)0xe1, (byte)0x49, (byte)0xd2, (byte)0x93, (byte)0xc6,
<del> (byte)0x92, (byte)0x72, (byte)0x9e, (byte)0x61, (byte)0xd1, (byte)0x63, (byte)0xfa, (byte)0xee,
<del> (byte)0xf4, (byte)0x19, (byte)0xd5, (byte)0xad, (byte)0x58, (byte)0xa4, (byte)0xbb, (byte)0xa1,
<del> (byte)0xdc, (byte)0xf2, (byte)0x83, (byte)0x37, (byte)0x42, (byte)0xe4, (byte)0x7a, (byte)0x32,
<del> (byte)0x9c, (byte)0xcc, (byte)0xab, (byte)0x4a, (byte)0x8f, (byte)0x6e, (byte)0x04, (byte)0x27,
<del> (byte)0x2e, (byte)0xe7, (byte)0xe2, (byte)0x5a, (byte)0x96, (byte)0x16, (byte)0x23, (byte)0x2b,
<del> (byte)0xc2, (byte)0x65, (byte)0x66, (byte)0x0f, (byte)0xbc, (byte)0xa9, (byte)0x47, (byte)0x41,
<del> (byte)0x34, (byte)0x48, (byte)0xfc, (byte)0xb7, (byte)0x6a, (byte)0x88, (byte)0xa5, (byte)0x53,
<del> (byte)0x86, (byte)0xf9, (byte)0x5b, (byte)0xdb, (byte)0x38, (byte)0x7b, (byte)0xc3, (byte)0x1e,
<del> (byte)0x22, (byte)0x33, (byte)0x24, (byte)0x28, (byte)0x36, (byte)0xc7, (byte)0xb2, (byte)0x3b,
<del> (byte)0x8e, (byte)0x77, (byte)0xba, (byte)0xf5, (byte)0x14, (byte)0x9f, (byte)0x08, (byte)0x55,
<del> (byte)0x9b, (byte)0x4c, (byte)0xfe, (byte)0x60, (byte)0x5c, (byte)0xda, (byte)0x18, (byte)0x46,
<del> (byte)0xcd, (byte)0x7d, (byte)0x21, (byte)0xb0, (byte)0x3f, (byte)0x1b, (byte)0x89, (byte)0xff,
<del> (byte)0xeb, (byte)0x84, (byte)0x69, (byte)0x3a, (byte)0x9d, (byte)0xd7, (byte)0xd3, (byte)0x70,
<del> (byte)0x67, (byte)0x40, (byte)0xb5, (byte)0xde, (byte)0x5d, (byte)0x30, (byte)0x91, (byte)0xb1,
<del> (byte)0x78, (byte)0x11, (byte)0x01, (byte)0xe5, (byte)0x00, (byte)0x68, (byte)0x98, (byte)0xa0,
<del> (byte)0xc5, (byte)0x02, (byte)0xa6, (byte)0x74, (byte)0x2d, (byte)0x0b, (byte)0xa2, (byte)0x76,
<del> (byte)0xb3, (byte)0xbe, (byte)0xce, (byte)0xbd, (byte)0xae, (byte)0xe9, (byte)0x8a, (byte)0x31,
<del> (byte)0x1c, (byte)0xec, (byte)0xf1, (byte)0x99, (byte)0x94, (byte)0xaa, (byte)0xf6, (byte)0x26,
<del> (byte)0x2f, (byte)0xef, (byte)0xe8, (byte)0x8c, (byte)0x35, (byte)0x03, (byte)0xd4, (byte)0x7f,
<del> (byte)0xfb, (byte)0x05, (byte)0xc1, (byte)0x5e, (byte)0x90, (byte)0x20, (byte)0x3d, (byte)0x82,
<del> (byte)0xf7, (byte)0xea, (byte)0x0a, (byte)0x0d, (byte)0x7e, (byte)0xf8, (byte)0x50, (byte)0x1a,
<del> (byte)0xc4, (byte)0x07, (byte)0x57, (byte)0xb8, (byte)0x3c, (byte)0x62, (byte)0xe3, (byte)0xc8,
<del> (byte)0xac, (byte)0x52, (byte)0x64, (byte)0x10, (byte)0xd0, (byte)0xd9, (byte)0x13, (byte)0x0c,
<del> (byte)0x12, (byte)0x29, (byte)0x51, (byte)0xb9, (byte)0xcf, (byte)0xd6, (byte)0x73, (byte)0x8d,
<del> (byte)0x81, (byte)0x54, (byte)0xc0, (byte)0xed, (byte)0x4e, (byte)0x44, (byte)0xa7, (byte)0x2a,
<del> (byte)0x85, (byte)0x25, (byte)0xe6, (byte)0xca, (byte)0x7c, (byte)0x8b, (byte)0x56, (byte)0x80
<del> },
<del>
<del> new byte[]
<del> {
<del> (byte)0xce, (byte)0xbb, (byte)0xeb, (byte)0x92, (byte)0xea, (byte)0xcb, (byte)0x13, (byte)0xc1,
<del> (byte)0xe9, (byte)0x3a, (byte)0xd6, (byte)0xb2, (byte)0xd2, (byte)0x90, (byte)0x17, (byte)0xf8,
<del> (byte)0x42, (byte)0x15, (byte)0x56, (byte)0xb4, (byte)0x65, (byte)0x1c, (byte)0x88, (byte)0x43,
<del> (byte)0xc5, (byte)0x5c, (byte)0x36, (byte)0xba, (byte)0xf5, (byte)0x57, (byte)0x67, (byte)0x8d,
<del> (byte)0x31, (byte)0xf6, (byte)0x64, (byte)0x58, (byte)0x9e, (byte)0xf4, (byte)0x22, (byte)0xaa,
<del> (byte)0x75, (byte)0x0f, (byte)0x02, (byte)0xb1, (byte)0xdf, (byte)0x6d, (byte)0x73, (byte)0x4d,
<del> (byte)0x7c, (byte)0x26, (byte)0x2e, (byte)0xf7, (byte)0x08, (byte)0x5d, (byte)0x44, (byte)0x3e,
<del> (byte)0x9f, (byte)0x14, (byte)0xc8, (byte)0xae, (byte)0x54, (byte)0x10, (byte)0xd8, (byte)0xbc,
<del> (byte)0x1a, (byte)0x6b, (byte)0x69, (byte)0xf3, (byte)0xbd, (byte)0x33, (byte)0xab, (byte)0xfa,
<del> (byte)0xd1, (byte)0x9b, (byte)0x68, (byte)0x4e, (byte)0x16, (byte)0x95, (byte)0x91, (byte)0xee,
<del> (byte)0x4c, (byte)0x63, (byte)0x8e, (byte)0x5b, (byte)0xcc, (byte)0x3c, (byte)0x19, (byte)0xa1,
<del> (byte)0x81, (byte)0x49, (byte)0x7b, (byte)0xd9, (byte)0x6f, (byte)0x37, (byte)0x60, (byte)0xca,
<del> (byte)0xe7, (byte)0x2b, (byte)0x48, (byte)0xfd, (byte)0x96, (byte)0x45, (byte)0xfc, (byte)0x41,
<del> (byte)0x12, (byte)0x0d, (byte)0x79, (byte)0xe5, (byte)0x89, (byte)0x8c, (byte)0xe3, (byte)0x20,
<del> (byte)0x30, (byte)0xdc, (byte)0xb7, (byte)0x6c, (byte)0x4a, (byte)0xb5, (byte)0x3f, (byte)0x97,
<del> (byte)0xd4, (byte)0x62, (byte)0x2d, (byte)0x06, (byte)0xa4, (byte)0xa5, (byte)0x83, (byte)0x5f,
<del> (byte)0x2a, (byte)0xda, (byte)0xc9, (byte)0x00, (byte)0x7e, (byte)0xa2, (byte)0x55, (byte)0xbf,
<del> (byte)0x11, (byte)0xd5, (byte)0x9c, (byte)0xcf, (byte)0x0e, (byte)0x0a, (byte)0x3d, (byte)0x51,
<del> (byte)0x7d, (byte)0x93, (byte)0x1b, (byte)0xfe, (byte)0xc4, (byte)0x47, (byte)0x09, (byte)0x86,
<del> (byte)0x0b, (byte)0x8f, (byte)0x9d, (byte)0x6a, (byte)0x07, (byte)0xb9, (byte)0xb0, (byte)0x98,
<del> (byte)0x18, (byte)0x32, (byte)0x71, (byte)0x4b, (byte)0xef, (byte)0x3b, (byte)0x70, (byte)0xa0,
<del> (byte)0xe4, (byte)0x40, (byte)0xff, (byte)0xc3, (byte)0xa9, (byte)0xe6, (byte)0x78, (byte)0xf9,
<del> (byte)0x8b, (byte)0x46, (byte)0x80, (byte)0x1e, (byte)0x38, (byte)0xe1, (byte)0xb8, (byte)0xa8,
<del> (byte)0xe0, (byte)0x0c, (byte)0x23, (byte)0x76, (byte)0x1d, (byte)0x25, (byte)0x24, (byte)0x05,
<del> (byte)0xf1, (byte)0x6e, (byte)0x94, (byte)0x28, (byte)0x9a, (byte)0x84, (byte)0xe8, (byte)0xa3,
<del> (byte)0x4f, (byte)0x77, (byte)0xd3, (byte)0x85, (byte)0xe2, (byte)0x52, (byte)0xf2, (byte)0x82,
<del> (byte)0x50, (byte)0x7a, (byte)0x2f, (byte)0x74, (byte)0x53, (byte)0xb3, (byte)0x61, (byte)0xaf,
<del> (byte)0x39, (byte)0x35, (byte)0xde, (byte)0xcd, (byte)0x1f, (byte)0x99, (byte)0xac, (byte)0xad,
<del> (byte)0x72, (byte)0x2c, (byte)0xdd, (byte)0xd0, (byte)0x87, (byte)0xbe, (byte)0x5e, (byte)0xa6,
<del> (byte)0xec, (byte)0x04, (byte)0xc6, (byte)0x03, (byte)0x34, (byte)0xfb, (byte)0xdb, (byte)0x59,
<del> (byte)0xb6, (byte)0xc2, (byte)0x01, (byte)0xf0, (byte)0x5a, (byte)0xed, (byte)0xa7, (byte)0x66,
<del> (byte)0x21, (byte)0x7f, (byte)0x8a, (byte)0x27, (byte)0xc7, (byte)0xc0, (byte)0x29, (byte)0xd7
<del> },
<del>
<del> new byte[]
<del> {
<del> (byte)0x93, (byte)0xd9, (byte)0x9a, (byte)0xb5, (byte)0x98, (byte)0x22, (byte)0x45, (byte)0xfc,
<del> (byte)0xba, (byte)0x6a, (byte)0xdf, (byte)0x02, (byte)0x9f, (byte)0xdc, (byte)0x51, (byte)0x59,
<del> (byte)0x4a, (byte)0x17, (byte)0x2b, (byte)0xc2, (byte)0x94, (byte)0xf4, (byte)0xbb, (byte)0xa3,
<del> (byte)0x62, (byte)0xe4, (byte)0x71, (byte)0xd4, (byte)0xcd, (byte)0x70, (byte)0x16, (byte)0xe1,
<del> (byte)0x49, (byte)0x3c, (byte)0xc0, (byte)0xd8, (byte)0x5c, (byte)0x9b, (byte)0xad, (byte)0x85,
<del> (byte)0x53, (byte)0xa1, (byte)0x7a, (byte)0xc8, (byte)0x2d, (byte)0xe0, (byte)0xd1, (byte)0x72,
<del> (byte)0xa6, (byte)0x2c, (byte)0xc4, (byte)0xe3, (byte)0x76, (byte)0x78, (byte)0xb7, (byte)0xb4,
<del> (byte)0x09, (byte)0x3b, (byte)0x0e, (byte)0x41, (byte)0x4c, (byte)0xde, (byte)0xb2, (byte)0x90,
<del> (byte)0x25, (byte)0xa5, (byte)0xd7, (byte)0x03, (byte)0x11, (byte)0x00, (byte)0xc3, (byte)0x2e,
<del> (byte)0x92, (byte)0xef, (byte)0x4e, (byte)0x12, (byte)0x9d, (byte)0x7d, (byte)0xcb, (byte)0x35,
<del> (byte)0x10, (byte)0xd5, (byte)0x4f, (byte)0x9e, (byte)0x4d, (byte)0xa9, (byte)0x55, (byte)0xc6,
<del> (byte)0xd0, (byte)0x7b, (byte)0x18, (byte)0x97, (byte)0xd3, (byte)0x36, (byte)0xe6, (byte)0x48,
<del> (byte)0x56, (byte)0x81, (byte)0x8f, (byte)0x77, (byte)0xcc, (byte)0x9c, (byte)0xb9, (byte)0xe2,
<del> (byte)0xac, (byte)0xb8, (byte)0x2f, (byte)0x15, (byte)0xa4, (byte)0x7c, (byte)0xda, (byte)0x38,
<del> (byte)0x1e, (byte)0x0b, (byte)0x05, (byte)0xd6, (byte)0x14, (byte)0x6e, (byte)0x6c, (byte)0x7e,
<del> (byte)0x66, (byte)0xfd, (byte)0xb1, (byte)0xe5, (byte)0x60, (byte)0xaf, (byte)0x5e, (byte)0x33,
<del> (byte)0x87, (byte)0xc9, (byte)0xf0, (byte)0x5d, (byte)0x6d, (byte)0x3f, (byte)0x88, (byte)0x8d,
<del> (byte)0xc7, (byte)0xf7, (byte)0x1d, (byte)0xe9, (byte)0xec, (byte)0xed, (byte)0x80, (byte)0x29,
<del> (byte)0x27, (byte)0xcf, (byte)0x99, (byte)0xa8, (byte)0x50, (byte)0x0f, (byte)0x37, (byte)0x24,
<del> (byte)0x28, (byte)0x30, (byte)0x95, (byte)0xd2, (byte)0x3e, (byte)0x5b, (byte)0x40, (byte)0x83,
<del> (byte)0xb3, (byte)0x69, (byte)0x57, (byte)0x1f, (byte)0x07, (byte)0x1c, (byte)0x8a, (byte)0xbc,
<del> (byte)0x20, (byte)0xeb, (byte)0xce, (byte)0x8e, (byte)0xab, (byte)0xee, (byte)0x31, (byte)0xa2,
<del> (byte)0x73, (byte)0xf9, (byte)0xca, (byte)0x3a, (byte)0x1a, (byte)0xfb, (byte)0x0d, (byte)0xc1,
<del> (byte)0xfe, (byte)0xfa, (byte)0xf2, (byte)0x6f, (byte)0xbd, (byte)0x96, (byte)0xdd, (byte)0x43,
<del> (byte)0x52, (byte)0xb6, (byte)0x08, (byte)0xf3, (byte)0xae, (byte)0xbe, (byte)0x19, (byte)0x89,
<del> (byte)0x32, (byte)0x26, (byte)0xb0, (byte)0xea, (byte)0x4b, (byte)0x64, (byte)0x84, (byte)0x82,
<del> (byte)0x6b, (byte)0xf5, (byte)0x79, (byte)0xbf, (byte)0x01, (byte)0x5f, (byte)0x75, (byte)0x63,
<del> (byte)0x1b, (byte)0x23, (byte)0x3d, (byte)0x68, (byte)0x2a, (byte)0x65, (byte)0xe8, (byte)0x91,
<del> (byte)0xf6, (byte)0xff, (byte)0x13, (byte)0x58, (byte)0xf1, (byte)0x47, (byte)0x0a, (byte)0x7f,
<del> (byte)0xc5, (byte)0xa7, (byte)0xe7, (byte)0x61, (byte)0x5a, (byte)0x06, (byte)0x46, (byte)0x44,
<del> (byte)0x42, (byte)0x04, (byte)0xa0, (byte)0xdb, (byte)0x39, (byte)0x86, (byte)0x54, (byte)0xaa,
<del> (byte)0x8c, (byte)0x34, (byte)0x21, (byte)0x8b, (byte)0xf8, (byte)0x0c, (byte)0x74, (byte)0x67
<del> },
<del>
<del> new byte[]
<del> {
<del> (byte)0x68, (byte)0x8d, (byte)0xca, (byte)0x4d, (byte)0x73, (byte)0x4b, (byte)0x4e, (byte)0x2a,
<del> (byte)0xd4, (byte)0x52, (byte)0x26, (byte)0xb3, (byte)0x54, (byte)0x1e, (byte)0x19, (byte)0x1f,
<del> (byte)0x22, (byte)0x03, (byte)0x46, (byte)0x3d, (byte)0x2d, (byte)0x4a, (byte)0x53, (byte)0x83,
<del> (byte)0x13, (byte)0x8a, (byte)0xb7, (byte)0xd5, (byte)0x25, (byte)0x79, (byte)0xf5, (byte)0xbd,
<del> (byte)0x58, (byte)0x2f, (byte)0x0d, (byte)0x02, (byte)0xed, (byte)0x51, (byte)0x9e, (byte)0x11,
<del> (byte)0xf2, (byte)0x3e, (byte)0x55, (byte)0x5e, (byte)0xd1, (byte)0x16, (byte)0x3c, (byte)0x66,
<del> (byte)0x70, (byte)0x5d, (byte)0xf3, (byte)0x45, (byte)0x40, (byte)0xcc, (byte)0xe8, (byte)0x94,
<del> (byte)0x56, (byte)0x08, (byte)0xce, (byte)0x1a, (byte)0x3a, (byte)0xd2, (byte)0xe1,(byte)0xdf,
<del> (byte)0xb5, (byte)0x38, (byte)0x6e, (byte)0x0e, (byte)0xe5, (byte)0xf4, (byte)0xf9, (byte)0x86,
<del> (byte)0xe9, (byte)0x4f, (byte)0xd6, (byte)0x85, (byte)0x23, (byte)0xcf, (byte)0x32, (byte)0x99,
<del> (byte)0x31, (byte)0x14, (byte)0xae, (byte)0xee, (byte)0xc8, (byte)0x48, (byte)0xd3, (byte)0x30,
<del> (byte)0xa1, (byte)0x92, (byte)0x41, (byte)0xb1, (byte)0x18, (byte)0xc4, (byte)0x2c, (byte)0x71,
<del> (byte)0x72, (byte)0x44, (byte)0x15, (byte)0xfd, (byte)0x37, (byte)0xbe, (byte)0x5f, (byte)0xaa,
<del> (byte)0x9b, (byte)0x88, (byte)0xd8, (byte)0xab, (byte)0x89, (byte)0x9c, (byte)0xfa, (byte)0x60,
<del> (byte)0xea, (byte)0xbc, (byte)0x62, (byte)0x0c, (byte)0x24, (byte)0xa6, (byte)0xa8, (byte)0xec,
<del> (byte)0x67, (byte)0x20, (byte)0xdb, (byte)0x7c, (byte)0x28, (byte)0xdd, (byte)0xac, (byte)0x5b,
<del> (byte)0x34, (byte)0x7e, (byte)0x10, (byte)0xf1, (byte)0x7b, (byte)0x8f, (byte)0x63, (byte)0xa0,
<del> (byte)0x05, (byte)0x9a, (byte)0x43, (byte)0x77, (byte)0x21, (byte)0xbf, (byte)0x27, (byte)0x09,
<del> (byte)0xc3, (byte)0x9f, (byte)0xb6, (byte)0xd7, (byte)0x29, (byte)0xc2, (byte)0xeb, (byte)0xc0,
<del> (byte)0xa4, (byte)0x8b, (byte)0x8c, (byte)0x1d, (byte)0xfb, (byte)0xff, (byte)0xc1, (byte)0xb2,
<del> (byte)0x97, (byte)0x2e, (byte)0xf8, (byte)0x65, (byte)0xf6, (byte)0x75, (byte)0x07, (byte)0x04,
<del> (byte)0x49, (byte)0x33, (byte)0xe4, (byte)0xd9, (byte)0xb9, (byte)0xd0, (byte)0x42, (byte)0xc7,
<del> (byte)0x6c, (byte)0x90, (byte)0x00, (byte)0x8e, (byte)0x6f, (byte)0x50, (byte)0x01, (byte)0xc5,
<del> (byte)0xda, (byte)0x47, (byte)0x3f, (byte)0xcd, (byte)0x69, (byte)0xa2, (byte)0xe2, (byte)0x7a,
<del> (byte)0xa7, (byte)0xc6, (byte)0x93, (byte)0x0f, (byte)0x0a, (byte)0x06, (byte)0xe6, (byte)0x2b,
<del> (byte)0x96, (byte)0xa3, (byte)0x1c, (byte)0xaf, (byte)0x6a, (byte)0x12, (byte)0x84, (byte)0x39,
<del> (byte)0xe7, (byte)0xb0, (byte)0x82, (byte)0xf7, (byte)0xfe, (byte)0x9d, (byte)0x87, (byte)0x5c,
<del> (byte)0x81, (byte)0x35, (byte)0xde, (byte)0xb4, (byte)0xa5, (byte)0xfc, (byte)0x80, (byte)0xef,
<del> (byte)0xcb, (byte)0xbb, (byte)0x6b, (byte)0x76, (byte)0xba, (byte)0x5a, (byte)0x7d, (byte)0x78,
<del> (byte)0x0b, (byte)0x95, (byte)0xe3, (byte)0xad, (byte)0x74, (byte)0x98, (byte)0x3b, (byte)0x36,
<del> (byte)0x64, (byte)0x6d, (byte)0xdc, (byte)0xf0, (byte)0x59, (byte)0xa9, (byte)0x4c, (byte)0x17,
<del> (byte)0x7f, (byte)0x91, (byte)0xb8, (byte)0xc9, (byte)0x57, (byte)0x1b, (byte)0xe0, (byte)0x61
<del> }
<del>
<del> };
<add> {
<add> new byte[]
<add> {
<add> (byte)0xa8, (byte)0x43, (byte)0x5f, (byte)0x06, (byte)0x6b, (byte)0x75, (byte)0x6c, (byte)0x59,
<add> (byte)0x71, (byte)0xdf, (byte)0x87, (byte)0x95, (byte)0x17, (byte)0xf0, (byte)0xd8, (byte)0x09,
<add> (byte)0x6d, (byte)0xf3, (byte)0x1d, (byte)0xcb, (byte)0xc9, (byte)0x4d, (byte)0x2c, (byte)0xaf,
<add> (byte)0x79, (byte)0xe0, (byte)0x97, (byte)0xfd, (byte)0x6f, (byte)0x4b, (byte)0x45, (byte)0x39,
<add> (byte)0x3e, (byte)0xdd, (byte)0xa3, (byte)0x4f, (byte)0xb4, (byte)0xb6, (byte)0x9a, (byte)0x0e,
<add> (byte)0x1f, (byte)0xbf, (byte)0x15, (byte)0xe1, (byte)0x49, (byte)0xd2, (byte)0x93, (byte)0xc6,
<add> (byte)0x92, (byte)0x72, (byte)0x9e, (byte)0x61, (byte)0xd1, (byte)0x63, (byte)0xfa, (byte)0xee,
<add> (byte)0xf4, (byte)0x19, (byte)0xd5, (byte)0xad, (byte)0x58, (byte)0xa4, (byte)0xbb, (byte)0xa1,
<add> (byte)0xdc, (byte)0xf2, (byte)0x83, (byte)0x37, (byte)0x42, (byte)0xe4, (byte)0x7a, (byte)0x32,
<add> (byte)0x9c, (byte)0xcc, (byte)0xab, (byte)0x4a, (byte)0x8f, (byte)0x6e, (byte)0x04, (byte)0x27,
<add> (byte)0x2e, (byte)0xe7, (byte)0xe2, (byte)0x5a, (byte)0x96, (byte)0x16, (byte)0x23, (byte)0x2b,
<add> (byte)0xc2, (byte)0x65, (byte)0x66, (byte)0x0f, (byte)0xbc, (byte)0xa9, (byte)0x47, (byte)0x41,
<add> (byte)0x34, (byte)0x48, (byte)0xfc, (byte)0xb7, (byte)0x6a, (byte)0x88, (byte)0xa5, (byte)0x53,
<add> (byte)0x86, (byte)0xf9, (byte)0x5b, (byte)0xdb, (byte)0x38, (byte)0x7b, (byte)0xc3, (byte)0x1e,
<add> (byte)0x22, (byte)0x33, (byte)0x24, (byte)0x28, (byte)0x36, (byte)0xc7, (byte)0xb2, (byte)0x3b,
<add> (byte)0x8e, (byte)0x77, (byte)0xba, (byte)0xf5, (byte)0x14, (byte)0x9f, (byte)0x08, (byte)0x55,
<add> (byte)0x9b, (byte)0x4c, (byte)0xfe, (byte)0x60, (byte)0x5c, (byte)0xda, (byte)0x18, (byte)0x46,
<add> (byte)0xcd, (byte)0x7d, (byte)0x21, (byte)0xb0, (byte)0x3f, (byte)0x1b, (byte)0x89, (byte)0xff,
<add> (byte)0xeb, (byte)0x84, (byte)0x69, (byte)0x3a, (byte)0x9d, (byte)0xd7, (byte)0xd3, (byte)0x70,
<add> (byte)0x67, (byte)0x40, (byte)0xb5, (byte)0xde, (byte)0x5d, (byte)0x30, (byte)0x91, (byte)0xb1,
<add> (byte)0x78, (byte)0x11, (byte)0x01, (byte)0xe5, (byte)0x00, (byte)0x68, (byte)0x98, (byte)0xa0,
<add> (byte)0xc5, (byte)0x02, (byte)0xa6, (byte)0x74, (byte)0x2d, (byte)0x0b, (byte)0xa2, (byte)0x76,
<add> (byte)0xb3, (byte)0xbe, (byte)0xce, (byte)0xbd, (byte)0xae, (byte)0xe9, (byte)0x8a, (byte)0x31,
<add> (byte)0x1c, (byte)0xec, (byte)0xf1, (byte)0x99, (byte)0x94, (byte)0xaa, (byte)0xf6, (byte)0x26,
<add> (byte)0x2f, (byte)0xef, (byte)0xe8, (byte)0x8c, (byte)0x35, (byte)0x03, (byte)0xd4, (byte)0x7f,
<add> (byte)0xfb, (byte)0x05, (byte)0xc1, (byte)0x5e, (byte)0x90, (byte)0x20, (byte)0x3d, (byte)0x82,
<add> (byte)0xf7, (byte)0xea, (byte)0x0a, (byte)0x0d, (byte)0x7e, (byte)0xf8, (byte)0x50, (byte)0x1a,
<add> (byte)0xc4, (byte)0x07, (byte)0x57, (byte)0xb8, (byte)0x3c, (byte)0x62, (byte)0xe3, (byte)0xc8,
<add> (byte)0xac, (byte)0x52, (byte)0x64, (byte)0x10, (byte)0xd0, (byte)0xd9, (byte)0x13, (byte)0x0c,
<add> (byte)0x12, (byte)0x29, (byte)0x51, (byte)0xb9, (byte)0xcf, (byte)0xd6, (byte)0x73, (byte)0x8d,
<add> (byte)0x81, (byte)0x54, (byte)0xc0, (byte)0xed, (byte)0x4e, (byte)0x44, (byte)0xa7, (byte)0x2a,
<add> (byte)0x85, (byte)0x25, (byte)0xe6, (byte)0xca, (byte)0x7c, (byte)0x8b, (byte)0x56, (byte)0x80
<add> },
<add>
<add> new byte[]
<add> {
<add> (byte)0xce, (byte)0xbb, (byte)0xeb, (byte)0x92, (byte)0xea, (byte)0xcb, (byte)0x13, (byte)0xc1,
<add> (byte)0xe9, (byte)0x3a, (byte)0xd6, (byte)0xb2, (byte)0xd2, (byte)0x90, (byte)0x17, (byte)0xf8,
<add> (byte)0x42, (byte)0x15, (byte)0x56, (byte)0xb4, (byte)0x65, (byte)0x1c, (byte)0x88, (byte)0x43,
<add> (byte)0xc5, (byte)0x5c, (byte)0x36, (byte)0xba, (byte)0xf5, (byte)0x57, (byte)0x67, (byte)0x8d,
<add> (byte)0x31, (byte)0xf6, (byte)0x64, (byte)0x58, (byte)0x9e, (byte)0xf4, (byte)0x22, (byte)0xaa,
<add> (byte)0x75, (byte)0x0f, (byte)0x02, (byte)0xb1, (byte)0xdf, (byte)0x6d, (byte)0x73, (byte)0x4d,
<add> (byte)0x7c, (byte)0x26, (byte)0x2e, (byte)0xf7, (byte)0x08, (byte)0x5d, (byte)0x44, (byte)0x3e,
<add> (byte)0x9f, (byte)0x14, (byte)0xc8, (byte)0xae, (byte)0x54, (byte)0x10, (byte)0xd8, (byte)0xbc,
<add> (byte)0x1a, (byte)0x6b, (byte)0x69, (byte)0xf3, (byte)0xbd, (byte)0x33, (byte)0xab, (byte)0xfa,
<add> (byte)0xd1, (byte)0x9b, (byte)0x68, (byte)0x4e, (byte)0x16, (byte)0x95, (byte)0x91, (byte)0xee,
<add> (byte)0x4c, (byte)0x63, (byte)0x8e, (byte)0x5b, (byte)0xcc, (byte)0x3c, (byte)0x19, (byte)0xa1,
<add> (byte)0x81, (byte)0x49, (byte)0x7b, (byte)0xd9, (byte)0x6f, (byte)0x37, (byte)0x60, (byte)0xca,
<add> (byte)0xe7, (byte)0x2b, (byte)0x48, (byte)0xfd, (byte)0x96, (byte)0x45, (byte)0xfc, (byte)0x41,
<add> (byte)0x12, (byte)0x0d, (byte)0x79, (byte)0xe5, (byte)0x89, (byte)0x8c, (byte)0xe3, (byte)0x20,
<add> (byte)0x30, (byte)0xdc, (byte)0xb7, (byte)0x6c, (byte)0x4a, (byte)0xb5, (byte)0x3f, (byte)0x97,
<add> (byte)0xd4, (byte)0x62, (byte)0x2d, (byte)0x06, (byte)0xa4, (byte)0xa5, (byte)0x83, (byte)0x5f,
<add> (byte)0x2a, (byte)0xda, (byte)0xc9, (byte)0x00, (byte)0x7e, (byte)0xa2, (byte)0x55, (byte)0xbf,
<add> (byte)0x11, (byte)0xd5, (byte)0x9c, (byte)0xcf, (byte)0x0e, (byte)0x0a, (byte)0x3d, (byte)0x51,
<add> (byte)0x7d, (byte)0x93, (byte)0x1b, (byte)0xfe, (byte)0xc4, (byte)0x47, (byte)0x09, (byte)0x86,
<add> (byte)0x0b, (byte)0x8f, (byte)0x9d, (byte)0x6a, (byte)0x07, (byte)0xb9, (byte)0xb0, (byte)0x98,
<add> (byte)0x18, (byte)0x32, (byte)0x71, (byte)0x4b, (byte)0xef, (byte)0x3b, (byte)0x70, (byte)0xa0,
<add> (byte)0xe4, (byte)0x40, (byte)0xff, (byte)0xc3, (byte)0xa9, (byte)0xe6, (byte)0x78, (byte)0xf9,
<add> (byte)0x8b, (byte)0x46, (byte)0x80, (byte)0x1e, (byte)0x38, (byte)0xe1, (byte)0xb8, (byte)0xa8,
<add> (byte)0xe0, (byte)0x0c, (byte)0x23, (byte)0x76, (byte)0x1d, (byte)0x25, (byte)0x24, (byte)0x05,
<add> (byte)0xf1, (byte)0x6e, (byte)0x94, (byte)0x28, (byte)0x9a, (byte)0x84, (byte)0xe8, (byte)0xa3,
<add> (byte)0x4f, (byte)0x77, (byte)0xd3, (byte)0x85, (byte)0xe2, (byte)0x52, (byte)0xf2, (byte)0x82,
<add> (byte)0x50, (byte)0x7a, (byte)0x2f, (byte)0x74, (byte)0x53, (byte)0xb3, (byte)0x61, (byte)0xaf,
<add> (byte)0x39, (byte)0x35, (byte)0xde, (byte)0xcd, (byte)0x1f, (byte)0x99, (byte)0xac, (byte)0xad,
<add> (byte)0x72, (byte)0x2c, (byte)0xdd, (byte)0xd0, (byte)0x87, (byte)0xbe, (byte)0x5e, (byte)0xa6,
<add> (byte)0xec, (byte)0x04, (byte)0xc6, (byte)0x03, (byte)0x34, (byte)0xfb, (byte)0xdb, (byte)0x59,
<add> (byte)0xb6, (byte)0xc2, (byte)0x01, (byte)0xf0, (byte)0x5a, (byte)0xed, (byte)0xa7, (byte)0x66,
<add> (byte)0x21, (byte)0x7f, (byte)0x8a, (byte)0x27, (byte)0xc7, (byte)0xc0, (byte)0x29, (byte)0xd7
<add> },
<add>
<add> new byte[]
<add> {
<add> (byte)0x93, (byte)0xd9, (byte)0x9a, (byte)0xb5, (byte)0x98, (byte)0x22, (byte)0x45, (byte)0xfc,
<add> (byte)0xba, (byte)0x6a, (byte)0xdf, (byte)0x02, (byte)0x9f, (byte)0xdc, (byte)0x51, (byte)0x59,
<add> (byte)0x4a, (byte)0x17, (byte)0x2b, (byte)0xc2, (byte)0x94, (byte)0xf4, (byte)0xbb, (byte)0xa3,
<add> (byte)0x62, (byte)0xe4, (byte)0x71, (byte)0xd4, (byte)0xcd, (byte)0x70, (byte)0x16, (byte)0xe1,
<add> (byte)0x49, (byte)0x3c, (byte)0xc0, (byte)0xd8, (byte)0x5c, (byte)0x9b, (byte)0xad, (byte)0x85,
<add> (byte)0x53, (byte)0xa1, (byte)0x7a, (byte)0xc8, (byte)0x2d, (byte)0xe0, (byte)0xd1, (byte)0x72,
<add> (byte)0xa6, (byte)0x2c, (byte)0xc4, (byte)0xe3, (byte)0x76, (byte)0x78, (byte)0xb7, (byte)0xb4,
<add> (byte)0x09, (byte)0x3b, (byte)0x0e, (byte)0x41, (byte)0x4c, (byte)0xde, (byte)0xb2, (byte)0x90,
<add> (byte)0x25, (byte)0xa5, (byte)0xd7, (byte)0x03, (byte)0x11, (byte)0x00, (byte)0xc3, (byte)0x2e,
<add> (byte)0x92, (byte)0xef, (byte)0x4e, (byte)0x12, (byte)0x9d, (byte)0x7d, (byte)0xcb, (byte)0x35,
<add> (byte)0x10, (byte)0xd5, (byte)0x4f, (byte)0x9e, (byte)0x4d, (byte)0xa9, (byte)0x55, (byte)0xc6,
<add> (byte)0xd0, (byte)0x7b, (byte)0x18, (byte)0x97, (byte)0xd3, (byte)0x36, (byte)0xe6, (byte)0x48,
<add> (byte)0x56, (byte)0x81, (byte)0x8f, (byte)0x77, (byte)0xcc, (byte)0x9c, (byte)0xb9, (byte)0xe2,
<add> (byte)0xac, (byte)0xb8, (byte)0x2f, (byte)0x15, (byte)0xa4, (byte)0x7c, (byte)0xda, (byte)0x38,
<add> (byte)0x1e, (byte)0x0b, (byte)0x05, (byte)0xd6, (byte)0x14, (byte)0x6e, (byte)0x6c, (byte)0x7e,
<add> (byte)0x66, (byte)0xfd, (byte)0xb1, (byte)0xe5, (byte)0x60, (byte)0xaf, (byte)0x5e, (byte)0x33,
<add> (byte)0x87, (byte)0xc9, (byte)0xf0, (byte)0x5d, (byte)0x6d, (byte)0x3f, (byte)0x88, (byte)0x8d,
<add> (byte)0xc7, (byte)0xf7, (byte)0x1d, (byte)0xe9, (byte)0xec, (byte)0xed, (byte)0x80, (byte)0x29,
<add> (byte)0x27, (byte)0xcf, (byte)0x99, (byte)0xa8, (byte)0x50, (byte)0x0f, (byte)0x37, (byte)0x24,
<add> (byte)0x28, (byte)0x30, (byte)0x95, (byte)0xd2, (byte)0x3e, (byte)0x5b, (byte)0x40, (byte)0x83,
<add> (byte)0xb3, (byte)0x69, (byte)0x57, (byte)0x1f, (byte)0x07, (byte)0x1c, (byte)0x8a, (byte)0xbc,
<add> (byte)0x20, (byte)0xeb, (byte)0xce, (byte)0x8e, (byte)0xab, (byte)0xee, (byte)0x31, (byte)0xa2,
<add> (byte)0x73, (byte)0xf9, (byte)0xca, (byte)0x3a, (byte)0x1a, (byte)0xfb, (byte)0x0d, (byte)0xc1,
<add> (byte)0xfe, (byte)0xfa, (byte)0xf2, (byte)0x6f, (byte)0xbd, (byte)0x96, (byte)0xdd, (byte)0x43,
<add> (byte)0x52, (byte)0xb6, (byte)0x08, (byte)0xf3, (byte)0xae, (byte)0xbe, (byte)0x19, (byte)0x89,
<add> (byte)0x32, (byte)0x26, (byte)0xb0, (byte)0xea, (byte)0x4b, (byte)0x64, (byte)0x84, (byte)0x82,
<add> (byte)0x6b, (byte)0xf5, (byte)0x79, (byte)0xbf, (byte)0x01, (byte)0x5f, (byte)0x75, (byte)0x63,
<add> (byte)0x1b, (byte)0x23, (byte)0x3d, (byte)0x68, (byte)0x2a, (byte)0x65, (byte)0xe8, (byte)0x91,
<add> (byte)0xf6, (byte)0xff, (byte)0x13, (byte)0x58, (byte)0xf1, (byte)0x47, (byte)0x0a, (byte)0x7f,
<add> (byte)0xc5, (byte)0xa7, (byte)0xe7, (byte)0x61, (byte)0x5a, (byte)0x06, (byte)0x46, (byte)0x44,
<add> (byte)0x42, (byte)0x04, (byte)0xa0, (byte)0xdb, (byte)0x39, (byte)0x86, (byte)0x54, (byte)0xaa,
<add> (byte)0x8c, (byte)0x34, (byte)0x21, (byte)0x8b, (byte)0xf8, (byte)0x0c, (byte)0x74, (byte)0x67
<add> },
<add>
<add> new byte[]
<add> {
<add> (byte)0x68, (byte)0x8d, (byte)0xca, (byte)0x4d, (byte)0x73, (byte)0x4b, (byte)0x4e, (byte)0x2a,
<add> (byte)0xd4, (byte)0x52, (byte)0x26, (byte)0xb3, (byte)0x54, (byte)0x1e, (byte)0x19, (byte)0x1f,
<add> (byte)0x22, (byte)0x03, (byte)0x46, (byte)0x3d, (byte)0x2d, (byte)0x4a, (byte)0x53, (byte)0x83,
<add> (byte)0x13, (byte)0x8a, (byte)0xb7, (byte)0xd5, (byte)0x25, (byte)0x79, (byte)0xf5, (byte)0xbd,
<add> (byte)0x58, (byte)0x2f, (byte)0x0d, (byte)0x02, (byte)0xed, (byte)0x51, (byte)0x9e, (byte)0x11,
<add> (byte)0xf2, (byte)0x3e, (byte)0x55, (byte)0x5e, (byte)0xd1, (byte)0x16, (byte)0x3c, (byte)0x66,
<add> (byte)0x70, (byte)0x5d, (byte)0xf3, (byte)0x45, (byte)0x40, (byte)0xcc, (byte)0xe8, (byte)0x94,
<add> (byte)0x56, (byte)0x08, (byte)0xce, (byte)0x1a, (byte)0x3a, (byte)0xd2, (byte)0xe1, (byte)0xdf,
<add> (byte)0xb5, (byte)0x38, (byte)0x6e, (byte)0x0e, (byte)0xe5, (byte)0xf4, (byte)0xf9, (byte)0x86,
<add> (byte)0xe9, (byte)0x4f, (byte)0xd6, (byte)0x85, (byte)0x23, (byte)0xcf, (byte)0x32, (byte)0x99,
<add> (byte)0x31, (byte)0x14, (byte)0xae, (byte)0xee, (byte)0xc8, (byte)0x48, (byte)0xd3, (byte)0x30,
<add> (byte)0xa1, (byte)0x92, (byte)0x41, (byte)0xb1, (byte)0x18, (byte)0xc4, (byte)0x2c, (byte)0x71,
<add> (byte)0x72, (byte)0x44, (byte)0x15, (byte)0xfd, (byte)0x37, (byte)0xbe, (byte)0x5f, (byte)0xaa,
<add> (byte)0x9b, (byte)0x88, (byte)0xd8, (byte)0xab, (byte)0x89, (byte)0x9c, (byte)0xfa, (byte)0x60,
<add> (byte)0xea, (byte)0xbc, (byte)0x62, (byte)0x0c, (byte)0x24, (byte)0xa6, (byte)0xa8, (byte)0xec,
<add> (byte)0x67, (byte)0x20, (byte)0xdb, (byte)0x7c, (byte)0x28, (byte)0xdd, (byte)0xac, (byte)0x5b,
<add> (byte)0x34, (byte)0x7e, (byte)0x10, (byte)0xf1, (byte)0x7b, (byte)0x8f, (byte)0x63, (byte)0xa0,
<add> (byte)0x05, (byte)0x9a, (byte)0x43, (byte)0x77, (byte)0x21, (byte)0xbf, (byte)0x27, (byte)0x09,
<add> (byte)0xc3, (byte)0x9f, (byte)0xb6, (byte)0xd7, (byte)0x29, (byte)0xc2, (byte)0xeb, (byte)0xc0,
<add> (byte)0xa4, (byte)0x8b, (byte)0x8c, (byte)0x1d, (byte)0xfb, (byte)0xff, (byte)0xc1, (byte)0xb2,
<add> (byte)0x97, (byte)0x2e, (byte)0xf8, (byte)0x65, (byte)0xf6, (byte)0x75, (byte)0x07, (byte)0x04,
<add> (byte)0x49, (byte)0x33, (byte)0xe4, (byte)0xd9, (byte)0xb9, (byte)0xd0, (byte)0x42, (byte)0xc7,
<add> (byte)0x6c, (byte)0x90, (byte)0x00, (byte)0x8e, (byte)0x6f, (byte)0x50, (byte)0x01, (byte)0xc5,
<add> (byte)0xda, (byte)0x47, (byte)0x3f, (byte)0xcd, (byte)0x69, (byte)0xa2, (byte)0xe2, (byte)0x7a,
<add> (byte)0xa7, (byte)0xc6, (byte)0x93, (byte)0x0f, (byte)0x0a, (byte)0x06, (byte)0xe6, (byte)0x2b,
<add> (byte)0x96, (byte)0xa3, (byte)0x1c, (byte)0xaf, (byte)0x6a, (byte)0x12, (byte)0x84, (byte)0x39,
<add> (byte)0xe7, (byte)0xb0, (byte)0x82, (byte)0xf7, (byte)0xfe, (byte)0x9d, (byte)0x87, (byte)0x5c,
<add> (byte)0x81, (byte)0x35, (byte)0xde, (byte)0xb4, (byte)0xa5, (byte)0xfc, (byte)0x80, (byte)0xef,
<add> (byte)0xcb, (byte)0xbb, (byte)0x6b, (byte)0x76, (byte)0xba, (byte)0x5a, (byte)0x7d, (byte)0x78,
<add> (byte)0x0b, (byte)0x95, (byte)0xe3, (byte)0xad, (byte)0x74, (byte)0x98, (byte)0x3b, (byte)0x36,
<add> (byte)0x64, (byte)0x6d, (byte)0xdc, (byte)0xf0, (byte)0x59, (byte)0xa9, (byte)0x4c, (byte)0x17,
<add> (byte)0x7f, (byte)0x91, (byte)0xb8, (byte)0xc9, (byte)0x57, (byte)0x1b, (byte)0xe0, (byte)0x61
<add> }
<add>
<add> };
<ide>
<ide>
<ide> private byte[][] sboxesForDecryption =
<del> {
<del> new byte[]
<del> {
<del> (byte)0xa4, (byte)0xa2, (byte)0xa9, (byte)0xc5, (byte)0x4e, (byte)0xc9, (byte)0x03, (byte)0xd9,
<del> (byte)0x7e, (byte)0x0f, (byte)0xd2, (byte)0xad, (byte)0xe7, (byte)0xd3, (byte)0x27, (byte)0x5b,
<del> (byte)0xe3, (byte)0xa1, (byte)0xe8, (byte)0xe6, (byte)0x7c, (byte)0x2a, (byte)0x55, (byte)0x0c,
<del> (byte)0x86, (byte)0x39, (byte)0xd7, (byte)0x8d, (byte)0xb8, (byte)0x12, (byte)0x6f, (byte)0x28,
<del> (byte)0xcd, (byte)0x8a, (byte)0x70, (byte)0x56, (byte)0x72, (byte)0xf9, (byte)0xbf, (byte)0x4f,
<del> (byte)0x73, (byte)0xe9, (byte)0xf7, (byte)0x57, (byte)0x16, (byte)0xac, (byte)0x50, (byte)0xc0,
<del> (byte)0x9d, (byte)0xb7, (byte)0x47, (byte)0x71, (byte)0x60, (byte)0xc4, (byte)0x74, (byte)0x43,
<del> (byte)0x6c, (byte)0x1f, (byte)0x93, (byte)0x77, (byte)0xdc, (byte)0xce, (byte)0x20, (byte)0x8c,
<del> (byte)0x99, (byte)0x5f, (byte)0x44, (byte)0x01, (byte)0xf5, (byte)0x1e, (byte)0x87, (byte)0x5e,
<del> (byte)0x61, (byte)0x2c, (byte)0x4b, (byte)0x1d, (byte)0x81, (byte)0x15, (byte)0xf4, (byte)0x23,
<del> (byte)0xd6, (byte)0xea, (byte)0xe1, (byte)0x67, (byte)0xf1, (byte)0x7f, (byte)0xfe, (byte)0xda,
<del> (byte)0x3c, (byte)0x07, (byte)0x53, (byte)0x6a, (byte)0x84, (byte)0x9c, (byte)0xcb, (byte)0x02,
<del> (byte)0x83, (byte)0x33, (byte)0xdd, (byte)0x35, (byte)0xe2, (byte)0x59, (byte)0x5a, (byte)0x98,
<del> (byte)0xa5, (byte)0x92, (byte)0x64, (byte)0x04, (byte)0x06, (byte)0x10, (byte)0x4d, (byte)0x1c,
<del> (byte)0x97, (byte)0x08, (byte)0x31, (byte)0xee, (byte)0xab, (byte)0x05, (byte)0xaf, (byte)0x79,
<del> (byte)0xa0, (byte)0x18, (byte)0x46, (byte)0x6d, (byte)0xfc, (byte)0x89, (byte)0xd4, (byte)0xc7,
<del> (byte)0xff, (byte)0xf0, (byte)0xcf, (byte)0x42, (byte)0x91, (byte)0xf8, (byte)0x68, (byte)0x0a,
<del> (byte)0x65, (byte)0x8e, (byte)0xb6, (byte)0xfd, (byte)0xc3, (byte)0xef, (byte)0x78, (byte)0x4c,
<del> (byte)0xcc, (byte)0x9e, (byte)0x30, (byte)0x2e, (byte)0xbc, (byte)0x0b, (byte)0x54, (byte)0x1a,
<del> (byte)0xa6, (byte)0xbb, (byte)0x26, (byte)0x80, (byte)0x48, (byte)0x94, (byte)0x32, (byte)0x7d,
<del> (byte)0xa7, (byte)0x3f, (byte)0xae, (byte)0x22, (byte)0x3d, (byte)0x66, (byte)0xaa, (byte)0xf6,
<del> (byte)0x00, (byte)0x5d, (byte)0xbd, (byte)0x4a, (byte)0xe0, (byte)0x3b, (byte)0xb4, (byte)0x17,
<del> (byte)0x8b, (byte)0x9f, (byte)0x76, (byte)0xb0, (byte)0x24, (byte)0x9a, (byte)0x25, (byte)0x63,
<del> (byte)0xdb, (byte)0xeb, (byte)0x7a, (byte)0x3e, (byte)0x5c, (byte)0xb3, (byte)0xb1, (byte)0x29,
<del> (byte)0xf2, (byte)0xca, (byte)0x58, (byte)0x6e, (byte)0xd8, (byte)0xa8, (byte)0x2f, (byte)0x75,
<del> (byte)0xdf, (byte)0x14, (byte)0xfb, (byte)0x13, (byte)0x49, (byte)0x88, (byte)0xb2, (byte)0xec,
<del> (byte)0xe4, (byte)0x34, (byte)0x2d, (byte)0x96, (byte)0xc6, (byte)0x3a, (byte)0xed, (byte)0x95,
<del> (byte)0x0e, (byte)0xe5, (byte)0x85, (byte)0x6b, (byte)0x40, (byte)0x21, (byte)0x9b, (byte)0x09,
<del> (byte)0x19, (byte)0x2b, (byte)0x52, (byte)0xde, (byte)0x45, (byte)0xa3, (byte)0xfa, (byte)0x51,
<del> (byte)0xc2, (byte)0xb5, (byte)0xd1, (byte)0x90, (byte)0xb9, (byte)0xf3, (byte)0x37, (byte)0xc1,
<del> (byte)0x0d, (byte)0xba, (byte)0x41, (byte)0x11, (byte)0x38, (byte)0x7b, (byte)0xbe, (byte)0xd0,
<del> (byte)0xd5, (byte)0x69, (byte)0x36, (byte)0xc8, (byte)0x62, (byte)0x1b, (byte)0x82, (byte)0x8f
<del> },
<del>
<del> new byte[]
<del> {
<del> (byte)0x83, (byte)0xf2, (byte)0x2a, (byte)0xeb, (byte)0xe9, (byte)0xbf, (byte)0x7b, (byte)0x9c,
<del> (byte)0x34, (byte)0x96, (byte)0x8d, (byte)0x98, (byte)0xb9, (byte)0x69, (byte)0x8c, (byte)0x29,
<del> (byte)0x3d, (byte)0x88, (byte)0x68, (byte)0x06, (byte)0x39, (byte)0x11, (byte)0x4c, (byte)0x0e,
<del> (byte)0xa0, (byte)0x56, (byte)0x40, (byte)0x92, (byte)0x15, (byte)0xbc, (byte)0xb3, (byte)0xdc,
<del> (byte)0x6f, (byte)0xf8, (byte)0x26, (byte)0xba, (byte)0xbe, (byte)0xbd, (byte)0x31, (byte)0xfb,
<del> (byte)0xc3, (byte)0xfe, (byte)0x80, (byte)0x61, (byte)0xe1, (byte)0x7a, (byte)0x32, (byte)0xd2,
<del> (byte)0x70, (byte)0x20, (byte)0xa1, (byte)0x45, (byte)0xec, (byte)0xd9, (byte)0x1a, (byte)0x5d,
<del> (byte)0xb4, (byte)0xd8, (byte)0x09, (byte)0xa5, (byte)0x55, (byte)0x8e, (byte)0x37, (byte)0x76,
<del> (byte)0xa9, (byte)0x67, (byte)0x10, (byte)0x17, (byte)0x36, (byte)0x65, (byte)0xb1, (byte)0x95,
<del> (byte)0x62, (byte)0x59, (byte)0x74, (byte)0xa3, (byte)0x50, (byte)0x2f, (byte)0x4b, (byte)0xc8,
<del> (byte)0xd0, (byte)0x8f, (byte)0xcd, (byte)0xd4, (byte)0x3c, (byte)0x86, (byte)0x12, (byte)0x1d,
<del> (byte)0x23, (byte)0xef, (byte)0xf4, (byte)0x53, (byte)0x19, (byte)0x35, (byte)0xe6, (byte)0x7f,
<del> (byte)0x5e, (byte)0xd6, (byte)0x79, (byte)0x51, (byte)0x22, (byte)0x14, (byte)0xf7, (byte)0x1e,
<del> (byte)0x4a, (byte)0x42, (byte)0x9b, (byte)0x41, (byte)0x73, (byte)0x2d, (byte)0xc1, (byte)0x5c,
<del> (byte)0xa6, (byte)0xa2, (byte)0xe0, (byte)0x2e, (byte)0xd3, (byte)0x28, (byte)0xbb, (byte)0xc9,
<del> (byte)0xae, (byte)0x6a, (byte)0xd1, (byte)0x5a, (byte)0x30, (byte)0x90, (byte)0x84, (byte)0xf9,
<del> (byte)0xb2, (byte)0x58, (byte)0xcf, (byte)0x7e, (byte)0xc5, (byte)0xcb, (byte)0x97, (byte)0xe4,
<del> (byte)0x16, (byte)0x6c, (byte)0xfa, (byte)0xb0, (byte)0x6d, (byte)0x1f, (byte)0x52, (byte)0x99,
<del> (byte)0x0d, (byte)0x4e, (byte)0x03, (byte)0x91, (byte)0xc2, (byte)0x4d, (byte)0x64, (byte)0x77,
<del> (byte)0x9f, (byte)0xdd, (byte)0xc4, (byte)0x49, (byte)0x8a, (byte)0x9a, (byte)0x24, (byte)0x38,
<del> (byte)0xa7, (byte)0x57, (byte)0x85, (byte)0xc7, (byte)0x7c, (byte)0x7d, (byte)0xe7, (byte)0xf6,
<del> (byte)0xb7, (byte)0xac, (byte)0x27, (byte)0x46, (byte)0xde, (byte)0xdf, (byte)0x3b, (byte)0xd7,
<del> (byte)0x9e, (byte)0x2b, (byte)0x0b, (byte)0xd5, (byte)0x13, (byte)0x75, (byte)0xf0, (byte)0x72,
<del> (byte)0xb6, (byte)0x9d, (byte)0x1b, (byte)0x01, (byte)0x3f, (byte)0x44, (byte)0xe5, (byte)0x87,
<del> (byte)0xfd, (byte)0x07, (byte)0xf1, (byte)0xab, (byte)0x94, (byte)0x18, (byte)0xea, (byte)0xfc,
<del> (byte)0x3a, (byte)0x82, (byte)0x5f, (byte)0x05, (byte)0x54, (byte)0xdb, (byte)0x00, (byte)0x8b,
<del> (byte)0xe3, (byte)0x48, (byte)0x0c, (byte)0xca, (byte)0x78, (byte)0x89, (byte)0x0a, (byte)0xff,
<del> (byte)0x3e, (byte)0x5b, (byte)0x81, (byte)0xee, (byte)0x71, (byte)0xe2, (byte)0xda, (byte)0x2c,
<del> (byte)0xb8, (byte)0xb5, (byte)0xcc, (byte)0x6e, (byte)0xa8, (byte)0x6b, (byte)0xad, (byte)0x60,
<del> (byte)0xc6, (byte)0x08, (byte)0x04, (byte)0x02, (byte)0xe8, (byte)0xf5, (byte)0x4f, (byte)0xa4,
<del> (byte)0xf3, (byte)0xc0, (byte)0xce, (byte)0x43, (byte)0x25, (byte)0x1c, (byte)0x21, (byte)0x33,
<del> (byte)0x0f, (byte)0xaf, (byte)0x47, (byte)0xed, (byte)0x66, (byte)0x63, (byte)0x93, (byte)0xaa
<del> },
<del>
<del> new byte[]
<del> {
<del> (byte)0x45, (byte)0xd4, (byte)0x0b, (byte)0x43, (byte)0xf1, (byte)0x72, (byte)0xed, (byte)0xa4,
<del> (byte)0xc2, (byte)0x38, (byte)0xe6, (byte)0x71, (byte)0xfd, (byte)0xb6, (byte)0x3a, (byte)0x95,
<del> (byte)0x50, (byte)0x44, (byte)0x4b, (byte)0xe2, (byte)0x74, (byte)0x6b, (byte)0x1e, (byte)0x11,
<del> (byte)0x5a, (byte)0xc6, (byte)0xb4, (byte)0xd8, (byte)0xa5, (byte)0x8a, (byte)0x70, (byte)0xa3,
<del> (byte)0xa8, (byte)0xfa, (byte)0x05, (byte)0xd9, (byte)0x97, (byte)0x40, (byte)0xc9, (byte)0x90,
<del> (byte)0x98, (byte)0x8f, (byte)0xdc, (byte)0x12, (byte)0x31, (byte)0x2c, (byte)0x47, (byte)0x6a,
<del> (byte)0x99, (byte)0xae, (byte)0xc8, (byte)0x7f, (byte)0xf9, (byte)0x4f, (byte)0x5d, (byte)0x96,
<del> (byte)0x6f, (byte)0xf4, (byte)0xb3, (byte)0x39, (byte)0x21, (byte)0xda, (byte)0x9c, (byte)0x85,
<del> (byte)0x9e, (byte)0x3b, (byte)0xf0, (byte)0xbf, (byte)0xef, (byte)0x06, (byte)0xee, (byte)0xe5,
<del> (byte)0x5f, (byte)0x20, (byte)0x10, (byte)0xcc, (byte)0x3c, (byte)0x54, (byte)0x4a, (byte)0x52,
<del> (byte)0x94, (byte)0x0e, (byte)0xc0, (byte)0x28, (byte)0xf6, (byte)0x56, (byte)0x60, (byte)0xa2,
<del> (byte)0xe3, (byte)0x0f, (byte)0xec, (byte)0x9d, (byte)0x24, (byte)0x83, (byte)0x7e, (byte)0xd5,
<del> (byte)0x7c, (byte)0xeb, (byte)0x18, (byte)0xd7, (byte)0xcd, (byte)0xdd, (byte)0x78, (byte)0xff,
<del> (byte)0xdb, (byte)0xa1, (byte)0x09, (byte)0xd0, (byte)0x76, (byte)0x84, (byte)0x75, (byte)0xbb,
<del> (byte)0x1d, (byte)0x1a, (byte)0x2f, (byte)0xb0, (byte)0xfe, (byte)0xd6, (byte)0x34, (byte)0x63,
<del> (byte)0x35, (byte)0xd2, (byte)0x2a, (byte)0x59, (byte)0x6d, (byte)0x4d, (byte)0x77, (byte)0xe7,
<del> (byte)0x8e, (byte)0x61, (byte)0xcf, (byte)0x9f, (byte)0xce, (byte)0x27, (byte)0xf5, (byte)0x80,
<del> (byte)0x86, (byte)0xc7, (byte)0xa6, (byte)0xfb, (byte)0xf8, (byte)0x87, (byte)0xab, (byte)0x62,
<del> (byte)0x3f, (byte)0xdf, (byte)0x48, (byte)0x00, (byte)0x14, (byte)0x9a, (byte)0xbd, (byte)0x5b,
<del> (byte)0x04, (byte)0x92, (byte)0x02, (byte)0x25, (byte)0x65, (byte)0x4c, (byte)0x53, (byte)0x0c,
<del> (byte)0xf2, (byte)0x29, (byte)0xaf, (byte)0x17, (byte)0x6c, (byte)0x41, (byte)0x30, (byte)0xe9,
<del> (byte)0x93, (byte)0x55, (byte)0xf7, (byte)0xac, (byte)0x68, (byte)0x26, (byte)0xc4, (byte)0x7d,
<del> (byte)0xca, (byte)0x7a, (byte)0x3e, (byte)0xa0, (byte)0x37, (byte)0x03, (byte)0xc1, (byte)0x36,
<del> (byte)0x69, (byte)0x66, (byte)0x08, (byte)0x16, (byte)0xa7, (byte)0xbc, (byte)0xc5, (byte)0xd3,
<del> (byte)0x22, (byte)0xb7, (byte)0x13, (byte)0x46, (byte)0x32, (byte)0xe8, (byte)0x57, (byte)0x88,
<del> (byte)0x2b, (byte)0x81, (byte)0xb2, (byte)0x4e, (byte)0x64, (byte)0x1c, (byte)0xaa, (byte)0x91,
<del> (byte)0x58, (byte)0x2e, (byte)0x9b, (byte)0x5c, (byte)0x1b, (byte)0x51, (byte)0x73, (byte)0x42,
<del> (byte)0x23, (byte)0x01, (byte)0x6e, (byte)0xf3, (byte)0x0d, (byte)0xbe, (byte)0x3d, (byte)0x0a,
<del> (byte)0x2d, (byte)0x1f, (byte)0x67, (byte)0x33, (byte)0x19, (byte)0x7b, (byte)0x5e, (byte)0xea,
<del> (byte)0xde, (byte)0x8b, (byte)0xcb, (byte)0xa9, (byte)0x8c, (byte)0x8d, (byte)0xad, (byte)0x49,
<del> (byte)0x82, (byte)0xe4, (byte)0xba, (byte)0xc3, (byte)0x15, (byte)0xd1, (byte)0xe0, (byte)0x89,
<del> (byte)0xfc, (byte)0xb1, (byte)0xb9, (byte)0xb5, (byte)0x07, (byte)0x79, (byte)0xb8, (byte)0xe1
<del> },
<del>
<del> new byte[]
<del> {
<del> (byte)0xb2, (byte)0xb6, (byte)0x23, (byte)0x11, (byte)0xa7, (byte)0x88, (byte)0xc5, (byte)0xa6,
<del> (byte)0x39, (byte)0x8f, (byte)0xc4, (byte)0xe8, (byte)0x73, (byte)0x22, (byte)0x43, (byte)0xc3,
<del> (byte)0x82, (byte)0x27, (byte)0xcd, (byte)0x18, (byte)0x51, (byte)0x62, (byte)0x2d, (byte)0xf7,
<del> (byte)0x5c, (byte)0x0e, (byte)0x3b, (byte)0xfd, (byte)0xca, (byte)0x9b, (byte)0x0d, (byte)0x0f,
<del> (byte)0x79, (byte)0x8c, (byte)0x10, (byte)0x4c, (byte)0x74, (byte)0x1c, (byte)0x0a, (byte)0x8e,
<del> (byte)0x7c, (byte)0x94, (byte)0x07, (byte)0xc7, (byte)0x5e, (byte)0x14, (byte)0xa1, (byte)0x21,
<del> (byte)0x57, (byte)0x50, (byte)0x4e, (byte)0xa9, (byte)0x80, (byte)0xd9, (byte)0xef, (byte)0x64,
<del> (byte)0x41, (byte)0xcf, (byte)0x3c, (byte)0xee, (byte)0x2e, (byte)0x13, (byte)0x29, (byte)0xba,
<del> (byte)0x34, (byte)0x5a, (byte)0xae, (byte)0x8a, (byte)0x61, (byte)0x33, (byte)0x12, (byte)0xb9,
<del> (byte)0x55, (byte)0xa8, (byte)0x15, (byte)0x05, (byte)0xf6, (byte)0x03, (byte)0x06, (byte)0x49,
<del> (byte)0xb5, (byte)0x25, (byte)0x09, (byte)0x16, (byte)0x0c, (byte)0x2a, (byte)0x38, (byte)0xfc,
<del> (byte)0x20, (byte)0xf4, (byte)0xe5, (byte)0x7f, (byte)0xd7, (byte)0x31, (byte)0x2b, (byte)0x66,
<del> (byte)0x6f, (byte)0xff, (byte)0x72, (byte)0x86, (byte)0xf0, (byte)0xa3, (byte)0x2f, (byte)0x78,
<del> (byte)0x00, (byte)0xbc, (byte)0xcc, (byte)0xe2, (byte)0xb0, (byte)0xf1, (byte)0x42, (byte)0xb4,
<del> (byte)0x30, (byte)0x5f, (byte)0x60, (byte)0x04, (byte)0xec, (byte)0xa5, (byte)0xe3, (byte)0x8b,
<del> (byte)0xe7, (byte)0x1d, (byte)0xbf, (byte)0x84, (byte)0x7b, (byte)0xe6, (byte)0x81, (byte)0xf8,
<del> (byte)0xde, (byte)0xd8, (byte)0xd2, (byte)0x17, (byte)0xce, (byte)0x4b, (byte)0x47, (byte)0xd6,
<del> (byte)0x69, (byte)0x6c, (byte)0x19, (byte)0x99, (byte)0x9a, (byte)0x01, (byte)0xb3, (byte)0x85,
<del> (byte)0xb1, (byte)0xf9, (byte)0x59, (byte)0xc2, (byte)0x37, (byte)0xe9, (byte)0xc8, (byte)0xa0,
<del> (byte)0xed, (byte)0x4f, (byte)0x89, (byte)0x68, (byte)0x6d, (byte)0xd5, (byte)0x26, (byte)0x91,
<del> (byte)0x87, (byte)0x58, (byte)0xbd, (byte)0xc9, (byte)0x98, (byte)0xdc, (byte)0x75, (byte)0xc0,
<del> (byte)0x76, (byte)0xf5, (byte)0x67, (byte)0x6b, (byte)0x7e, (byte)0xeb, (byte)0x52, (byte)0xcb,
<del> (byte)0xd1, (byte)0x5b, (byte)0x9f, (byte)0x0b, (byte)0xdb, (byte)0x40, (byte)0x92, (byte)0x1a,
<del> (byte)0xfa, (byte)0xac, (byte)0xe4, (byte)0xe1, (byte)0x71, (byte)0x1f, (byte)0x65, (byte)0x8d,
<del> (byte)0x97, (byte)0x9e, (byte)0x95, (byte)0x90, (byte)0x5d, (byte)0xb7, (byte)0xc1, (byte)0xaf,
<del> (byte)0x54, (byte)0xfb, (byte)0x02, (byte)0xe0, (byte)0x35, (byte)0xbb, (byte)0x3a, (byte)0x4d,
<del> (byte)0xad, (byte)0x2c, (byte)0x3d, (byte)0x56, (byte)0x08, (byte)0x1b, (byte)0x4a, (byte)0x93,
<del> (byte)0x6a, (byte)0xab, (byte)0xb8, (byte)0x7a, (byte)0xf2, (byte)0x7d, (byte)0xda, (byte)0x3f,
<del> (byte)0xfe, (byte)0x3e, (byte)0xbe, (byte)0xea, (byte)0xaa, (byte)0x44, (byte)0xc6, (byte)0xd0,
<del> (byte)0x36, (byte)0x48, (byte)0x70, (byte)0x96, (byte)0x77, (byte)0x24, (byte)0x53, (byte)0xdf,
<del> (byte)0xf3, (byte)0x83, (byte)0x28, (byte)0x32, (byte)0x45, (byte)0x1e, (byte)0xa4, (byte)0xd3,
<del> (byte)0xa2, (byte)0x46, (byte)0x6e, (byte)0x9c, (byte)0xdd, (byte)0x63, (byte)0xd4, (byte)0x9d
<del> }
<del> };
<add> {
<add> new byte[]
<add> {
<add> (byte)0xa4, (byte)0xa2, (byte)0xa9, (byte)0xc5, (byte)0x4e, (byte)0xc9, (byte)0x03, (byte)0xd9,
<add> (byte)0x7e, (byte)0x0f, (byte)0xd2, (byte)0xad, (byte)0xe7, (byte)0xd3, (byte)0x27, (byte)0x5b,
<add> (byte)0xe3, (byte)0xa1, (byte)0xe8, (byte)0xe6, (byte)0x7c, (byte)0x2a, (byte)0x55, (byte)0x0c,
<add> (byte)0x86, (byte)0x39, (byte)0xd7, (byte)0x8d, (byte)0xb8, (byte)0x12, (byte)0x6f, (byte)0x28,
<add> (byte)0xcd, (byte)0x8a, (byte)0x70, (byte)0x56, (byte)0x72, (byte)0xf9, (byte)0xbf, (byte)0x4f,
<add> (byte)0x73, (byte)0xe9, (byte)0xf7, (byte)0x57, (byte)0x16, (byte)0xac, (byte)0x50, (byte)0xc0,
<add> (byte)0x9d, (byte)0xb7, (byte)0x47, (byte)0x71, (byte)0x60, (byte)0xc4, (byte)0x74, (byte)0x43,
<add> (byte)0x6c, (byte)0x1f, (byte)0x93, (byte)0x77, (byte)0xdc, (byte)0xce, (byte)0x20, (byte)0x8c,
<add> (byte)0x99, (byte)0x5f, (byte)0x44, (byte)0x01, (byte)0xf5, (byte)0x1e, (byte)0x87, (byte)0x5e,
<add> (byte)0x61, (byte)0x2c, (byte)0x4b, (byte)0x1d, (byte)0x81, (byte)0x15, (byte)0xf4, (byte)0x23,
<add> (byte)0xd6, (byte)0xea, (byte)0xe1, (byte)0x67, (byte)0xf1, (byte)0x7f, (byte)0xfe, (byte)0xda,
<add> (byte)0x3c, (byte)0x07, (byte)0x53, (byte)0x6a, (byte)0x84, (byte)0x9c, (byte)0xcb, (byte)0x02,
<add> (byte)0x83, (byte)0x33, (byte)0xdd, (byte)0x35, (byte)0xe2, (byte)0x59, (byte)0x5a, (byte)0x98,
<add> (byte)0xa5, (byte)0x92, (byte)0x64, (byte)0x04, (byte)0x06, (byte)0x10, (byte)0x4d, (byte)0x1c,
<add> (byte)0x97, (byte)0x08, (byte)0x31, (byte)0xee, (byte)0xab, (byte)0x05, (byte)0xaf, (byte)0x79,
<add> (byte)0xa0, (byte)0x18, (byte)0x46, (byte)0x6d, (byte)0xfc, (byte)0x89, (byte)0xd4, (byte)0xc7,
<add> (byte)0xff, (byte)0xf0, (byte)0xcf, (byte)0x42, (byte)0x91, (byte)0xf8, (byte)0x68, (byte)0x0a,
<add> (byte)0x65, (byte)0x8e, (byte)0xb6, (byte)0xfd, (byte)0xc3, (byte)0xef, (byte)0x78, (byte)0x4c,
<add> (byte)0xcc, (byte)0x9e, (byte)0x30, (byte)0x2e, (byte)0xbc, (byte)0x0b, (byte)0x54, (byte)0x1a,
<add> (byte)0xa6, (byte)0xbb, (byte)0x26, (byte)0x80, (byte)0x48, (byte)0x94, (byte)0x32, (byte)0x7d,
<add> (byte)0xa7, (byte)0x3f, (byte)0xae, (byte)0x22, (byte)0x3d, (byte)0x66, (byte)0xaa, (byte)0xf6,
<add> (byte)0x00, (byte)0x5d, (byte)0xbd, (byte)0x4a, (byte)0xe0, (byte)0x3b, (byte)0xb4, (byte)0x17,
<add> (byte)0x8b, (byte)0x9f, (byte)0x76, (byte)0xb0, (byte)0x24, (byte)0x9a, (byte)0x25, (byte)0x63,
<add> (byte)0xdb, (byte)0xeb, (byte)0x7a, (byte)0x3e, (byte)0x5c, (byte)0xb3, (byte)0xb1, (byte)0x29,
<add> (byte)0xf2, (byte)0xca, (byte)0x58, (byte)0x6e, (byte)0xd8, (byte)0xa8, (byte)0x2f, (byte)0x75,
<add> (byte)0xdf, (byte)0x14, (byte)0xfb, (byte)0x13, (byte)0x49, (byte)0x88, (byte)0xb2, (byte)0xec,
<add> (byte)0xe4, (byte)0x34, (byte)0x2d, (byte)0x96, (byte)0xc6, (byte)0x3a, (byte)0xed, (byte)0x95,
<add> (byte)0x0e, (byte)0xe5, (byte)0x85, (byte)0x6b, (byte)0x40, (byte)0x21, (byte)0x9b, (byte)0x09,
<add> (byte)0x19, (byte)0x2b, (byte)0x52, (byte)0xde, (byte)0x45, (byte)0xa3, (byte)0xfa, (byte)0x51,
<add> (byte)0xc2, (byte)0xb5, (byte)0xd1, (byte)0x90, (byte)0xb9, (byte)0xf3, (byte)0x37, (byte)0xc1,
<add> (byte)0x0d, (byte)0xba, (byte)0x41, (byte)0x11, (byte)0x38, (byte)0x7b, (byte)0xbe, (byte)0xd0,
<add> (byte)0xd5, (byte)0x69, (byte)0x36, (byte)0xc8, (byte)0x62, (byte)0x1b, (byte)0x82, (byte)0x8f
<add> },
<add>
<add> new byte[]
<add> {
<add> (byte)0x83, (byte)0xf2, (byte)0x2a, (byte)0xeb, (byte)0xe9, (byte)0xbf, (byte)0x7b, (byte)0x9c,
<add> (byte)0x34, (byte)0x96, (byte)0x8d, (byte)0x98, (byte)0xb9, (byte)0x69, (byte)0x8c, (byte)0x29,
<add> (byte)0x3d, (byte)0x88, (byte)0x68, (byte)0x06, (byte)0x39, (byte)0x11, (byte)0x4c, (byte)0x0e,
<add> (byte)0xa0, (byte)0x56, (byte)0x40, (byte)0x92, (byte)0x15, (byte)0xbc, (byte)0xb3, (byte)0xdc,
<add> (byte)0x6f, (byte)0xf8, (byte)0x26, (byte)0xba, (byte)0xbe, (byte)0xbd, (byte)0x31, (byte)0xfb,
<add> (byte)0xc3, (byte)0xfe, (byte)0x80, (byte)0x61, (byte)0xe1, (byte)0x7a, (byte)0x32, (byte)0xd2,
<add> (byte)0x70, (byte)0x20, (byte)0xa1, (byte)0x45, (byte)0xec, (byte)0xd9, (byte)0x1a, (byte)0x5d,
<add> (byte)0xb4, (byte)0xd8, (byte)0x09, (byte)0xa5, (byte)0x55, (byte)0x8e, (byte)0x37, (byte)0x76,
<add> (byte)0xa9, (byte)0x67, (byte)0x10, (byte)0x17, (byte)0x36, (byte)0x65, (byte)0xb1, (byte)0x95,
<add> (byte)0x62, (byte)0x59, (byte)0x74, (byte)0xa3, (byte)0x50, (byte)0x2f, (byte)0x4b, (byte)0xc8,
<add> (byte)0xd0, (byte)0x8f, (byte)0xcd, (byte)0xd4, (byte)0x3c, (byte)0x86, (byte)0x12, (byte)0x1d,
<add> (byte)0x23, (byte)0xef, (byte)0xf4, (byte)0x53, (byte)0x19, (byte)0x35, (byte)0xe6, (byte)0x7f,
<add> (byte)0x5e, (byte)0xd6, (byte)0x79, (byte)0x51, (byte)0x22, (byte)0x14, (byte)0xf7, (byte)0x1e,
<add> (byte)0x4a, (byte)0x42, (byte)0x9b, (byte)0x41, (byte)0x73, (byte)0x2d, (byte)0xc1, (byte)0x5c,
<add> (byte)0xa6, (byte)0xa2, (byte)0xe0, (byte)0x2e, (byte)0xd3, (byte)0x28, (byte)0xbb, (byte)0xc9,
<add> (byte)0xae, (byte)0x6a, (byte)0xd1, (byte)0x5a, (byte)0x30, (byte)0x90, (byte)0x84, (byte)0xf9,
<add> (byte)0xb2, (byte)0x58, (byte)0xcf, (byte)0x7e, (byte)0xc5, (byte)0xcb, (byte)0x97, (byte)0xe4,
<add> (byte)0x16, (byte)0x6c, (byte)0xfa, (byte)0xb0, (byte)0x6d, (byte)0x1f, (byte)0x52, (byte)0x99,
<add> (byte)0x0d, (byte)0x4e, (byte)0x03, (byte)0x91, (byte)0xc2, (byte)0x4d, (byte)0x64, (byte)0x77,
<add> (byte)0x9f, (byte)0xdd, (byte)0xc4, (byte)0x49, (byte)0x8a, (byte)0x9a, (byte)0x24, (byte)0x38,
<add> (byte)0xa7, (byte)0x57, (byte)0x85, (byte)0xc7, (byte)0x7c, (byte)0x7d, (byte)0xe7, (byte)0xf6,
<add> (byte)0xb7, (byte)0xac, (byte)0x27, (byte)0x46, (byte)0xde, (byte)0xdf, (byte)0x3b, (byte)0xd7,
<add> (byte)0x9e, (byte)0x2b, (byte)0x0b, (byte)0xd5, (byte)0x13, (byte)0x75, (byte)0xf0, (byte)0x72,
<add> (byte)0xb6, (byte)0x9d, (byte)0x1b, (byte)0x01, (byte)0x3f, (byte)0x44, (byte)0xe5, (byte)0x87,
<add> (byte)0xfd, (byte)0x07, (byte)0xf1, (byte)0xab, (byte)0x94, (byte)0x18, (byte)0xea, (byte)0xfc,
<add> (byte)0x3a, (byte)0x82, (byte)0x5f, (byte)0x05, (byte)0x54, (byte)0xdb, (byte)0x00, (byte)0x8b,
<add> (byte)0xe3, (byte)0x48, (byte)0x0c, (byte)0xca, (byte)0x78, (byte)0x89, (byte)0x0a, (byte)0xff,
<add> (byte)0x3e, (byte)0x5b, (byte)0x81, (byte)0xee, (byte)0x71, (byte)0xe2, (byte)0xda, (byte)0x2c,
<add> (byte)0xb8, (byte)0xb5, (byte)0xcc, (byte)0x6e, (byte)0xa8, (byte)0x6b, (byte)0xad, (byte)0x60,
<add> (byte)0xc6, (byte)0x08, (byte)0x04, (byte)0x02, (byte)0xe8, (byte)0xf5, (byte)0x4f, (byte)0xa4,
<add> (byte)0xf3, (byte)0xc0, (byte)0xce, (byte)0x43, (byte)0x25, (byte)0x1c, (byte)0x21, (byte)0x33,
<add> (byte)0x0f, (byte)0xaf, (byte)0x47, (byte)0xed, (byte)0x66, (byte)0x63, (byte)0x93, (byte)0xaa
<add> },
<add>
<add> new byte[]
<add> {
<add> (byte)0x45, (byte)0xd4, (byte)0x0b, (byte)0x43, (byte)0xf1, (byte)0x72, (byte)0xed, (byte)0xa4,
<add> (byte)0xc2, (byte)0x38, (byte)0xe6, (byte)0x71, (byte)0xfd, (byte)0xb6, (byte)0x3a, (byte)0x95,
<add> (byte)0x50, (byte)0x44, (byte)0x4b, (byte)0xe2, (byte)0x74, (byte)0x6b, (byte)0x1e, (byte)0x11,
<add> (byte)0x5a, (byte)0xc6, (byte)0xb4, (byte)0xd8, (byte)0xa5, (byte)0x8a, (byte)0x70, (byte)0xa3,
<add> (byte)0xa8, (byte)0xfa, (byte)0x05, (byte)0xd9, (byte)0x97, (byte)0x40, (byte)0xc9, (byte)0x90,
<add> (byte)0x98, (byte)0x8f, (byte)0xdc, (byte)0x12, (byte)0x31, (byte)0x2c, (byte)0x47, (byte)0x6a,
<add> (byte)0x99, (byte)0xae, (byte)0xc8, (byte)0x7f, (byte)0xf9, (byte)0x4f, (byte)0x5d, (byte)0x96,
<add> (byte)0x6f, (byte)0xf4, (byte)0xb3, (byte)0x39, (byte)0x21, (byte)0xda, (byte)0x9c, (byte)0x85,
<add> (byte)0x9e, (byte)0x3b, (byte)0xf0, (byte)0xbf, (byte)0xef, (byte)0x06, (byte)0xee, (byte)0xe5,
<add> (byte)0x5f, (byte)0x20, (byte)0x10, (byte)0xcc, (byte)0x3c, (byte)0x54, (byte)0x4a, (byte)0x52,
<add> (byte)0x94, (byte)0x0e, (byte)0xc0, (byte)0x28, (byte)0xf6, (byte)0x56, (byte)0x60, (byte)0xa2,
<add> (byte)0xe3, (byte)0x0f, (byte)0xec, (byte)0x9d, (byte)0x24, (byte)0x83, (byte)0x7e, (byte)0xd5,
<add> (byte)0x7c, (byte)0xeb, (byte)0x18, (byte)0xd7, (byte)0xcd, (byte)0xdd, (byte)0x78, (byte)0xff,
<add> (byte)0xdb, (byte)0xa1, (byte)0x09, (byte)0xd0, (byte)0x76, (byte)0x84, (byte)0x75, (byte)0xbb,
<add> (byte)0x1d, (byte)0x1a, (byte)0x2f, (byte)0xb0, (byte)0xfe, (byte)0xd6, (byte)0x34, (byte)0x63,
<add> (byte)0x35, (byte)0xd2, (byte)0x2a, (byte)0x59, (byte)0x6d, (byte)0x4d, (byte)0x77, (byte)0xe7,
<add> (byte)0x8e, (byte)0x61, (byte)0xcf, (byte)0x9f, (byte)0xce, (byte)0x27, (byte)0xf5, (byte)0x80,
<add> (byte)0x86, (byte)0xc7, (byte)0xa6, (byte)0xfb, (byte)0xf8, (byte)0x87, (byte)0xab, (byte)0x62,
<add> (byte)0x3f, (byte)0xdf, (byte)0x48, (byte)0x00, (byte)0x14, (byte)0x9a, (byte)0xbd, (byte)0x5b,
<add> (byte)0x04, (byte)0x92, (byte)0x02, (byte)0x25, (byte)0x65, (byte)0x4c, (byte)0x53, (byte)0x0c,
<add> (byte)0xf2, (byte)0x29, (byte)0xaf, (byte)0x17, (byte)0x6c, (byte)0x41, (byte)0x30, (byte)0xe9,
<add> (byte)0x93, (byte)0x55, (byte)0xf7, (byte)0xac, (byte)0x68, (byte)0x26, (byte)0xc4, (byte)0x7d,
<add> (byte)0xca, (byte)0x7a, (byte)0x3e, (byte)0xa0, (byte)0x37, (byte)0x03, (byte)0xc1, (byte)0x36,
<add> (byte)0x69, (byte)0x66, (byte)0x08, (byte)0x16, (byte)0xa7, (byte)0xbc, (byte)0xc5, (byte)0xd3,
<add> (byte)0x22, (byte)0xb7, (byte)0x13, (byte)0x46, (byte)0x32, (byte)0xe8, (byte)0x57, (byte)0x88,
<add> (byte)0x2b, (byte)0x81, (byte)0xb2, (byte)0x4e, (byte)0x64, (byte)0x1c, (byte)0xaa, (byte)0x91,
<add> (byte)0x58, (byte)0x2e, (byte)0x9b, (byte)0x5c, (byte)0x1b, (byte)0x51, (byte)0x73, (byte)0x42,
<add> (byte)0x23, (byte)0x01, (byte)0x6e, (byte)0xf3, (byte)0x0d, (byte)0xbe, (byte)0x3d, (byte)0x0a,
<add> (byte)0x2d, (byte)0x1f, (byte)0x67, (byte)0x33, (byte)0x19, (byte)0x7b, (byte)0x5e, (byte)0xea,
<add> (byte)0xde, (byte)0x8b, (byte)0xcb, (byte)0xa9, (byte)0x8c, (byte)0x8d, (byte)0xad, (byte)0x49,
<add> (byte)0x82, (byte)0xe4, (byte)0xba, (byte)0xc3, (byte)0x15, (byte)0xd1, (byte)0xe0, (byte)0x89,
<add> (byte)0xfc, (byte)0xb1, (byte)0xb9, (byte)0xb5, (byte)0x07, (byte)0x79, (byte)0xb8, (byte)0xe1
<add> },
<add>
<add> new byte[]
<add> {
<add> (byte)0xb2, (byte)0xb6, (byte)0x23, (byte)0x11, (byte)0xa7, (byte)0x88, (byte)0xc5, (byte)0xa6,
<add> (byte)0x39, (byte)0x8f, (byte)0xc4, (byte)0xe8, (byte)0x73, (byte)0x22, (byte)0x43, (byte)0xc3,
<add> (byte)0x82, (byte)0x27, (byte)0xcd, (byte)0x18, (byte)0x51, (byte)0x62, (byte)0x2d, (byte)0xf7,
<add> (byte)0x5c, (byte)0x0e, (byte)0x3b, (byte)0xfd, (byte)0xca, (byte)0x9b, (byte)0x0d, (byte)0x0f,
<add> (byte)0x79, (byte)0x8c, (byte)0x10, (byte)0x4c, (byte)0x74, (byte)0x1c, (byte)0x0a, (byte)0x8e,
<add> (byte)0x7c, (byte)0x94, (byte)0x07, (byte)0xc7, (byte)0x5e, (byte)0x14, (byte)0xa1, (byte)0x21,
<add> (byte)0x57, (byte)0x50, (byte)0x4e, (byte)0xa9, (byte)0x80, (byte)0xd9, (byte)0xef, (byte)0x64,
<add> (byte)0x41, (byte)0xcf, (byte)0x3c, (byte)0xee, (byte)0x2e, (byte)0x13, (byte)0x29, (byte)0xba,
<add> (byte)0x34, (byte)0x5a, (byte)0xae, (byte)0x8a, (byte)0x61, (byte)0x33, (byte)0x12, (byte)0xb9,
<add> (byte)0x55, (byte)0xa8, (byte)0x15, (byte)0x05, (byte)0xf6, (byte)0x03, (byte)0x06, (byte)0x49,
<add> (byte)0xb5, (byte)0x25, (byte)0x09, (byte)0x16, (byte)0x0c, (byte)0x2a, (byte)0x38, (byte)0xfc,
<add> (byte)0x20, (byte)0xf4, (byte)0xe5, (byte)0x7f, (byte)0xd7, (byte)0x31, (byte)0x2b, (byte)0x66,
<add> (byte)0x6f, (byte)0xff, (byte)0x72, (byte)0x86, (byte)0xf0, (byte)0xa3, (byte)0x2f, (byte)0x78,
<add> (byte)0x00, (byte)0xbc, (byte)0xcc, (byte)0xe2, (byte)0xb0, (byte)0xf1, (byte)0x42, (byte)0xb4,
<add> (byte)0x30, (byte)0x5f, (byte)0x60, (byte)0x04, (byte)0xec, (byte)0xa5, (byte)0xe3, (byte)0x8b,
<add> (byte)0xe7, (byte)0x1d, (byte)0xbf, (byte)0x84, (byte)0x7b, (byte)0xe6, (byte)0x81, (byte)0xf8,
<add> (byte)0xde, (byte)0xd8, (byte)0xd2, (byte)0x17, (byte)0xce, (byte)0x4b, (byte)0x47, (byte)0xd6,
<add> (byte)0x69, (byte)0x6c, (byte)0x19, (byte)0x99, (byte)0x9a, (byte)0x01, (byte)0xb3, (byte)0x85,
<add> (byte)0xb1, (byte)0xf9, (byte)0x59, (byte)0xc2, (byte)0x37, (byte)0xe9, (byte)0xc8, (byte)0xa0,
<add> (byte)0xed, (byte)0x4f, (byte)0x89, (byte)0x68, (byte)0x6d, (byte)0xd5, (byte)0x26, (byte)0x91,
<add> (byte)0x87, (byte)0x58, (byte)0xbd, (byte)0xc9, (byte)0x98, (byte)0xdc, (byte)0x75, (byte)0xc0,
<add> (byte)0x76, (byte)0xf5, (byte)0x67, (byte)0x6b, (byte)0x7e, (byte)0xeb, (byte)0x52, (byte)0xcb,
<add> (byte)0xd1, (byte)0x5b, (byte)0x9f, (byte)0x0b, (byte)0xdb, (byte)0x40, (byte)0x92, (byte)0x1a,
<add> (byte)0xfa, (byte)0xac, (byte)0xe4, (byte)0xe1, (byte)0x71, (byte)0x1f, (byte)0x65, (byte)0x8d,
<add> (byte)0x97, (byte)0x9e, (byte)0x95, (byte)0x90, (byte)0x5d, (byte)0xb7, (byte)0xc1, (byte)0xaf,
<add> (byte)0x54, (byte)0xfb, (byte)0x02, (byte)0xe0, (byte)0x35, (byte)0xbb, (byte)0x3a, (byte)0x4d,
<add> (byte)0xad, (byte)0x2c, (byte)0x3d, (byte)0x56, (byte)0x08, (byte)0x1b, (byte)0x4a, (byte)0x93,
<add> (byte)0x6a, (byte)0xab, (byte)0xb8, (byte)0x7a, (byte)0xf2, (byte)0x7d, (byte)0xda, (byte)0x3f,
<add> (byte)0xfe, (byte)0x3e, (byte)0xbe, (byte)0xea, (byte)0xaa, (byte)0x44, (byte)0xc6, (byte)0xd0,
<add> (byte)0x36, (byte)0x48, (byte)0x70, (byte)0x96, (byte)0x77, (byte)0x24, (byte)0x53, (byte)0xdf,
<add> (byte)0xf3, (byte)0x83, (byte)0x28, (byte)0x32, (byte)0x45, (byte)0x1e, (byte)0xa4, (byte)0xd3,
<add> (byte)0xa2, (byte)0x46, (byte)0x6e, (byte)0x9c, (byte)0xdd, (byte)0x63, (byte)0xd4, (byte)0x9d
<add> }
<add> };
<ide>
<ide> //endregion
<ide> |
|
Java | mit | 533d02646742d02f083d76af818e2774443aa900 | 0 | c4d3r/p2groep04,c4d3r/p2groep04 | package controller;
import model.*;
import entity.*;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import jfxtras.scene.control.agenda.Agenda;
import jfxtras.scene.control.agenda.Agenda.AppointmentImpl;
/**
* import util.JPAUtil;
*/
public class PlanningController {
private PresentationRepository presentationRepository = new PresentationRepository();
private TimeFrameRepository timeFrameRepository = new TimeFrameRepository();
private CampusRepository campusRepository = new CampusRepository();
private LocationRepository locationRepository = new LocationRepository();
private PlanningRepository planningRepository = new PlanningRepository();
public PresentationProperty retrievePresentations() {
List<AppointmentImpl> presentaties = new ArrayList();
Calendar cal = GregorianCalendar.getInstance();
Calendar cal2 = GregorianCalendar.getInstance();
List<Presentation> presentations = presentationRepository.findAllByPlanning(planningRepository.findOneById(1));
for (Presentation p : presentations) {
cal = ((Calendar) cal.clone());
cal.setTime(p.getDate());
cal.set(Calendar.HOUR_OF_DAY, p.getTimeFrame().getStartTime().getHours());
cal.set(Calendar.MINUTE, p.getTimeFrame().getStartTime().getMinutes());
cal2 = ((Calendar) cal2.clone());
cal2.setTime(p.getDate());
cal2.set(Calendar.HOUR_OF_DAY, p.getTimeFrame().getEndTime().getHours());
cal2.set(Calendar.MINUTE, p.getTimeFrame().getEndTime().getMinutes());
presentaties.add(new PresentationProperty()
.withPresentation(p)
.withStartTime(cal)
.withEndTime(cal2)
.withSummary(p.getPresentator().getFirstName() + " " + p.getPresentator().getLastName())
.withDescription(p.getPresentator().getApprovedSuggestion().toString())
.withAppointmentGroup(new Agenda.AppointmentGroupImpl().withStyleClass("group15"))
);
}
return presentaties.toArray(new AppointmentImpl[presentaties.size()]);
}
public Planning retrievePlanning(int id) {
return planningRepository.findOneById(id);
}
/**
*
* @param presentation
*/
public void removePresentation(Presentation presentation) {
//TODO: delete methode naar repository brengen
/* EntityManager manager = JPAUtil.getEntityManagerFactory().createEntityManager();
manager.getTransaction().begin();
Query q = (Query) manager.createQuery("DELETE FROM Presentation WHERE id =" + presentation.getId() + ")");
manager.getTransaction().commit();
manager.close();*/
EntityManager em = planningRepository.getEm();
em.getTransaction().begin();
em.remove(presentation);
em.flush();
em.getTransaction().commit();
}
/**
*
* @param planning
* @param visible
*/
public void changePlanningVisibility(Planning planning, boolean visible) {
planning.setVisible(visible);
}
/**
*
* @param planning
* @param startTime
* @param endTime
*/
public void registerVisibilityPeriod(Planning planning, java.sql.Timestamp startTime, java.sql.Timestamp endTime) {
planningRepository.changePlanningVisbilityPeriod(planning, startTime, endTime);
}
public List<TimeFrame> retrieveTimeFrames() {
return timeFrameRepository.findAll();
}
public List<Campus> retrieveCampuses() {
return campusRepository.findAll();
}
/**
*
* @param campus
*/
public List<Location> retrieveLocations(Campus campus) {
return locationRepository.findByCampus(campus);
}
/**
*
* @param timeFrame
* @param campus
* @param lokaal
* @param promotor
* @param coPromotor
* @param presentator
* @param onderwerp
* @param tijdstip
*/
public void createPresentation(Calendar calendar, TimeFrame timeFrame, Location lokaal, Promotor promotor, Promotor coPromotor, Student presentator) {
//check if presentation is already on this timeframe and date
if (presentationRepository.findExistsByCalendarTimeFrame(calendar, timeFrame)) {
throw new IllegalArgumentException("Presentation already exists");
}
EntityManager em = planningRepository.getEm();
em.getTransaction().begin();
Presentation presentation = new Presentation();
presentation.setDate(new Date(calendar.getTime().getTime()));
presentation.setTimeFrame(timeFrame);
presentation.setPresentator(presentator);
presentation.setLocation(lokaal);
presentation.setPlanning(retrievePlanning(1));
presentation.setPromotor(promotor);
presentation.setCoPromotor(coPromotor);
em.persist(presentation);
em.flush();
em.getTransaction().commit();
}
/**
*
* @param planning
*/
public void notifyStakeHolders(Planning planning) {
// TODO - implement PlanningController.notifyStakeHolders
throw new UnsupportedOperationException();
}
public Agenda.Appointment[] retrievePresentationsByPromotor(Promotor promotor) {
List<AppointmentImpl> presentaties = new ArrayList();
Calendar cal = GregorianCalendar.getInstance();
Calendar cal2 = GregorianCalendar.getInstance();
List<Presentation> presentations = presentationRepository.findAllByPlanningPromotor(planningRepository.findOneById(1), promotor);
for (Presentation p : presentations) {
cal = ((Calendar) cal.clone());
cal.setTime(p.getDate());
cal.set(Calendar.HOUR_OF_DAY, p.getTimeFrame().getStartTime().getHours());
cal.set(Calendar.MINUTE, p.getTimeFrame().getStartTime().getMinutes());
cal2 = ((Calendar) cal2.clone());
cal2.setTime(p.getDate());
cal2.set(Calendar.HOUR_OF_DAY, p.getTimeFrame().getEndTime().getHours());
cal2.set(Calendar.MINUTE, p.getTimeFrame().getEndTime().getMinutes());
presentaties.add(new AppointmentImpl()
.withStartTime(cal)
.withEndTime(cal2)
.withSummary(p.getPresentator().getFirstName() + " " + p.getPresentator().getLastName())
.withDescription(p.getPresentator().getApprovedSuggestion().toString())
.withAppointmentGroup(new Agenda.AppointmentGroupImpl().withStyleClass("group15"))
);
}
return presentaties.toArray(new AppointmentImpl[presentaties.size()]);
}
public Agenda.Appointment[] retrievePresentationsByResearchdomain(ResearchDomain researchDomain) {
List<AppointmentImpl> presentaties = new ArrayList();
Calendar cal = GregorianCalendar.getInstance();
Calendar cal2 = GregorianCalendar.getInstance();
List<Presentation> presentations = presentationRepository.findAllByPlanningResearchdomain(planningRepository.findOneById(1), researchDomain);
for (Presentation p : presentations) {
cal = ((Calendar) cal.clone());
cal.setTime(p.getDate());
cal.set(Calendar.HOUR_OF_DAY, p.getTimeFrame().getStartTime().getHours());
cal.set(Calendar.MINUTE, p.getTimeFrame().getStartTime().getMinutes());
cal2 = ((Calendar) cal2.clone());
cal2.setTime(p.getDate());
cal2.set(Calendar.HOUR_OF_DAY, p.getTimeFrame().getEndTime().getHours());
cal2.set(Calendar.MINUTE, p.getTimeFrame().getEndTime().getMinutes());
presentaties.add(new AppointmentImpl()
.withStartTime(cal)
.withEndTime(cal2)
.withSummary(p.getPresentator().getFirstName() + " " + p.getPresentator().getLastName())
.withDescription(p.getPresentator().getApprovedSuggestion().toString())
.withAppointmentGroup(new Agenda.AppointmentGroupImpl().withStyleClass("group15"))
);
}
return presentaties.toArray(new AppointmentImpl[presentaties.size()]);
}
public void attachJury(Promotor promotor, Promotor coPromotor, Presentation presentation) {
EntityManager em = planningRepository.getEm();
em.getTransaction().begin();
presentation.setPromotor(promotor);
presentation.setCoPromotor(coPromotor);
em.persist(presentation);
em.flush();
em.getTransaction().commit();
changePlanningVisibility(presentation.getPlanning(), true);
}
}
| src/controller/PlanningController.java | package controller;
import model.*;
import entity.*;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import jfxtras.scene.control.agenda.Agenda;
import jfxtras.scene.control.agenda.Agenda.AppointmentImpl;
/**
* import util.JPAUtil;
*/
public class PlanningController {
private PresentationRepository presentationRepository = new PresentationRepository();
private TimeFrameRepository timeFrameRepository = new TimeFrameRepository();
private CampusRepository campusRepository = new CampusRepository();
private LocationRepository locationRepository = new LocationRepository();
private PlanningRepository planningRepository = new PlanningRepository();
public AppointmentImpl[] retrievePresentations() {
List<AppointmentImpl> presentaties = new ArrayList();
Calendar cal = GregorianCalendar.getInstance();
Calendar cal2 = GregorianCalendar.getInstance();
List<Presentation> presentations = presentationRepository.findAllByPlanning(planningRepository.findOneById(1));
for (Presentation p : presentations) {
cal = ((Calendar) cal.clone());
cal.setTime(p.getDate());
cal.set(Calendar.HOUR_OF_DAY, p.getTimeFrame().getStartTime().getHours());
cal.set(Calendar.MINUTE, p.getTimeFrame().getStartTime().getMinutes());
cal2 = ((Calendar) cal2.clone());
cal2.setTime(p.getDate());
cal2.set(Calendar.HOUR_OF_DAY, p.getTimeFrame().getEndTime().getHours());
cal2.set(Calendar.MINUTE, p.getTimeFrame().getEndTime().getMinutes());
presentaties.add(new AppointmentImpl()
.withStartTime(cal)
.withEndTime(cal2)
.withSummary(p.getPresentator().getFirstName() + " " + p.getPresentator().getLastName())
.withDescription(p.getPresentator().getApprovedSuggestion().toString())
.withAppointmentGroup(new Agenda.AppointmentGroupImpl().withStyleClass("group15"))
);
}
return presentaties.toArray(new AppointmentImpl[presentaties.size()]);
}
public Planning retrievePlanning(int id) {
return planningRepository.findOneById(id);
}
/**
*
* @param presentation
*/
public void removePresentation(Presentation presentation) {
//TODO: delete methode naar repository brengen
/* EntityManager manager = JPAUtil.getEntityManagerFactory().createEntityManager();
manager.getTransaction().begin();
Query q = (Query) manager.createQuery("DELETE FROM Presentation WHERE id =" + presentation.getId() + ")");
manager.getTransaction().commit();
manager.close();*/
EntityManager em = planningRepository.getEm();
em.getTransaction().begin();
em.remove(presentation);
em.flush();
em.getTransaction().commit();
}
/**
*
* @param planning
* @param visible
*/
public void changePlanningVisibility(Planning planning, boolean visible) {
planning.setVisible(visible);
}
/**
*
* @param planning
* @param startTime
* @param endTime
*/
public void registerVisibilityPeriod(Planning planning, java.sql.Timestamp startTime, java.sql.Timestamp endTime) {
planningRepository.changePlanningVisbilityPeriod(planning, startTime, endTime);
}
public List<TimeFrame> retrieveTimeFrames() {
return timeFrameRepository.findAll();
}
public List<Campus> retrieveCampuses() {
return campusRepository.findAll();
}
/**
*
* @param campus
*/
public List<Location> retrieveLocations(Campus campus) {
return locationRepository.findByCampus(campus);
}
/**
*
* @param timeFrame
* @param campus
* @param lokaal
* @param promotor
* @param coPromotor
* @param presentator
* @param onderwerp
* @param tijdstip
*/
public void createPresentation(Calendar calendar, TimeFrame timeFrame, Location lokaal, Promotor promotor, Promotor coPromotor, Student presentator) {
//check if presentation is already on this timeframe and date
if (presentationRepository.findExistsByCalendarTimeFrame(calendar, timeFrame)) {
throw new IllegalArgumentException("Presentation already exists");
}
EntityManager em = planningRepository.getEm();
em.getTransaction().begin();
Presentation presentation = new Presentation();
presentation.setDate(new Date(calendar.getTime().getTime()));
presentation.setTimeFrame(timeFrame);
presentation.setPresentator(presentator);
presentation.setLocation(lokaal);
presentation.setPlanning(retrievePlanning(1));
presentation.setPromotor(promotor);
presentation.setCoPromotor(coPromotor);
em.persist(presentation);
em.flush();
em.getTransaction().commit();
}
/**
*
* @param planning
*/
public void notifyStakeHolders(Planning planning) {
// TODO - implement PlanningController.notifyStakeHolders
throw new UnsupportedOperationException();
}
public Agenda.Appointment[] retrievePresentationsByPromotor(Promotor promotor) {
List<AppointmentImpl> presentaties = new ArrayList();
Calendar cal = GregorianCalendar.getInstance();
Calendar cal2 = GregorianCalendar.getInstance();
List<Presentation> presentations = presentationRepository.findAllByPlanningPromotor(planningRepository.findOneById(1), promotor);
for (Presentation p : presentations) {
cal = ((Calendar) cal.clone());
cal.setTime(p.getDate());
cal.set(Calendar.HOUR_OF_DAY, p.getTimeFrame().getStartTime().getHours());
cal.set(Calendar.MINUTE, p.getTimeFrame().getStartTime().getMinutes());
cal2 = ((Calendar) cal2.clone());
cal2.setTime(p.getDate());
cal2.set(Calendar.HOUR_OF_DAY, p.getTimeFrame().getEndTime().getHours());
cal2.set(Calendar.MINUTE, p.getTimeFrame().getEndTime().getMinutes());
presentaties.add(new AppointmentImpl()
.withStartTime(cal)
.withEndTime(cal2)
.withSummary(p.getPresentator().getFirstName() + " " + p.getPresentator().getLastName())
.withDescription(p.getPresentator().getApprovedSuggestion().toString())
.withAppointmentGroup(new Agenda.AppointmentGroupImpl().withStyleClass("group15"))
);
}
return presentaties.toArray(new AppointmentImpl[presentaties.size()]);
}
public Agenda.Appointment[] retrievePresentationsByResearchdomain(ResearchDomain researchDomain) {
List<AppointmentImpl> presentaties = new ArrayList();
Calendar cal = GregorianCalendar.getInstance();
Calendar cal2 = GregorianCalendar.getInstance();
List<Presentation> presentations = presentationRepository.findAllByPlanningResearchdomain(planningRepository.findOneById(1), researchDomain);
for (Presentation p : presentations) {
cal = ((Calendar) cal.clone());
cal.setTime(p.getDate());
cal.set(Calendar.HOUR_OF_DAY, p.getTimeFrame().getStartTime().getHours());
cal.set(Calendar.MINUTE, p.getTimeFrame().getStartTime().getMinutes());
cal2 = ((Calendar) cal2.clone());
cal2.setTime(p.getDate());
cal2.set(Calendar.HOUR_OF_DAY, p.getTimeFrame().getEndTime().getHours());
cal2.set(Calendar.MINUTE, p.getTimeFrame().getEndTime().getMinutes());
presentaties.add(new AppointmentImpl()
.withStartTime(cal)
.withEndTime(cal2)
.withSummary(p.getPresentator().getFirstName() + " " + p.getPresentator().getLastName())
.withDescription(p.getPresentator().getApprovedSuggestion().toString())
.withAppointmentGroup(new Agenda.AppointmentGroupImpl().withStyleClass("group15"))
);
}
return presentaties.toArray(new AppointmentImpl[presentaties.size()]);
}
public void attachJury(Promotor promotor, Promotor coPromotor, Presentation presentation) {
EntityManager em = planningRepository.getEm();
em.getTransaction().begin();
presentation.setPromotor(promotor);
presentation.setCoPromotor(coPromotor);
em.persist(presentation);
em.flush();
em.getTransaction().commit();
changePlanningVisibility(presentation.getPlanning(), true);
}
}
| code bijvoegen | src/controller/PlanningController.java | code bijvoegen | <ide><path>rc/controller/PlanningController.java
<ide> private LocationRepository locationRepository = new LocationRepository();
<ide> private PlanningRepository planningRepository = new PlanningRepository();
<ide>
<del> public AppointmentImpl[] retrievePresentations() {
<add> public PresentationProperty retrievePresentations() {
<ide> List<AppointmentImpl> presentaties = new ArrayList();
<ide> Calendar cal = GregorianCalendar.getInstance();
<ide> Calendar cal2 = GregorianCalendar.getInstance();
<ide> cal2.set(Calendar.HOUR_OF_DAY, p.getTimeFrame().getEndTime().getHours());
<ide> cal2.set(Calendar.MINUTE, p.getTimeFrame().getEndTime().getMinutes());
<ide>
<del> presentaties.add(new AppointmentImpl()
<del> .withStartTime(cal)
<del> .withEndTime(cal2)
<del> .withSummary(p.getPresentator().getFirstName() + " " + p.getPresentator().getLastName())
<del> .withDescription(p.getPresentator().getApprovedSuggestion().toString())
<del> .withAppointmentGroup(new Agenda.AppointmentGroupImpl().withStyleClass("group15"))
<add> presentaties.add(new PresentationProperty()
<add> .withPresentation(p)
<add> .withStartTime(cal)
<add> .withEndTime(cal2)
<add> .withSummary(p.getPresentator().getFirstName() + " " + p.getPresentator().getLastName())
<add> .withDescription(p.getPresentator().getApprovedSuggestion().toString())
<add> .withAppointmentGroup(new Agenda.AppointmentGroupImpl().withStyleClass("group15"))
<ide> );
<ide> }
<ide>
<ide> throw new UnsupportedOperationException();
<ide> }
<ide>
<add>
<ide> public Agenda.Appointment[] retrievePresentationsByPromotor(Promotor promotor) {
<ide> List<AppointmentImpl> presentaties = new ArrayList();
<ide> Calendar cal = GregorianCalendar.getInstance();
<ide> public void attachJury(Promotor promotor, Promotor coPromotor, Presentation presentation) {
<ide> EntityManager em = planningRepository.getEm();
<ide> em.getTransaction().begin();
<del>
<add>
<ide> presentation.setPromotor(promotor);
<ide> presentation.setCoPromotor(coPromotor);
<del>
<add>
<ide> em.persist(presentation);
<ide> em.flush();
<del> em.getTransaction().commit();
<del>
<add> em.getTransaction().commit();
<add>
<ide> changePlanningVisibility(presentation.getPlanning(), true);
<del>
<add>
<ide> }
<ide>
<ide> } |
|
Java | apache-2.0 | 72d0370a1c97b3acc7a2a4905603794f4bd26fa7 | 0 | material-components/material-components-android | /*
* Copyright (C) 2015 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 android.support.design.widget;
import static android.support.annotation.RestrictTo.Scope.LIBRARY_GROUP;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Rect;
import android.os.Build;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.IntDef;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.annotation.RestrictTo;
import android.support.annotation.VisibleForTesting;
import android.support.design.R;
import android.support.design.animation.AnimationUtils;
import android.support.v4.util.ObjectsCompat;
import android.support.v4.view.AbsSavedState;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewCompat.NestedScrollType;
import android.support.v4.view.WindowInsetsCompat;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Interpolator;
import android.widget.LinearLayout;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
/**
* AppBarLayout is a vertical {@link LinearLayout} which implements many of the features of material
* designs app bar concept, namely scrolling gestures.
*
* <p>Children should provide their desired scrolling behavior through {@link
* LayoutParams#setScrollFlags(int)} and the associated layout xml attribute: {@code
* app:layout_scrollFlags}.
*
* <p>This view depends heavily on being used as a direct child within a {@link CoordinatorLayout}.
* If you use AppBarLayout within a different {@link ViewGroup}, most of it's functionality will not
* work.
*
* <p>AppBarLayout also requires a separate scrolling sibling in order to know when to scroll. The
* binding is done through the {@link ScrollingViewBehavior} behavior class, meaning that you should
* set your scrolling view's behavior to be an instance of {@link ScrollingViewBehavior}. A string
* resource containing the full class name is available.
*
* <pre>
* <android.support.design.widget.CoordinatorLayout
* xmlns:android="http://schemas.android.com/apk/res/android"
* xmlns:app="http://schemas.android.com/apk/res-auto"
* android:layout_width="match_parent"
* android:layout_height="match_parent">
*
* <android.support.v4.widget.NestedScrollView
* android:layout_width="match_parent"
* android:layout_height="match_parent"
* app:layout_behavior="@string/appbar_scrolling_view_behavior">
*
* <!-- Your scrolling content -->
*
* </android.support.v4.widget.NestedScrollView>
*
* <android.support.design.widget.AppBarLayout
* android:layout_height="wrap_content"
* android:layout_width="match_parent">
*
* <android.support.v7.widget.Toolbar
* ...
* app:layout_scrollFlags="scroll|enterAlways"/>
*
* <android.support.design.widget.TabLayout
* ...
* app:layout_scrollFlags="scroll|enterAlways"/>
*
* </android.support.design.widget.AppBarLayout>
*
* </android.support.design.widget.CoordinatorLayout>
* </pre>
*
* @see <a href="http://www.google.com/design/spec/layout/structure.html#structure-app-bar">
* http://www.google.com/design/spec/layout/structure.html#structure-app-bar</a>
*/
@CoordinatorLayout.DefaultBehavior(AppBarLayout.Behavior.class)
public class AppBarLayout extends LinearLayout {
static final int PENDING_ACTION_NONE = 0x0;
static final int PENDING_ACTION_EXPANDED = 0x1;
static final int PENDING_ACTION_COLLAPSED = 0x2;
static final int PENDING_ACTION_ANIMATE_ENABLED = 0x4;
static final int PENDING_ACTION_FORCE = 0x8;
/**
* Interface definition for a callback to be invoked when an {@link AppBarLayout}'s vertical
* offset changes.
*/
public interface OnOffsetChangedListener {
/**
* Called when the {@link AppBarLayout}'s layout offset has been changed. This allows child
* views to implement custom behavior based on the offset (for instance pinning a view at a
* certain y value).
*
* @param appBarLayout the {@link AppBarLayout} which offset has changed
* @param verticalOffset the vertical offset for the parent {@link AppBarLayout}, in px
*/
void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset);
}
private static final int INVALID_SCROLL_RANGE = -1;
private int totalScrollRange = INVALID_SCROLL_RANGE;
private int downPreScrollRange = INVALID_SCROLL_RANGE;
private int downScrollRange = INVALID_SCROLL_RANGE;
private boolean haveChildWithInterpolator;
private int pendingAction = PENDING_ACTION_NONE;
private WindowInsetsCompat lastInsets;
private List<OnOffsetChangedListener> listeners;
private boolean collapsible;
private boolean collapsed;
private int[] tmpStatesArray;
public AppBarLayout(Context context) {
this(context, null);
}
public AppBarLayout(Context context, AttributeSet attrs) {
super(context, attrs);
setOrientation(VERTICAL);
ThemeUtils.checkAppCompatTheme(context);
if (Build.VERSION.SDK_INT >= 21) {
// Use the bounds view outline provider so that we cast a shadow, even without a
// background
ViewUtilsLollipop.setBoundsViewOutlineProvider(this);
// If we're running on API 21+, we should reset any state list animator from our
// default style
ViewUtilsLollipop.setStateListAnimatorFromAttrs(
this, attrs, 0, R.style.Widget_Design_AppBarLayout);
}
final TypedArray a =
context.obtainStyledAttributes(
attrs, R.styleable.AppBarLayout, 0, R.style.Widget_Design_AppBarLayout);
ViewCompat.setBackground(this, a.getDrawable(R.styleable.AppBarLayout_android_background));
if (a.hasValue(R.styleable.AppBarLayout_expanded)) {
setExpanded(
a.getBoolean(R.styleable.AppBarLayout_expanded, false),
false, /* animate */
false /* force */);
}
if (Build.VERSION.SDK_INT >= 21 && a.hasValue(R.styleable.AppBarLayout_elevation)) {
ViewUtilsLollipop.setDefaultAppBarLayoutStateListAnimator(
this, a.getDimensionPixelSize(R.styleable.AppBarLayout_elevation, 0));
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// In O+, we have these values set in the style. Since there is no defStyleAttr for
// AppBarLayout at the AppCompat level, check for these attributes here.
if (a.hasValue(R.styleable.AppBarLayout_android_keyboardNavigationCluster)) {
this.setKeyboardNavigationCluster(
a.getBoolean(R.styleable.AppBarLayout_android_keyboardNavigationCluster, false));
}
if (a.hasValue(R.styleable.AppBarLayout_android_touchscreenBlocksFocus)) {
this.setTouchscreenBlocksFocus(
a.getBoolean(R.styleable.AppBarLayout_android_touchscreenBlocksFocus, false));
}
}
a.recycle();
ViewCompat.setOnApplyWindowInsetsListener(
this,
new android.support.v4.view.OnApplyWindowInsetsListener() {
@Override
public WindowInsetsCompat onApplyWindowInsets(View v, WindowInsetsCompat insets) {
return onWindowInsetChanged(insets);
}
});
}
/**
* Add a listener that will be called when the offset of this {@link AppBarLayout} changes.
*
* @param listener The listener that will be called when the offset changes.]
* @see #removeOnOffsetChangedListener(OnOffsetChangedListener)
*/
public void addOnOffsetChangedListener(OnOffsetChangedListener listener) {
if (listeners == null) {
listeners = new ArrayList<>();
}
if (listener != null && !listeners.contains(listener)) {
listeners.add(listener);
}
}
/**
* Remove the previously added {@link OnOffsetChangedListener}.
*
* @param listener the listener to remove.
*/
public void removeOnOffsetChangedListener(OnOffsetChangedListener listener) {
if (listeners != null && listener != null) {
listeners.remove(listener);
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
invalidateScrollRanges();
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
invalidateScrollRanges();
haveChildWithInterpolator = false;
for (int i = 0, z = getChildCount(); i < z; i++) {
final View child = getChildAt(i);
final LayoutParams childLp = (LayoutParams) child.getLayoutParams();
final Interpolator interpolator = childLp.getScrollInterpolator();
if (interpolator != null) {
haveChildWithInterpolator = true;
break;
}
}
updateCollapsible();
}
private void updateCollapsible() {
boolean haveCollapsibleChild = false;
for (int i = 0, z = getChildCount(); i < z; i++) {
if (((LayoutParams) getChildAt(i).getLayoutParams()).isCollapsible()) {
haveCollapsibleChild = true;
break;
}
}
setCollapsibleState(haveCollapsibleChild);
}
private void invalidateScrollRanges() {
// Invalidate the scroll ranges
totalScrollRange = INVALID_SCROLL_RANGE;
downPreScrollRange = INVALID_SCROLL_RANGE;
downScrollRange = INVALID_SCROLL_RANGE;
}
@Override
public void setOrientation(int orientation) {
if (orientation != VERTICAL) {
throw new IllegalArgumentException(
"AppBarLayout is always vertical and does" + " not support horizontal orientation");
}
super.setOrientation(orientation);
}
/**
* Sets whether this {@link AppBarLayout} is expanded or not, animating if it has already been
* laid out.
*
* <p>As with {@link AppBarLayout}'s scrolling, this method relies on this layout being a direct
* child of a {@link CoordinatorLayout}.
*
* @param expanded true if the layout should be fully expanded, false if it should be fully
* collapsed
* @attr ref android.support.design.R.styleable#AppBarLayout_expanded
*/
public void setExpanded(boolean expanded) {
setExpanded(expanded, ViewCompat.isLaidOut(this));
}
/**
* Sets whether this {@link AppBarLayout} is expanded or not.
*
* <p>As with {@link AppBarLayout}'s scrolling, this method relies on this layout being a direct
* child of a {@link CoordinatorLayout}.
*
* @param expanded true if the layout should be fully expanded, false if it should be fully
* collapsed
* @param animate Whether to animate to the new state
* @attr ref android.support.design.R.styleable#AppBarLayout_expanded
*/
public void setExpanded(boolean expanded, boolean animate) {
setExpanded(expanded, animate, true);
}
private void setExpanded(boolean expanded, boolean animate, boolean force) {
pendingAction =
(expanded ? PENDING_ACTION_EXPANDED : PENDING_ACTION_COLLAPSED)
| (animate ? PENDING_ACTION_ANIMATE_ENABLED : 0)
| (force ? PENDING_ACTION_FORCE : 0);
requestLayout();
}
@Override
protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
return p instanceof LayoutParams;
}
@Override
protected LayoutParams generateDefaultLayoutParams() {
return new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
}
@Override
public LayoutParams generateLayoutParams(AttributeSet attrs) {
return new LayoutParams(getContext(), attrs);
}
@Override
protected LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
if (Build.VERSION.SDK_INT >= 19 && p instanceof LinearLayout.LayoutParams) {
return new LayoutParams((LinearLayout.LayoutParams) p);
} else if (p instanceof MarginLayoutParams) {
return new LayoutParams((MarginLayoutParams) p);
}
return new LayoutParams(p);
}
boolean hasChildWithInterpolator() {
return haveChildWithInterpolator;
}
/**
* Returns the scroll range of all children.
*
* @return the scroll range in px
*/
public final int getTotalScrollRange() {
if (totalScrollRange != INVALID_SCROLL_RANGE) {
return totalScrollRange;
}
int range = 0;
for (int i = 0, z = getChildCount(); i < z; i++) {
final View child = getChildAt(i);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
final int childHeight = child.getMeasuredHeight();
final int flags = lp.scrollFlags;
if ((flags & LayoutParams.SCROLL_FLAG_SCROLL) != 0) {
// We're set to scroll so add the child's height
range += childHeight + lp.topMargin + lp.bottomMargin;
if ((flags & LayoutParams.SCROLL_FLAG_EXIT_UNTIL_COLLAPSED) != 0) {
// For a collapsing scroll, we to take the collapsed height into account.
// We also break straight away since later views can't scroll beneath
// us
range -= ViewCompat.getMinimumHeight(child);
break;
}
} else {
// As soon as a view doesn't have the scroll flag, we end the range calculation.
// This is because views below can not scroll under a fixed view.
break;
}
}
return totalScrollRange = Math.max(0, range - getTopInset());
}
boolean hasScrollableChildren() {
return getTotalScrollRange() != 0;
}
/** Return the scroll range when scrolling up from a nested pre-scroll. */
int getUpNestedPreScrollRange() {
return getTotalScrollRange();
}
/** Return the scroll range when scrolling down from a nested pre-scroll. */
int getDownNestedPreScrollRange() {
if (downPreScrollRange != INVALID_SCROLL_RANGE) {
// If we already have a valid value, return it
return downPreScrollRange;
}
int range = 0;
for (int i = getChildCount() - 1; i >= 0; i--) {
final View child = getChildAt(i);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
final int childHeight = child.getMeasuredHeight();
final int flags = lp.scrollFlags;
if ((flags & LayoutParams.FLAG_QUICK_RETURN) == LayoutParams.FLAG_QUICK_RETURN) {
// First take the margin into account
range += lp.topMargin + lp.bottomMargin;
// The view has the quick return flag combination...
if ((flags & LayoutParams.SCROLL_FLAG_ENTER_ALWAYS_COLLAPSED) != 0) {
// If they're set to enter collapsed, use the minimum height
range += ViewCompat.getMinimumHeight(child);
} else if ((flags & LayoutParams.SCROLL_FLAG_EXIT_UNTIL_COLLAPSED) != 0) {
// Only enter by the amount of the collapsed height
range += childHeight - ViewCompat.getMinimumHeight(child);
} else {
// Else use the full height (minus the top inset)
range += childHeight - getTopInset();
}
} else if (range > 0) {
// If we've hit an non-quick return scrollable view, and we've already hit a
// quick return view, return now
break;
}
}
return downPreScrollRange = Math.max(0, range);
}
/** Return the scroll range when scrolling down from a nested scroll. */
int getDownNestedScrollRange() {
if (downScrollRange != INVALID_SCROLL_RANGE) {
// If we already have a valid value, return it
return downScrollRange;
}
int range = 0;
for (int i = 0, z = getChildCount(); i < z; i++) {
final View child = getChildAt(i);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
int childHeight = child.getMeasuredHeight();
childHeight += lp.topMargin + lp.bottomMargin;
final int flags = lp.scrollFlags;
if ((flags & LayoutParams.SCROLL_FLAG_SCROLL) != 0) {
// We're set to scroll so add the child's height
range += childHeight;
if ((flags & LayoutParams.SCROLL_FLAG_EXIT_UNTIL_COLLAPSED) != 0) {
// For a collapsing exit scroll, we to take the collapsed height into account.
// We also break the range straight away since later views can't scroll
// beneath us
range -= ViewCompat.getMinimumHeight(child) + getTopInset();
break;
}
} else {
// As soon as a view doesn't have the scroll flag, we end the range calculation.
// This is because views below can not scroll under a fixed view.
break;
}
}
return downScrollRange = Math.max(0, range);
}
void dispatchOffsetUpdates(int offset) {
// Iterate backwards through the list so that most recently added listeners
// get the first chance to decide
if (listeners != null) {
for (int i = 0, z = listeners.size(); i < z; i++) {
final OnOffsetChangedListener listener = listeners.get(i);
if (listener != null) {
listener.onOffsetChanged(this, offset);
}
}
}
}
final int getMinimumHeightForVisibleOverlappingContent() {
final int topInset = getTopInset();
final int minHeight = ViewCompat.getMinimumHeight(this);
if (minHeight != 0) {
// If this layout has a min height, use it (doubled)
return (minHeight * 2) + topInset;
}
// Otherwise, we'll use twice the min height of our last child
final int childCount = getChildCount();
final int lastChildMinHeight =
childCount >= 1 ? ViewCompat.getMinimumHeight(getChildAt(childCount - 1)) : 0;
if (lastChildMinHeight != 0) {
return (lastChildMinHeight * 2) + topInset;
}
// If we reach here then we don't have a min height explicitly set. Instead we'll take a
// guess at 1/3 of our height being visible
return getHeight() / 3;
}
@Override
protected int[] onCreateDrawableState(int extraSpace) {
if (tmpStatesArray == null) {
// Note that we can't allocate this at the class level (in declaration) since
// some paths in super View constructor are going to call this method before
// that
tmpStatesArray = new int[2];
}
final int[] extraStates = tmpStatesArray;
final int[] states = super.onCreateDrawableState(extraSpace + extraStates.length);
extraStates[0] = collapsible ? R.attr.state_collapsible : -R.attr.state_collapsible;
extraStates[1] = collapsible && collapsed ? R.attr.state_collapsed : -R.attr.state_collapsed;
return mergeDrawableStates(states, extraStates);
}
/**
* Sets whether the AppBarLayout has collapsible children or not.
*
* @return true if the collapsible state changed
*/
private boolean setCollapsibleState(boolean collapsible) {
if (this.collapsible != collapsible) {
this.collapsible = collapsible;
refreshDrawableState();
return true;
}
return false;
}
/**
* Sets whether the AppBarLayout is in a collapsed state or not.
*
* @return true if the collapsed state changed
*/
boolean setCollapsedState(boolean collapsed) {
if (this.collapsed != collapsed) {
this.collapsed = collapsed;
refreshDrawableState();
return true;
}
return false;
}
/**
* @deprecated target elevation is now deprecated. AppBarLayout's elevation is now controlled via
* a {@link android.animation.StateListAnimator}. If a target elevation is set, either by this
* method or the {@code app:elevation} attribute, a new state list animator is created which
* uses the given {@code elevation} value.
* @attr ref android.support.design.R.styleable#AppBarLayout_elevation
*/
@Deprecated
public void setTargetElevation(float elevation) {
if (Build.VERSION.SDK_INT >= 21) {
ViewUtilsLollipop.setDefaultAppBarLayoutStateListAnimator(this, elevation);
}
}
/**
* @deprecated target elevation is now deprecated. AppBarLayout's elevation is now controlled via
* a {@link android.animation.StateListAnimator}. This method now always returns 0.
*/
@Deprecated
public float getTargetElevation() {
return 0;
}
int getPendingAction() {
return pendingAction;
}
void resetPendingAction() {
pendingAction = PENDING_ACTION_NONE;
}
@VisibleForTesting
final int getTopInset() {
return lastInsets != null ? lastInsets.getSystemWindowInsetTop() : 0;
}
WindowInsetsCompat onWindowInsetChanged(final WindowInsetsCompat insets) {
WindowInsetsCompat newInsets = null;
if (ViewCompat.getFitsSystemWindows(this)) {
// If we're set to fit system windows, keep the insets
newInsets = insets;
}
// If our insets have changed, keep them and invalidate the scroll ranges...
if (!ObjectsCompat.equals(lastInsets, newInsets)) {
lastInsets = newInsets;
invalidateScrollRanges();
}
return insets;
}
public static class LayoutParams extends LinearLayout.LayoutParams {
/** @hide */
@RestrictTo(LIBRARY_GROUP)
@IntDef(
flag = true,
value = {
SCROLL_FLAG_SCROLL,
SCROLL_FLAG_EXIT_UNTIL_COLLAPSED,
SCROLL_FLAG_ENTER_ALWAYS,
SCROLL_FLAG_ENTER_ALWAYS_COLLAPSED,
SCROLL_FLAG_SNAP
}
)
@Retention(RetentionPolicy.SOURCE)
public @interface ScrollFlags {}
/**
* The view will be scroll in direct relation to scroll events. This flag needs to be set for
* any of the other flags to take effect. If any sibling views before this one do not have this
* flag, then this value has no effect.
*/
public static final int SCROLL_FLAG_SCROLL = 0x1;
/**
* When exiting (scrolling off screen) the view will be scrolled until it is 'collapsed'. The
* collapsed height is defined by the view's minimum height.
*
* @see ViewCompat#getMinimumHeight(View)
* @see View#setMinimumHeight(int)
*/
public static final int SCROLL_FLAG_EXIT_UNTIL_COLLAPSED = 0x2;
/**
* When entering (scrolling on screen) the view will scroll on any downwards scroll event,
* regardless of whether the scrolling view is also scrolling. This is commonly referred to as
* the 'quick return' pattern.
*/
public static final int SCROLL_FLAG_ENTER_ALWAYS = 0x4;
/**
* An additional flag for 'enterAlways' which modifies the returning view to only initially
* scroll back to it's collapsed height. Once the scrolling view has reached the end of it's
* scroll range, the remainder of this view will be scrolled into view. The collapsed height is
* defined by the view's minimum height.
*
* @see ViewCompat#getMinimumHeight(View)
* @see View#setMinimumHeight(int)
*/
public static final int SCROLL_FLAG_ENTER_ALWAYS_COLLAPSED = 0x8;
/**
* Upon a scroll ending, if the view is only partially visible then it will be snapped and
* scrolled to it's closest edge. For example, if the view only has it's bottom 25% displayed,
* it will be scrolled off screen completely. Conversely, if it's bottom 75% is visible then it
* will be scrolled fully into view.
*/
public static final int SCROLL_FLAG_SNAP = 0x10;
/** Internal flags which allows quick checking features */
static final int FLAG_QUICK_RETURN = SCROLL_FLAG_SCROLL | SCROLL_FLAG_ENTER_ALWAYS;
static final int FLAG_SNAP = SCROLL_FLAG_SCROLL | SCROLL_FLAG_SNAP;
static final int COLLAPSIBLE_FLAGS =
SCROLL_FLAG_EXIT_UNTIL_COLLAPSED | SCROLL_FLAG_ENTER_ALWAYS_COLLAPSED;
int scrollFlags = SCROLL_FLAG_SCROLL;
Interpolator scrollInterpolator;
public LayoutParams(Context c, AttributeSet attrs) {
super(c, attrs);
TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.AppBarLayout_Layout);
scrollFlags = a.getInt(R.styleable.AppBarLayout_Layout_layout_scrollFlags, 0);
if (a.hasValue(R.styleable.AppBarLayout_Layout_layout_scrollInterpolator)) {
int resId = a.getResourceId(R.styleable.AppBarLayout_Layout_layout_scrollInterpolator, 0);
scrollInterpolator = android.view.animation.AnimationUtils.loadInterpolator(c, resId);
}
a.recycle();
}
public LayoutParams(int width, int height) {
super(width, height);
}
public LayoutParams(int width, int height, float weight) {
super(width, height, weight);
}
public LayoutParams(ViewGroup.LayoutParams p) {
super(p);
}
public LayoutParams(MarginLayoutParams source) {
super(source);
}
@RequiresApi(19)
public LayoutParams(LinearLayout.LayoutParams source) {
// The copy constructor called here only exists on API 19+.
super(source);
}
@RequiresApi(19)
public LayoutParams(LayoutParams source) {
// The copy constructor called here only exists on API 19+.
super(source);
scrollFlags = source.scrollFlags;
scrollInterpolator = source.scrollInterpolator;
}
/**
* Set the scrolling flags.
*
* @param flags bitwise int of {@link #SCROLL_FLAG_SCROLL}, {@link
* #SCROLL_FLAG_EXIT_UNTIL_COLLAPSED}, {@link #SCROLL_FLAG_ENTER_ALWAYS}, {@link
* #SCROLL_FLAG_ENTER_ALWAYS_COLLAPSED} and {@link #SCROLL_FLAG_SNAP }.
* @see #getScrollFlags()
* @attr ref android.support.design.R.styleable#AppBarLayout_Layout_layout_scrollFlags
*/
public void setScrollFlags(@ScrollFlags int flags) {
scrollFlags = flags;
}
/**
* Returns the scrolling flags.
*
* @see #setScrollFlags(int)
* @attr ref android.support.design.R.styleable#AppBarLayout_Layout_layout_scrollFlags
*/
@ScrollFlags
public int getScrollFlags() {
return scrollFlags;
}
/**
* Set the interpolator to when scrolling the view associated with this {@link LayoutParams}.
*
* @param interpolator the interpolator to use, or null to use normal 1-to-1 scrolling.
* @attr ref android.support.design.R.styleable#AppBarLayout_Layout_layout_scrollInterpolator
* @see #getScrollInterpolator()
*/
public void setScrollInterpolator(Interpolator interpolator) {
scrollInterpolator = interpolator;
}
/**
* Returns the {@link Interpolator} being used for scrolling the view associated with this
* {@link LayoutParams}. Null indicates 'normal' 1-to-1 scrolling.
*
* @attr ref android.support.design.R.styleable#AppBarLayout_Layout_layout_scrollInterpolator
* @see #setScrollInterpolator(Interpolator)
*/
public Interpolator getScrollInterpolator() {
return scrollInterpolator;
}
/** Returns true if the scroll flags are compatible for 'collapsing' */
boolean isCollapsible() {
return (scrollFlags & SCROLL_FLAG_SCROLL) == SCROLL_FLAG_SCROLL
&& (scrollFlags & COLLAPSIBLE_FLAGS) != 0;
}
}
/**
* The default {@link Behavior} for {@link AppBarLayout}. Implements the necessary nested scroll
* handling with offsetting.
*/
public static class Behavior extends HeaderBehavior<AppBarLayout> {
private static final int MAX_OFFSET_ANIMATION_DURATION = 600; // ms
private static final int INVALID_POSITION = -1;
/** Callback to allow control over any {@link AppBarLayout} dragging. */
public abstract static class DragCallback {
/**
* Allows control over whether the given {@link AppBarLayout} can be dragged or not.
*
* <p>Dragging is defined as a direct touch on the AppBarLayout with movement. This call does
* not affect any nested scrolling.
*
* @return true if we are in a position to scroll the AppBarLayout via a drag, false if not.
*/
public abstract boolean canDrag(@NonNull AppBarLayout appBarLayout);
}
private int offsetDelta;
@NestedScrollType
private int lastStartedType;
private ValueAnimator offsetAnimator;
private int offsetToChildIndexOnLayout = INVALID_POSITION;
private boolean offsetToChildIndexOnLayoutIsMinHeight;
private float offsetToChildIndexOnLayoutPerc;
private WeakReference<View> lastNestedScrollingChildRef;
private DragCallback onDragCallback;
public Behavior() {}
public Behavior(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean onStartNestedScroll(
CoordinatorLayout parent,
AppBarLayout child,
View directTargetChild,
View target,
int nestedScrollAxes,
int type) {
// Return true if we're nested scrolling vertically, and we have scrollable children
// and the scrolling view is big enough to scroll
final boolean started =
(nestedScrollAxes & ViewCompat.SCROLL_AXIS_VERTICAL) != 0
&& child.hasScrollableChildren()
&& parent.getHeight() - directTargetChild.getHeight() <= child.getHeight();
if (started && offsetAnimator != null) {
// Cancel any offset animation
offsetAnimator.cancel();
}
// A new nested scroll has started so clear out the previous ref
lastNestedScrollingChildRef = null;
// Track the last started type so we know if a fling is about to happen once scrolling ends
lastStartedType = type;
return started;
}
@Override
public void onNestedPreScroll(
CoordinatorLayout coordinatorLayout,
AppBarLayout child,
View target,
int dx,
int dy,
int[] consumed,
int type) {
if (dy != 0) {
int min;
int max;
if (dy < 0) {
// We're scrolling down
min = -child.getTotalScrollRange();
max = min + child.getDownNestedPreScrollRange();
} else {
// We're scrolling up
min = -child.getUpNestedPreScrollRange();
max = 0;
}
if (min != max) {
consumed[1] = scroll(coordinatorLayout, child, dy, min, max);
stopNestedScrollIfNeeded(dy, child, target, type);
}
}
}
@Override
public void onNestedScroll(
CoordinatorLayout coordinatorLayout,
AppBarLayout child,
View target,
int dxConsumed,
int dyConsumed,
int dxUnconsumed,
int dyUnconsumed,
int type) {
if (dyUnconsumed < 0) {
// If the scrolling view is scrolling down but not consuming, it's probably be at
// the top of it's content
scroll(coordinatorLayout, child, dyUnconsumed, -child.getDownNestedScrollRange(), 0);
stopNestedScrollIfNeeded(dyUnconsumed, child, target, type);
}
}
private void stopNestedScrollIfNeeded(int dy, AppBarLayout child, View target, int type) {
if (type == ViewCompat.TYPE_NON_TOUCH) {
final int curOffset = getTopBottomOffsetForScrollingSibling();
if ((dy < 0 && curOffset == 0)
|| (dy > 0 && curOffset == -child.getDownNestedScrollRange())) {
ViewCompat.stopNestedScroll(target, ViewCompat.TYPE_NON_TOUCH);
}
}
}
@Override
public void onStopNestedScroll(
CoordinatorLayout coordinatorLayout, AppBarLayout abl, View target, int type) {
// onStartNestedScroll for a fling will happen before onStopNestedScroll for the scroll. This
// isn't necessarily guaranteed yet, but it should be in the future. We use this to our
// advantage to check if a fling (ViewCompat.TYPE_NON_TOUCH) will start after the touch scroll
// (ViewCompat.TYPE_TOUCH) ends
if (lastStartedType == ViewCompat.TYPE_TOUCH || type == ViewCompat.TYPE_NON_TOUCH) {
// If we haven't been flung, or a fling is ending
snapToChildIfNeeded(coordinatorLayout, abl);
}
// Keep a reference to the previous nested scrolling child
lastNestedScrollingChildRef = new WeakReference<>(target);
}
/**
* Set a callback to control any {@link AppBarLayout} dragging.
*
* @param callback the callback to use, or {@code null} to use the default behavior.
*/
public void setDragCallback(@Nullable DragCallback callback) {
onDragCallback = callback;
}
private void animateOffsetTo(
final CoordinatorLayout coordinatorLayout,
final AppBarLayout child,
final int offset,
float velocity) {
final int distance = Math.abs(getTopBottomOffsetForScrollingSibling() - offset);
final int duration;
velocity = Math.abs(velocity);
if (velocity > 0) {
duration = 3 * Math.round(1000 * (distance / velocity));
} else {
final float distanceRatio = (float) distance / child.getHeight();
duration = (int) ((distanceRatio + 1) * 150);
}
animateOffsetWithDuration(coordinatorLayout, child, offset, duration);
}
private void animateOffsetWithDuration(
final CoordinatorLayout coordinatorLayout,
final AppBarLayout child,
final int offset,
final int duration) {
final int currentOffset = getTopBottomOffsetForScrollingSibling();
if (currentOffset == offset) {
if (offsetAnimator != null && offsetAnimator.isRunning()) {
offsetAnimator.cancel();
}
return;
}
if (offsetAnimator == null) {
offsetAnimator = new ValueAnimator();
offsetAnimator.setInterpolator(AnimationUtils.DECELERATE_INTERPOLATOR);
offsetAnimator.addUpdateListener(
new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animator) {
setHeaderTopBottomOffset(
coordinatorLayout, child, (int) animator.getAnimatedValue());
}
});
} else {
offsetAnimator.cancel();
}
offsetAnimator.setDuration(Math.min(duration, MAX_OFFSET_ANIMATION_DURATION));
offsetAnimator.setIntValues(currentOffset, offset);
offsetAnimator.start();
}
private int getChildIndexOnOffset(AppBarLayout abl, final int offset) {
for (int i = 0, count = abl.getChildCount(); i < count; i++) {
View child = abl.getChildAt(i);
if (child.getTop() <= -offset && child.getBottom() >= -offset) {
return i;
}
}
return -1;
}
private void snapToChildIfNeeded(CoordinatorLayout coordinatorLayout, AppBarLayout abl) {
final int offset = getTopBottomOffsetForScrollingSibling();
final int offsetChildIndex = getChildIndexOnOffset(abl, offset);
if (offsetChildIndex >= 0) {
final View offsetChild = abl.getChildAt(offsetChildIndex);
final LayoutParams lp = (LayoutParams) offsetChild.getLayoutParams();
final int flags = lp.getScrollFlags();
if ((flags & LayoutParams.FLAG_SNAP) == LayoutParams.FLAG_SNAP) {
// We're set the snap, so animate the offset to the nearest edge
int snapTop = -offsetChild.getTop();
int snapBottom = -offsetChild.getBottom();
if (offsetChildIndex == abl.getChildCount() - 1) {
// If this is the last child, we need to take the top inset into account
snapBottom += abl.getTopInset();
}
if (checkFlag(flags, LayoutParams.SCROLL_FLAG_EXIT_UNTIL_COLLAPSED)) {
// If the view is set only exit until it is collapsed, we'll abide by that
snapBottom += ViewCompat.getMinimumHeight(offsetChild);
} else if (checkFlag(
flags, LayoutParams.FLAG_QUICK_RETURN | LayoutParams.SCROLL_FLAG_ENTER_ALWAYS)) {
// If it's set to always enter collapsed, it actually has two states. We
// select the state and then snap within the state
final int seam = snapBottom + ViewCompat.getMinimumHeight(offsetChild);
if (offset < seam) {
snapTop = seam;
} else {
snapBottom = seam;
}
}
final int newOffset = offset < (snapBottom + snapTop) / 2 ? snapBottom : snapTop;
animateOffsetTo(
coordinatorLayout,
abl,
MathUtils.constrain(newOffset, -abl.getTotalScrollRange(), 0),
0);
}
}
}
private static boolean checkFlag(final int flags, final int check) {
return (flags & check) == check;
}
@Override
public boolean onMeasureChild(
CoordinatorLayout parent,
AppBarLayout child,
int parentWidthMeasureSpec,
int widthUsed,
int parentHeightMeasureSpec,
int heightUsed) {
final CoordinatorLayout.LayoutParams lp =
(CoordinatorLayout.LayoutParams) child.getLayoutParams();
if (lp.height == CoordinatorLayout.LayoutParams.WRAP_CONTENT) {
// If the view is set to wrap on it's height, CoordinatorLayout by default will
// cap the view at the CoL's height. Since the AppBarLayout can scroll, this isn't
// what we actually want, so we measure it ourselves with an unspecified spec to
// allow the child to be larger than it's parent
parent.onMeasureChild(
child,
parentWidthMeasureSpec,
widthUsed,
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
heightUsed);
return true;
}
// Let the parent handle it as normal
return super.onMeasureChild(
parent, child, parentWidthMeasureSpec, widthUsed, parentHeightMeasureSpec, heightUsed);
}
@Override
public boolean onLayoutChild(CoordinatorLayout parent, AppBarLayout abl, int layoutDirection) {
boolean handled = super.onLayoutChild(parent, abl, layoutDirection);
// The priority for actions here is (first which is true wins):
// 1. forced pending actions
// 2. offsets for restorations
// 3. non-forced pending actions
final int pendingAction = abl.getPendingAction();
if (offsetToChildIndexOnLayout >= 0 && (pendingAction & PENDING_ACTION_FORCE) == 0) {
View child = abl.getChildAt(offsetToChildIndexOnLayout);
int offset = -child.getBottom();
if (offsetToChildIndexOnLayoutIsMinHeight) {
offset += ViewCompat.getMinimumHeight(child) + abl.getTopInset();
} else {
offset += Math.round(child.getHeight() * offsetToChildIndexOnLayoutPerc);
}
setHeaderTopBottomOffset(parent, abl, offset);
} else if (pendingAction != PENDING_ACTION_NONE) {
final boolean animate = (pendingAction & PENDING_ACTION_ANIMATE_ENABLED) != 0;
if ((pendingAction & PENDING_ACTION_COLLAPSED) != 0) {
final int offset = -abl.getUpNestedPreScrollRange();
if (animate) {
animateOffsetTo(parent, abl, offset, 0);
} else {
setHeaderTopBottomOffset(parent, abl, offset);
}
} else if ((pendingAction & PENDING_ACTION_EXPANDED) != 0) {
if (animate) {
animateOffsetTo(parent, abl, 0, 0);
} else {
setHeaderTopBottomOffset(parent, abl, 0);
}
}
}
// Finally reset any pending states
abl.resetPendingAction();
offsetToChildIndexOnLayout = INVALID_POSITION;
// We may have changed size, so let's constrain the top and bottom offset correctly,
// just in case we're out of the bounds
setTopAndBottomOffset(
MathUtils.constrain(getTopAndBottomOffset(), -abl.getTotalScrollRange(), 0));
// Update the AppBarLayout's drawable state for any elevation changes. This is needed so that
// the elevation is set in the first layout, so that we don't get a visual jump pre-N (due to
// the draw dispatch skip)
updateAppBarLayoutDrawableState(
parent, abl, getTopAndBottomOffset(), 0 /* direction */, true /* forceJump */);
// Make sure we dispatch the offset update
abl.dispatchOffsetUpdates(getTopAndBottomOffset());
return handled;
}
@Override
boolean canDragView(AppBarLayout view) {
if (onDragCallback != null) {
// If there is a drag callback set, it's in control
return onDragCallback.canDrag(view);
}
// Else we'll use the default behaviour of seeing if it can scroll down
if (lastNestedScrollingChildRef != null) {
// If we have a reference to a scrolling view, check it
final View scrollingView = lastNestedScrollingChildRef.get();
return scrollingView != null
&& scrollingView.isShown()
&& !scrollingView.canScrollVertically(-1);
} else {
// Otherwise we assume that the scrolling view hasn't been scrolled and can drag.
return true;
}
}
@Override
void onFlingFinished(CoordinatorLayout parent, AppBarLayout layout) {
// At the end of a manual fling, check to see if we need to snap to the edge-child
snapToChildIfNeeded(parent, layout);
}
@Override
int getMaxDragOffset(AppBarLayout view) {
return -view.getDownNestedScrollRange();
}
@Override
int getScrollRangeForDragFling(AppBarLayout view) {
return view.getTotalScrollRange();
}
@Override
int setHeaderTopBottomOffset(
CoordinatorLayout coordinatorLayout,
AppBarLayout appBarLayout,
int newOffset,
int minOffset,
int maxOffset) {
final int curOffset = getTopBottomOffsetForScrollingSibling();
int consumed = 0;
if (minOffset != 0 && curOffset >= minOffset && curOffset <= maxOffset) {
// If we have some scrolling range, and we're currently within the min and max
// offsets, calculate a new offset
newOffset = MathUtils.constrain(newOffset, minOffset, maxOffset);
if (curOffset != newOffset) {
final int interpolatedOffset =
appBarLayout.hasChildWithInterpolator()
? interpolateOffset(appBarLayout, newOffset)
: newOffset;
final boolean offsetChanged = setTopAndBottomOffset(interpolatedOffset);
// Update how much dy we have consumed
consumed = curOffset - newOffset;
// Update the stored sibling offset
offsetDelta = newOffset - interpolatedOffset;
if (!offsetChanged && appBarLayout.hasChildWithInterpolator()) {
// If the offset hasn't changed and we're using an interpolated scroll
// then we need to keep any dependent views updated. CoL will do this for
// us when we move, but we need to do it manually when we don't (as an
// interpolated scroll may finish early).
coordinatorLayout.dispatchDependentViewsChanged(appBarLayout);
}
// Dispatch the updates to any listeners
appBarLayout.dispatchOffsetUpdates(getTopAndBottomOffset());
// Update the AppBarLayout's drawable state (for any elevation changes)
updateAppBarLayoutDrawableState(
coordinatorLayout,
appBarLayout,
newOffset,
newOffset < curOffset ? -1 : 1,
false /* forceJump */);
}
} else {
// Reset the offset delta
offsetDelta = 0;
}
return consumed;
}
@VisibleForTesting
boolean isOffsetAnimatorRunning() {
return offsetAnimator != null && offsetAnimator.isRunning();
}
private int interpolateOffset(AppBarLayout layout, final int offset) {
final int absOffset = Math.abs(offset);
for (int i = 0, z = layout.getChildCount(); i < z; i++) {
final View child = layout.getChildAt(i);
final AppBarLayout.LayoutParams childLp = (LayoutParams) child.getLayoutParams();
final Interpolator interpolator = childLp.getScrollInterpolator();
if (absOffset >= child.getTop() && absOffset <= child.getBottom()) {
if (interpolator != null) {
int childScrollableHeight = 0;
final int flags = childLp.getScrollFlags();
if ((flags & LayoutParams.SCROLL_FLAG_SCROLL) != 0) {
// We're set to scroll so add the child's height plus margin
childScrollableHeight += child.getHeight() + childLp.topMargin + childLp.bottomMargin;
if ((flags & LayoutParams.SCROLL_FLAG_EXIT_UNTIL_COLLAPSED) != 0) {
// For a collapsing scroll, we to take the collapsed height
// into account.
childScrollableHeight -= ViewCompat.getMinimumHeight(child);
}
}
if (ViewCompat.getFitsSystemWindows(child)) {
childScrollableHeight -= layout.getTopInset();
}
if (childScrollableHeight > 0) {
final int offsetForView = absOffset - child.getTop();
final int interpolatedDiff =
Math.round(
childScrollableHeight
* interpolator.getInterpolation(
offsetForView / (float) childScrollableHeight));
return Integer.signum(offset) * (child.getTop() + interpolatedDiff);
}
}
// If we get to here then the view on the offset isn't suitable for interpolated
// scrolling. So break out of the loop
break;
}
}
return offset;
}
private void updateAppBarLayoutDrawableState(
final CoordinatorLayout parent,
final AppBarLayout layout,
final int offset,
final int direction,
final boolean forceJump) {
final View child = getAppBarChildOnOffset(layout, offset);
if (child != null) {
final AppBarLayout.LayoutParams childLp = (LayoutParams) child.getLayoutParams();
final int flags = childLp.getScrollFlags();
boolean collapsed = false;
if ((flags & LayoutParams.SCROLL_FLAG_SCROLL) != 0) {
final int minHeight = ViewCompat.getMinimumHeight(child);
if (direction > 0
&& (flags
& (LayoutParams.SCROLL_FLAG_ENTER_ALWAYS
| LayoutParams.SCROLL_FLAG_ENTER_ALWAYS_COLLAPSED))
!= 0) {
// We're set to enter always collapsed so we are only collapsed when
// being scrolled down, and in a collapsed offset
collapsed = -offset >= child.getBottom() - minHeight - layout.getTopInset();
} else if ((flags & LayoutParams.SCROLL_FLAG_EXIT_UNTIL_COLLAPSED) != 0) {
// We're set to exit until collapsed, so any offset which results in
// the minimum height (or less) being shown is collapsed
collapsed = -offset >= child.getBottom() - minHeight - layout.getTopInset();
}
}
final boolean changed = layout.setCollapsedState(collapsed);
if (Build.VERSION.SDK_INT >= 11
&& (forceJump || (changed && shouldJumpElevationState(parent, layout)))) {
// If the collapsed state changed, we may need to
// jump to the current state if we have an overlapping view
layout.jumpDrawablesToCurrentState();
}
}
}
private boolean shouldJumpElevationState(CoordinatorLayout parent, AppBarLayout layout) {
// We should jump the elevated state if we have a dependent scrolling view which has
// an overlapping top (i.e. overlaps us)
final List<View> dependencies = parent.getDependents(layout);
for (int i = 0, size = dependencies.size(); i < size; i++) {
final View dependency = dependencies.get(i);
final CoordinatorLayout.LayoutParams lp =
(CoordinatorLayout.LayoutParams) dependency.getLayoutParams();
final CoordinatorLayout.Behavior behavior = lp.getBehavior();
if (behavior instanceof ScrollingViewBehavior) {
return ((ScrollingViewBehavior) behavior).getOverlayTop() != 0;
}
}
return false;
}
private static View getAppBarChildOnOffset(final AppBarLayout layout, final int offset) {
final int absOffset = Math.abs(offset);
for (int i = 0, z = layout.getChildCount(); i < z; i++) {
final View child = layout.getChildAt(i);
if (absOffset >= child.getTop() && absOffset <= child.getBottom()) {
return child;
}
}
return null;
}
@Override
int getTopBottomOffsetForScrollingSibling() {
return getTopAndBottomOffset() + offsetDelta;
}
@Override
public Parcelable onSaveInstanceState(CoordinatorLayout parent, AppBarLayout abl) {
final Parcelable superState = super.onSaveInstanceState(parent, abl);
final int offset = getTopAndBottomOffset();
// Try and find the first visible child...
for (int i = 0, count = abl.getChildCount(); i < count; i++) {
View child = abl.getChildAt(i);
final int visBottom = child.getBottom() + offset;
if (child.getTop() + offset <= 0 && visBottom >= 0) {
final SavedState ss = new SavedState(superState);
ss.firstVisibleChildIndex = i;
ss.firstVisibleChildAtMinimumHeight =
visBottom == (ViewCompat.getMinimumHeight(child) + abl.getTopInset());
ss.firstVisibleChildPercentageShown = visBottom / (float) child.getHeight();
return ss;
}
}
// Else we'll just return the super state
return superState;
}
@Override
public void onRestoreInstanceState(
CoordinatorLayout parent, AppBarLayout appBarLayout, Parcelable state) {
if (state instanceof SavedState) {
final SavedState ss = (SavedState) state;
super.onRestoreInstanceState(parent, appBarLayout, ss.getSuperState());
offsetToChildIndexOnLayout = ss.firstVisibleChildIndex;
offsetToChildIndexOnLayoutPerc = ss.firstVisibleChildPercentageShown;
offsetToChildIndexOnLayoutIsMinHeight = ss.firstVisibleChildAtMinimumHeight;
} else {
super.onRestoreInstanceState(parent, appBarLayout, state);
offsetToChildIndexOnLayout = INVALID_POSITION;
}
}
protected static class SavedState extends AbsSavedState {
int firstVisibleChildIndex;
float firstVisibleChildPercentageShown;
boolean firstVisibleChildAtMinimumHeight;
public SavedState(Parcel source, ClassLoader loader) {
super(source, loader);
firstVisibleChildIndex = source.readInt();
firstVisibleChildPercentageShown = source.readFloat();
firstVisibleChildAtMinimumHeight = source.readByte() != 0;
}
public SavedState(Parcelable superState) {
super(superState);
}
@Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeInt(firstVisibleChildIndex);
dest.writeFloat(firstVisibleChildPercentageShown);
dest.writeByte((byte) (firstVisibleChildAtMinimumHeight ? 1 : 0));
}
public static final Creator<SavedState> CREATOR =
new ClassLoaderCreator<SavedState>() {
@Override
public SavedState createFromParcel(Parcel source, ClassLoader loader) {
return new SavedState(source, loader);
}
@Override
public SavedState createFromParcel(Parcel source) {
return new SavedState(source, null);
}
@Override
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
}
/**
* Behavior which should be used by {@link View}s which can scroll vertically and support nested
* scrolling to automatically scroll any {@link AppBarLayout} siblings.
*/
public static class ScrollingViewBehavior extends HeaderScrollingViewBehavior {
public ScrollingViewBehavior() {}
public ScrollingViewBehavior(Context context, AttributeSet attrs) {
super(context, attrs);
final TypedArray a =
context.obtainStyledAttributes(attrs, R.styleable.ScrollingViewBehavior_Layout);
setOverlayTop(
a.getDimensionPixelSize(R.styleable.ScrollingViewBehavior_Layout_behavior_overlapTop, 0));
a.recycle();
}
@Override
public boolean layoutDependsOn(CoordinatorLayout parent, View child, View dependency) {
// We depend on any AppBarLayouts
return dependency instanceof AppBarLayout;
}
@Override
public boolean onDependentViewChanged(CoordinatorLayout parent, View child, View dependency) {
offsetChildAsNeeded(child, dependency);
return false;
}
@Override
public boolean onRequestChildRectangleOnScreen(
CoordinatorLayout parent, View child, Rect rectangle, boolean immediate) {
final AppBarLayout header = findFirstDependency(parent.getDependencies(child));
if (header != null) {
// Offset the rect by the child's left/top
rectangle.offset(child.getLeft(), child.getTop());
final Rect parentRect = tempRect1;
parentRect.set(0, 0, parent.getWidth(), parent.getHeight());
if (!parentRect.contains(rectangle)) {
// If the rectangle can not be fully seen the visible bounds, collapse
// the AppBarLayout
header.setExpanded(false, !immediate);
return true;
}
}
return false;
}
private void offsetChildAsNeeded(View child, View dependency) {
final CoordinatorLayout.Behavior behavior =
((CoordinatorLayout.LayoutParams) dependency.getLayoutParams()).getBehavior();
if (behavior instanceof Behavior) {
// Offset the child, pinning it to the bottom the header-dependency, maintaining
// any vertical gap and overlap
final Behavior ablBehavior = (Behavior) behavior;
ViewCompat.offsetTopAndBottom(
child,
(dependency.getBottom() - child.getTop())
+ ablBehavior.offsetDelta
+ getVerticalLayoutGap()
- getOverlapPixelsForOffset(dependency));
}
}
@Override
float getOverlapRatioForOffset(final View header) {
if (header instanceof AppBarLayout) {
final AppBarLayout abl = (AppBarLayout) header;
final int totalScrollRange = abl.getTotalScrollRange();
final int preScrollDown = abl.getDownNestedPreScrollRange();
final int offset = getAppBarLayoutOffset(abl);
if (preScrollDown != 0 && (totalScrollRange + offset) <= preScrollDown) {
// If we're in a pre-scroll down. Don't use the offset at all.
return 0;
} else {
final int availScrollRange = totalScrollRange - preScrollDown;
if (availScrollRange != 0) {
// Else we'll use a interpolated ratio of the overlap, depending on offset
return 1f + (offset / (float) availScrollRange);
}
}
}
return 0f;
}
private static int getAppBarLayoutOffset(AppBarLayout abl) {
final CoordinatorLayout.Behavior behavior =
((CoordinatorLayout.LayoutParams) abl.getLayoutParams()).getBehavior();
if (behavior instanceof Behavior) {
return ((Behavior) behavior).getTopBottomOffsetForScrollingSibling();
}
return 0;
}
@Override
AppBarLayout findFirstDependency(List<View> views) {
for (int i = 0, z = views.size(); i < z; i++) {
View view = views.get(i);
if (view instanceof AppBarLayout) {
return (AppBarLayout) view;
}
}
return null;
}
@Override
int getScrollRange(View v) {
if (v instanceof AppBarLayout) {
return ((AppBarLayout) v).getTotalScrollRange();
} else {
return super.getScrollRange(v);
}
}
}
}
| lib/java/android/support/design/widget/AppBarLayout.java | /*
* Copyright (C) 2015 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 android.support.design.widget;
import static android.support.annotation.RestrictTo.Scope.LIBRARY_GROUP;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Rect;
import android.os.Build;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.IntDef;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.annotation.RestrictTo;
import android.support.annotation.VisibleForTesting;
import android.support.design.R;
import android.support.design.animation.AnimationUtils;
import android.support.v4.util.ObjectsCompat;
import android.support.v4.view.AbsSavedState;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.WindowInsetsCompat;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Interpolator;
import android.widget.LinearLayout;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
/**
* AppBarLayout is a vertical {@link LinearLayout} which implements many of the features of material
* designs app bar concept, namely scrolling gestures.
*
* <p>Children should provide their desired scrolling behavior through {@link
* LayoutParams#setScrollFlags(int)} and the associated layout xml attribute: {@code
* app:layout_scrollFlags}.
*
* <p>This view depends heavily on being used as a direct child within a {@link CoordinatorLayout}.
* If you use AppBarLayout within a different {@link ViewGroup}, most of it's functionality will not
* work.
*
* <p>AppBarLayout also requires a separate scrolling sibling in order to know when to scroll. The
* binding is done through the {@link ScrollingViewBehavior} behavior class, meaning that you should
* set your scrolling view's behavior to be an instance of {@link ScrollingViewBehavior}. A string
* resource containing the full class name is available.
*
* <pre>
* <android.support.design.widget.CoordinatorLayout
* xmlns:android="http://schemas.android.com/apk/res/android"
* xmlns:app="http://schemas.android.com/apk/res-auto"
* android:layout_width="match_parent"
* android:layout_height="match_parent">
*
* <android.support.v4.widget.NestedScrollView
* android:layout_width="match_parent"
* android:layout_height="match_parent"
* app:layout_behavior="@string/appbar_scrolling_view_behavior">
*
* <!-- Your scrolling content -->
*
* </android.support.v4.widget.NestedScrollView>
*
* <android.support.design.widget.AppBarLayout
* android:layout_height="wrap_content"
* android:layout_width="match_parent">
*
* <android.support.v7.widget.Toolbar
* ...
* app:layout_scrollFlags="scroll|enterAlways"/>
*
* <android.support.design.widget.TabLayout
* ...
* app:layout_scrollFlags="scroll|enterAlways"/>
*
* </android.support.design.widget.AppBarLayout>
*
* </android.support.design.widget.CoordinatorLayout>
* </pre>
*
* @see <a href="http://www.google.com/design/spec/layout/structure.html#structure-app-bar">
* http://www.google.com/design/spec/layout/structure.html#structure-app-bar</a>
*/
@CoordinatorLayout.DefaultBehavior(AppBarLayout.Behavior.class)
public class AppBarLayout extends LinearLayout {
static final int PENDING_ACTION_NONE = 0x0;
static final int PENDING_ACTION_EXPANDED = 0x1;
static final int PENDING_ACTION_COLLAPSED = 0x2;
static final int PENDING_ACTION_ANIMATE_ENABLED = 0x4;
static final int PENDING_ACTION_FORCE = 0x8;
/**
* Interface definition for a callback to be invoked when an {@link AppBarLayout}'s vertical
* offset changes.
*/
public interface OnOffsetChangedListener {
/**
* Called when the {@link AppBarLayout}'s layout offset has been changed. This allows child
* views to implement custom behavior based on the offset (for instance pinning a view at a
* certain y value).
*
* @param appBarLayout the {@link AppBarLayout} which offset has changed
* @param verticalOffset the vertical offset for the parent {@link AppBarLayout}, in px
*/
void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset);
}
private static final int INVALID_SCROLL_RANGE = -1;
private int totalScrollRange = INVALID_SCROLL_RANGE;
private int downPreScrollRange = INVALID_SCROLL_RANGE;
private int downScrollRange = INVALID_SCROLL_RANGE;
private boolean haveChildWithInterpolator;
private int pendingAction = PENDING_ACTION_NONE;
private WindowInsetsCompat lastInsets;
private List<OnOffsetChangedListener> listeners;
private boolean collapsible;
private boolean collapsed;
private int[] tmpStatesArray;
public AppBarLayout(Context context) {
this(context, null);
}
public AppBarLayout(Context context, AttributeSet attrs) {
super(context, attrs);
setOrientation(VERTICAL);
ThemeUtils.checkAppCompatTheme(context);
if (Build.VERSION.SDK_INT >= 21) {
// Use the bounds view outline provider so that we cast a shadow, even without a
// background
ViewUtilsLollipop.setBoundsViewOutlineProvider(this);
// If we're running on API 21+, we should reset any state list animator from our
// default style
ViewUtilsLollipop.setStateListAnimatorFromAttrs(
this, attrs, 0, R.style.Widget_Design_AppBarLayout);
}
final TypedArray a =
context.obtainStyledAttributes(
attrs, R.styleable.AppBarLayout, 0, R.style.Widget_Design_AppBarLayout);
ViewCompat.setBackground(this, a.getDrawable(R.styleable.AppBarLayout_android_background));
if (a.hasValue(R.styleable.AppBarLayout_expanded)) {
setExpanded(
a.getBoolean(R.styleable.AppBarLayout_expanded, false),
false, /* animate */
false /* force */);
}
if (Build.VERSION.SDK_INT >= 21 && a.hasValue(R.styleable.AppBarLayout_elevation)) {
ViewUtilsLollipop.setDefaultAppBarLayoutStateListAnimator(
this, a.getDimensionPixelSize(R.styleable.AppBarLayout_elevation, 0));
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// In O+, we have these values set in the style. Since there is no defStyleAttr for
// AppBarLayout at the AppCompat level, check for these attributes here.
if (a.hasValue(R.styleable.AppBarLayout_android_keyboardNavigationCluster)) {
this.setKeyboardNavigationCluster(
a.getBoolean(R.styleable.AppBarLayout_android_keyboardNavigationCluster, false));
}
if (a.hasValue(R.styleable.AppBarLayout_android_touchscreenBlocksFocus)) {
this.setTouchscreenBlocksFocus(
a.getBoolean(R.styleable.AppBarLayout_android_touchscreenBlocksFocus, false));
}
}
a.recycle();
ViewCompat.setOnApplyWindowInsetsListener(
this,
new android.support.v4.view.OnApplyWindowInsetsListener() {
@Override
public WindowInsetsCompat onApplyWindowInsets(View v, WindowInsetsCompat insets) {
return onWindowInsetChanged(insets);
}
});
}
/**
* Add a listener that will be called when the offset of this {@link AppBarLayout} changes.
*
* @param listener The listener that will be called when the offset changes.]
* @see #removeOnOffsetChangedListener(OnOffsetChangedListener)
*/
public void addOnOffsetChangedListener(OnOffsetChangedListener listener) {
if (listeners == null) {
listeners = new ArrayList<>();
}
if (listener != null && !listeners.contains(listener)) {
listeners.add(listener);
}
}
/**
* Remove the previously added {@link OnOffsetChangedListener}.
*
* @param listener the listener to remove.
*/
public void removeOnOffsetChangedListener(OnOffsetChangedListener listener) {
if (listeners != null && listener != null) {
listeners.remove(listener);
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
invalidateScrollRanges();
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
invalidateScrollRanges();
haveChildWithInterpolator = false;
for (int i = 0, z = getChildCount(); i < z; i++) {
final View child = getChildAt(i);
final LayoutParams childLp = (LayoutParams) child.getLayoutParams();
final Interpolator interpolator = childLp.getScrollInterpolator();
if (interpolator != null) {
haveChildWithInterpolator = true;
break;
}
}
updateCollapsible();
}
private void updateCollapsible() {
boolean haveCollapsibleChild = false;
for (int i = 0, z = getChildCount(); i < z; i++) {
if (((LayoutParams) getChildAt(i).getLayoutParams()).isCollapsible()) {
haveCollapsibleChild = true;
break;
}
}
setCollapsibleState(haveCollapsibleChild);
}
private void invalidateScrollRanges() {
// Invalidate the scroll ranges
totalScrollRange = INVALID_SCROLL_RANGE;
downPreScrollRange = INVALID_SCROLL_RANGE;
downScrollRange = INVALID_SCROLL_RANGE;
}
@Override
public void setOrientation(int orientation) {
if (orientation != VERTICAL) {
throw new IllegalArgumentException(
"AppBarLayout is always vertical and does" + " not support horizontal orientation");
}
super.setOrientation(orientation);
}
/**
* Sets whether this {@link AppBarLayout} is expanded or not, animating if it has already been
* laid out.
*
* <p>As with {@link AppBarLayout}'s scrolling, this method relies on this layout being a direct
* child of a {@link CoordinatorLayout}.
*
* @param expanded true if the layout should be fully expanded, false if it should be fully
* collapsed
* @attr ref android.support.design.R.styleable#AppBarLayout_expanded
*/
public void setExpanded(boolean expanded) {
setExpanded(expanded, ViewCompat.isLaidOut(this));
}
/**
* Sets whether this {@link AppBarLayout} is expanded or not.
*
* <p>As with {@link AppBarLayout}'s scrolling, this method relies on this layout being a direct
* child of a {@link CoordinatorLayout}.
*
* @param expanded true if the layout should be fully expanded, false if it should be fully
* collapsed
* @param animate Whether to animate to the new state
* @attr ref android.support.design.R.styleable#AppBarLayout_expanded
*/
public void setExpanded(boolean expanded, boolean animate) {
setExpanded(expanded, animate, true);
}
private void setExpanded(boolean expanded, boolean animate, boolean force) {
pendingAction =
(expanded ? PENDING_ACTION_EXPANDED : PENDING_ACTION_COLLAPSED)
| (animate ? PENDING_ACTION_ANIMATE_ENABLED : 0)
| (force ? PENDING_ACTION_FORCE : 0);
requestLayout();
}
@Override
protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
return p instanceof LayoutParams;
}
@Override
protected LayoutParams generateDefaultLayoutParams() {
return new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
}
@Override
public LayoutParams generateLayoutParams(AttributeSet attrs) {
return new LayoutParams(getContext(), attrs);
}
@Override
protected LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
if (Build.VERSION.SDK_INT >= 19 && p instanceof LinearLayout.LayoutParams) {
return new LayoutParams((LinearLayout.LayoutParams) p);
} else if (p instanceof MarginLayoutParams) {
return new LayoutParams((MarginLayoutParams) p);
}
return new LayoutParams(p);
}
boolean hasChildWithInterpolator() {
return haveChildWithInterpolator;
}
/**
* Returns the scroll range of all children.
*
* @return the scroll range in px
*/
public final int getTotalScrollRange() {
if (totalScrollRange != INVALID_SCROLL_RANGE) {
return totalScrollRange;
}
int range = 0;
for (int i = 0, z = getChildCount(); i < z; i++) {
final View child = getChildAt(i);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
final int childHeight = child.getMeasuredHeight();
final int flags = lp.scrollFlags;
if ((flags & LayoutParams.SCROLL_FLAG_SCROLL) != 0) {
// We're set to scroll so add the child's height
range += childHeight + lp.topMargin + lp.bottomMargin;
if ((flags & LayoutParams.SCROLL_FLAG_EXIT_UNTIL_COLLAPSED) != 0) {
// For a collapsing scroll, we to take the collapsed height into account.
// We also break straight away since later views can't scroll beneath
// us
range -= ViewCompat.getMinimumHeight(child);
break;
}
} else {
// As soon as a view doesn't have the scroll flag, we end the range calculation.
// This is because views below can not scroll under a fixed view.
break;
}
}
return totalScrollRange = Math.max(0, range - getTopInset());
}
boolean hasScrollableChildren() {
return getTotalScrollRange() != 0;
}
/** Return the scroll range when scrolling up from a nested pre-scroll. */
int getUpNestedPreScrollRange() {
return getTotalScrollRange();
}
/** Return the scroll range when scrolling down from a nested pre-scroll. */
int getDownNestedPreScrollRange() {
if (downPreScrollRange != INVALID_SCROLL_RANGE) {
// If we already have a valid value, return it
return downPreScrollRange;
}
int range = 0;
for (int i = getChildCount() - 1; i >= 0; i--) {
final View child = getChildAt(i);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
final int childHeight = child.getMeasuredHeight();
final int flags = lp.scrollFlags;
if ((flags & LayoutParams.FLAG_QUICK_RETURN) == LayoutParams.FLAG_QUICK_RETURN) {
// First take the margin into account
range += lp.topMargin + lp.bottomMargin;
// The view has the quick return flag combination...
if ((flags & LayoutParams.SCROLL_FLAG_ENTER_ALWAYS_COLLAPSED) != 0) {
// If they're set to enter collapsed, use the minimum height
range += ViewCompat.getMinimumHeight(child);
} else if ((flags & LayoutParams.SCROLL_FLAG_EXIT_UNTIL_COLLAPSED) != 0) {
// Only enter by the amount of the collapsed height
range += childHeight - ViewCompat.getMinimumHeight(child);
} else {
// Else use the full height (minus the top inset)
range += childHeight - getTopInset();
}
} else if (range > 0) {
// If we've hit an non-quick return scrollable view, and we've already hit a
// quick return view, return now
break;
}
}
return downPreScrollRange = Math.max(0, range);
}
/** Return the scroll range when scrolling down from a nested scroll. */
int getDownNestedScrollRange() {
if (downScrollRange != INVALID_SCROLL_RANGE) {
// If we already have a valid value, return it
return downScrollRange;
}
int range = 0;
for (int i = 0, z = getChildCount(); i < z; i++) {
final View child = getChildAt(i);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
int childHeight = child.getMeasuredHeight();
childHeight += lp.topMargin + lp.bottomMargin;
final int flags = lp.scrollFlags;
if ((flags & LayoutParams.SCROLL_FLAG_SCROLL) != 0) {
// We're set to scroll so add the child's height
range += childHeight;
if ((flags & LayoutParams.SCROLL_FLAG_EXIT_UNTIL_COLLAPSED) != 0) {
// For a collapsing exit scroll, we to take the collapsed height into account.
// We also break the range straight away since later views can't scroll
// beneath us
range -= ViewCompat.getMinimumHeight(child) + getTopInset();
break;
}
} else {
// As soon as a view doesn't have the scroll flag, we end the range calculation.
// This is because views below can not scroll under a fixed view.
break;
}
}
return downScrollRange = Math.max(0, range);
}
void dispatchOffsetUpdates(int offset) {
// Iterate backwards through the list so that most recently added listeners
// get the first chance to decide
if (listeners != null) {
for (int i = 0, z = listeners.size(); i < z; i++) {
final OnOffsetChangedListener listener = listeners.get(i);
if (listener != null) {
listener.onOffsetChanged(this, offset);
}
}
}
}
final int getMinimumHeightForVisibleOverlappingContent() {
final int topInset = getTopInset();
final int minHeight = ViewCompat.getMinimumHeight(this);
if (minHeight != 0) {
// If this layout has a min height, use it (doubled)
return (minHeight * 2) + topInset;
}
// Otherwise, we'll use twice the min height of our last child
final int childCount = getChildCount();
final int lastChildMinHeight =
childCount >= 1 ? ViewCompat.getMinimumHeight(getChildAt(childCount - 1)) : 0;
if (lastChildMinHeight != 0) {
return (lastChildMinHeight * 2) + topInset;
}
// If we reach here then we don't have a min height explicitly set. Instead we'll take a
// guess at 1/3 of our height being visible
return getHeight() / 3;
}
@Override
protected int[] onCreateDrawableState(int extraSpace) {
if (tmpStatesArray == null) {
// Note that we can't allocate this at the class level (in declaration) since
// some paths in super View constructor are going to call this method before
// that
tmpStatesArray = new int[2];
}
final int[] extraStates = tmpStatesArray;
final int[] states = super.onCreateDrawableState(extraSpace + extraStates.length);
extraStates[0] = collapsible ? R.attr.state_collapsible : -R.attr.state_collapsible;
extraStates[1] = collapsible && collapsed ? R.attr.state_collapsed : -R.attr.state_collapsed;
return mergeDrawableStates(states, extraStates);
}
/**
* Sets whether the AppBarLayout has collapsible children or not.
*
* @return true if the collapsible state changed
*/
private boolean setCollapsibleState(boolean collapsible) {
if (this.collapsible != collapsible) {
this.collapsible = collapsible;
refreshDrawableState();
return true;
}
return false;
}
/**
* Sets whether the AppBarLayout is in a collapsed state or not.
*
* @return true if the collapsed state changed
*/
boolean setCollapsedState(boolean collapsed) {
if (this.collapsed != collapsed) {
this.collapsed = collapsed;
refreshDrawableState();
return true;
}
return false;
}
/**
* @deprecated target elevation is now deprecated. AppBarLayout's elevation is now controlled via
* a {@link android.animation.StateListAnimator}. If a target elevation is set, either by this
* method or the {@code app:elevation} attribute, a new state list animator is created which
* uses the given {@code elevation} value.
* @attr ref android.support.design.R.styleable#AppBarLayout_elevation
*/
@Deprecated
public void setTargetElevation(float elevation) {
if (Build.VERSION.SDK_INT >= 21) {
ViewUtilsLollipop.setDefaultAppBarLayoutStateListAnimator(this, elevation);
}
}
/**
* @deprecated target elevation is now deprecated. AppBarLayout's elevation is now controlled via
* a {@link android.animation.StateListAnimator}. This method now always returns 0.
*/
@Deprecated
public float getTargetElevation() {
return 0;
}
int getPendingAction() {
return pendingAction;
}
void resetPendingAction() {
pendingAction = PENDING_ACTION_NONE;
}
@VisibleForTesting
final int getTopInset() {
return lastInsets != null ? lastInsets.getSystemWindowInsetTop() : 0;
}
WindowInsetsCompat onWindowInsetChanged(final WindowInsetsCompat insets) {
WindowInsetsCompat newInsets = null;
if (ViewCompat.getFitsSystemWindows(this)) {
// If we're set to fit system windows, keep the insets
newInsets = insets;
}
// If our insets have changed, keep them and invalidate the scroll ranges...
if (!ObjectsCompat.equals(lastInsets, newInsets)) {
lastInsets = newInsets;
invalidateScrollRanges();
}
return insets;
}
public static class LayoutParams extends LinearLayout.LayoutParams {
/** @hide */
@RestrictTo(LIBRARY_GROUP)
@IntDef(
flag = true,
value = {
SCROLL_FLAG_SCROLL,
SCROLL_FLAG_EXIT_UNTIL_COLLAPSED,
SCROLL_FLAG_ENTER_ALWAYS,
SCROLL_FLAG_ENTER_ALWAYS_COLLAPSED,
SCROLL_FLAG_SNAP
}
)
@Retention(RetentionPolicy.SOURCE)
public @interface ScrollFlags {}
/**
* The view will be scroll in direct relation to scroll events. This flag needs to be set for
* any of the other flags to take effect. If any sibling views before this one do not have this
* flag, then this value has no effect.
*/
public static final int SCROLL_FLAG_SCROLL = 0x1;
/**
* When exiting (scrolling off screen) the view will be scrolled until it is 'collapsed'. The
* collapsed height is defined by the view's minimum height.
*
* @see ViewCompat#getMinimumHeight(View)
* @see View#setMinimumHeight(int)
*/
public static final int SCROLL_FLAG_EXIT_UNTIL_COLLAPSED = 0x2;
/**
* When entering (scrolling on screen) the view will scroll on any downwards scroll event,
* regardless of whether the scrolling view is also scrolling. This is commonly referred to as
* the 'quick return' pattern.
*/
public static final int SCROLL_FLAG_ENTER_ALWAYS = 0x4;
/**
* An additional flag for 'enterAlways' which modifies the returning view to only initially
* scroll back to it's collapsed height. Once the scrolling view has reached the end of it's
* scroll range, the remainder of this view will be scrolled into view. The collapsed height is
* defined by the view's minimum height.
*
* @see ViewCompat#getMinimumHeight(View)
* @see View#setMinimumHeight(int)
*/
public static final int SCROLL_FLAG_ENTER_ALWAYS_COLLAPSED = 0x8;
/**
* Upon a scroll ending, if the view is only partially visible then it will be snapped and
* scrolled to it's closest edge. For example, if the view only has it's bottom 25% displayed,
* it will be scrolled off screen completely. Conversely, if it's bottom 75% is visible then it
* will be scrolled fully into view.
*/
public static final int SCROLL_FLAG_SNAP = 0x10;
/** Internal flags which allows quick checking features */
static final int FLAG_QUICK_RETURN = SCROLL_FLAG_SCROLL | SCROLL_FLAG_ENTER_ALWAYS;
static final int FLAG_SNAP = SCROLL_FLAG_SCROLL | SCROLL_FLAG_SNAP;
static final int COLLAPSIBLE_FLAGS =
SCROLL_FLAG_EXIT_UNTIL_COLLAPSED | SCROLL_FLAG_ENTER_ALWAYS_COLLAPSED;
int scrollFlags = SCROLL_FLAG_SCROLL;
Interpolator scrollInterpolator;
public LayoutParams(Context c, AttributeSet attrs) {
super(c, attrs);
TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.AppBarLayout_Layout);
scrollFlags = a.getInt(R.styleable.AppBarLayout_Layout_layout_scrollFlags, 0);
if (a.hasValue(R.styleable.AppBarLayout_Layout_layout_scrollInterpolator)) {
int resId = a.getResourceId(R.styleable.AppBarLayout_Layout_layout_scrollInterpolator, 0);
scrollInterpolator = android.view.animation.AnimationUtils.loadInterpolator(c, resId);
}
a.recycle();
}
public LayoutParams(int width, int height) {
super(width, height);
}
public LayoutParams(int width, int height, float weight) {
super(width, height, weight);
}
public LayoutParams(ViewGroup.LayoutParams p) {
super(p);
}
public LayoutParams(MarginLayoutParams source) {
super(source);
}
@RequiresApi(19)
public LayoutParams(LinearLayout.LayoutParams source) {
// The copy constructor called here only exists on API 19+.
super(source);
}
@RequiresApi(19)
public LayoutParams(LayoutParams source) {
// The copy constructor called here only exists on API 19+.
super(source);
scrollFlags = source.scrollFlags;
scrollInterpolator = source.scrollInterpolator;
}
/**
* Set the scrolling flags.
*
* @param flags bitwise int of {@link #SCROLL_FLAG_SCROLL}, {@link
* #SCROLL_FLAG_EXIT_UNTIL_COLLAPSED}, {@link #SCROLL_FLAG_ENTER_ALWAYS}, {@link
* #SCROLL_FLAG_ENTER_ALWAYS_COLLAPSED} and {@link #SCROLL_FLAG_SNAP }.
* @see #getScrollFlags()
* @attr ref android.support.design.R.styleable#AppBarLayout_Layout_layout_scrollFlags
*/
public void setScrollFlags(@ScrollFlags int flags) {
scrollFlags = flags;
}
/**
* Returns the scrolling flags.
*
* @see #setScrollFlags(int)
* @attr ref android.support.design.R.styleable#AppBarLayout_Layout_layout_scrollFlags
*/
@ScrollFlags
public int getScrollFlags() {
return scrollFlags;
}
/**
* Set the interpolator to when scrolling the view associated with this {@link LayoutParams}.
*
* @param interpolator the interpolator to use, or null to use normal 1-to-1 scrolling.
* @attr ref android.support.design.R.styleable#AppBarLayout_Layout_layout_scrollInterpolator
* @see #getScrollInterpolator()
*/
public void setScrollInterpolator(Interpolator interpolator) {
scrollInterpolator = interpolator;
}
/**
* Returns the {@link Interpolator} being used for scrolling the view associated with this
* {@link LayoutParams}. Null indicates 'normal' 1-to-1 scrolling.
*
* @attr ref android.support.design.R.styleable#AppBarLayout_Layout_layout_scrollInterpolator
* @see #setScrollInterpolator(Interpolator)
*/
public Interpolator getScrollInterpolator() {
return scrollInterpolator;
}
/** Returns true if the scroll flags are compatible for 'collapsing' */
boolean isCollapsible() {
return (scrollFlags & SCROLL_FLAG_SCROLL) == SCROLL_FLAG_SCROLL
&& (scrollFlags & COLLAPSIBLE_FLAGS) != 0;
}
}
/**
* The default {@link Behavior} for {@link AppBarLayout}. Implements the necessary nested scroll
* handling with offsetting.
*/
public static class Behavior extends HeaderBehavior<AppBarLayout> {
private static final int MAX_OFFSET_ANIMATION_DURATION = 600; // ms
private static final int INVALID_POSITION = -1;
/** Callback to allow control over any {@link AppBarLayout} dragging. */
public abstract static class DragCallback {
/**
* Allows control over whether the given {@link AppBarLayout} can be dragged or not.
*
* <p>Dragging is defined as a direct touch on the AppBarLayout with movement. This call does
* not affect any nested scrolling.
*
* @return true if we are in a position to scroll the AppBarLayout via a drag, false if not.
*/
public abstract boolean canDrag(@NonNull AppBarLayout appBarLayout);
}
private int offsetDelta;
private ValueAnimator offsetAnimator;
private int offsetToChildIndexOnLayout = INVALID_POSITION;
private boolean offsetToChildIndexOnLayoutIsMinHeight;
private float offsetToChildIndexOnLayoutPerc;
private WeakReference<View> lastNestedScrollingChildRef;
private DragCallback onDragCallback;
public Behavior() {}
public Behavior(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean onStartNestedScroll(
CoordinatorLayout parent,
AppBarLayout child,
View directTargetChild,
View target,
int nestedScrollAxes,
int type) {
// Return true if we're nested scrolling vertically, and we have scrollable children
// and the scrolling view is big enough to scroll
final boolean started =
(nestedScrollAxes & ViewCompat.SCROLL_AXIS_VERTICAL) != 0
&& child.hasScrollableChildren()
&& parent.getHeight() - directTargetChild.getHeight() <= child.getHeight();
if (started && offsetAnimator != null) {
// Cancel any offset animation
offsetAnimator.cancel();
}
// A new nested scroll has started so clear out the previous ref
lastNestedScrollingChildRef = null;
return started;
}
@Override
public void onNestedPreScroll(
CoordinatorLayout coordinatorLayout,
AppBarLayout child,
View target,
int dx,
int dy,
int[] consumed,
int type) {
if (dy != 0) {
int min;
int max;
if (dy < 0) {
// We're scrolling down
min = -child.getTotalScrollRange();
max = min + child.getDownNestedPreScrollRange();
} else {
// We're scrolling up
min = -child.getUpNestedPreScrollRange();
max = 0;
}
if (min != max) {
consumed[1] = scroll(coordinatorLayout, child, dy, min, max);
stopNestedScrollIfNeeded(dy, child, target, type);
}
}
}
@Override
public void onNestedScroll(
CoordinatorLayout coordinatorLayout,
AppBarLayout child,
View target,
int dxConsumed,
int dyConsumed,
int dxUnconsumed,
int dyUnconsumed,
int type) {
if (dyUnconsumed < 0) {
// If the scrolling view is scrolling down but not consuming, it's probably be at
// the top of it's content
scroll(coordinatorLayout, child, dyUnconsumed, -child.getDownNestedScrollRange(), 0);
stopNestedScrollIfNeeded(dyUnconsumed, child, target, type);
}
}
private void stopNestedScrollIfNeeded(int dy, AppBarLayout child, View target, int type) {
if (type == ViewCompat.TYPE_NON_TOUCH) {
final int curOffset = getTopBottomOffsetForScrollingSibling();
if ((dy < 0 && curOffset == 0)
|| (dy > 0 && curOffset == -child.getDownNestedScrollRange())) {
ViewCompat.stopNestedScroll(target, ViewCompat.TYPE_NON_TOUCH);
}
}
}
@Override
public void onStopNestedScroll(
CoordinatorLayout coordinatorLayout, AppBarLayout abl, View target, int type) {
if (type == ViewCompat.TYPE_TOUCH) {
// If we haven't been flung then let's see if the current view has been set to snap
snapToChildIfNeeded(coordinatorLayout, abl);
}
// Keep a reference to the previous nested scrolling child
lastNestedScrollingChildRef = new WeakReference<>(target);
}
/**
* Set a callback to control any {@link AppBarLayout} dragging.
*
* @param callback the callback to use, or {@code null} to use the default behavior.
*/
public void setDragCallback(@Nullable DragCallback callback) {
onDragCallback = callback;
}
private void animateOffsetTo(
final CoordinatorLayout coordinatorLayout,
final AppBarLayout child,
final int offset,
float velocity) {
final int distance = Math.abs(getTopBottomOffsetForScrollingSibling() - offset);
final int duration;
velocity = Math.abs(velocity);
if (velocity > 0) {
duration = 3 * Math.round(1000 * (distance / velocity));
} else {
final float distanceRatio = (float) distance / child.getHeight();
duration = (int) ((distanceRatio + 1) * 150);
}
animateOffsetWithDuration(coordinatorLayout, child, offset, duration);
}
private void animateOffsetWithDuration(
final CoordinatorLayout coordinatorLayout,
final AppBarLayout child,
final int offset,
final int duration) {
final int currentOffset = getTopBottomOffsetForScrollingSibling();
if (currentOffset == offset) {
if (offsetAnimator != null && offsetAnimator.isRunning()) {
offsetAnimator.cancel();
}
return;
}
if (offsetAnimator == null) {
offsetAnimator = new ValueAnimator();
offsetAnimator.setInterpolator(AnimationUtils.DECELERATE_INTERPOLATOR);
offsetAnimator.addUpdateListener(
new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animator) {
setHeaderTopBottomOffset(
coordinatorLayout, child, (int) animator.getAnimatedValue());
}
});
} else {
offsetAnimator.cancel();
}
offsetAnimator.setDuration(Math.min(duration, MAX_OFFSET_ANIMATION_DURATION));
offsetAnimator.setIntValues(currentOffset, offset);
offsetAnimator.start();
}
private int getChildIndexOnOffset(AppBarLayout abl, final int offset) {
for (int i = 0, count = abl.getChildCount(); i < count; i++) {
View child = abl.getChildAt(i);
if (child.getTop() <= -offset && child.getBottom() >= -offset) {
return i;
}
}
return -1;
}
private void snapToChildIfNeeded(CoordinatorLayout coordinatorLayout, AppBarLayout abl) {
final int offset = getTopBottomOffsetForScrollingSibling();
final int offsetChildIndex = getChildIndexOnOffset(abl, offset);
if (offsetChildIndex >= 0) {
final View offsetChild = abl.getChildAt(offsetChildIndex);
final LayoutParams lp = (LayoutParams) offsetChild.getLayoutParams();
final int flags = lp.getScrollFlags();
if ((flags & LayoutParams.FLAG_SNAP) == LayoutParams.FLAG_SNAP) {
// We're set the snap, so animate the offset to the nearest edge
int snapTop = -offsetChild.getTop();
int snapBottom = -offsetChild.getBottom();
if (offsetChildIndex == abl.getChildCount() - 1) {
// If this is the last child, we need to take the top inset into account
snapBottom += abl.getTopInset();
}
if (checkFlag(flags, LayoutParams.SCROLL_FLAG_EXIT_UNTIL_COLLAPSED)) {
// If the view is set only exit until it is collapsed, we'll abide by that
snapBottom += ViewCompat.getMinimumHeight(offsetChild);
} else if (checkFlag(
flags, LayoutParams.FLAG_QUICK_RETURN | LayoutParams.SCROLL_FLAG_ENTER_ALWAYS)) {
// If it's set to always enter collapsed, it actually has two states. We
// select the state and then snap within the state
final int seam = snapBottom + ViewCompat.getMinimumHeight(offsetChild);
if (offset < seam) {
snapTop = seam;
} else {
snapBottom = seam;
}
}
final int newOffset = offset < (snapBottom + snapTop) / 2 ? snapBottom : snapTop;
animateOffsetTo(
coordinatorLayout,
abl,
MathUtils.constrain(newOffset, -abl.getTotalScrollRange(), 0),
0);
}
}
}
private static boolean checkFlag(final int flags, final int check) {
return (flags & check) == check;
}
@Override
public boolean onMeasureChild(
CoordinatorLayout parent,
AppBarLayout child,
int parentWidthMeasureSpec,
int widthUsed,
int parentHeightMeasureSpec,
int heightUsed) {
final CoordinatorLayout.LayoutParams lp =
(CoordinatorLayout.LayoutParams) child.getLayoutParams();
if (lp.height == CoordinatorLayout.LayoutParams.WRAP_CONTENT) {
// If the view is set to wrap on it's height, CoordinatorLayout by default will
// cap the view at the CoL's height. Since the AppBarLayout can scroll, this isn't
// what we actually want, so we measure it ourselves with an unspecified spec to
// allow the child to be larger than it's parent
parent.onMeasureChild(
child,
parentWidthMeasureSpec,
widthUsed,
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
heightUsed);
return true;
}
// Let the parent handle it as normal
return super.onMeasureChild(
parent, child, parentWidthMeasureSpec, widthUsed, parentHeightMeasureSpec, heightUsed);
}
@Override
public boolean onLayoutChild(CoordinatorLayout parent, AppBarLayout abl, int layoutDirection) {
boolean handled = super.onLayoutChild(parent, abl, layoutDirection);
// The priority for actions here is (first which is true wins):
// 1. forced pending actions
// 2. offsets for restorations
// 3. non-forced pending actions
final int pendingAction = abl.getPendingAction();
if (offsetToChildIndexOnLayout >= 0 && (pendingAction & PENDING_ACTION_FORCE) == 0) {
View child = abl.getChildAt(offsetToChildIndexOnLayout);
int offset = -child.getBottom();
if (offsetToChildIndexOnLayoutIsMinHeight) {
offset += ViewCompat.getMinimumHeight(child) + abl.getTopInset();
} else {
offset += Math.round(child.getHeight() * offsetToChildIndexOnLayoutPerc);
}
setHeaderTopBottomOffset(parent, abl, offset);
} else if (pendingAction != PENDING_ACTION_NONE) {
final boolean animate = (pendingAction & PENDING_ACTION_ANIMATE_ENABLED) != 0;
if ((pendingAction & PENDING_ACTION_COLLAPSED) != 0) {
final int offset = -abl.getUpNestedPreScrollRange();
if (animate) {
animateOffsetTo(parent, abl, offset, 0);
} else {
setHeaderTopBottomOffset(parent, abl, offset);
}
} else if ((pendingAction & PENDING_ACTION_EXPANDED) != 0) {
if (animate) {
animateOffsetTo(parent, abl, 0, 0);
} else {
setHeaderTopBottomOffset(parent, abl, 0);
}
}
}
// Finally reset any pending states
abl.resetPendingAction();
offsetToChildIndexOnLayout = INVALID_POSITION;
// We may have changed size, so let's constrain the top and bottom offset correctly,
// just in case we're out of the bounds
setTopAndBottomOffset(
MathUtils.constrain(getTopAndBottomOffset(), -abl.getTotalScrollRange(), 0));
// Update the AppBarLayout's drawable state for any elevation changes. This is needed so that
// the elevation is set in the first layout, so that we don't get a visual jump pre-N (due to
// the draw dispatch skip)
updateAppBarLayoutDrawableState(
parent, abl, getTopAndBottomOffset(), 0 /* direction */, true /* forceJump */);
// Make sure we dispatch the offset update
abl.dispatchOffsetUpdates(getTopAndBottomOffset());
return handled;
}
@Override
boolean canDragView(AppBarLayout view) {
if (onDragCallback != null) {
// If there is a drag callback set, it's in control
return onDragCallback.canDrag(view);
}
// Else we'll use the default behaviour of seeing if it can scroll down
if (lastNestedScrollingChildRef != null) {
// If we have a reference to a scrolling view, check it
final View scrollingView = lastNestedScrollingChildRef.get();
return scrollingView != null
&& scrollingView.isShown()
&& !scrollingView.canScrollVertically(-1);
} else {
// Otherwise we assume that the scrolling view hasn't been scrolled and can drag.
return true;
}
}
@Override
void onFlingFinished(CoordinatorLayout parent, AppBarLayout layout) {
// At the end of a manual fling, check to see if we need to snap to the edge-child
snapToChildIfNeeded(parent, layout);
}
@Override
int getMaxDragOffset(AppBarLayout view) {
return -view.getDownNestedScrollRange();
}
@Override
int getScrollRangeForDragFling(AppBarLayout view) {
return view.getTotalScrollRange();
}
@Override
int setHeaderTopBottomOffset(
CoordinatorLayout coordinatorLayout,
AppBarLayout appBarLayout,
int newOffset,
int minOffset,
int maxOffset) {
final int curOffset = getTopBottomOffsetForScrollingSibling();
int consumed = 0;
if (minOffset != 0 && curOffset >= minOffset && curOffset <= maxOffset) {
// If we have some scrolling range, and we're currently within the min and max
// offsets, calculate a new offset
newOffset = MathUtils.constrain(newOffset, minOffset, maxOffset);
if (curOffset != newOffset) {
final int interpolatedOffset =
appBarLayout.hasChildWithInterpolator()
? interpolateOffset(appBarLayout, newOffset)
: newOffset;
final boolean offsetChanged = setTopAndBottomOffset(interpolatedOffset);
// Update how much dy we have consumed
consumed = curOffset - newOffset;
// Update the stored sibling offset
offsetDelta = newOffset - interpolatedOffset;
if (!offsetChanged && appBarLayout.hasChildWithInterpolator()) {
// If the offset hasn't changed and we're using an interpolated scroll
// then we need to keep any dependent views updated. CoL will do this for
// us when we move, but we need to do it manually when we don't (as an
// interpolated scroll may finish early).
coordinatorLayout.dispatchDependentViewsChanged(appBarLayout);
}
// Dispatch the updates to any listeners
appBarLayout.dispatchOffsetUpdates(getTopAndBottomOffset());
// Update the AppBarLayout's drawable state (for any elevation changes)
updateAppBarLayoutDrawableState(
coordinatorLayout,
appBarLayout,
newOffset,
newOffset < curOffset ? -1 : 1,
false /* forceJump */);
}
} else {
// Reset the offset delta
offsetDelta = 0;
}
return consumed;
}
@VisibleForTesting
boolean isOffsetAnimatorRunning() {
return offsetAnimator != null && offsetAnimator.isRunning();
}
private int interpolateOffset(AppBarLayout layout, final int offset) {
final int absOffset = Math.abs(offset);
for (int i = 0, z = layout.getChildCount(); i < z; i++) {
final View child = layout.getChildAt(i);
final AppBarLayout.LayoutParams childLp = (LayoutParams) child.getLayoutParams();
final Interpolator interpolator = childLp.getScrollInterpolator();
if (absOffset >= child.getTop() && absOffset <= child.getBottom()) {
if (interpolator != null) {
int childScrollableHeight = 0;
final int flags = childLp.getScrollFlags();
if ((flags & LayoutParams.SCROLL_FLAG_SCROLL) != 0) {
// We're set to scroll so add the child's height plus margin
childScrollableHeight += child.getHeight() + childLp.topMargin + childLp.bottomMargin;
if ((flags & LayoutParams.SCROLL_FLAG_EXIT_UNTIL_COLLAPSED) != 0) {
// For a collapsing scroll, we to take the collapsed height
// into account.
childScrollableHeight -= ViewCompat.getMinimumHeight(child);
}
}
if (ViewCompat.getFitsSystemWindows(child)) {
childScrollableHeight -= layout.getTopInset();
}
if (childScrollableHeight > 0) {
final int offsetForView = absOffset - child.getTop();
final int interpolatedDiff =
Math.round(
childScrollableHeight
* interpolator.getInterpolation(
offsetForView / (float) childScrollableHeight));
return Integer.signum(offset) * (child.getTop() + interpolatedDiff);
}
}
// If we get to here then the view on the offset isn't suitable for interpolated
// scrolling. So break out of the loop
break;
}
}
return offset;
}
private void updateAppBarLayoutDrawableState(
final CoordinatorLayout parent,
final AppBarLayout layout,
final int offset,
final int direction,
final boolean forceJump) {
final View child = getAppBarChildOnOffset(layout, offset);
if (child != null) {
final AppBarLayout.LayoutParams childLp = (LayoutParams) child.getLayoutParams();
final int flags = childLp.getScrollFlags();
boolean collapsed = false;
if ((flags & LayoutParams.SCROLL_FLAG_SCROLL) != 0) {
final int minHeight = ViewCompat.getMinimumHeight(child);
if (direction > 0
&& (flags
& (LayoutParams.SCROLL_FLAG_ENTER_ALWAYS
| LayoutParams.SCROLL_FLAG_ENTER_ALWAYS_COLLAPSED))
!= 0) {
// We're set to enter always collapsed so we are only collapsed when
// being scrolled down, and in a collapsed offset
collapsed = -offset >= child.getBottom() - minHeight - layout.getTopInset();
} else if ((flags & LayoutParams.SCROLL_FLAG_EXIT_UNTIL_COLLAPSED) != 0) {
// We're set to exit until collapsed, so any offset which results in
// the minimum height (or less) being shown is collapsed
collapsed = -offset >= child.getBottom() - minHeight - layout.getTopInset();
}
}
final boolean changed = layout.setCollapsedState(collapsed);
if (Build.VERSION.SDK_INT >= 11
&& (forceJump || (changed && shouldJumpElevationState(parent, layout)))) {
// If the collapsed state changed, we may need to
// jump to the current state if we have an overlapping view
layout.jumpDrawablesToCurrentState();
}
}
}
private boolean shouldJumpElevationState(CoordinatorLayout parent, AppBarLayout layout) {
// We should jump the elevated state if we have a dependent scrolling view which has
// an overlapping top (i.e. overlaps us)
final List<View> dependencies = parent.getDependents(layout);
for (int i = 0, size = dependencies.size(); i < size; i++) {
final View dependency = dependencies.get(i);
final CoordinatorLayout.LayoutParams lp =
(CoordinatorLayout.LayoutParams) dependency.getLayoutParams();
final CoordinatorLayout.Behavior behavior = lp.getBehavior();
if (behavior instanceof ScrollingViewBehavior) {
return ((ScrollingViewBehavior) behavior).getOverlayTop() != 0;
}
}
return false;
}
private static View getAppBarChildOnOffset(final AppBarLayout layout, final int offset) {
final int absOffset = Math.abs(offset);
for (int i = 0, z = layout.getChildCount(); i < z; i++) {
final View child = layout.getChildAt(i);
if (absOffset >= child.getTop() && absOffset <= child.getBottom()) {
return child;
}
}
return null;
}
@Override
int getTopBottomOffsetForScrollingSibling() {
return getTopAndBottomOffset() + offsetDelta;
}
@Override
public Parcelable onSaveInstanceState(CoordinatorLayout parent, AppBarLayout abl) {
final Parcelable superState = super.onSaveInstanceState(parent, abl);
final int offset = getTopAndBottomOffset();
// Try and find the first visible child...
for (int i = 0, count = abl.getChildCount(); i < count; i++) {
View child = abl.getChildAt(i);
final int visBottom = child.getBottom() + offset;
if (child.getTop() + offset <= 0 && visBottom >= 0) {
final SavedState ss = new SavedState(superState);
ss.firstVisibleChildIndex = i;
ss.firstVisibleChildAtMinimumHeight =
visBottom == (ViewCompat.getMinimumHeight(child) + abl.getTopInset());
ss.firstVisibleChildPercentageShown = visBottom / (float) child.getHeight();
return ss;
}
}
// Else we'll just return the super state
return superState;
}
@Override
public void onRestoreInstanceState(
CoordinatorLayout parent, AppBarLayout appBarLayout, Parcelable state) {
if (state instanceof SavedState) {
final SavedState ss = (SavedState) state;
super.onRestoreInstanceState(parent, appBarLayout, ss.getSuperState());
offsetToChildIndexOnLayout = ss.firstVisibleChildIndex;
offsetToChildIndexOnLayoutPerc = ss.firstVisibleChildPercentageShown;
offsetToChildIndexOnLayoutIsMinHeight = ss.firstVisibleChildAtMinimumHeight;
} else {
super.onRestoreInstanceState(parent, appBarLayout, state);
offsetToChildIndexOnLayout = INVALID_POSITION;
}
}
protected static class SavedState extends AbsSavedState {
int firstVisibleChildIndex;
float firstVisibleChildPercentageShown;
boolean firstVisibleChildAtMinimumHeight;
public SavedState(Parcel source, ClassLoader loader) {
super(source, loader);
firstVisibleChildIndex = source.readInt();
firstVisibleChildPercentageShown = source.readFloat();
firstVisibleChildAtMinimumHeight = source.readByte() != 0;
}
public SavedState(Parcelable superState) {
super(superState);
}
@Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeInt(firstVisibleChildIndex);
dest.writeFloat(firstVisibleChildPercentageShown);
dest.writeByte((byte) (firstVisibleChildAtMinimumHeight ? 1 : 0));
}
public static final Creator<SavedState> CREATOR =
new ClassLoaderCreator<SavedState>() {
@Override
public SavedState createFromParcel(Parcel source, ClassLoader loader) {
return new SavedState(source, loader);
}
@Override
public SavedState createFromParcel(Parcel source) {
return new SavedState(source, null);
}
@Override
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
}
/**
* Behavior which should be used by {@link View}s which can scroll vertically and support nested
* scrolling to automatically scroll any {@link AppBarLayout} siblings.
*/
public static class ScrollingViewBehavior extends HeaderScrollingViewBehavior {
public ScrollingViewBehavior() {}
public ScrollingViewBehavior(Context context, AttributeSet attrs) {
super(context, attrs);
final TypedArray a =
context.obtainStyledAttributes(attrs, R.styleable.ScrollingViewBehavior_Layout);
setOverlayTop(
a.getDimensionPixelSize(R.styleable.ScrollingViewBehavior_Layout_behavior_overlapTop, 0));
a.recycle();
}
@Override
public boolean layoutDependsOn(CoordinatorLayout parent, View child, View dependency) {
// We depend on any AppBarLayouts
return dependency instanceof AppBarLayout;
}
@Override
public boolean onDependentViewChanged(CoordinatorLayout parent, View child, View dependency) {
offsetChildAsNeeded(parent, child, dependency);
return false;
}
@Override
public boolean onRequestChildRectangleOnScreen(
CoordinatorLayout parent, View child, Rect rectangle, boolean immediate) {
final AppBarLayout header = findFirstDependency(parent.getDependencies(child));
if (header != null) {
// Offset the rect by the child's left/top
rectangle.offset(child.getLeft(), child.getTop());
final Rect parentRect = tempRect1;
parentRect.set(0, 0, parent.getWidth(), parent.getHeight());
if (!parentRect.contains(rectangle)) {
// If the rectangle can not be fully seen the visible bounds, collapse
// the AppBarLayout
header.setExpanded(false, !immediate);
return true;
}
}
return false;
}
private void offsetChildAsNeeded(CoordinatorLayout parent, View child, View dependency) {
final CoordinatorLayout.Behavior behavior =
((CoordinatorLayout.LayoutParams) dependency.getLayoutParams()).getBehavior();
if (behavior instanceof Behavior) {
// Offset the child, pinning it to the bottom the header-dependency, maintaining
// any vertical gap and overlap
final Behavior ablBehavior = (Behavior) behavior;
ViewCompat.offsetTopAndBottom(
child,
(dependency.getBottom() - child.getTop())
+ ablBehavior.offsetDelta
+ getVerticalLayoutGap()
- getOverlapPixelsForOffset(dependency));
}
}
@Override
float getOverlapRatioForOffset(final View header) {
if (header instanceof AppBarLayout) {
final AppBarLayout abl = (AppBarLayout) header;
final int totalScrollRange = abl.getTotalScrollRange();
final int preScrollDown = abl.getDownNestedPreScrollRange();
final int offset = getAppBarLayoutOffset(abl);
if (preScrollDown != 0 && (totalScrollRange + offset) <= preScrollDown) {
// If we're in a pre-scroll down. Don't use the offset at all.
return 0;
} else {
final int availScrollRange = totalScrollRange - preScrollDown;
if (availScrollRange != 0) {
// Else we'll use a interpolated ratio of the overlap, depending on offset
return 1f + (offset / (float) availScrollRange);
}
}
}
return 0f;
}
private static int getAppBarLayoutOffset(AppBarLayout abl) {
final CoordinatorLayout.Behavior behavior =
((CoordinatorLayout.LayoutParams) abl.getLayoutParams()).getBehavior();
if (behavior instanceof Behavior) {
return ((Behavior) behavior).getTopBottomOffsetForScrollingSibling();
}
return 0;
}
@Override
AppBarLayout findFirstDependency(List<View> views) {
for (int i = 0, z = views.size(); i < z; i++) {
View view = views.get(i);
if (view instanceof AppBarLayout) {
return (AppBarLayout) view;
}
}
return null;
}
@Override
int getScrollRange(View v) {
if (v instanceof AppBarLayout) {
return ((AppBarLayout) v).getTotalScrollRange();
} else {
return super.getScrollRange(v);
}
}
}
}
| Fix bouncy behavior with nested scrolling v2
Adds condition to only snap the CoordinatorLayout if a fling is ending, or a fling won't be started
PiperOrigin-RevId: 178374659
| lib/java/android/support/design/widget/AppBarLayout.java | Fix bouncy behavior with nested scrolling v2 | <ide><path>ib/java/android/support/design/widget/AppBarLayout.java
<ide> import android.support.v4.util.ObjectsCompat;
<ide> import android.support.v4.view.AbsSavedState;
<ide> import android.support.v4.view.ViewCompat;
<add>import android.support.v4.view.ViewCompat.NestedScrollType;
<ide> import android.support.v4.view.WindowInsetsCompat;
<ide> import android.util.AttributeSet;
<ide> import android.view.View;
<ide>
<ide> private int offsetDelta;
<ide>
<add> @NestedScrollType
<add> private int lastStartedType;
<add>
<ide> private ValueAnimator offsetAnimator;
<ide>
<ide> private int offsetToChildIndexOnLayout = INVALID_POSITION;
<ide>
<ide> // A new nested scroll has started so clear out the previous ref
<ide> lastNestedScrollingChildRef = null;
<add>
<add> // Track the last started type so we know if a fling is about to happen once scrolling ends
<add> lastStartedType = type;
<ide>
<ide> return started;
<ide> }
<ide> @Override
<ide> public void onStopNestedScroll(
<ide> CoordinatorLayout coordinatorLayout, AppBarLayout abl, View target, int type) {
<del> if (type == ViewCompat.TYPE_TOUCH) {
<del> // If we haven't been flung then let's see if the current view has been set to snap
<add> // onStartNestedScroll for a fling will happen before onStopNestedScroll for the scroll. This
<add> // isn't necessarily guaranteed yet, but it should be in the future. We use this to our
<add> // advantage to check if a fling (ViewCompat.TYPE_NON_TOUCH) will start after the touch scroll
<add> // (ViewCompat.TYPE_TOUCH) ends
<add> if (lastStartedType == ViewCompat.TYPE_TOUCH || type == ViewCompat.TYPE_NON_TOUCH) {
<add> // If we haven't been flung, or a fling is ending
<ide> snapToChildIfNeeded(coordinatorLayout, abl);
<ide> }
<ide>
<ide>
<ide> @Override
<ide> public boolean onDependentViewChanged(CoordinatorLayout parent, View child, View dependency) {
<del> offsetChildAsNeeded(parent, child, dependency);
<add> offsetChildAsNeeded(child, dependency);
<ide> return false;
<ide> }
<ide>
<ide> return false;
<ide> }
<ide>
<del> private void offsetChildAsNeeded(CoordinatorLayout parent, View child, View dependency) {
<add> private void offsetChildAsNeeded(View child, View dependency) {
<ide> final CoordinatorLayout.Behavior behavior =
<ide> ((CoordinatorLayout.LayoutParams) dependency.getLayoutParams()).getBehavior();
<ide> if (behavior instanceof Behavior) { |
|
JavaScript | mit | 4d6963581064cef00117ce5edad78953e34a72ca | 0 | Clare-MCR/ClarePunts,Clare-MCR/ClarePunts,Clare-MCR/ClarePunts | (function () {
'use strict';
angular
.module('app.layout')
.directive('cpTopNav', cpTopNav);
/* @ngInject */
function cpTopNav() {
var directive = {
bindToController: true,
controller: TopNavController,
controllerAs: 'vm',
restrict: 'EA',
scope: {},
templateUrl: 'app/layout/cp-top-nav.html'
};
TopNavController.$inject = ['$state', 'routerHelper', 'config', 'UserServices'];
/* @ngInject */
function TopNavController($state, routerHelper, config, UserServices) {
var vm = this;
vm.title = config.appTitle;
vm.user = '';
vm.admin = false;
vm.navRoutes = [];
vm.adminRoutes = [];
var states = routerHelper.getStates();
vm.isCurrent = isCurrent;
activate();
function activate() {
getNavRoutes();
getuser();
}
function getNavRoutes() {
vm.navRoutes = states.filter(function (r) {
return r.settings && r.settings.nav && !r.settings.admin;
}).sort(function (r1, r2) {
return r1.settings.nav - r2.settings.nav;
});
vm.adminRoutes = states.filter(function (r) {
return r.settings && r.settings.nav && r.settings.admin;
}).sort(function (r1, r2) {
return r1.settings.nav - r2.settings.nav;
});
}
function getuser() {
vm.user = UserServices.get(
function (data) {
vm.admin = data.admin === '1';
}
);
}
function isCurrent(route) {
if (!route.title || !$state.current || !$state.current.title) {
return '';
}
var menuName = route.title;
return $state.current.title.substr(0, menuName.length) === menuName ? 'current' : '';
}
}
return directive;
}
})();
| src/client/app/layout/cp-top-nav.directive.js | (function () {
'use strict';
angular
.module('app.layout')
.directive('cpTopNav', cpTopNav);
/* @ngInject */
function cpTopNav() {
var directive = {
bindToController: true,
controller: TopNavController,
controllerAs: 'vm',
restrict: 'EA',
scope: {},
templateUrl: 'app/layout/cp-top-nav.html'
};
TopNavController.$inject = ['$state', 'routerHelper', 'config', 'UserServices'];
/* @ngInject */
function TopNavController($state, routerHelper, config, UserServices) {
var vm = this;
vm.title = config.appTitle;
vm.user = '';
vm.admin = false;
vm.navRoutes = [];
vm.adminRoutes = [];
var states = routerHelper.getStates();
vm.isCurrent = isCurrent;
activate();
function activate() {
getNavRoutes();
getuser();
}
function getNavRoutes() {
vm.navRoutes = states.filter(function (r) {
return r.settings && r.settings.nav && !r.settings.admin;
}).sort(function (r1, r2) {
return r1.settings.nav - r2.settings.nav;
});
vm.adminRoutes = states.filter(function (r) {
return r.settings && r.settings.nav && r.settings.admin;
}).sort(function (r1, r2) {
return r1.settings.nav - r2.settings.nav;
});
}
function getuser() {
vm.user = UserServices.get(
function (data) {
vm.admin = Boolean(data.admin);
}
);
}
function isCurrent(route) {
if (!route.title || !$state.current || !$state.current.title) {
return '';
}
var menuName = route.title;
return $state.current.title.substr(0, menuName.length) === menuName ? 'current' : '';
}
}
return directive;
}
})();
| Fix to hide admin menu
| src/client/app/layout/cp-top-nav.directive.js | Fix to hide admin menu | <ide><path>rc/client/app/layout/cp-top-nav.directive.js
<ide> function getuser() {
<ide> vm.user = UserServices.get(
<ide> function (data) {
<del> vm.admin = Boolean(data.admin);
<add> vm.admin = data.admin === '1';
<ide> }
<ide> );
<ide> } |
|
JavaScript | mpl-2.0 | 2268e7dd46ce1a96bdd1846d84b29b0cebba8e3f | 0 | tdeekens/DOMPurify,neilj/DOMPurify,tdeekens/DOMPurify,neilj/DOMPurify,tdeekens/DOMPurify,neilj/DOMPurify | /* jshint node: true, esnext: true */
/* global QUnit */
'use strict';
// Test DOMPurify + jsdom using Node.js (version 4 and up)
const
dompurify = require('../dist/purify'),
jsdom = require('jsdom'),
testSuite = require('./test-suite'),
tests = require('./fixtures/expect'),
xssTests = tests.filter( element => /alert/.test( element.payload ) );
require('qunit-parameterize/qunit-parameterize');
QUnit.assert.contains = function( needle, haystack, message ) {
const result = haystack.indexOf(needle) > -1;
this.push(result, needle, haystack, message);
};
QUnit.config.autostart = false;
jsdom.env({
html: `<html><head></head><body><div id="qunit-fixture"></div></body></html>`,
scripts: ['node_modules/jquery/dist/jquery.js'],
features: {
ProcessExternalResources: ["script"] // needed for firing the onload event for about:blank iframes
},
done(err, window) {
QUnit.module('DOMPurify in jsdom');
if (err) {
console.error('Unexpected error returned by jsdom.env():', err, err.stack);
process.exit(1);
}
if (!window.jQuery) {
console.warn('Unable to load jQuery');
}
const DOMPurify = dompurify(window);
if (!DOMPurify.isSupported) {
console.error('Unexpected error returned by jsdom.env():', err, err.stack);
process.exit(1);
}
window.alert = () => {
window.xssed = true;
};
testSuite(DOMPurify, window, tests, xssTests);
QUnit.start();
}
});
| test/jsdom-node.js | /* jshint node: true, esnext: true */
/* global QUnit */
'use strict';
// Test DOMPurify + jsdom using Node.js (version 4 and up)
const
dompurify = require('../'),
jsdom = require('jsdom'),
testSuite = require('./test-suite'),
tests = require('./fixtures/expect'),
xssTests = tests.filter( element => /alert/.test( element.payload ) );
require('qunit-parameterize/qunit-parameterize');
QUnit.assert.contains = function( needle, haystack, message ) {
const result = haystack.indexOf(needle) > -1;
this.push(result, needle, haystack, message);
};
QUnit.config.autostart = false;
jsdom.env({
html: `<html><head></head><body><div id="qunit-fixture"></div></body></html>`,
scripts: ['node_modules/jquery/dist/jquery.js'],
features: {
ProcessExternalResources: ["script"] // needed for firing the onload event for about:blank iframes
},
done(err, window) {
QUnit.module('DOMPurify in jsdom');
if (err) {
console.error('Unexpected error returned by jsdom.env():', err, err.stack);
process.exit(1);
}
if (!window.jQuery) {
console.warn('Unable to load jQuery');
}
const DOMPurify = dompurify(window);
if (!DOMPurify.isSupported) {
console.error('Unexpected error returned by jsdom.env():', err, err.stack);
process.exit(1);
}
window.alert = () => {
window.xssed = true;
};
testSuite(DOMPurify, window, tests, xssTests);
QUnit.start();
}
});
| Change jsdom tests to consume built version.
| test/jsdom-node.js | Change jsdom tests to consume built version. | <ide><path>est/jsdom-node.js
<ide>
<ide> // Test DOMPurify + jsdom using Node.js (version 4 and up)
<ide> const
<del> dompurify = require('../'),
<add> dompurify = require('../dist/purify'),
<ide> jsdom = require('jsdom'),
<ide> testSuite = require('./test-suite'),
<ide> tests = require('./fixtures/expect'), |
|
Java | apache-2.0 | e300692e84cbf360403ba5e83ef093e87c70ece8 | 0 | apache/isis,niv0/isis,peridotperiod/isis,niv0/isis,apache/isis,kidaa/isis,oscarbou/isis,niv0/isis,incodehq/isis,sanderginn/isis,apache/isis,peridotperiod/isis,howepeng/isis,oscarbou/isis,kidaa/isis,estatio/isis,incodehq/isis,sanderginn/isis,estatio/isis,incodehq/isis,kidaa/isis,apache/isis,peridotperiod/isis,sanderginn/isis,howepeng/isis,incodehq/isis,sanderginn/isis,howepeng/isis,estatio/isis,oscarbou/isis,peridotperiod/isis,kidaa/isis,howepeng/isis,niv0/isis,estatio/isis,apache/isis,apache/isis,oscarbou/isis | package org.nakedobjects.distribution.xml;
import org.nakedobjects.distribution.ClientDistribution;
import org.nakedobjects.distribution.Data;
import org.nakedobjects.distribution.DataHelper;
import org.nakedobjects.distribution.ObjectData;
import org.nakedobjects.distribution.xml.request.AbortTransaction;
import org.nakedobjects.distribution.xml.request.AllInstances;
import org.nakedobjects.distribution.xml.request.ClearAssociation;
import org.nakedobjects.distribution.xml.request.EndTransaction;
import org.nakedobjects.distribution.xml.request.ExecuteAction;
import org.nakedobjects.distribution.xml.request.FindInstancesByTitle;
import org.nakedobjects.distribution.xml.request.HasInstances;
import org.nakedobjects.distribution.xml.request.MakePersistent;
import org.nakedobjects.distribution.xml.request.SetAssociation;
import org.nakedobjects.distribution.xml.request.SetValue;
import org.nakedobjects.distribution.xml.request.StartTransaction;
import org.nakedobjects.object.DirtyObjectSet;
import org.nakedobjects.object.NakedObjectRuntimeException;
import org.nakedobjects.object.control.Hint;
import org.nakedobjects.object.persistence.InstancesCriteria;
import org.nakedobjects.object.persistence.Oid;
import org.nakedobjects.object.persistence.TitleCriteria;
import org.nakedobjects.object.security.Session;
import org.nakedobjects.utility.NotImplementedException;
import org.apache.log4j.Logger;
import com.thoughtworks.xstream.XStream;
public class XmlClient implements ClientDistribution {
private static final Logger LOG = Logger.getLogger(XmlClient.class);
private ClientConnection connection;
private DirtyObjectSet updateNotifier;
public XmlClient() {
connection = new ClientConnection();
connection.init();
}
public ObjectData[] allInstances(Session session, String fullName, boolean includeSubclasses) {
AllInstances request = new AllInstances(session, fullName, includeSubclasses);
remoteExecute(request);
return request.getInstances();
}
public void clearAssociation(Session session, String fieldIdentifier, Oid objectOid, String objectType, Oid associateOid,
String associateType) {
Request request = new ClearAssociation(session, fieldIdentifier, objectOid, objectType, associateOid, associateType);
remoteExecute(request);
}
public void destroyObject(Session session, Oid oid, String type) {
throw new NotImplementedException();
}
public Data executeAction(Session session, String actionType, String actionIdentifier, String[] parameterTypes,
Oid objectOid, String objectType, Data[] parameters) {
ExecuteAction request = new ExecuteAction(session, actionType, actionIdentifier, parameterTypes, objectOid, objectType,
parameters);
remoteExecute(request);
return request.getActionResult();
}
public ObjectData[] findInstances(Session session, InstancesCriteria criteria) {
if(criteria instanceof TitleCriteria) {
FindInstancesByTitle request = new FindInstancesByTitle(session, (TitleCriteria) criteria);
remoteExecute(request);
return request.getInstances();
} else {
throw new NakedObjectRuntimeException();
}
}
public Hint getActionHint(Session session, String actionType, String actionIdentifier, String[] parameterTypes,
Oid objectOid, String objectType, Data[] parameters) {
throw new NotImplementedException();
}
public ObjectData getObject(Session session, Oid oid, String fullName) {
throw new NotImplementedException();
}
public boolean hasInstances(Session session, String fullName) {
HasInstances request = new HasInstances(session, fullName);
remoteExecute(request);
return request.getFlag();
}
public Oid[] makePersistent(Session session, ObjectData data) {
MakePersistent request = new MakePersistent(session, data);
remoteExecute(request);
return request.getOids();
}
public int numberOfInstances(Session session, String fullName) {
throw new NotImplementedException();
}
private void remoteExecute(Request request) {
XStream xstream = new XStream();
String requestData = xstream.toXML(request);
String responseData = connection.request(requestData);
Response response = (Response) xstream.fromXML(responseData);
if (request.getId() != response.getId()) {
throw new NakedObjectRuntimeException("Response out of sequence with respect to the request: " + request.getId()
+ " & " + response.getId() + " respectively");
}
request.setResponse(response.getObject());
ObjectData[] updates = response.getUpdates();
for (int i = 0; i < updates.length; i++) {
LOG.debug("update " + updates[i]);
DataHelper.update(updates[i], updateNotifier);
}
}
public void setAssociation(Session session, String fieldIdentifier, Oid objectOid, String objectType, Oid associateOid,
String associateType) {
Request request = new SetAssociation(session, fieldIdentifier, objectOid, objectType, associateOid, associateType);
remoteExecute(request);
}
public void setValue(Session session, String fieldIdentifier, Oid oid, String objectType, Object associate) {
Request request = new SetValue(session, fieldIdentifier, oid, objectType, associate);
remoteExecute(request);
}
public void abortTransaction(Session session) {
Request request = new AbortTransaction(session);
remoteExecute(request);
}
public void endTransaction(Session session) {
Request request = new EndTransaction(session);
remoteExecute(request);
}
public void startTransaction(Session session) {
Request request = new StartTransaction(session);
remoteExecute(request);
}
public void setUpdateNotifier(DirtyObjectSet updateNotifier) {
this.updateNotifier = updateNotifier;
}
}
/*
* Naked Objects - a framework that exposes behaviourally complete business
* objects directly to the user. Copyright (C) 2000 - 2005 Naked Objects Group
* Ltd
*
* 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
*
* The authors can be contacted via www.nakedobjects.org (the registered address
* of Naked Objects Group is Kingsway House, 123 Goldworth Road, Woking GU21
* 1NR, UK).
*/ | no-distribution-xml/src/org/nakedobjects/distribution/xml/XmlClient.java | package org.nakedobjects.distribution.xml;
import org.nakedobjects.distribution.ClientDistribution;
import org.nakedobjects.distribution.Data;
import org.nakedobjects.distribution.DataHelper;
import org.nakedobjects.distribution.ObjectData;
import org.nakedobjects.distribution.xml.request.AbortTransaction;
import org.nakedobjects.distribution.xml.request.AllInstances;
import org.nakedobjects.distribution.xml.request.ClearAssociation;
import org.nakedobjects.distribution.xml.request.EndTransaction;
import org.nakedobjects.distribution.xml.request.ExecuteAction;
import org.nakedobjects.distribution.xml.request.FindInstancesByTitle;
import org.nakedobjects.distribution.xml.request.HasInstances;
import org.nakedobjects.distribution.xml.request.MakePersistent;
import org.nakedobjects.distribution.xml.request.SetAssociation;
import org.nakedobjects.distribution.xml.request.SetValue;
import org.nakedobjects.distribution.xml.request.StartTransaction;
import org.nakedobjects.object.NakedObjectRuntimeException;
import org.nakedobjects.object.control.Hint;
import org.nakedobjects.object.persistence.InstancesCriteria;
import org.nakedobjects.object.persistence.Oid;
import org.nakedobjects.object.persistence.TitleCriteria;
import org.nakedobjects.object.security.Session;
import org.nakedobjects.utility.NotImplementedException;
import com.thoughtworks.xstream.XStream;
public class XmlClient implements ClientDistribution {
private ClientConnection connection;
public XmlClient() {
connection = new ClientConnection();
connection.init();
}
public ObjectData[] allInstances(Session session, String fullName, boolean includeSubclasses) {
AllInstances request = new AllInstances(session, fullName, includeSubclasses);
remoteExecute(request);
return request.getInstances();
}
public void clearAssociation(Session session, String fieldIdentifier, Oid objectOid, String objectType, Oid associateOid,
String associateType) {
Request request = new ClearAssociation(session, fieldIdentifier, objectOid, objectType, associateOid, associateType);
remoteExecute(request);
}
public void destroyObject(Session session, Oid oid, String type) {
throw new NotImplementedException();
}
public Data executeAction(Session session, String actionType, String actionIdentifier, String[] parameterTypes,
Oid objectOid, String objectType, Data[] parameters) {
ExecuteAction request = new ExecuteAction(session, actionType, actionIdentifier, parameterTypes, objectOid, objectType,
parameters);
remoteExecute(request);
return request.getActionResult();
}
public ObjectData[] findInstances(Session session, InstancesCriteria criteria) {
if(criteria instanceof TitleCriteria) {
FindInstancesByTitle request = new FindInstancesByTitle(session, (TitleCriteria) criteria);
remoteExecute(request);
return request.getInstances();
} else {
throw new NakedObjectRuntimeException();
}
}
public Hint getActionHint(Session session, String actionType, String actionIdentifier, String[] parameterTypes,
Oid objectOid, String objectType, Data[] parameters) {
throw new NotImplementedException();
}
public ObjectData getObject(Session session, Oid oid, String fullName) {
throw new NotImplementedException();
}
public boolean hasInstances(Session session, String fullName) {
HasInstances request = new HasInstances(session, fullName);
remoteExecute(request);
return request.getFlag();
}
public Oid[] makePersistent(Session session, ObjectData data) {
MakePersistent request = new MakePersistent(session, data);
remoteExecute(request);
return request.getOids();
}
public int numberOfInstances(Session session, String fullName) {
throw new NotImplementedException();
}
private void remoteExecute(Request request) {
XStream xstream = new XStream();
String requestData = xstream.toXML(request);
String responseData = connection.request(requestData);
Response response = (Response) xstream.fromXML(responseData);
if (request.getId() != response.getId()) {
throw new NakedObjectRuntimeException("Response out of sequence with respect to the request: " + request.getId()
+ " & " + response.getId() + " respectively");
}
request.setResponse(response.getObject());
ObjectData[] updates = response.getUpdates();
for (int i = 0; i < updates.length; i++) {
DataHelper.update(updates[i]);
}
}
public void setAssociation(Session session, String fieldIdentifier, Oid objectOid, String objectType, Oid associateOid,
String associateType) {
Request request = new SetAssociation(session, fieldIdentifier, objectOid, objectType, associateOid, associateType);
remoteExecute(request);
}
public void setValue(Session session, String fieldIdentifier, Oid oid, String objectType, Object associate) {
Request request = new SetValue(session, fieldIdentifier, oid, objectType, associate);
remoteExecute(request);
}
public void abortTransaction(Session session) {
Request request = new AbortTransaction(session);
remoteExecute(request);
}
public void endTransaction(Session session) {
Request request = new EndTransaction(session);
remoteExecute(request);
}
public void startTransaction(Session session) {
Request request = new StartTransaction(session);
remoteExecute(request);
}
}
/*
* Naked Objects - a framework that exposes behaviourally complete business
* objects directly to the user. Copyright (C) 2000 - 2005 Naked Objects Group
* Ltd
*
* 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
*
* The authors can be contacted via www.nakedobjects.org (the registered address
* of Naked Objects Group is Kingsway House, 123 Goldworth Road, Woking GU21
* 1NR, UK).
*/ | Datahelper now passes on the changes to object to the dirty object set, allowing the viewer to refresh views that have changed.
git-svn-id: 3f09329b2f6451ddff3637e937fd5de689f72c1f@1007098 13f79535-47bb-0310-9956-ffa450edef68
| no-distribution-xml/src/org/nakedobjects/distribution/xml/XmlClient.java | Datahelper now passes on the changes to object to the dirty object set, allowing the viewer to refresh views that have changed. | <ide><path>o-distribution-xml/src/org/nakedobjects/distribution/xml/XmlClient.java
<ide> import org.nakedobjects.distribution.xml.request.SetAssociation;
<ide> import org.nakedobjects.distribution.xml.request.SetValue;
<ide> import org.nakedobjects.distribution.xml.request.StartTransaction;
<add>import org.nakedobjects.object.DirtyObjectSet;
<ide> import org.nakedobjects.object.NakedObjectRuntimeException;
<ide> import org.nakedobjects.object.control.Hint;
<ide> import org.nakedobjects.object.persistence.InstancesCriteria;
<ide> import org.nakedobjects.object.security.Session;
<ide> import org.nakedobjects.utility.NotImplementedException;
<ide>
<add>import org.apache.log4j.Logger;
<add>
<ide> import com.thoughtworks.xstream.XStream;
<ide>
<ide>
<ide> public class XmlClient implements ClientDistribution {
<add> private static final Logger LOG = Logger.getLogger(XmlClient.class);
<ide> private ClientConnection connection;
<add> private DirtyObjectSet updateNotifier;
<ide>
<ide> public XmlClient() {
<ide> connection = new ClientConnection();
<ide>
<ide> ObjectData[] updates = response.getUpdates();
<ide> for (int i = 0; i < updates.length; i++) {
<del> DataHelper.update(updates[i]);
<add> LOG.debug("update " + updates[i]);
<add> DataHelper.update(updates[i], updateNotifier);
<ide> }
<ide> }
<ide>
<ide> remoteExecute(request);
<ide> }
<ide>
<add> public void setUpdateNotifier(DirtyObjectSet updateNotifier) {
<add> this.updateNotifier = updateNotifier;
<add> }
<add>
<ide> }
<ide>
<ide> /* |
|
JavaScript | mit | 5102a79fcc0c309fc7d41ba80d1d31a4ef32bab9 | 0 | 3ev/tev_glossary,3ev/tev_glossary,3ev/tev_glossary,3ev/tev_glossary | (function ($, config) {
var justOnce = []
/*
* Constructor.
*/
function TevGlossary(options) {
var defaults = {
selector: 'p'
, position: 'top'
, toggle: 'hover'
, enable: true
, firstOccOnly: true
}
this.options = $.extend(defaults, options)
// If the window is in https, set the URL to make an https request instead of http
if(window.location.protocol === 'https:') {
this.options.url = this.options.url.replace(/^http:\/\//i, 'https://');
}
}
/*
* Replace text in the given DOM node and its children with a glossary popup
* for the given entry, if that entry exists.
*/
TevGlossary.prototype.replaceTextInNode = function (node, entry, noTraversal) {
// Check if the current node is a text node. If it is, search for the
// glossary term. If not, iterate its direct child text nodes and search
// them
if (node.nodeType === 3) {
var pos = node.nodeValue.toLowerCase().indexOf(entry.term.toLowerCase())
, wr = new RegExp('\\W')
, wb
, wa
// Check for non-word chars before
if (pos > 0) {
wb = wr.test(node.nodeValue.substr(pos - 1, 1))
} else {
wb = true
}
// Check for non-word chars after
if ((pos >= 0) && ((pos + entry.term.length - 1) < (node.nodeValue.length - 1))) {
wa = wr.test(node.nodeValue.substr(pos + entry.term.length, 1))
} else {
wa = true
}
if ((pos >= 0) && wb && wa) {
// Find the start of the chunk to replace
var replace = node.splitText(pos)
// Trim off the unwanted part from the end of the chunk
replace.splitText(entry.term.length)
// Create the wrapper
var withPopover = $('<span/>')
.addClass('tev-glossary-highlighted')
.attr('data-toggle', 'popover')
.attr('data-content', entry.definition)
.attr('title', entry.term)
.append(replace.cloneNode(true))
// Insert the replacement back into the parent node.
if(!(justOnce.indexOf(entry.term.toLowerCase()) >= 0)) {
replace.parentNode.replaceChild(withPopover[0], replace)
// Only the first occurrence of each word will be used if this option is true.
if (this.options.firstOccOnly) {
justOnce.push(entry.term.toLowerCase())
}
}
// Return a skip value, to ensure we don't iterate the replaced
// node and create an infinite loop
return 1
} else {
return 0
}
} else if (!noTraversal && (node.nodeType === 1 && node.childNodes)) {
for (var i = 0; i < node.childNodes.length; i++) {
i += this.replaceTextInNode(node.childNodes[i], entry, true)
}
return 0
}
}
/*
* Search all target nodes for all target glossary entries, and setup
* glossary tooltips.
*/
TevGlossary.prototype.searchForEntries = function (entries) {
var self = this
, $nodes = $(self.options.selector)
// Search all entries in all nodes
$.each(entries, function (i, entry) {
$nodes.each(function (j, el) {
self.replaceTextInNode(el, entry)
})
})
// Run the Bootstrap popover on the created glossary terms
$('.tev-glossary-highlighted').popover({
container: 'body'
, placement: this.options.position
, trigger: this.options.toggle
, template: '<div class="popover tev-glossary-popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'
})
}
/*
* Run the service.
*/
TevGlossary.prototype.run = function () {
var self = this
if (this.options.enable) {
$.ajax({
type: 'GET'
, url: this.options.url
, dataType: 'json'
, success: function (data) {
self.searchForEntries(data)
}
})
}
}
// Create and run service instance.
new TevGlossary(config).run()
})(window.jQuery, window.tevGlossaryConfig);
| Resources/Public/js/tev-glossary.js | (function ($, config) {
var justOnce = []
/*
* Constructor.
*/
function TevGlossary(options) {
var defaults = {
selector: 'p'
, position: 'top'
, toggle: 'hover'
, enable: true
, firstOccOnly: true
}
this.options = $.extend(defaults, options)
}
/*
* Replace text in the given DOM node and its children with a glossary popup
* for the given entry, if that entry exists.
*/
TevGlossary.prototype.replaceTextInNode = function (node, entry, noTraversal) {
// Check if the current node is a text node. If it is, search for the
// glossary term. If not, iterate its direct child text nodes and search
// them
if (node.nodeType === 3) {
var pos = node.nodeValue.toLowerCase().indexOf(entry.term.toLowerCase())
, wr = new RegExp('\\W')
, wb
, wa
// Check for non-word chars before
if (pos > 0) {
wb = wr.test(node.nodeValue.substr(pos - 1, 1))
} else {
wb = true
}
// Check for non-word chars after
if ((pos >= 0) && ((pos + entry.term.length - 1) < (node.nodeValue.length - 1))) {
wa = wr.test(node.nodeValue.substr(pos + entry.term.length, 1))
} else {
wa = true
}
if ((pos >= 0) && wb && wa) {
// Find the start of the chunk to replace
var replace = node.splitText(pos)
// Trim off the unwanted part from the end of the chunk
replace.splitText(entry.term.length)
// Create the wrapper
var withPopover = $('<span/>')
.addClass('tev-glossary-highlighted')
.attr('data-toggle', 'popover')
.attr('data-content', entry.definition)
.attr('title', entry.term)
.append(replace.cloneNode(true))
// Insert the replacement back into the parent node.
if(!(justOnce.indexOf(entry.term.toLowerCase()) >= 0)) {
replace.parentNode.replaceChild(withPopover[0], replace)
// Only the first occurrence of each word will be used if this option is true.
if (this.options.firstOccOnly) {
justOnce.push(entry.term.toLowerCase())
}
}
// Return a skip value, to ensure we don't iterate the replaced
// node and create an infinite loop
return 1
} else {
return 0
}
} else if (!noTraversal && (node.nodeType === 1 && node.childNodes)) {
for (var i = 0; i < node.childNodes.length; i++) {
i += this.replaceTextInNode(node.childNodes[i], entry, true)
}
return 0
}
}
/*
* Search all target nodes for all target glossary entries, and setup
* glossary tooltips.
*/
TevGlossary.prototype.searchForEntries = function (entries) {
var self = this
, $nodes = $(self.options.selector)
// Search all entries in all nodes
$.each(entries, function (i, entry) {
$nodes.each(function (j, el) {
self.replaceTextInNode(el, entry)
})
})
// Run the Bootstrap popover on the created glossary terms
$('.tev-glossary-highlighted').popover({
container: 'body'
, placement: this.options.position
, trigger: this.options.toggle
, template: '<div class="popover tev-glossary-popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'
})
}
/*
* Run the service.
*/
TevGlossary.prototype.run = function () {
var self = this
if (this.options.enable) {
$.ajax({
type: 'GET'
, url: this.options.url
, dataType: 'json'
, success: function (data) {
self.searchForEntries(data)
}
})
}
}
// Create and run service instance.
new TevGlossary(config).run()
})(window.jQuery, window.tevGlossaryConfig);
| Added a way to switch the URL to https | Resources/Public/js/tev-glossary.js | Added a way to switch the URL to https | <ide><path>esources/Public/js/tev-glossary.js
<ide> }
<ide>
<ide> this.options = $.extend(defaults, options)
<add>
<add> // If the window is in https, set the URL to make an https request instead of http
<add> if(window.location.protocol === 'https:') {
<add> this.options.url = this.options.url.replace(/^http:\/\//i, 'https://');
<add> }
<ide> }
<ide>
<ide> /* |
|
Java | apache-2.0 | 6f88ccbc5c345865a1dacd6fae0f53d2510a314d | 0 | billho/symphony,qiangber/symphony,qiangber/symphony,qiangber/symphony,billho/symphony,billho/symphony | /*
* Copyright (c) 2012-2016, b3log.org & hacpai.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 org.b3log.symphony.service;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang.time.DateUtils;
import org.b3log.latke.Keys;
import org.b3log.latke.Latkes;
import org.b3log.latke.logging.Level;
import org.b3log.latke.logging.Logger;
import org.b3log.latke.model.Pagination;
import org.b3log.latke.model.Role;
import org.b3log.latke.model.User;
import org.b3log.latke.repository.CompositeFilter;
import org.b3log.latke.repository.CompositeFilterOperator;
import org.b3log.latke.repository.Filter;
import org.b3log.latke.repository.FilterOperator;
import org.b3log.latke.repository.PropertyFilter;
import org.b3log.latke.repository.Query;
import org.b3log.latke.repository.RepositoryException;
import org.b3log.latke.repository.SortDirection;
import org.b3log.latke.service.LangPropsService;
import org.b3log.latke.service.ServiceException;
import org.b3log.latke.service.annotation.Service;
import org.b3log.latke.util.CollectionUtils;
import org.b3log.latke.util.Paginator;
import org.b3log.latke.util.Strings;
import org.b3log.symphony.model.Article;
import org.b3log.symphony.model.Comment;
import org.b3log.symphony.model.Common;
import org.b3log.symphony.model.Tag;
import org.b3log.symphony.model.UserExt;
import org.b3log.symphony.processor.channel.ArticleChannel;
import org.b3log.symphony.repository.ArticleRepository;
import org.b3log.symphony.repository.CommentRepository;
import org.b3log.symphony.repository.DomainTagRepository;
import org.b3log.symphony.repository.TagArticleRepository;
import org.b3log.symphony.repository.TagRepository;
import org.b3log.symphony.repository.UserRepository;
import org.b3log.symphony.util.Emotions;
import org.b3log.symphony.util.Markdowns;
import org.b3log.symphony.util.Symphonys;
import org.b3log.symphony.util.Times;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.safety.Whitelist;
/**
* Article query service.
*
* @author <a href="http://88250.b3log.org">Liang Ding</a>
* @version 1.12.10.18, Mar 23, 2016
* @since 0.2.0
*/
@Service
public class ArticleQueryService {
/**
* Logger.
*/
private static final Logger LOGGER = Logger.getLogger(ArticleQueryService.class.getName());
/**
* Article repository.
*/
@Inject
private ArticleRepository articleRepository;
/**
* Comment repository.
*/
@Inject
private CommentRepository commentRepository;
/**
* Tag-Article repository.
*/
@Inject
private TagArticleRepository tagArticleRepository;
/**
* Tag repository.
*/
@Inject
private TagRepository tagRepository;
/**
* User repository.
*/
@Inject
private UserRepository userRepository;
/**
* Domain tag repository.
*/
@Inject
private DomainTagRepository domainTagRepository;
/**
* Comment query service.
*/
@Inject
private CommentQueryService commentQueryService;
/**
* User query service.
*/
@Inject
private UserQueryService userQueryService;
/**
* Avatar query service.
*/
@Inject
private AvatarQueryService avatarQueryService;
/**
* Short link query service.
*/
@Inject
private ShortLinkQueryService shortLinkQueryService;
/**
* Language service.
*/
@Inject
private LangPropsService langPropsService;
/**
* Count to fetch article tags for relevant articles.
*/
private static final int RELEVANT_ARTICLE_RANDOM_FETCH_TAG_CNT = 3;
/**
* Gets domain articles.
*
* @param domainId the specified domain id
* @param currentPageNum the specified current page number
* @param pageSize the specified page size
* @return result
* @throws ServiceException service exception
*/
public JSONObject getDomainArticles(final String domainId, final int currentPageNum, final int pageSize)
throws ServiceException {
final JSONObject ret = new JSONObject();
ret.put(Article.ARTICLES, (Object) Collections.emptyList());
final JSONObject pagination = new JSONObject();
ret.put(Pagination.PAGINATION, pagination);
pagination.put(Pagination.PAGINATION_PAGE_COUNT, 0);
pagination.put(Pagination.PAGINATION_PAGE_NUMS, (Object) Collections.emptyList());
try {
final JSONArray domainTags = domainTagRepository.getByDomainId(domainId, 1, Integer.MAX_VALUE)
.optJSONArray(Keys.RESULTS);
if (domainTags.length() <= 0) {
return ret;
}
final List<String> tagIds = new ArrayList<String>();
for (int i = 0; i < domainTags.length(); i++) {
tagIds.add(domainTags.optJSONObject(i).optString(Tag.TAG + "_" + Keys.OBJECT_ID));
}
Query query = new Query().setFilter(
new PropertyFilter(Tag.TAG + "_" + Keys.OBJECT_ID, FilterOperator.IN, tagIds)).
setCurrentPageNum(currentPageNum).setPageSize(pageSize).
addSort(Keys.OBJECT_ID, SortDirection.DESCENDING);
JSONObject result = tagArticleRepository.get(query);
final JSONArray tagArticles = result.optJSONArray(Keys.RESULTS);
if (tagArticles.length() <= 0) {
return ret;
}
final int pageCount = result.optJSONObject(Pagination.PAGINATION).optInt(Pagination.PAGINATION_PAGE_COUNT);
final int windowSize = Symphonys.getInt("latestArticlesWindowSize");
final List<Integer> pageNums = Paginator.paginate(currentPageNum, pageSize, pageCount, windowSize);
pagination.put(Pagination.PAGINATION_PAGE_COUNT, pageCount);
pagination.put(Pagination.PAGINATION_PAGE_NUMS, (Object) pageNums);
final Set<String> articleIds = new HashSet<String>();
for (int i = 0; i < tagArticles.length(); i++) {
articleIds.add(tagArticles.optJSONObject(i).optString(Article.ARTICLE + "_" + Keys.OBJECT_ID));
}
query = new Query().setFilter(CompositeFilterOperator.and(
new PropertyFilter(Keys.OBJECT_ID, FilterOperator.IN, articleIds),
new PropertyFilter(Article.ARTICLE_STATUS, FilterOperator.EQUAL, Article.ARTICLE_STATUS_C_VALID))).
setPageCount(1).addSort(Keys.OBJECT_ID, SortDirection.DESCENDING);
final List<JSONObject> articles
= CollectionUtils.<JSONObject>jsonArrayToList(articleRepository.get(query).optJSONArray(Keys.RESULTS));
try {
organizeArticles(articles);
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Organizes articles failed", e);
throw new ServiceException(e);
}
final Integer participantsCnt = Symphonys.getInt("latestArticleParticipantsCnt");
genParticipants(articles, participantsCnt);
ret.put(Article.ARTICLES, (Object) articles);
return ret;
} catch (final Exception e) {
LOGGER.log(Level.ERROR, "Gets domain articles error", e);
throw new ServiceException(e);
}
}
/**
* Gets the relevant articles of the specified article with the specified fetch size.
*
* <p>
* The relevant articles exist the same tag with the specified article.
* </p>
*
* @param article the specified article
* @param fetchSize the specified fetch size
* @return relevant articles, returns an empty list if not found
* @throws ServiceException service exception
*/
public List<JSONObject> getRelevantArticles(final JSONObject article, final int fetchSize) throws ServiceException {
final String tagsString = article.optString(Article.ARTICLE_TAGS);
final String[] tagTitles = tagsString.split(",");
final int tagTitlesLength = tagTitles.length;
final int subCnt = tagTitlesLength > RELEVANT_ARTICLE_RANDOM_FETCH_TAG_CNT
? RELEVANT_ARTICLE_RANDOM_FETCH_TAG_CNT : tagTitlesLength;
final List<Integer> tagIdx = CollectionUtils.getRandomIntegers(0, tagTitlesLength, subCnt);
final int subFetchSize = fetchSize / subCnt;
final Set<String> fetchedArticleIds = new HashSet<String>();
final List<JSONObject> ret = new ArrayList<JSONObject>();
try {
for (int i = 0; i < tagIdx.size(); i++) {
final String tagTitle = tagTitles[tagIdx.get(i)].trim();
final JSONObject tag = tagRepository.getByTitle(tagTitle);
final String tagId = tag.optString(Keys.OBJECT_ID);
JSONObject result = tagArticleRepository.getByTagId(tagId, 1, subFetchSize);
final JSONArray tagArticleRelations = result.optJSONArray(Keys.RESULTS);
final Set<String> articleIds = new HashSet<String>();
for (int j = 0; j < tagArticleRelations.length(); j++) {
final String articleId = tagArticleRelations.optJSONObject(j).optString(Article.ARTICLE + '_' + Keys.OBJECT_ID);
if (fetchedArticleIds.contains(articleId)) {
continue;
}
articleIds.add(articleId);
fetchedArticleIds.add(articleId);
}
articleIds.remove(article.optString(Keys.OBJECT_ID));
final Query query = new Query().setFilter(new PropertyFilter(Keys.OBJECT_ID, FilterOperator.IN, articleIds));
result = articleRepository.get(query);
ret.addAll(CollectionUtils.<JSONObject>jsonArrayToList(result.optJSONArray(Keys.RESULTS)));
}
organizeArticles(ret);
return ret;
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Gets relevant articles failed", e);
throw new ServiceException(e);
}
}
/**
* Gets broadcasts (articles permalink equals to "aBroadcast").
*
* @param currentPageNum the specified page number
* @param pageSize the specified page size
* @return articles, return an empty list if not found
* @throws ServiceException service exception
*/
public List<JSONObject> getBroadcasts(final int currentPageNum, final int pageSize) throws ServiceException {
try {
final Query query = new Query().setCurrentPageNum(currentPageNum).setPageSize(pageSize).setFilter(
new PropertyFilter(Article.ARTICLE_CLIENT_ARTICLE_ID, FilterOperator.EQUAL, "aBroadcast")).
addSort(Article.ARTICLE_CREATE_TIME, SortDirection.DESCENDING);
final JSONObject result = articleRepository.get(query);
final JSONArray articles = result.optJSONArray(Keys.RESULTS);
if (0 == articles.length()) {
return Collections.emptyList();
}
final List<JSONObject> ret = CollectionUtils.<JSONObject>jsonArrayToList(articles);
for (final JSONObject article : ret) {
article.put(Article.ARTICLE_PERMALINK, Latkes.getServePath() + article.optString(Article.ARTICLE_PERMALINK));
article.remove(Article.ARTICLE_CONTENT);
}
return ret;
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Gets broadcasts [currentPageNum=" + currentPageNum + ", pageSize=" + pageSize + "] failed", e);
throw new ServiceException(e);
}
}
/**
* Gets interest articles.
*
* @param currentPageNum the specified current page number
* @param pageSize the specified fetch size
* @param tagTitles the specified tag titles
* @return articles, return an empty list if not found
* @throws ServiceException service exception
*/
public List<JSONObject> getInterests(final int currentPageNum, final int pageSize, final String... tagTitles)
throws ServiceException {
try {
final List<JSONObject> tagList = new ArrayList<JSONObject>();
for (int i = 0; i < tagTitles.length; i++) {
final String tagTitle = tagTitles[i];
final JSONObject tag = tagRepository.getByTitle(tagTitle);
if (null == tag) {
continue;
}
tagList.add(tag);
}
final Map<String, Class<?>> articleFields = new HashMap<String, Class<?>>();
articleFields.put(Article.ARTICLE_TITLE, String.class);
articleFields.put(Article.ARTICLE_PERMALINK, String.class);
articleFields.put(Article.ARTICLE_CREATE_TIME, Long.class);
final List<JSONObject> ret = new ArrayList<JSONObject>();
if (!tagList.isEmpty()) {
final List<JSONObject> tagArticles
= getArticlesByTags(currentPageNum, pageSize, articleFields, tagList.toArray(new JSONObject[0]));
for (final JSONObject article : tagArticles) {
article.remove(Article.ARTICLE_T_PARTICIPANTS);
article.remove(Article.ARTICLE_T_PARTICIPANT_NAME);
article.remove(Article.ARTICLE_T_PARTICIPANT_THUMBNAIL_URL);
article.remove(Article.ARTICLE_LATEST_CMT_TIME);
article.remove(Article.ARTICLE_UPDATE_TIME);
article.remove(Article.ARTICLE_T_HEAT);
article.remove(Article.ARTICLE_T_TITLE_EMOJI);
article.remove(Common.TIME_AGO);
article.put(Article.ARTICLE_CREATE_TIME, ((Date) article.get(Article.ARTICLE_CREATE_TIME)).getTime());
}
ret.addAll(tagArticles);
}
final List<Filter> filters = new ArrayList<Filter>();
filters.add(new PropertyFilter(Article.ARTICLE_STATUS, FilterOperator.EQUAL, Article.ARTICLE_STATUS_C_VALID));
filters.add(new PropertyFilter(Article.ARTICLE_TYPE, FilterOperator.NOT_EQUAL, Article.ARTICLE_TYPE_C_DISCUSSION));
final Query query = new Query().addSort(Keys.OBJECT_ID, SortDirection.DESCENDING)
.setPageCount(currentPageNum).setPageSize(pageSize).setCurrentPageNum(1);
query.setFilter(new CompositeFilter(CompositeFilterOperator.AND, filters));
for (final Map.Entry<String, Class<?>> articleField : articleFields.entrySet()) {
query.addProjection(articleField.getKey(), articleField.getValue());
}
final JSONObject result = articleRepository.get(query);
final List<JSONObject> recentArticles = CollectionUtils.<JSONObject>jsonArrayToList(result.optJSONArray(Keys.RESULTS));
ret.addAll(recentArticles);
for (final JSONObject article : ret) {
article.put(Article.ARTICLE_PERMALINK, Latkes.getServePath() + article.optString(Article.ARTICLE_PERMALINK));
}
return ret;
} catch (final Exception e) {
LOGGER.log(Level.ERROR, "Gets interests failed", e);
throw new ServiceException(e);
}
}
/**
* Gets news (articles tags contains "B3log Announcement").
*
* @param currentPageNum the specified page number
* @param pageSize the specified page size
* @return articles, return an empty list if not found
* @throws ServiceException service exception
*/
public List<JSONObject> getNews(final int currentPageNum, final int pageSize) throws ServiceException {
try {
JSONObject oldAnnouncementTag = tagRepository.getByTitle("B3log Announcement");
JSONObject currentAnnouncementTag = tagRepository.getByTitle("B3log公告");
if (null == oldAnnouncementTag && null == currentAnnouncementTag) {
return Collections.emptyList();
}
if (null == oldAnnouncementTag) {
oldAnnouncementTag = new JSONObject();
}
if (null == currentAnnouncementTag) {
currentAnnouncementTag = new JSONObject();
}
Query query = new Query().addSort(Keys.OBJECT_ID, SortDirection.DESCENDING).
setFilter(CompositeFilterOperator.or(
new PropertyFilter(Tag.TAG + '_' + Keys.OBJECT_ID, FilterOperator.EQUAL,
oldAnnouncementTag.optString(Keys.OBJECT_ID)),
new PropertyFilter(Tag.TAG + '_' + Keys.OBJECT_ID, FilterOperator.EQUAL,
currentAnnouncementTag.optString(Keys.OBJECT_ID))
))
.setPageCount(1).setPageSize(pageSize).setCurrentPageNum(currentPageNum);
JSONObject result = tagArticleRepository.get(query);
final JSONArray tagArticleRelations = result.optJSONArray(Keys.RESULTS);
final Set<String> articleIds = new HashSet<String>();
for (int i = 0; i < tagArticleRelations.length(); i++) {
articleIds.add(tagArticleRelations.optJSONObject(i).optString(Article.ARTICLE + '_' + Keys.OBJECT_ID));
}
final JSONObject sa = userQueryService.getSA();
final List<Filter> subFilters = new ArrayList<Filter>();
subFilters.add(new PropertyFilter(Keys.OBJECT_ID, FilterOperator.IN, articleIds));
subFilters.add(new PropertyFilter(Article.ARTICLE_AUTHOR_EMAIL, FilterOperator.EQUAL, sa.optString(User.USER_EMAIL)));
query = new Query().setFilter(new CompositeFilter(CompositeFilterOperator.AND, subFilters))
.addProjection(Article.ARTICLE_TITLE, String.class).addProjection(Article.ARTICLE_PERMALINK, String.class)
.addProjection(Article.ARTICLE_CREATE_TIME, Long.class).addSort(Article.ARTICLE_CREATE_TIME, SortDirection.DESCENDING);
result = articleRepository.get(query);
final List<JSONObject> ret = CollectionUtils.<JSONObject>jsonArrayToList(result.optJSONArray(Keys.RESULTS));
for (final JSONObject article : ret) {
article.put(Article.ARTICLE_PERMALINK, Latkes.getServePath() + article.optString(Article.ARTICLE_PERMALINK));
}
return ret;
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Gets news failed", e);
throw new ServiceException(e);
}
}
/**
* Gets articles by the specified tags (order by article create date desc).
*
* @param tags the specified tags
* @param currentPageNum the specified page number
* @param articleFields the specified article fields to return
* @param pageSize the specified page size
* @return articles, return an empty list if not found
* @throws ServiceException service exception
*/
public List<JSONObject> getArticlesByTags(final int currentPageNum, final int pageSize,
final Map<String, Class<?>> articleFields, final JSONObject... tags) throws ServiceException {
try {
final List<Filter> filters = new ArrayList<Filter>();
for (final JSONObject tag : tags) {
filters.add(new PropertyFilter(Tag.TAG + '_' + Keys.OBJECT_ID, FilterOperator.EQUAL, tag.optString(Keys.OBJECT_ID)));
}
Filter filter;
if (filters.size() >= 2) {
filter = new CompositeFilter(CompositeFilterOperator.OR, filters);
} else {
filter = filters.get(0);
}
// XXX: 这里的分页是有问题的,后面取文章的时候会少(因为一篇文章可以有多个标签,但是文章 id 一样)
Query query = new Query().addSort(Keys.OBJECT_ID, SortDirection.DESCENDING).
setFilter(filter).setPageCount(1).setPageSize(pageSize).setCurrentPageNum(currentPageNum);
JSONObject result = tagArticleRepository.get(query);
final JSONArray tagArticleRelations = result.optJSONArray(Keys.RESULTS);
final Set<String> articleIds = new HashSet<String>();
for (int i = 0; i < tagArticleRelations.length(); i++) {
articleIds.add(tagArticleRelations.optJSONObject(i).optString(Article.ARTICLE + '_' + Keys.OBJECT_ID));
}
query = new Query().setFilter(new PropertyFilter(Keys.OBJECT_ID, FilterOperator.IN, articleIds)).
addSort(Keys.OBJECT_ID, SortDirection.DESCENDING);
for (final Map.Entry<String, Class<?>> articleField : articleFields.entrySet()) {
query.addProjection(articleField.getKey(), articleField.getValue());
}
result = articleRepository.get(query);
final List<JSONObject> ret = CollectionUtils.<JSONObject>jsonArrayToList(result.optJSONArray(Keys.RESULTS));
organizeArticles(ret);
final Integer participantsCnt = Symphonys.getInt("tagArticleParticipantsCnt");
genParticipants(ret, participantsCnt);
return ret;
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Gets articles by tags [tagLength=" + tags.length + "] failed", e);
throw new ServiceException(e);
}
}
/**
* Gets articles by the specified city (order by article create date desc).
*
* @param city the specified city
* @param currentPageNum the specified page number
* @param pageSize the specified page size
* @return articles, return an empty list if not found
* @throws ServiceException service exception
*/
public List<JSONObject> getArticlesByCity(final String city, final int currentPageNum, final int pageSize)
throws ServiceException {
try {
final Query query = new Query().addSort(Keys.OBJECT_ID, SortDirection.DESCENDING).
setFilter(new PropertyFilter(Article.ARTICLE_CITY, FilterOperator.EQUAL, city))
.setPageCount(1).setPageSize(pageSize).setCurrentPageNum(currentPageNum);
final JSONObject result = articleRepository.get(query);
final List<JSONObject> ret = CollectionUtils.<JSONObject>jsonArrayToList(result.optJSONArray(Keys.RESULTS));
organizeArticles(ret);
final Integer participantsCnt = Symphonys.getInt("cityArticleParticipantsCnt");
genParticipants(ret, participantsCnt);
return ret;
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Gets articles by city [" + city + "] failed", e);
throw new ServiceException(e);
}
}
/**
* Gets articles by the specified tag (order by article create date desc).
*
* @param tag the specified tag
* @param currentPageNum the specified page number
* @param pageSize the specified page size
* @return articles, return an empty list if not found
* @throws ServiceException service exception
*/
public List<JSONObject> getArticlesByTag(final JSONObject tag, final int currentPageNum, final int pageSize)
throws ServiceException {
try {
Query query = new Query().addSort(Keys.OBJECT_ID, SortDirection.DESCENDING).
setFilter(new PropertyFilter(Tag.TAG + '_' + Keys.OBJECT_ID, FilterOperator.EQUAL, tag.optString(Keys.OBJECT_ID)))
.setPageCount(1).setPageSize(pageSize).setCurrentPageNum(currentPageNum);
JSONObject result = tagArticleRepository.get(query);
final JSONArray tagArticleRelations = result.optJSONArray(Keys.RESULTS);
final Set<String> articleIds = new HashSet<String>();
for (int i = 0; i < tagArticleRelations.length(); i++) {
articleIds.add(tagArticleRelations.optJSONObject(i).optString(Article.ARTICLE + '_' + Keys.OBJECT_ID));
}
query = new Query().setFilter(new PropertyFilter(Keys.OBJECT_ID, FilterOperator.IN, articleIds)).
addSort(Keys.OBJECT_ID, SortDirection.DESCENDING);
result = articleRepository.get(query);
final List<JSONObject> ret = CollectionUtils.<JSONObject>jsonArrayToList(result.optJSONArray(Keys.RESULTS));
organizeArticles(ret);
final Integer participantsCnt = Symphonys.getInt("tagArticleParticipantsCnt");
genParticipants(ret, participantsCnt);
return ret;
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Gets articles by tag [tagTitle=" + tag.optString(Tag.TAG_TITLE) + "] failed", e);
throw new ServiceException(e);
}
}
/**
* Gets an article by the specified client article id.
*
* @param authorId the specified author id
* @param clientArticleId the specified client article id
* @return article, return {@code null} if not found
* @throws ServiceException service exception
*/
public JSONObject getArticleByClientArticleId(final String authorId, final String clientArticleId) throws ServiceException {
final List<Filter> filters = new ArrayList<Filter>();
filters.add(new PropertyFilter(Article.ARTICLE_CLIENT_ARTICLE_ID, FilterOperator.EQUAL, clientArticleId));
filters.add(new PropertyFilter(Article.ARTICLE_AUTHOR_ID, FilterOperator.EQUAL, authorId));
final Query query = new Query().setFilter(new CompositeFilter(CompositeFilterOperator.AND, filters));
try {
final JSONObject result = articleRepository.get(query);
final JSONArray array = result.optJSONArray(Keys.RESULTS);
if (0 == array.length()) {
return null;
}
return array.optJSONObject(0);
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Gets article [clientArticleId=" + clientArticleId + "] failed", e);
throw new ServiceException(e);
}
}
/**
* Gets an article with {@link #organizeArticle(org.json.JSONObject)} by the specified id.
*
* @param articleId the specified id
* @return article, return {@code null} if not found
* @throws ServiceException service exception
*/
public JSONObject getArticleById(final String articleId) throws ServiceException {
try {
final JSONObject ret = articleRepository.get(articleId);
if (null == ret) {
return null;
}
organizeArticle(ret);
return ret;
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Gets an article [articleId=" + articleId + "] failed", e);
throw new ServiceException(e);
}
}
/**
* Gets an article by the specified id.
*
* @param articleId the specified id
* @return article, return {@code null} if not found
* @throws ServiceException service exception
*/
public JSONObject getArticle(final String articleId) throws ServiceException {
try {
final JSONObject ret = articleRepository.get(articleId);
if (null == ret) {
return null;
}
return ret;
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Gets an article [articleId=" + articleId + "] failed", e);
throw new ServiceException(e);
}
}
/**
* Gets preview content of the article specified with the given article id.
*
* @param articleId the given article id
* @param request the specified request
* @return preview content
* @throws ServiceException service exception
*/
public String getArticlePreviewContent(final String articleId, final HttpServletRequest request) throws ServiceException {
final JSONObject article = getArticle(articleId);
if (null == article) {
return null;
}
return getPreviewContent(article, request);
}
private String getPreviewContent(final JSONObject article, final HttpServletRequest request) throws ServiceException {
final int length = Integer.valueOf("150");
String ret = article.optString(Article.ARTICLE_CONTENT);
final String authorId = article.optString(Article.ARTICLE_AUTHOR_ID);
final JSONObject author = userQueryService.getUser(authorId);
if (null != author && UserExt.USER_STATUS_C_INVALID == author.optInt(UserExt.USER_STATUS)
|| Article.ARTICLE_STATUS_C_INVALID == article.optInt(Article.ARTICLE_STATUS)) {
return langPropsService.get("articleContentBlockLabel");
}
final Set<String> userNames = userQueryService.getUserNames(ret);
final JSONObject currentUser = userQueryService.getCurrentUser(request);
final String currentUserName = null == currentUser ? "" : currentUser.optString(User.USER_NAME);
final String authorName = author.optString(User.USER_NAME);
if (Article.ARTICLE_TYPE_C_DISCUSSION == article.optInt(Article.ARTICLE_TYPE)
&& !authorName.equals(currentUserName)) {
boolean invited = false;
for (final String userName : userNames) {
if (userName.equals(currentUserName)) {
invited = true;
break;
}
}
if (!invited) {
String blockContent = langPropsService.get("articleDiscussionLabel");
blockContent = blockContent.replace("{user}", "<a href='" + Latkes.getServePath()
+ "/member/" + authorName + "'>" + authorName + "</a>");
return blockContent;
}
}
ret = Emotions.convert(ret);
ret = Markdowns.toHTML(ret);
ret = Jsoup.clean(ret, Whitelist.none());
if (ret.length() >= length) {
ret = StringUtils.substring(ret, 0, length)
+ " ....";
}
return ret;
}
/**
* Gets the user articles with the specified user id, page number and page size.
*
* @param userId the specified user id
* @param currentPageNum the specified page number
* @param pageSize the specified page size
* @return user articles, return an empty list if not found
* @throws ServiceException service exception
*/
public List<JSONObject> getUserArticles(final String userId, final int currentPageNum, final int pageSize) throws ServiceException {
final Query query = new Query().addSort(Article.ARTICLE_CREATE_TIME, SortDirection.DESCENDING)
.setCurrentPageNum(currentPageNum).setPageSize(pageSize).
setFilter(CompositeFilterOperator.and(
new PropertyFilter(Article.ARTICLE_AUTHOR_ID, FilterOperator.EQUAL, userId),
new PropertyFilter(Article.ARTICLE_STATUS, FilterOperator.EQUAL, Article.ARTICLE_STATUS_C_VALID)));
try {
final JSONObject result = articleRepository.get(query);
final List<JSONObject> ret = CollectionUtils.<JSONObject>jsonArrayToList(result.optJSONArray(Keys.RESULTS));
organizeArticles(ret);
return ret;
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Gets user articles failed", e);
throw new ServiceException(e);
}
}
/**
* Gets hot articles with the specified fetch size.
*
* @param fetchSize the specified fetch size
* @return recent articles, returns an empty list if not found
* @throws ServiceException service exception
*/
public List<JSONObject> getHotArticles(final int fetchSize) throws ServiceException {
final String id = String.valueOf(DateUtils.addDays(new Date(), -15).getTime());
try {
final Query query = new Query().addSort(Article.ARTICLE_COMMENT_CNT, SortDirection.DESCENDING).
addSort(Keys.OBJECT_ID, SortDirection.ASCENDING).setCurrentPageNum(1).setPageSize(fetchSize);
final List<Filter> filters = new ArrayList<Filter>();
filters.add(new PropertyFilter(Keys.OBJECT_ID, FilterOperator.GREATER_THAN_OR_EQUAL, id));
filters.add(new PropertyFilter(Article.ARTICLE_TYPE, FilterOperator.NOT_EQUAL, Article.ARTICLE_TYPE_C_DISCUSSION));
query.setFilter(new CompositeFilter(CompositeFilterOperator.AND, filters));
final JSONObject result = articleRepository.get(query);
final List<JSONObject> ret = CollectionUtils.<JSONObject>jsonArrayToList(result.optJSONArray(Keys.RESULTS));
organizeArticles(ret);
return ret;
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Gets hot articles failed", e);
throw new ServiceException(e);
}
}
/**
* Gets the random articles with the specified fetch size.
*
* @param fetchSize the specified fetch size
* @return random articles, returns an empty list if not found
* @throws ServiceException service exception
*/
public List<JSONObject> getRandomArticles(final int fetchSize) throws ServiceException {
try {
final List<JSONObject> ret = articleRepository.getRandomly(fetchSize);
organizeArticles(ret);
return ret;
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Gets random articles failed", e);
throw new ServiceException(e);
}
}
/**
* Makes article showing filters.
*
* @return filter the article showing to user
*/
private CompositeFilter makeArticleShowingFilter() {
final List<Filter> filters = new ArrayList<Filter>();
filters.add(new PropertyFilter(Article.ARTICLE_STATUS, FilterOperator.EQUAL, Article.ARTICLE_STATUS_C_VALID));
filters.add(new PropertyFilter(Article.ARTICLE_TYPE, FilterOperator.NOT_EQUAL, Article.ARTICLE_TYPE_C_DISCUSSION));
return new CompositeFilter(CompositeFilterOperator.AND, filters);
}
/**
* Makes the recent (sort by create time) articles with the specified fetch size.
*
* @param currentPageNum the specified current page number
* @param fetchSize the specified fetch size
* @return recent articles query
*/
private Query makeRecentQuery(final int currentPageNum, final int fetchSize) {
final Query query = new Query()
.addSort(Keys.OBJECT_ID, SortDirection.DESCENDING)
.setPageSize(fetchSize).setCurrentPageNum(currentPageNum);
query.setFilter(makeArticleShowingFilter());
return query;
}
/**
* Makes the top articles with the specified fetch size.
*
* @param currentPageNum the specified current page number
* @param fetchSize the specified fetch size
* @return top articles query
*/
private Query makeTopQuery(final int currentPageNum, final int fetchSize) {
final Query query = new Query()
.addSort(Article.REDDIT_SCORE, SortDirection.DESCENDING)
.addSort(Article.ARTICLE_LATEST_CMT_TIME, SortDirection.DESCENDING)
.setPageCount(1).setPageSize(fetchSize).setCurrentPageNum(currentPageNum);
query.setFilter(makeArticleShowingFilter());
return query;
}
/**
* Gets the recent (sort by create time) articles with the specified fetch size.
*
* @param currentPageNum the specified current page number
* @param fetchSize the specified fetch size
* @return for example, <pre>
* {
* "pagination": {
* "paginationPageCount": 100,
* "paginationPageNums": [1, 2, 3, 4, 5]
* },
* "articles": [{
* "oId": "",
* "articleTitle": "",
* "articleContent": "",
* ....
* }, ....]
* }
* </pre>
*
* @throws ServiceException service exception
*/
public JSONObject getRecentArticles(final int currentPageNum, final int fetchSize) throws ServiceException {
final JSONObject ret = new JSONObject();
final Query query = makeRecentQuery(currentPageNum, fetchSize);
JSONObject result = null;
try {
result = articleRepository.get(query);
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Gets articles failed", e);
throw new ServiceException(e);
}
final int pageCount = result.optJSONObject(Pagination.PAGINATION).optInt(Pagination.PAGINATION_PAGE_COUNT);
final JSONObject pagination = new JSONObject();
ret.put(Pagination.PAGINATION, pagination);
final int windowSize = Symphonys.getInt("latestArticlesWindowSize");
final List<Integer> pageNums = Paginator.paginate(currentPageNum, fetchSize, pageCount, windowSize);
pagination.put(Pagination.PAGINATION_PAGE_COUNT, pageCount);
pagination.put(Pagination.PAGINATION_PAGE_NUMS, (Object) pageNums);
final JSONArray data = result.optJSONArray(Keys.RESULTS);
final List<JSONObject> articles = CollectionUtils.<JSONObject>jsonArrayToList(data);
try {
organizeArticles(articles);
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Organizes articles failed", e);
throw new ServiceException(e);
}
final Integer participantsCnt = Symphonys.getInt("latestArticleParticipantsCnt");
genParticipants(articles, participantsCnt);
ret.put(Article.ARTICLES, (Object) articles);
return ret;
}
/**
* Gets the index articles with the specified fetch size.
*
* @param fetchSize the specified fetch size
* @return recent articles, returns an empty list if not found
* @throws ServiceException service exception
*/
public List<JSONObject> getIndexArticles(final int fetchSize) throws ServiceException {
final Query query = makeTopQuery(1, fetchSize);
try {
final JSONObject result = articleRepository.get(query);
final List<JSONObject> ret = CollectionUtils.<JSONObject>jsonArrayToList(result.optJSONArray(Keys.RESULTS));
organizeArticles(ret);
for (final JSONObject article : ret) {
final String authorId = article.optString(Article.ARTICLE_AUTHOR_ID);
final JSONObject author = userRepository.get(authorId);
if (UserExt.USER_STATUS_C_INVALID == author.optInt(UserExt.USER_STATUS)) {
article.put(Article.ARTICLE_TITLE, langPropsService.get("articleTitleBlockLabel"));
}
}
final Integer participantsCnt = Symphonys.getInt("indexArticleParticipantsCnt");
genParticipants(ret, participantsCnt);
return ret;
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Gets index articles failed", e);
throw new ServiceException(e);
}
}
/**
* Gets the recent articles with the specified fetch size.
*
* @param currentPageNum the specified current page number
* @param fetchSize the specified fetch size
* @return recent articles, returns an empty list if not found
* @throws ServiceException service exception
*/
public List<JSONObject> getRecentArticlesWithComments(final int currentPageNum, final int fetchSize) throws ServiceException {
return getArticles(makeRecentQuery(currentPageNum, fetchSize));
}
/**
* Gets the index articles with the specified fetch size.
*
* @param currentPageNum the specified current page number
* @param fetchSize the specified fetch size
* @return recent articles, returns an empty list if not found
* @throws ServiceException service exception
*/
public List<JSONObject> getTopArticlesWithComments(final int currentPageNum, final int fetchSize) throws ServiceException {
return getArticles(makeTopQuery(currentPageNum, fetchSize));
}
/**
* The specific articles.
*
* @param query conditions
* @return articles
* @throws ServiceException service exception
*/
private List<JSONObject> getArticles(final Query query) throws ServiceException {
try {
final JSONObject result = articleRepository.get(query);
final List<JSONObject> ret = CollectionUtils.<JSONObject>jsonArrayToList(result.optJSONArray(Keys.RESULTS));
organizeArticles(ret);
final List<JSONObject> stories = new ArrayList<JSONObject>();
for (final JSONObject article : ret) {
final JSONObject story = new JSONObject();
final String authorId = article.optString(Article.ARTICLE_AUTHOR_ID);
final JSONObject author = userRepository.get(authorId);
if (UserExt.USER_STATUS_C_INVALID == author.optInt(UserExt.USER_STATUS)) {
story.put("title", langPropsService.get("articleTitleBlockLabel"));
} else {
story.put("title", article.optString(Article.ARTICLE_TITLE));
}
story.put("id", article.optLong("oId"));
story.put("url", Latkes.getServePath() + article.optString(Article.ARTICLE_PERMALINK));
story.put("user_display_name", article.optString(Article.ARTICLE_T_AUTHOR_NAME));
story.put("user_job", author.optString(UserExt.USER_INTRO));
story.put("comment_html", article.optString(Article.ARTICLE_CONTENT));
story.put("comment_count", article.optInt(Article.ARTICLE_COMMENT_CNT));
story.put("vote_count", article.optInt(Article.ARTICLE_GOOD_CNT));
story.put("created_at", formatDate(article.get(Article.ARTICLE_CREATE_TIME)));
story.put("user_portrait_url", article.optString(Article.ARTICLE_T_AUTHOR_THUMBNAIL_URL));
story.put("comments", getAllComments(article.optString("oId")));
final String tagsString = article.optString(Article.ARTICLE_TAGS);
String[] tags = null;
if (!Strings.isEmptyOrNull(tagsString)) {
tags = tagsString.split(",");
}
story.put("badge", tags == null ? "" : tags[0]);
stories.add(story);
}
final Integer participantsCnt = Symphonys.getInt("indexArticleParticipantsCnt");
genParticipants(stories, participantsCnt);
return stories;
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Gets index articles failed", e);
throw new ServiceException(e);
} catch (final JSONException ex) {
LOGGER.log(Level.ERROR, "Gets index articles failed", ex);
throw new ServiceException(ex);
}
}
/**
* Gets the article comments with the specified article id.
*
* @param articleId the specified article id
* @return comments, return an empty list if not found
* @throws ServiceException service exception
* @throws JSONException json exception
* @throws RepositoryException repository exception
*/
private List<JSONObject> getAllComments(final String articleId) throws ServiceException, JSONException, RepositoryException {
final List<JSONObject> commments = new ArrayList<JSONObject>();
final List<JSONObject> articleComments = commentQueryService.getArticleComments(articleId, 1, Integer.MAX_VALUE);
for (final JSONObject ac : articleComments) {
final JSONObject comment = new JSONObject();
final JSONObject author = userRepository.get(ac.optString(Comment.COMMENT_AUTHOR_ID));
comment.put("id", ac.optLong("oId"));
comment.put("body_html", ac.optString(Comment.COMMENT_CONTENT));
comment.put("depth", 0);
comment.put("user_display_name", ac.optString(Comment.COMMENT_T_AUTHOR_NAME));
comment.put("user_job", author.optString(UserExt.USER_INTRO));
comment.put("vote_count", 0);
comment.put("created_at", formatDate(ac.get(Comment.COMMENT_CREATE_TIME)));
comment.put("user_portrait_url", ac.optString(Comment.COMMENT_T_ARTICLE_AUTHOR_THUMBNAIL_URL));
commments.add(comment);
}
return commments;
}
/**
* The demand format date.
*
* @param date the original date
* @return the format date like "2015-08-03T07:26:57Z"
*/
private String formatDate(final Object date) {
return DateFormatUtils.format(((Date) date).getTime(), "yyyy-MM-dd")
+ "T" + DateFormatUtils.format(((Date) date).getTime(), "HH:mm:ss") + "Z";
}
/**
* Organizes the specified articles.
*
* <ul>
* <li>converts create/update/latest comment time (long) to date type</li>
* <li>generates author thumbnail URL</li>
* <li>generates author name</li>
* <li>escapes article title < and ></li>
* <li>generates article heat</li>
* <li>generates article view count display format(1k+/1.5k+...)</li>
* <li>generates time ago text</li>
* </ul>
*
* @param articles the specified articles
* @throws RepositoryException repository exception
*/
public void organizeArticles(final List<JSONObject> articles) throws RepositoryException {
for (final JSONObject article : articles) {
organizeArticle(article);
}
}
/**
* Organizes the specified article.
*
* <ul>
* <li>converts create/update/latest comment time (long) to date type</li>
* <li>generates author thumbnail URL</li>
* <li>generates author name</li>
* <li>escapes article title < and ></li>
* <li>generates article heat</li>
* <li>generates article view count display format(1k+/1.5k+...)</li>
* <li>generates time ago text</li>
* </ul>
*
* @param article the specified article
* @throws RepositoryException repository exception
*/
public void organizeArticle(final JSONObject article) throws RepositoryException {
toArticleDate(article);
genArticleAuthor(article);
String title = article.optString(Article.ARTICLE_TITLE).replace("<", "<").replace(">", ">");
title = Markdowns.clean(title, "");
article.put(Article.ARTICLE_TITLE, title);
article.put(Article.ARTICLE_T_TITLE_EMOJI, Emotions.convert(title));
if (Article.ARTICLE_STATUS_C_INVALID == article.optInt(Article.ARTICLE_STATUS)) {
article.put(Article.ARTICLE_TITLE, langPropsService.get("articleTitleBlockLabel"));
article.put(Article.ARTICLE_T_TITLE_EMOJI, langPropsService.get("articleTitleBlockLabel"));
article.put(Article.ARTICLE_CONTENT, langPropsService.get("articleContentBlockLabel"));
}
final String articleId = article.optString(Keys.OBJECT_ID);
Integer viewingCnt = ArticleChannel.ARTICLE_VIEWS.get(articleId);
if (null == viewingCnt) {
viewingCnt = 0;
}
article.put(Article.ARTICLE_T_HEAT, viewingCnt);
final int viewCnt = article.optInt(Article.ARTICLE_VIEW_CNT);
final double views = (double) viewCnt / 1000;
if (views >= 1) {
final DecimalFormat df = new DecimalFormat("#.#");
article.put(Article.ARTICLE_T_VIEW_CNT_DISPLAY_FORMAT, df.format(views) + "K");
}
}
/**
* Converts the specified article create/update/latest comment time (long) to date type.
*
* @param article the specified article
*/
private void toArticleDate(final JSONObject article) {
article.put(Common.TIME_AGO, Times.getTimeAgo(article.optLong(Article.ARTICLE_CREATE_TIME), Latkes.getLocale()));
article.put(Article.ARTICLE_CREATE_TIME, new Date(article.optLong(Article.ARTICLE_CREATE_TIME)));
article.put(Article.ARTICLE_UPDATE_TIME, new Date(article.optLong(Article.ARTICLE_UPDATE_TIME)));
article.put(Article.ARTICLE_LATEST_CMT_TIME, new Date(article.optLong(Article.ARTICLE_LATEST_CMT_TIME)));
}
/**
* Generates the specified article author name and thumbnail URL.
*
* @param article the specified article
* @throws RepositoryException repository exception
*/
private void genArticleAuthor(final JSONObject article) throws RepositoryException {
final String authorId = article.optString(Article.ARTICLE_AUTHOR_ID);
if (Strings.isEmptyOrNull(authorId)) {
return;
}
final JSONObject author = userRepository.get(authorId);
article.put(Article.ARTICLE_T_AUTHOR_THUMBNAIL_URL, avatarQueryService.getAvatarURLByUser(author));
article.put(Article.ARTICLE_T_AUTHOR, author);
article.put(Article.ARTICLE_T_AUTHOR_NAME, author.optString(User.USER_NAME));
}
/**
* Generates participants for the specified articles.
*
* @param articles the specified articles
* @param participantsCnt the specified generate size
* @throws ServiceException service exception
*/
private void genParticipants(final List<JSONObject> articles, final Integer participantsCnt) throws ServiceException {
for (final JSONObject article : articles) {
final String participantName = "";
final String participantThumbnailURL = "";
final List<JSONObject> articleParticipants
= getArticleLatestParticipants(article.optString(Keys.OBJECT_ID), participantsCnt);
article.put(Article.ARTICLE_T_PARTICIPANTS, (Object) articleParticipants);
article.put(Article.ARTICLE_T_PARTICIPANT_NAME, participantName);
article.put(Article.ARTICLE_T_PARTICIPANT_THUMBNAIL_URL, participantThumbnailURL);
}
}
/**
* Gets the article participants (commenters) with the specified article article id and fetch size.
*
* @param articleId the specified article id
* @param fetchSize the specified fetch size
* @return article participants, for example, <pre>
* [
* {
* "oId": "",
* "articleParticipantName": "",
* "articleParticipantThumbnailURL": "",
* "articleParticipantThumbnailUpdateTime": long,
* "commentId": ""
* }, ....
* ]
* </pre>, returns an empty list if not found
*
* @throws ServiceException service exception
*/
public List<JSONObject> getArticleLatestParticipants(final String articleId, final int fetchSize) throws ServiceException {
final Query query = new Query().addSort(Keys.OBJECT_ID, SortDirection.DESCENDING)
.setFilter(new PropertyFilter(Comment.COMMENT_ON_ARTICLE_ID, FilterOperator.EQUAL, articleId))
.addProjection(Comment.COMMENT_AUTHOR_EMAIL, String.class)
.addProjection(Keys.OBJECT_ID, String.class)
.addProjection(Comment.COMMENT_AUTHOR_ID, String.class)
.setPageCount(1).setCurrentPageNum(1).setPageSize(fetchSize);
final List<JSONObject> ret = new ArrayList<JSONObject>();
try {
final JSONObject result = commentRepository.get(query);
final List<JSONObject> comments = new ArrayList<JSONObject>();
final JSONArray records = result.optJSONArray(Keys.RESULTS);
for (int i = 0; i < records.length(); i++) {
final JSONObject comment = records.optJSONObject(i);
boolean exist = false;
// deduplicate
for (final JSONObject c : comments) {
if (comment.optString(Comment.COMMENT_AUTHOR_ID).equals(
c.optString(Comment.COMMENT_AUTHOR_ID))) {
exist = true;
break;
}
}
if (!exist) {
comments.add(comment);
}
}
for (final JSONObject comment : comments) {
final String email = comment.optString(Comment.COMMENT_AUTHOR_EMAIL);
final String userId = comment.optString(Comment.COMMENT_AUTHOR_ID);
final JSONObject commenter = userRepository.get(userId);
String thumbnailURL = Symphonys.get("defaultThumbnailURL");
if (!UserExt.DEFAULT_CMTER_EMAIL.equals(email)) {
thumbnailURL = avatarQueryService.getAvatarURLByUser(commenter);
}
final JSONObject participant = new JSONObject();
participant.put(Article.ARTICLE_T_PARTICIPANT_NAME, commenter.optString(User.USER_NAME));
participant.put(Article.ARTICLE_T_PARTICIPANT_THUMBNAIL_URL, thumbnailURL);
participant.put(Article.ARTICLE_T_PARTICIPANT_THUMBNAIL_UPDATE_TIME,
commenter.optLong(UserExt.USER_UPDATE_TIME));
participant.put(Article.ARTICLE_T_PARTICIPANT_URL, commenter.optString(User.USER_URL));
participant.put(Keys.OBJECT_ID, commenter.optString(Keys.OBJECT_ID));
participant.put(Comment.COMMENT_T_ID, comment.optString(Keys.OBJECT_ID));
ret.add(participant);
}
return ret;
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Gets article [" + articleId + "] participants failed", e);
throw new ServiceException(e);
}
}
/**
* Processes the specified article content.
*
* <ul>
* <li>Generates @username home URL</li>
* <li>Markdowns</li>
* <li>Generates secured article content</li>
* <li>Blocks the article if need</li>
* <li>Generates emotion images</li>
* <li>Generates article link with article id</li>
* <li>Generates article abstract (preview content)</li>
* </ul>
*
* @param article the specified article, for example, <pre>
* {
* "articleTitle": "",
* ....,
* "author": {}
* }
* </pre>
*
* @param request the specified request
* @throws ServiceException service exception
*/
public void processArticleContent(final JSONObject article, final HttpServletRequest request)
throws ServiceException {
final JSONObject author = article.optJSONObject(Article.ARTICLE_T_AUTHOR);
if (null != author && UserExt.USER_STATUS_C_INVALID == author.optInt(UserExt.USER_STATUS)
|| Article.ARTICLE_STATUS_C_INVALID == article.optInt(Article.ARTICLE_STATUS)) {
article.put(Article.ARTICLE_TITLE, langPropsService.get("articleTitleBlockLabel"));
article.put(Article.ARTICLE_CONTENT, langPropsService.get("articleContentBlockLabel"));
article.put(Article.ARTICLE_T_PREVIEW_CONTENT, langPropsService.get("articleContentBlockLabel"));
article.put(Article.ARTICLE_REWARD_CONTENT, "");
article.put(Article.ARTICLE_REWARD_POINT, 0);
return;
}
String previewContent = getPreviewContent(article, request);
previewContent = Jsoup.parse(previewContent).text();
previewContent = previewContent.replaceAll("\"", "'");
article.put(Article.ARTICLE_T_PREVIEW_CONTENT, previewContent);
String articleContent = article.optString(Article.ARTICLE_CONTENT);
article.put(Common.DISCUSSION_VIEWABLE, true);
final Set<String> userNames = userQueryService.getUserNames(articleContent);
final JSONObject currentUser = userQueryService.getCurrentUser(request);
final String currentUserName = null == currentUser ? "" : currentUser.optString(User.USER_NAME);
final String currentRole = null == currentUser ? "" : currentUser.optString(User.USER_ROLE);
final String authorName = article.optString(Article.ARTICLE_T_AUTHOR_NAME);
if (Article.ARTICLE_TYPE_C_DISCUSSION == article.optInt(Article.ARTICLE_TYPE)
&& !authorName.equals(currentUserName) && !Role.ADMIN_ROLE.equals(currentRole)) {
boolean invited = false;
for (final String userName : userNames) {
if (userName.equals(currentUserName)) {
invited = true;
break;
}
}
if (!invited) {
String blockContent = langPropsService.get("articleDiscussionLabel");
blockContent = blockContent.replace("{user}", "<a href='" + Latkes.getServePath()
+ "/member/" + authorName + "'>" + authorName + "</a>");
article.put(Article.ARTICLE_CONTENT, blockContent);
article.put(Common.DISCUSSION_VIEWABLE, false);
article.put(Article.ARTICLE_REWARD_CONTENT, "");
article.put(Article.ARTICLE_REWARD_POINT, 0);
return;
}
}
for (final String userName : userNames) {
articleContent = articleContent.replace('@' + userName, "@<a href='" + Latkes.getServePath()
+ "/member/" + userName + "'>" + userName + "</a>");
}
articleContent = shortLinkQueryService.linkArticle(articleContent);
articleContent = shortLinkQueryService.linkTag(articleContent);
articleContent = Emotions.convert(articleContent);
article.put(Article.ARTICLE_CONTENT, articleContent);
if (article.optInt(Article.ARTICLE_REWARD_POINT) > 0) {
String articleRewardContent = article.optString(Article.ARTICLE_REWARD_CONTENT);
final Set<String> rewordContentUserNames = userQueryService.getUserNames(articleRewardContent);
for (final String userName : rewordContentUserNames) {
articleRewardContent = articleRewardContent.replace('@' + userName, "@<a href='" + Latkes.getServePath()
+ "/member/" + userName + "'>" + userName + "</a>");
}
articleRewardContent = Emotions.convert(articleRewardContent);
article.put(Article.ARTICLE_REWARD_CONTENT, articleRewardContent);
}
markdown(article);
}
/**
* Gets articles by the specified request json object.
*
* @param requestJSONObject the specified request json object, for example, <pre>
* {
* "oId": "", // optional
* "paginationCurrentPageNum": 1,
* "paginationPageSize": 20,
* "paginationWindowSize": 10
* }, see {@link Pagination} for more details
* </pre>
*
* @param articleFields the specified article fields to return
*
* @return for example, <pre>
* {
* "pagination": {
* "paginationPageCount": 100,
* "paginationPageNums": [1, 2, 3, 4, 5]
* },
* "articles": [{
* "oId": "",
* "articleTitle": "",
* "articleContent": "",
* ....
* }, ....]
* }
* </pre>
*
* @throws ServiceException service exception
* @see Pagination
*/
public JSONObject getArticles(final JSONObject requestJSONObject, final Map<String, Class<?>> articleFields) throws ServiceException {
final JSONObject ret = new JSONObject();
final int currentPageNum = requestJSONObject.optInt(Pagination.PAGINATION_CURRENT_PAGE_NUM);
final int pageSize = requestJSONObject.optInt(Pagination.PAGINATION_PAGE_SIZE);
final int windowSize = requestJSONObject.optInt(Pagination.PAGINATION_WINDOW_SIZE);
final Query query = new Query().setCurrentPageNum(currentPageNum).setPageSize(pageSize).
addSort(Article.ARTICLE_UPDATE_TIME, SortDirection.DESCENDING);
for (final Map.Entry<String, Class<?>> articleField : articleFields.entrySet()) {
query.addProjection(articleField.getKey(), articleField.getValue());
}
if (requestJSONObject.has(Keys.OBJECT_ID)) {
query.setFilter(new PropertyFilter(Keys.OBJECT_ID, FilterOperator.EQUAL, requestJSONObject.optString(Keys.OBJECT_ID)));
}
JSONObject result = null;
try {
result = articleRepository.get(query);
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Gets articles failed", e);
throw new ServiceException(e);
}
final int pageCount = result.optJSONObject(Pagination.PAGINATION).optInt(Pagination.PAGINATION_PAGE_COUNT);
final JSONObject pagination = new JSONObject();
ret.put(Pagination.PAGINATION, pagination);
final List<Integer> pageNums = Paginator.paginate(currentPageNum, pageSize, pageCount, windowSize);
pagination.put(Pagination.PAGINATION_PAGE_COUNT, pageCount);
pagination.put(Pagination.PAGINATION_PAGE_NUMS, pageNums);
final JSONArray data = result.optJSONArray(Keys.RESULTS);
final List<JSONObject> articles = CollectionUtils.<JSONObject>jsonArrayToList(data);
try {
organizeArticles(articles);
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Organizes articles failed", e);
throw new ServiceException(e);
}
ret.put(Article.ARTICLES, articles);
return ret;
}
/**
* Markdowns the specified article content.
*
* <ul>
* <li>Markdowns article content/reward content</li>
* <li>Generates secured article content/reward content</li>
* </ul>
*
* @param article the specified article content
*/
private void markdown(final JSONObject article) {
String content = article.optString(Article.ARTICLE_CONTENT);
final int articleType = article.optInt(Article.ARTICLE_TYPE);
if (Article.ARTICLE_TYPE_C_THOUGHT != articleType) {
content = Markdowns.toHTML(content);
content = Markdowns.clean(content, Latkes.getServePath() + article.optString(Article.ARTICLE_PERMALINK));
} else {
final Document.OutputSettings outputSettings = new Document.OutputSettings();
outputSettings.prettyPrint(false);
content = Jsoup.clean(content, Latkes.getServePath() + article.optString(Article.ARTICLE_PERMALINK),
Whitelist.relaxed().addAttributes(":all", "id", "target", "class").
addTags("span", "hr").addAttributes("iframe", "src", "width", "height")
.addAttributes("audio", "controls", "src"), outputSettings);
content = content.replace("\n", "\\n").replace("'", "\\'")
.replace("\"", "\\\"");
}
article.put(Article.ARTICLE_CONTENT, content);
if (article.optInt(Article.ARTICLE_REWARD_POINT) > 0) {
String rewardContent = article.optString(Article.ARTICLE_REWARD_CONTENT);
rewardContent = Markdowns.toHTML(rewardContent);
rewardContent = Markdowns.clean(rewardContent,
Latkes.getServePath() + article.optString(Article.ARTICLE_PERMALINK));
article.put(Article.ARTICLE_REWARD_CONTENT, rewardContent);
}
}
}
| src/main/java/org/b3log/symphony/service/ArticleQueryService.java | /*
* Copyright (c) 2012-2016, b3log.org & hacpai.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 org.b3log.symphony.service;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang.time.DateUtils;
import org.b3log.latke.Keys;
import org.b3log.latke.Latkes;
import org.b3log.latke.logging.Level;
import org.b3log.latke.logging.Logger;
import org.b3log.latke.model.Pagination;
import org.b3log.latke.model.Role;
import org.b3log.latke.model.User;
import org.b3log.latke.repository.CompositeFilter;
import org.b3log.latke.repository.CompositeFilterOperator;
import org.b3log.latke.repository.Filter;
import org.b3log.latke.repository.FilterOperator;
import org.b3log.latke.repository.PropertyFilter;
import org.b3log.latke.repository.Query;
import org.b3log.latke.repository.RepositoryException;
import org.b3log.latke.repository.SortDirection;
import org.b3log.latke.service.LangPropsService;
import org.b3log.latke.service.ServiceException;
import org.b3log.latke.service.annotation.Service;
import org.b3log.latke.util.CollectionUtils;
import org.b3log.latke.util.Paginator;
import org.b3log.latke.util.Strings;
import org.b3log.symphony.model.Article;
import org.b3log.symphony.model.Comment;
import org.b3log.symphony.model.Common;
import org.b3log.symphony.model.Tag;
import org.b3log.symphony.model.UserExt;
import org.b3log.symphony.processor.channel.ArticleChannel;
import org.b3log.symphony.repository.ArticleRepository;
import org.b3log.symphony.repository.CommentRepository;
import org.b3log.symphony.repository.DomainTagRepository;
import org.b3log.symphony.repository.TagArticleRepository;
import org.b3log.symphony.repository.TagRepository;
import org.b3log.symphony.repository.UserRepository;
import org.b3log.symphony.util.Emotions;
import org.b3log.symphony.util.Markdowns;
import org.b3log.symphony.util.Symphonys;
import org.b3log.symphony.util.Times;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.safety.Whitelist;
/**
* Article query service.
*
* @author <a href="http://88250.b3log.org">Liang Ding</a>
* @version 1.12.10.17, Mar 15, 2016
* @since 0.2.0
*/
@Service
public class ArticleQueryService {
/**
* Logger.
*/
private static final Logger LOGGER = Logger.getLogger(ArticleQueryService.class.getName());
/**
* Article repository.
*/
@Inject
private ArticleRepository articleRepository;
/**
* Comment repository.
*/
@Inject
private CommentRepository commentRepository;
/**
* Tag-Article repository.
*/
@Inject
private TagArticleRepository tagArticleRepository;
/**
* Tag repository.
*/
@Inject
private TagRepository tagRepository;
/**
* User repository.
*/
@Inject
private UserRepository userRepository;
/**
* Domain tag repository.
*/
@Inject
private DomainTagRepository domainTagRepository;
/**
* Comment query service.
*/
@Inject
private CommentQueryService commentQueryService;
/**
* User query service.
*/
@Inject
private UserQueryService userQueryService;
/**
* Avatar query service.
*/
@Inject
private AvatarQueryService avatarQueryService;
/**
* Short link query service.
*/
@Inject
private ShortLinkQueryService shortLinkQueryService;
/**
* Language service.
*/
@Inject
private LangPropsService langPropsService;
/**
* Count to fetch article tags for relevant articles.
*/
private static final int RELEVANT_ARTICLE_RANDOM_FETCH_TAG_CNT = 3;
/**
* Gets domain articles.
*
* @param domainId the specified domain id
* @param currentPageNum the specified current page number
* @param pageSize the specified page size
* @return result
* @throws ServiceException service exception
*/
public JSONObject getDomainArticles(final String domainId, final int currentPageNum, final int pageSize)
throws ServiceException {
final JSONObject ret = new JSONObject();
ret.put(Article.ARTICLES, (Object) Collections.emptyList());
final JSONObject pagination = new JSONObject();
ret.put(Pagination.PAGINATION, pagination);
pagination.put(Pagination.PAGINATION_PAGE_COUNT, 0);
pagination.put(Pagination.PAGINATION_PAGE_NUMS, (Object) Collections.emptyList());
try {
final JSONArray domainTags = domainTagRepository.getByDomainId(domainId, 1, Integer.MAX_VALUE)
.optJSONArray(Keys.RESULTS);
if (domainTags.length() <= 0) {
return ret;
}
final List<String> tagIds = new ArrayList<String>();
for (int i = 0; i < domainTags.length(); i++) {
tagIds.add(domainTags.optJSONObject(i).optString(Tag.TAG + "_" + Keys.OBJECT_ID));
}
Query query = new Query().setFilter(
new PropertyFilter(Tag.TAG + "_" + Keys.OBJECT_ID, FilterOperator.IN, tagIds)).
setCurrentPageNum(currentPageNum).setPageSize(pageSize).
addSort(Keys.OBJECT_ID, SortDirection.DESCENDING);
JSONObject result = tagArticleRepository.get(query);
final JSONArray tagArticles = result.optJSONArray(Keys.RESULTS);
if (tagArticles.length() <= 0) {
return ret;
}
final int pageCount = result.optJSONObject(Pagination.PAGINATION).optInt(Pagination.PAGINATION_PAGE_COUNT);
final int windowSize = Symphonys.getInt("latestArticlesWindowSize");
final List<Integer> pageNums = Paginator.paginate(currentPageNum, pageSize, pageCount, windowSize);
pagination.put(Pagination.PAGINATION_PAGE_COUNT, pageCount);
pagination.put(Pagination.PAGINATION_PAGE_NUMS, (Object) pageNums);
final Set<String> articleIds = new HashSet<String>();
for (int i = 0; i < tagArticles.length(); i++) {
articleIds.add(tagArticles.optJSONObject(i).optString(Article.ARTICLE + "_" + Keys.OBJECT_ID));
}
query = new Query().setFilter(CompositeFilterOperator.and(
new PropertyFilter(Keys.OBJECT_ID, FilterOperator.IN, articleIds),
new PropertyFilter(Article.ARTICLE_STATUS, FilterOperator.EQUAL, Article.ARTICLE_STATUS_C_VALID))).
setPageCount(1).addSort(Keys.OBJECT_ID, SortDirection.DESCENDING);
final List<JSONObject> articles
= CollectionUtils.<JSONObject>jsonArrayToList(articleRepository.get(query).optJSONArray(Keys.RESULTS));
try {
organizeArticles(articles);
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Organizes articles failed", e);
throw new ServiceException(e);
}
final Integer participantsCnt = Symphonys.getInt("latestArticleParticipantsCnt");
genParticipants(articles, participantsCnt);
ret.put(Article.ARTICLES, (Object) articles);
return ret;
} catch (final Exception e) {
LOGGER.log(Level.ERROR, "Gets domain articles error", e);
throw new ServiceException(e);
}
}
/**
* Gets the relevant articles of the specified article with the specified fetch size.
*
* <p>
* The relevant articles exist the same tag with the specified article.
* </p>
*
* @param article the specified article
* @param fetchSize the specified fetch size
* @return relevant articles, returns an empty list if not found
* @throws ServiceException service exception
*/
public List<JSONObject> getRelevantArticles(final JSONObject article, final int fetchSize) throws ServiceException {
final String tagsString = article.optString(Article.ARTICLE_TAGS);
final String[] tagTitles = tagsString.split(",");
final int tagTitlesLength = tagTitles.length;
final int subCnt = tagTitlesLength > RELEVANT_ARTICLE_RANDOM_FETCH_TAG_CNT
? RELEVANT_ARTICLE_RANDOM_FETCH_TAG_CNT : tagTitlesLength;
final List<Integer> tagIdx = CollectionUtils.getRandomIntegers(0, tagTitlesLength, subCnt);
final int subFetchSize = fetchSize / subCnt;
final Set<String> fetchedArticleIds = new HashSet<String>();
final List<JSONObject> ret = new ArrayList<JSONObject>();
try {
for (int i = 0; i < tagIdx.size(); i++) {
final String tagTitle = tagTitles[tagIdx.get(i)].trim();
final JSONObject tag = tagRepository.getByTitle(tagTitle);
final String tagId = tag.optString(Keys.OBJECT_ID);
JSONObject result = tagArticleRepository.getByTagId(tagId, 1, subFetchSize);
final JSONArray tagArticleRelations = result.optJSONArray(Keys.RESULTS);
final Set<String> articleIds = new HashSet<String>();
for (int j = 0; j < tagArticleRelations.length(); j++) {
final String articleId = tagArticleRelations.optJSONObject(j).optString(Article.ARTICLE + '_' + Keys.OBJECT_ID);
if (fetchedArticleIds.contains(articleId)) {
continue;
}
articleIds.add(articleId);
fetchedArticleIds.add(articleId);
}
articleIds.remove(article.optString(Keys.OBJECT_ID));
final Query query = new Query().setFilter(new PropertyFilter(Keys.OBJECT_ID, FilterOperator.IN, articleIds));
result = articleRepository.get(query);
ret.addAll(CollectionUtils.<JSONObject>jsonArrayToList(result.optJSONArray(Keys.RESULTS)));
}
organizeArticles(ret);
return ret;
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Gets relevant articles failed", e);
throw new ServiceException(e);
}
}
/**
* Gets broadcasts (articles permalink equals to "aBroadcast").
*
* @param currentPageNum the specified page number
* @param pageSize the specified page size
* @return articles, return an empty list if not found
* @throws ServiceException service exception
*/
public List<JSONObject> getBroadcasts(final int currentPageNum, final int pageSize) throws ServiceException {
try {
final Query query = new Query().setCurrentPageNum(currentPageNum).setPageSize(pageSize).setFilter(
new PropertyFilter(Article.ARTICLE_CLIENT_ARTICLE_ID, FilterOperator.EQUAL, "aBroadcast")).
addSort(Article.ARTICLE_CREATE_TIME, SortDirection.DESCENDING);
final JSONObject result = articleRepository.get(query);
final JSONArray articles = result.optJSONArray(Keys.RESULTS);
if (0 == articles.length()) {
return Collections.emptyList();
}
final List<JSONObject> ret = CollectionUtils.<JSONObject>jsonArrayToList(articles);
for (final JSONObject article : ret) {
article.put(Article.ARTICLE_PERMALINK, Latkes.getServePath() + article.optString(Article.ARTICLE_PERMALINK));
article.remove(Article.ARTICLE_CONTENT);
}
return ret;
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Gets broadcasts [currentPageNum=" + currentPageNum + ", pageSize=" + pageSize + "] failed", e);
throw new ServiceException(e);
}
}
/**
* Gets interest articles.
*
* @param currentPageNum the specified current page number
* @param pageSize the specified fetch size
* @param tagTitles the specified tag titles
* @return articles, return an empty list if not found
* @throws ServiceException service exception
*/
public List<JSONObject> getInterests(final int currentPageNum, final int pageSize, final String... tagTitles)
throws ServiceException {
try {
final List<JSONObject> tagList = new ArrayList<JSONObject>();
for (int i = 0; i < tagTitles.length; i++) {
final String tagTitle = tagTitles[i];
final JSONObject tag = tagRepository.getByTitle(tagTitle);
if (null == tag) {
continue;
}
tagList.add(tag);
}
final Map<String, Class<?>> articleFields = new HashMap<String, Class<?>>();
articleFields.put(Article.ARTICLE_TITLE, String.class);
articleFields.put(Article.ARTICLE_PERMALINK, String.class);
articleFields.put(Article.ARTICLE_CREATE_TIME, Long.class);
final List<JSONObject> ret = new ArrayList<JSONObject>();
if (!tagList.isEmpty()) {
final List<JSONObject> tagArticles
= getArticlesByTags(currentPageNum, pageSize, articleFields, tagList.toArray(new JSONObject[0]));
for (final JSONObject article : tagArticles) {
article.remove(Article.ARTICLE_T_PARTICIPANTS);
article.remove(Article.ARTICLE_T_PARTICIPANT_NAME);
article.remove(Article.ARTICLE_T_PARTICIPANT_THUMBNAIL_URL);
article.remove(Article.ARTICLE_LATEST_CMT_TIME);
article.remove(Article.ARTICLE_UPDATE_TIME);
article.remove(Article.ARTICLE_T_HEAT);
article.remove(Article.ARTICLE_T_TITLE_EMOJI);
article.remove(Common.TIME_AGO);
article.put(Article.ARTICLE_CREATE_TIME, ((Date) article.get(Article.ARTICLE_CREATE_TIME)).getTime());
}
ret.addAll(tagArticles);
}
final List<Filter> filters = new ArrayList<Filter>();
filters.add(new PropertyFilter(Article.ARTICLE_STATUS, FilterOperator.EQUAL, Article.ARTICLE_STATUS_C_VALID));
filters.add(new PropertyFilter(Article.ARTICLE_TYPE, FilterOperator.NOT_EQUAL, Article.ARTICLE_TYPE_C_DISCUSSION));
final Query query = new Query().addSort(Keys.OBJECT_ID, SortDirection.DESCENDING)
.setPageCount(currentPageNum).setPageSize(pageSize).setCurrentPageNum(1);
query.setFilter(new CompositeFilter(CompositeFilterOperator.AND, filters));
for (final Map.Entry<String, Class<?>> articleField : articleFields.entrySet()) {
query.addProjection(articleField.getKey(), articleField.getValue());
}
final JSONObject result = articleRepository.get(query);
final List<JSONObject> recentArticles = CollectionUtils.<JSONObject>jsonArrayToList(result.optJSONArray(Keys.RESULTS));
ret.addAll(recentArticles);
for (final JSONObject article : ret) {
article.put(Article.ARTICLE_PERMALINK, Latkes.getServePath() + article.optString(Article.ARTICLE_PERMALINK));
}
return ret;
} catch (final Exception e) {
LOGGER.log(Level.ERROR, "Gets interests failed", e);
throw new ServiceException(e);
}
}
/**
* Gets news (articles tags contains "B3log Announcement").
*
* @param currentPageNum the specified page number
* @param pageSize the specified page size
* @return articles, return an empty list if not found
* @throws ServiceException service exception
*/
public List<JSONObject> getNews(final int currentPageNum, final int pageSize) throws ServiceException {
try {
JSONObject oldAnnouncementTag = tagRepository.getByTitle("B3log Announcement");
JSONObject currentAnnouncementTag = tagRepository.getByTitle("B3log公告");
if (null == oldAnnouncementTag && null == currentAnnouncementTag) {
return Collections.emptyList();
}
if (null == oldAnnouncementTag) {
oldAnnouncementTag = new JSONObject();
}
if (null == currentAnnouncementTag) {
currentAnnouncementTag = new JSONObject();
}
Query query = new Query().addSort(Keys.OBJECT_ID, SortDirection.DESCENDING).
setFilter(CompositeFilterOperator.or(
new PropertyFilter(Tag.TAG + '_' + Keys.OBJECT_ID, FilterOperator.EQUAL,
oldAnnouncementTag.optString(Keys.OBJECT_ID)),
new PropertyFilter(Tag.TAG + '_' + Keys.OBJECT_ID, FilterOperator.EQUAL,
currentAnnouncementTag.optString(Keys.OBJECT_ID))
))
.setPageCount(1).setPageSize(pageSize).setCurrentPageNum(currentPageNum);
JSONObject result = tagArticleRepository.get(query);
final JSONArray tagArticleRelations = result.optJSONArray(Keys.RESULTS);
final Set<String> articleIds = new HashSet<String>();
for (int i = 0; i < tagArticleRelations.length(); i++) {
articleIds.add(tagArticleRelations.optJSONObject(i).optString(Article.ARTICLE + '_' + Keys.OBJECT_ID));
}
final JSONObject sa = userQueryService.getSA();
final List<Filter> subFilters = new ArrayList<Filter>();
subFilters.add(new PropertyFilter(Keys.OBJECT_ID, FilterOperator.IN, articleIds));
subFilters.add(new PropertyFilter(Article.ARTICLE_AUTHOR_EMAIL, FilterOperator.EQUAL, sa.optString(User.USER_EMAIL)));
query = new Query().setFilter(new CompositeFilter(CompositeFilterOperator.AND, subFilters))
.addProjection(Article.ARTICLE_TITLE, String.class).addProjection(Article.ARTICLE_PERMALINK, String.class)
.addProjection(Article.ARTICLE_CREATE_TIME, Long.class).addSort(Article.ARTICLE_CREATE_TIME, SortDirection.DESCENDING);
result = articleRepository.get(query);
final List<JSONObject> ret = CollectionUtils.<JSONObject>jsonArrayToList(result.optJSONArray(Keys.RESULTS));
for (final JSONObject article : ret) {
article.put(Article.ARTICLE_PERMALINK, Latkes.getServePath() + article.optString(Article.ARTICLE_PERMALINK));
}
return ret;
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Gets news failed", e);
throw new ServiceException(e);
}
}
/**
* Gets articles by the specified tags (order by article create date desc).
*
* @param tags the specified tags
* @param currentPageNum the specified page number
* @param articleFields the specified article fields to return
* @param pageSize the specified page size
* @return articles, return an empty list if not found
* @throws ServiceException service exception
*/
public List<JSONObject> getArticlesByTags(final int currentPageNum, final int pageSize,
final Map<String, Class<?>> articleFields, final JSONObject... tags) throws ServiceException {
try {
final List<Filter> filters = new ArrayList<Filter>();
for (final JSONObject tag : tags) {
filters.add(new PropertyFilter(Tag.TAG + '_' + Keys.OBJECT_ID, FilterOperator.EQUAL, tag.optString(Keys.OBJECT_ID)));
}
Filter filter;
if (filters.size() >= 2) {
filter = new CompositeFilter(CompositeFilterOperator.OR, filters);
} else {
filter = filters.get(0);
}
// XXX: 这里的分页是有问题的,后面取文章的时候会少(因为一篇文章可以有多个标签,但是文章 id 一样)
Query query = new Query().addSort(Keys.OBJECT_ID, SortDirection.DESCENDING).
setFilter(filter).setPageCount(1).setPageSize(pageSize).setCurrentPageNum(currentPageNum);
JSONObject result = tagArticleRepository.get(query);
final JSONArray tagArticleRelations = result.optJSONArray(Keys.RESULTS);
final Set<String> articleIds = new HashSet<String>();
for (int i = 0; i < tagArticleRelations.length(); i++) {
articleIds.add(tagArticleRelations.optJSONObject(i).optString(Article.ARTICLE + '_' + Keys.OBJECT_ID));
}
query = new Query().setFilter(new PropertyFilter(Keys.OBJECT_ID, FilterOperator.IN, articleIds)).
addSort(Keys.OBJECT_ID, SortDirection.DESCENDING);
for (final Map.Entry<String, Class<?>> articleField : articleFields.entrySet()) {
query.addProjection(articleField.getKey(), articleField.getValue());
}
result = articleRepository.get(query);
final List<JSONObject> ret = CollectionUtils.<JSONObject>jsonArrayToList(result.optJSONArray(Keys.RESULTS));
organizeArticles(ret);
final Integer participantsCnt = Symphonys.getInt("tagArticleParticipantsCnt");
genParticipants(ret, participantsCnt);
return ret;
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Gets articles by tags [tagLength=" + tags.length + "] failed", e);
throw new ServiceException(e);
}
}
/**
* Gets articles by the specified city (order by article create date desc).
*
* @param city the specified city
* @param currentPageNum the specified page number
* @param pageSize the specified page size
* @return articles, return an empty list if not found
* @throws ServiceException service exception
*/
public List<JSONObject> getArticlesByCity(final String city, final int currentPageNum, final int pageSize)
throws ServiceException {
try {
final Query query = new Query().addSort(Keys.OBJECT_ID, SortDirection.DESCENDING).
setFilter(new PropertyFilter(Article.ARTICLE_CITY, FilterOperator.EQUAL, city))
.setPageCount(1).setPageSize(pageSize).setCurrentPageNum(currentPageNum);
final JSONObject result = articleRepository.get(query);
final List<JSONObject> ret = CollectionUtils.<JSONObject>jsonArrayToList(result.optJSONArray(Keys.RESULTS));
organizeArticles(ret);
final Integer participantsCnt = Symphonys.getInt("cityArticleParticipantsCnt");
genParticipants(ret, participantsCnt);
return ret;
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Gets articles by city [" + city + "] failed", e);
throw new ServiceException(e);
}
}
/**
* Gets articles by the specified tag (order by article create date desc).
*
* @param tag the specified tag
* @param currentPageNum the specified page number
* @param pageSize the specified page size
* @return articles, return an empty list if not found
* @throws ServiceException service exception
*/
public List<JSONObject> getArticlesByTag(final JSONObject tag, final int currentPageNum, final int pageSize)
throws ServiceException {
try {
Query query = new Query().addSort(Keys.OBJECT_ID, SortDirection.DESCENDING).
setFilter(new PropertyFilter(Tag.TAG + '_' + Keys.OBJECT_ID, FilterOperator.EQUAL, tag.optString(Keys.OBJECT_ID)))
.setPageCount(1).setPageSize(pageSize).setCurrentPageNum(currentPageNum);
JSONObject result = tagArticleRepository.get(query);
final JSONArray tagArticleRelations = result.optJSONArray(Keys.RESULTS);
final Set<String> articleIds = new HashSet<String>();
for (int i = 0; i < tagArticleRelations.length(); i++) {
articleIds.add(tagArticleRelations.optJSONObject(i).optString(Article.ARTICLE + '_' + Keys.OBJECT_ID));
}
query = new Query().setFilter(new PropertyFilter(Keys.OBJECT_ID, FilterOperator.IN, articleIds)).
addSort(Keys.OBJECT_ID, SortDirection.DESCENDING);
result = articleRepository.get(query);
final List<JSONObject> ret = CollectionUtils.<JSONObject>jsonArrayToList(result.optJSONArray(Keys.RESULTS));
organizeArticles(ret);
final Integer participantsCnt = Symphonys.getInt("tagArticleParticipantsCnt");
genParticipants(ret, participantsCnt);
return ret;
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Gets articles by tag [tagTitle=" + tag.optString(Tag.TAG_TITLE) + "] failed", e);
throw new ServiceException(e);
}
}
/**
* Gets an article by the specified client article id.
*
* @param authorId the specified author id
* @param clientArticleId the specified client article id
* @return article, return {@code null} if not found
* @throws ServiceException service exception
*/
public JSONObject getArticleByClientArticleId(final String authorId, final String clientArticleId) throws ServiceException {
final List<Filter> filters = new ArrayList<Filter>();
filters.add(new PropertyFilter(Article.ARTICLE_CLIENT_ARTICLE_ID, FilterOperator.EQUAL, clientArticleId));
filters.add(new PropertyFilter(Article.ARTICLE_AUTHOR_ID, FilterOperator.EQUAL, authorId));
final Query query = new Query().setFilter(new CompositeFilter(CompositeFilterOperator.AND, filters));
try {
final JSONObject result = articleRepository.get(query);
final JSONArray array = result.optJSONArray(Keys.RESULTS);
if (0 == array.length()) {
return null;
}
return array.optJSONObject(0);
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Gets article [clientArticleId=" + clientArticleId + "] failed", e);
throw new ServiceException(e);
}
}
/**
* Gets an article with {@link #organizeArticle(org.json.JSONObject)} by the specified id.
*
* @param articleId the specified id
* @return article, return {@code null} if not found
* @throws ServiceException service exception
*/
public JSONObject getArticleById(final String articleId) throws ServiceException {
try {
final JSONObject ret = articleRepository.get(articleId);
if (null == ret) {
return null;
}
organizeArticle(ret);
return ret;
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Gets an article [articleId=" + articleId + "] failed", e);
throw new ServiceException(e);
}
}
/**
* Gets an article by the specified id.
*
* @param articleId the specified id
* @return article, return {@code null} if not found
* @throws ServiceException service exception
*/
public JSONObject getArticle(final String articleId) throws ServiceException {
try {
final JSONObject ret = articleRepository.get(articleId);
if (null == ret) {
return null;
}
return ret;
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Gets an article [articleId=" + articleId + "] failed", e);
throw new ServiceException(e);
}
}
/**
* Gets preview content of the article specified with the given article id.
*
* @param articleId the given article id
* @param request the specified request
* @return preview content
* @throws ServiceException service exception
*/
public String getArticlePreviewContent(final String articleId, final HttpServletRequest request) throws ServiceException {
final JSONObject article = getArticle(articleId);
if (null == article) {
return null;
}
return getPreviewContent(article, request);
}
private String getPreviewContent(final JSONObject article, final HttpServletRequest request) throws ServiceException {
final int length = Integer.valueOf("150");
String ret = article.optString(Article.ARTICLE_CONTENT);
final String authorId = article.optString(Article.ARTICLE_AUTHOR_ID);
final JSONObject author = userQueryService.getUser(authorId);
if (null != author && UserExt.USER_STATUS_C_INVALID == author.optInt(UserExt.USER_STATUS)
|| Article.ARTICLE_STATUS_C_INVALID == article.optInt(Article.ARTICLE_STATUS)) {
return langPropsService.get("articleContentBlockLabel");
}
final Set<String> userNames = userQueryService.getUserNames(ret);
final JSONObject currentUser = userQueryService.getCurrentUser(request);
final String currentUserName = null == currentUser ? "" : currentUser.optString(User.USER_NAME);
final String authorName = author.optString(User.USER_NAME);
if (Article.ARTICLE_TYPE_C_DISCUSSION == article.optInt(Article.ARTICLE_TYPE)
&& !authorName.equals(currentUserName)) {
boolean invited = false;
for (final String userName : userNames) {
if (userName.equals(currentUserName)) {
invited = true;
break;
}
}
if (!invited) {
String blockContent = langPropsService.get("articleDiscussionLabel");
blockContent = blockContent.replace("{user}", "<a href='" + Latkes.getServePath()
+ "/member/" + authorName + "'>" + authorName + "</a>");
return blockContent;
}
}
ret = Emotions.convert(ret);
ret = Markdowns.toHTML(ret);
ret = Jsoup.clean(ret, Whitelist.none());
if (ret.length() >= length) {
ret = StringUtils.substring(ret, 0, length)
+ " ....";
}
return ret;
}
/**
* Gets the user articles with the specified user id, page number and page size.
*
* @param userId the specified user id
* @param currentPageNum the specified page number
* @param pageSize the specified page size
* @return user articles, return an empty list if not found
* @throws ServiceException service exception
*/
public List<JSONObject> getUserArticles(final String userId, final int currentPageNum, final int pageSize) throws ServiceException {
final Query query = new Query().addSort(Article.ARTICLE_CREATE_TIME, SortDirection.DESCENDING)
.setCurrentPageNum(currentPageNum).setPageSize(pageSize).
setFilter(CompositeFilterOperator.and(
new PropertyFilter(Article.ARTICLE_AUTHOR_ID, FilterOperator.EQUAL, userId),
new PropertyFilter(Article.ARTICLE_STATUS, FilterOperator.EQUAL, Article.ARTICLE_STATUS_C_VALID)));
try {
final JSONObject result = articleRepository.get(query);
final List<JSONObject> ret = CollectionUtils.<JSONObject>jsonArrayToList(result.optJSONArray(Keys.RESULTS));
organizeArticles(ret);
return ret;
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Gets user articles failed", e);
throw new ServiceException(e);
}
}
/**
* Gets hot articles with the specified fetch size.
*
* @param fetchSize the specified fetch size
* @return recent articles, returns an empty list if not found
* @throws ServiceException service exception
*/
public List<JSONObject> getHotArticles(final int fetchSize) throws ServiceException {
final String id = String.valueOf(DateUtils.addDays(new Date(), -15).getTime());
try {
final Query query = new Query().addSort(Article.ARTICLE_COMMENT_CNT, SortDirection.DESCENDING).
addSort(Keys.OBJECT_ID, SortDirection.ASCENDING).setCurrentPageNum(1).setPageSize(fetchSize);
final List<Filter> filters = new ArrayList<Filter>();
filters.add(new PropertyFilter(Keys.OBJECT_ID, FilterOperator.GREATER_THAN_OR_EQUAL, id));
filters.add(new PropertyFilter(Article.ARTICLE_TYPE, FilterOperator.NOT_EQUAL, Article.ARTICLE_TYPE_C_DISCUSSION));
query.setFilter(new CompositeFilter(CompositeFilterOperator.AND, filters));
final JSONObject result = articleRepository.get(query);
final List<JSONObject> ret = CollectionUtils.<JSONObject>jsonArrayToList(result.optJSONArray(Keys.RESULTS));
organizeArticles(ret);
return ret;
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Gets hot articles failed", e);
throw new ServiceException(e);
}
}
/**
* Gets the random articles with the specified fetch size.
*
* @param fetchSize the specified fetch size
* @return random articles, returns an empty list if not found
* @throws ServiceException service exception
*/
public List<JSONObject> getRandomArticles(final int fetchSize) throws ServiceException {
try {
final List<JSONObject> ret = articleRepository.getRandomly(fetchSize);
organizeArticles(ret);
return ret;
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Gets random articles failed", e);
throw new ServiceException(e);
}
}
/**
* Makes article showing filters.
*
* @return filter the article showing to user
*/
private CompositeFilter makeArticleShowingFilter() {
final List<Filter> filters = new ArrayList<Filter>();
filters.add(new PropertyFilter(Article.ARTICLE_STATUS, FilterOperator.EQUAL, Article.ARTICLE_STATUS_C_VALID));
filters.add(new PropertyFilter(Article.ARTICLE_TYPE, FilterOperator.NOT_EQUAL, Article.ARTICLE_TYPE_C_DISCUSSION));
return new CompositeFilter(CompositeFilterOperator.AND, filters);
}
/**
* Makes the recent (sort by create time) articles with the specified fetch size.
*
* @param currentPageNum the specified current page number
* @param fetchSize the specified fetch size
* @return recent articles query
*/
private Query makeRecentQuery(final int currentPageNum, final int fetchSize) {
final Query query = new Query()
.addSort(Keys.OBJECT_ID, SortDirection.DESCENDING)
.setPageSize(fetchSize).setCurrentPageNum(currentPageNum);
query.setFilter(makeArticleShowingFilter());
return query;
}
/**
* Makes the top articles with the specified fetch size.
*
* @param currentPageNum the specified current page number
* @param fetchSize the specified fetch size
* @return top articles query
*/
private Query makeTopQuery(final int currentPageNum, final int fetchSize) {
final Query query = new Query()
.addSort(Article.REDDIT_SCORE, SortDirection.DESCENDING)
.addSort(Article.ARTICLE_LATEST_CMT_TIME, SortDirection.DESCENDING)
.setPageCount(1).setPageSize(fetchSize).setCurrentPageNum(currentPageNum);
query.setFilter(makeArticleShowingFilter());
return query;
}
/**
* Gets the recent (sort by create time) articles with the specified fetch size.
*
* @param currentPageNum the specified current page number
* @param fetchSize the specified fetch size
* @return for example, <pre>
* {
* "pagination": {
* "paginationPageCount": 100,
* "paginationPageNums": [1, 2, 3, 4, 5]
* },
* "articles": [{
* "oId": "",
* "articleTitle": "",
* "articleContent": "",
* ....
* }, ....]
* }
* </pre>
*
* @throws ServiceException service exception
*/
public JSONObject getRecentArticles(final int currentPageNum, final int fetchSize) throws ServiceException {
final JSONObject ret = new JSONObject();
final Query query = makeRecentQuery(currentPageNum, fetchSize);
JSONObject result = null;
try {
result = articleRepository.get(query);
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Gets articles failed", e);
throw new ServiceException(e);
}
final int pageCount = result.optJSONObject(Pagination.PAGINATION).optInt(Pagination.PAGINATION_PAGE_COUNT);
final JSONObject pagination = new JSONObject();
ret.put(Pagination.PAGINATION, pagination);
final int windowSize = Symphonys.getInt("latestArticlesWindowSize");
final List<Integer> pageNums = Paginator.paginate(currentPageNum, fetchSize, pageCount, windowSize);
pagination.put(Pagination.PAGINATION_PAGE_COUNT, pageCount);
pagination.put(Pagination.PAGINATION_PAGE_NUMS, (Object) pageNums);
final JSONArray data = result.optJSONArray(Keys.RESULTS);
final List<JSONObject> articles = CollectionUtils.<JSONObject>jsonArrayToList(data);
try {
organizeArticles(articles);
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Organizes articles failed", e);
throw new ServiceException(e);
}
final Integer participantsCnt = Symphonys.getInt("latestArticleParticipantsCnt");
genParticipants(articles, participantsCnt);
ret.put(Article.ARTICLES, (Object) articles);
return ret;
}
/**
* Gets the index articles with the specified fetch size.
*
* @param fetchSize the specified fetch size
* @return recent articles, returns an empty list if not found
* @throws ServiceException service exception
*/
public List<JSONObject> getIndexArticles(final int fetchSize) throws ServiceException {
final Query query = makeTopQuery(1, fetchSize);
try {
final JSONObject result = articleRepository.get(query);
final List<JSONObject> ret = CollectionUtils.<JSONObject>jsonArrayToList(result.optJSONArray(Keys.RESULTS));
organizeArticles(ret);
for (final JSONObject article : ret) {
final String authorId = article.optString(Article.ARTICLE_AUTHOR_ID);
final JSONObject author = userRepository.get(authorId);
if (UserExt.USER_STATUS_C_INVALID == author.optInt(UserExt.USER_STATUS)) {
article.put(Article.ARTICLE_TITLE, langPropsService.get("articleTitleBlockLabel"));
}
}
final Integer participantsCnt = Symphonys.getInt("indexArticleParticipantsCnt");
genParticipants(ret, participantsCnt);
return ret;
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Gets index articles failed", e);
throw new ServiceException(e);
}
}
/**
* Gets the recent articles with the specified fetch size.
*
* @param currentPageNum the specified current page number
* @param fetchSize the specified fetch size
* @return recent articles, returns an empty list if not found
* @throws ServiceException service exception
*/
public List<JSONObject> getRecentArticlesWithComments(final int currentPageNum, final int fetchSize) throws ServiceException {
return getArticles(makeRecentQuery(currentPageNum, fetchSize));
}
/**
* Gets the index articles with the specified fetch size.
*
* @param currentPageNum the specified current page number
* @param fetchSize the specified fetch size
* @return recent articles, returns an empty list if not found
* @throws ServiceException service exception
*/
public List<JSONObject> getTopArticlesWithComments(final int currentPageNum, final int fetchSize) throws ServiceException {
return getArticles(makeTopQuery(currentPageNum, fetchSize));
}
/**
* The specific articles.
*
* @param query conditions
* @return articles
* @throws ServiceException service exception
*/
private List<JSONObject> getArticles(final Query query) throws ServiceException {
try {
final JSONObject result = articleRepository.get(query);
final List<JSONObject> ret = CollectionUtils.<JSONObject>jsonArrayToList(result.optJSONArray(Keys.RESULTS));
organizeArticles(ret);
final List<JSONObject> stories = new ArrayList<JSONObject>();
for (final JSONObject article : ret) {
final JSONObject story = new JSONObject();
final String authorId = article.optString(Article.ARTICLE_AUTHOR_ID);
final JSONObject author = userRepository.get(authorId);
if (UserExt.USER_STATUS_C_INVALID == author.optInt(UserExt.USER_STATUS)) {
story.put("title", langPropsService.get("articleTitleBlockLabel"));
} else {
story.put("title", article.optString(Article.ARTICLE_TITLE));
}
story.put("id", article.optLong("oId"));
story.put("url", Latkes.getServePath() + article.optString(Article.ARTICLE_PERMALINK));
story.put("user_display_name", article.optString(Article.ARTICLE_T_AUTHOR_NAME));
story.put("user_job", author.optString(UserExt.USER_INTRO));
story.put("comment_html", article.optString(Article.ARTICLE_CONTENT));
story.put("comment_count", article.optInt(Article.ARTICLE_COMMENT_CNT));
story.put("vote_count", article.optInt(Article.ARTICLE_GOOD_CNT));
story.put("created_at", formatDate(article.get(Article.ARTICLE_CREATE_TIME)));
story.put("user_portrait_url", article.optString(Article.ARTICLE_T_AUTHOR_THUMBNAIL_URL));
story.put("comments", getAllComments(article.optString("oId")));
final String tagsString = article.optString(Article.ARTICLE_TAGS);
String[] tags = null;
if (!Strings.isEmptyOrNull(tagsString)) {
tags = tagsString.split(",");
}
story.put("badge", tags == null ? "" : tags[0]);
stories.add(story);
}
final Integer participantsCnt = Symphonys.getInt("indexArticleParticipantsCnt");
genParticipants(stories, participantsCnt);
return stories;
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Gets index articles failed", e);
throw new ServiceException(e);
} catch (final JSONException ex) {
LOGGER.log(Level.ERROR, "Gets index articles failed", ex);
throw new ServiceException(ex);
}
}
/**
* Gets the article comments with the specified article id.
*
* @param articleId the specified article id
* @return comments, return an empty list if not found
* @throws ServiceException service exception
* @throws JSONException json exception
* @throws RepositoryException repository exception
*/
private List<JSONObject> getAllComments(final String articleId) throws ServiceException, JSONException, RepositoryException {
final List<JSONObject> commments = new ArrayList<JSONObject>();
final List<JSONObject> articleComments = commentQueryService.getArticleComments(articleId, 1, Integer.MAX_VALUE);
for (final JSONObject ac : articleComments) {
final JSONObject comment = new JSONObject();
final JSONObject author = userRepository.get(ac.optString(Comment.COMMENT_AUTHOR_ID));
comment.put("id", ac.optLong("oId"));
comment.put("body_html", ac.optString(Comment.COMMENT_CONTENT));
comment.put("depth", 0);
comment.put("user_display_name", ac.optString(Comment.COMMENT_T_AUTHOR_NAME));
comment.put("user_job", author.optString(UserExt.USER_INTRO));
comment.put("vote_count", 0);
comment.put("created_at", formatDate(ac.get(Comment.COMMENT_CREATE_TIME)));
comment.put("user_portrait_url", ac.optString(Comment.COMMENT_T_ARTICLE_AUTHOR_THUMBNAIL_URL));
commments.add(comment);
}
return commments;
}
/**
* The demand format date.
*
* @param date the original date
* @return the format date like "2015-08-03T07:26:57Z"
*/
private String formatDate(final Object date) {
return DateFormatUtils.format(((Date) date).getTime(), "yyyy-MM-dd")
+ "T" + DateFormatUtils.format(((Date) date).getTime(), "HH:mm:ss") + "Z";
}
/**
* Organizes the specified articles.
*
* <ul>
* <li>converts create/update/latest comment time (long) to date type</li>
* <li>generates author thumbnail URL</li>
* <li>generates author name</li>
* <li>escapes article title < and ></li>
* <li>generates article heat</li>
* <li>generates article view count display format(1k+/1.5k+...)</li>
* <li>generates time ago text</li>
* </ul>
*
* @param articles the specified articles
* @throws RepositoryException repository exception
*/
public void organizeArticles(final List<JSONObject> articles) throws RepositoryException {
for (final JSONObject article : articles) {
organizeArticle(article);
}
}
/**
* Organizes the specified article.
*
* <ul>
* <li>converts create/update/latest comment time (long) to date type</li>
* <li>generates author thumbnail URL</li>
* <li>generates author name</li>
* <li>escapes article title < and ></li>
* <li>generates article heat</li>
* <li>generates article view count display format(1k+/1.5k+...)</li>
* <li>generates time ago text</li>
* </ul>
*
* @param article the specified article
* @throws RepositoryException repository exception
*/
public void organizeArticle(final JSONObject article) throws RepositoryException {
toArticleDate(article);
genArticleAuthor(article);
String title = article.optString(Article.ARTICLE_TITLE).replace("<", "<").replace(">", ">");
title = Markdowns.clean(title, "");
article.put(Article.ARTICLE_TITLE, title);
article.put(Article.ARTICLE_T_TITLE_EMOJI, Emotions.convert(title));
if (Article.ARTICLE_STATUS_C_INVALID == article.optInt(Article.ARTICLE_STATUS)) {
article.put(Article.ARTICLE_TITLE, langPropsService.get("articleTitleBlockLabel"));
article.put(Article.ARTICLE_T_TITLE_EMOJI, langPropsService.get("articleTitleBlockLabel"));
article.put(Article.ARTICLE_CONTENT, langPropsService.get("articleContentBlockLabel"));
}
final String articleId = article.optString(Keys.OBJECT_ID);
Integer viewingCnt = ArticleChannel.ARTICLE_VIEWS.get(articleId);
if (null == viewingCnt) {
viewingCnt = 0;
}
article.put(Article.ARTICLE_T_HEAT, viewingCnt);
final int viewCnt = article.optInt(Article.ARTICLE_VIEW_CNT);
final double views = (double) viewCnt / 1000;
if (views >= 1) {
final DecimalFormat df = new DecimalFormat("#.#");
article.put(Article.ARTICLE_T_VIEW_CNT_DISPLAY_FORMAT, df.format(views) + "K");
}
}
/**
* Converts the specified article create/update/latest comment time (long) to date type.
*
* @param article the specified article
*/
private void toArticleDate(final JSONObject article) {
article.put(Common.TIME_AGO, Times.getTimeAgo(article.optLong(Article.ARTICLE_CREATE_TIME), Latkes.getLocale()));
article.put(Article.ARTICLE_CREATE_TIME, new Date(article.optLong(Article.ARTICLE_CREATE_TIME)));
article.put(Article.ARTICLE_UPDATE_TIME, new Date(article.optLong(Article.ARTICLE_UPDATE_TIME)));
article.put(Article.ARTICLE_LATEST_CMT_TIME, new Date(article.optLong(Article.ARTICLE_LATEST_CMT_TIME)));
}
/**
* Generates the specified article author name and thumbnail URL.
*
* @param article the specified article
* @throws RepositoryException repository exception
*/
private void genArticleAuthor(final JSONObject article) throws RepositoryException {
final String authorId = article.optString(Article.ARTICLE_AUTHOR_ID);
if (Strings.isEmptyOrNull(authorId)) {
return;
}
final JSONObject author = userRepository.get(authorId);
article.put(Article.ARTICLE_T_AUTHOR_THUMBNAIL_URL, avatarQueryService.getAvatarURLByUser(author));
article.put(Article.ARTICLE_T_AUTHOR, author);
article.put(Article.ARTICLE_T_AUTHOR_NAME, author.optString(User.USER_NAME));
}
/**
* Generates participants for the specified articles.
*
* @param articles the specified articles
* @param participantsCnt the specified generate size
* @throws ServiceException service exception
*/
private void genParticipants(final List<JSONObject> articles, final Integer participantsCnt) throws ServiceException {
for (final JSONObject article : articles) {
final String participantName = "";
final String participantThumbnailURL = "";
final List<JSONObject> articleParticipants
= getArticleLatestParticipants(article.optString(Keys.OBJECT_ID), participantsCnt);
article.put(Article.ARTICLE_T_PARTICIPANTS, (Object) articleParticipants);
article.put(Article.ARTICLE_T_PARTICIPANT_NAME, participantName);
article.put(Article.ARTICLE_T_PARTICIPANT_THUMBNAIL_URL, participantThumbnailURL);
}
}
/**
* Gets the article participants (commenters) with the specified article article id and fetch size.
*
* @param articleId the specified article id
* @param fetchSize the specified fetch size
* @return article participants, for example, <pre>
* [
* {
* "oId": "",
* "articleParticipantName": "",
* "articleParticipantThumbnailURL": "",
* "articleParticipantThumbnailUpdateTime": long,
* "commentId": ""
* }, ....
* ]
* </pre>, returns an empty list if not found
*
* @throws ServiceException service exception
*/
public List<JSONObject> getArticleLatestParticipants(final String articleId, final int fetchSize) throws ServiceException {
final Query query = new Query().addSort(Keys.OBJECT_ID, SortDirection.DESCENDING)
.setFilter(new PropertyFilter(Comment.COMMENT_ON_ARTICLE_ID, FilterOperator.EQUAL, articleId))
.addProjection(Comment.COMMENT_AUTHOR_EMAIL, String.class)
.addProjection(Keys.OBJECT_ID, String.class)
.addProjection(Comment.COMMENT_AUTHOR_ID, String.class)
.setPageCount(1).setCurrentPageNum(1).setPageSize(fetchSize);
final List<JSONObject> ret = new ArrayList<JSONObject>();
try {
final JSONObject result = commentRepository.get(query);
final List<JSONObject> comments = CollectionUtils.<JSONObject>jsonArrayToList(result.optJSONArray(Keys.RESULTS));
for (final JSONObject comment : comments) {
final String email = comment.optString(Comment.COMMENT_AUTHOR_EMAIL);
final String userId = comment.optString(Comment.COMMENT_AUTHOR_ID);
final JSONObject commenter = userRepository.get(userId);
String thumbnailURL = Symphonys.get("defaultThumbnailURL");
if (!UserExt.DEFAULT_CMTER_EMAIL.equals(email)) {
thumbnailURL = avatarQueryService.getAvatarURLByUser(commenter);
}
final JSONObject participant = new JSONObject();
participant.put(Article.ARTICLE_T_PARTICIPANT_NAME, commenter.optString(User.USER_NAME));
participant.put(Article.ARTICLE_T_PARTICIPANT_THUMBNAIL_URL, thumbnailURL);
participant.put(Article.ARTICLE_T_PARTICIPANT_THUMBNAIL_UPDATE_TIME,
commenter.optLong(UserExt.USER_UPDATE_TIME));
participant.put(Article.ARTICLE_T_PARTICIPANT_URL, commenter.optString(User.USER_URL));
participant.put(Keys.OBJECT_ID, commenter.optString(Keys.OBJECT_ID));
participant.put(Comment.COMMENT_T_ID, comment.optString(Keys.OBJECT_ID));
ret.add(participant);
}
return ret;
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Gets article [" + articleId + "] participants failed", e);
throw new ServiceException(e);
}
}
/**
* Processes the specified article content.
*
* <ul>
* <li>Generates @username home URL</li>
* <li>Markdowns</li>
* <li>Generates secured article content</li>
* <li>Blocks the article if need</li>
* <li>Generates emotion images</li>
* <li>Generates article link with article id</li>
* <li>Generates article abstract (preview content)</li>
* </ul>
*
* @param article the specified article, for example, <pre>
* {
* "articleTitle": "",
* ....,
* "author": {}
* }
* </pre>
*
* @param request the specified request
* @throws ServiceException service exception
*/
public void processArticleContent(final JSONObject article, final HttpServletRequest request)
throws ServiceException {
final JSONObject author = article.optJSONObject(Article.ARTICLE_T_AUTHOR);
if (null != author && UserExt.USER_STATUS_C_INVALID == author.optInt(UserExt.USER_STATUS)
|| Article.ARTICLE_STATUS_C_INVALID == article.optInt(Article.ARTICLE_STATUS)) {
article.put(Article.ARTICLE_TITLE, langPropsService.get("articleTitleBlockLabel"));
article.put(Article.ARTICLE_CONTENT, langPropsService.get("articleContentBlockLabel"));
article.put(Article.ARTICLE_T_PREVIEW_CONTENT, langPropsService.get("articleContentBlockLabel"));
article.put(Article.ARTICLE_REWARD_CONTENT, "");
article.put(Article.ARTICLE_REWARD_POINT, 0);
return;
}
String previewContent = getPreviewContent(article, request);
previewContent = Jsoup.parse(previewContent).text();
previewContent = previewContent.replaceAll("\"", "'");
article.put(Article.ARTICLE_T_PREVIEW_CONTENT, previewContent);
String articleContent = article.optString(Article.ARTICLE_CONTENT);
article.put(Common.DISCUSSION_VIEWABLE, true);
final Set<String> userNames = userQueryService.getUserNames(articleContent);
final JSONObject currentUser = userQueryService.getCurrentUser(request);
final String currentUserName = null == currentUser ? "" : currentUser.optString(User.USER_NAME);
final String currentRole = null == currentUser ? "" : currentUser.optString(User.USER_ROLE);
final String authorName = article.optString(Article.ARTICLE_T_AUTHOR_NAME);
if (Article.ARTICLE_TYPE_C_DISCUSSION == article.optInt(Article.ARTICLE_TYPE)
&& !authorName.equals(currentUserName) && !Role.ADMIN_ROLE.equals(currentRole)) {
boolean invited = false;
for (final String userName : userNames) {
if (userName.equals(currentUserName)) {
invited = true;
break;
}
}
if (!invited) {
String blockContent = langPropsService.get("articleDiscussionLabel");
blockContent = blockContent.replace("{user}", "<a href='" + Latkes.getServePath()
+ "/member/" + authorName + "'>" + authorName + "</a>");
article.put(Article.ARTICLE_CONTENT, blockContent);
article.put(Common.DISCUSSION_VIEWABLE, false);
article.put(Article.ARTICLE_REWARD_CONTENT, "");
article.put(Article.ARTICLE_REWARD_POINT, 0);
return;
}
}
for (final String userName : userNames) {
articleContent = articleContent.replace('@' + userName, "@<a href='" + Latkes.getServePath()
+ "/member/" + userName + "'>" + userName + "</a>");
}
articleContent = shortLinkQueryService.linkArticle(articleContent);
articleContent = shortLinkQueryService.linkTag(articleContent);
articleContent = Emotions.convert(articleContent);
article.put(Article.ARTICLE_CONTENT, articleContent);
if (article.optInt(Article.ARTICLE_REWARD_POINT) > 0) {
String articleRewardContent = article.optString(Article.ARTICLE_REWARD_CONTENT);
final Set<String> rewordContentUserNames = userQueryService.getUserNames(articleRewardContent);
for (final String userName : rewordContentUserNames) {
articleRewardContent = articleRewardContent.replace('@' + userName, "@<a href='" + Latkes.getServePath()
+ "/member/" + userName + "'>" + userName + "</a>");
}
articleRewardContent = Emotions.convert(articleRewardContent);
article.put(Article.ARTICLE_REWARD_CONTENT, articleRewardContent);
}
markdown(article);
}
/**
* Gets articles by the specified request json object.
*
* @param requestJSONObject the specified request json object, for example, <pre>
* {
* "oId": "", // optional
* "paginationCurrentPageNum": 1,
* "paginationPageSize": 20,
* "paginationWindowSize": 10
* }, see {@link Pagination} for more details
* </pre>
*
* @param articleFields the specified article fields to return
*
* @return for example, <pre>
* {
* "pagination": {
* "paginationPageCount": 100,
* "paginationPageNums": [1, 2, 3, 4, 5]
* },
* "articles": [{
* "oId": "",
* "articleTitle": "",
* "articleContent": "",
* ....
* }, ....]
* }
* </pre>
*
* @throws ServiceException service exception
* @see Pagination
*/
public JSONObject getArticles(final JSONObject requestJSONObject, final Map<String, Class<?>> articleFields) throws ServiceException {
final JSONObject ret = new JSONObject();
final int currentPageNum = requestJSONObject.optInt(Pagination.PAGINATION_CURRENT_PAGE_NUM);
final int pageSize = requestJSONObject.optInt(Pagination.PAGINATION_PAGE_SIZE);
final int windowSize = requestJSONObject.optInt(Pagination.PAGINATION_WINDOW_SIZE);
final Query query = new Query().setCurrentPageNum(currentPageNum).setPageSize(pageSize).
addSort(Article.ARTICLE_UPDATE_TIME, SortDirection.DESCENDING);
for (final Map.Entry<String, Class<?>> articleField : articleFields.entrySet()) {
query.addProjection(articleField.getKey(), articleField.getValue());
}
if (requestJSONObject.has(Keys.OBJECT_ID)) {
query.setFilter(new PropertyFilter(Keys.OBJECT_ID, FilterOperator.EQUAL, requestJSONObject.optString(Keys.OBJECT_ID)));
}
JSONObject result = null;
try {
result = articleRepository.get(query);
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Gets articles failed", e);
throw new ServiceException(e);
}
final int pageCount = result.optJSONObject(Pagination.PAGINATION).optInt(Pagination.PAGINATION_PAGE_COUNT);
final JSONObject pagination = new JSONObject();
ret.put(Pagination.PAGINATION, pagination);
final List<Integer> pageNums = Paginator.paginate(currentPageNum, pageSize, pageCount, windowSize);
pagination.put(Pagination.PAGINATION_PAGE_COUNT, pageCount);
pagination.put(Pagination.PAGINATION_PAGE_NUMS, pageNums);
final JSONArray data = result.optJSONArray(Keys.RESULTS);
final List<JSONObject> articles = CollectionUtils.<JSONObject>jsonArrayToList(data);
try {
organizeArticles(articles);
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Organizes articles failed", e);
throw new ServiceException(e);
}
ret.put(Article.ARTICLES, articles);
return ret;
}
/**
* Markdowns the specified article content.
*
* <ul>
* <li>Markdowns article content/reward content</li>
* <li>Generates secured article content/reward content</li>
* </ul>
*
* @param article the specified article content
*/
private void markdown(final JSONObject article) {
String content = article.optString(Article.ARTICLE_CONTENT);
final int articleType = article.optInt(Article.ARTICLE_TYPE);
if (Article.ARTICLE_TYPE_C_THOUGHT != articleType) {
content = Markdowns.toHTML(content);
content = Markdowns.clean(content, Latkes.getServePath() + article.optString(Article.ARTICLE_PERMALINK));
} else {
final Document.OutputSettings outputSettings = new Document.OutputSettings();
outputSettings.prettyPrint(false);
content = Jsoup.clean(content, Latkes.getServePath() + article.optString(Article.ARTICLE_PERMALINK),
Whitelist.relaxed().addAttributes(":all", "id", "target", "class").
addTags("span", "hr").addAttributes("iframe", "src", "width", "height")
.addAttributes("audio", "controls", "src"), outputSettings);
content = content.replace("\n", "\\n").replace("'", "\\'")
.replace("\"", "\\\"");
}
article.put(Article.ARTICLE_CONTENT, content);
if (article.optInt(Article.ARTICLE_REWARD_POINT) > 0) {
String rewardContent = article.optString(Article.ARTICLE_REWARD_CONTENT);
rewardContent = Markdowns.toHTML(rewardContent);
rewardContent = Markdowns.clean(rewardContent,
Latkes.getServePath() + article.optString(Article.ARTICLE_PERMALINK));
article.put(Article.ARTICLE_REWARD_CONTENT, rewardContent);
}
}
}
| 帖子参与者去重
| src/main/java/org/b3log/symphony/service/ArticleQueryService.java | 帖子参与者去重 | <ide><path>rc/main/java/org/b3log/symphony/service/ArticleQueryService.java
<ide> * Article query service.
<ide> *
<ide> * @author <a href="http://88250.b3log.org">Liang Ding</a>
<del> * @version 1.12.10.17, Mar 15, 2016
<add> * @version 1.12.10.18, Mar 23, 2016
<ide> * @since 0.2.0
<ide> */
<ide> @Service
<ide>
<ide> try {
<ide> final JSONObject result = commentRepository.get(query);
<del> final List<JSONObject> comments = CollectionUtils.<JSONObject>jsonArrayToList(result.optJSONArray(Keys.RESULTS));
<add>
<add> final List<JSONObject> comments = new ArrayList<JSONObject>();
<add> final JSONArray records = result.optJSONArray(Keys.RESULTS);
<add> for (int i = 0; i < records.length(); i++) {
<add> final JSONObject comment = records.optJSONObject(i);
<add>
<add> boolean exist = false;
<add> // deduplicate
<add> for (final JSONObject c : comments) {
<add> if (comment.optString(Comment.COMMENT_AUTHOR_ID).equals(
<add> c.optString(Comment.COMMENT_AUTHOR_ID))) {
<add> exist = true;
<add>
<add> break;
<add> }
<add> }
<add>
<add> if (!exist) {
<add> comments.add(comment);
<add> }
<add> }
<ide>
<ide> for (final JSONObject comment : comments) {
<ide> final String email = comment.optString(Comment.COMMENT_AUTHOR_EMAIL); |
|
Java | lgpl-2.1 | 3f17073fec1517c2553745e86536cfd6726153f3 | 0 | samskivert/samskivert,samskivert/samskivert | //
// $Id: ServerControl.java,v 1.5 2002/03/03 17:21:29 mdb Exp $
package robodj.util;
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.StringTokenizer;
import javax.swing.SwingUtilities;
import com.samskivert.util.StringUtil;
import robodj.Log;
/**
* A simple class used to remotely control the music server through its
* network interface.
*/
public class ServerControl
implements Runnable
{
/**
* Used to report changes to the playing song.
*/
public static interface PlayingListener
{
/**
* Called when the playing song is known to have changed to the
* specified songid.
*
* @param songid the id of the song that's playing or -1 if
* nothing is playing.
* @param paused true if the music daemon is paused.
*/
public void playingUpdated (int songid, boolean paused);
}
public ServerControl (String host, int port)
throws IOException
{
// create our server connection
_conn = new Socket(host, port);
// create our IO objects
_in = new BufferedReader(new InputStreamReader(
_conn.getInputStream()));
_out = new PrintWriter(_conn.getOutputStream());
}
public void addPlayingListener (PlayingListener listener)
{
_listeners.add(listener);
}
public void removePlayingListener (PlayingListener listener)
{
_listeners.remove(listener);
}
public void pause ()
{
sendCommand("PAUSE");
refreshPlaying();
}
public void play ()
{
sendCommand("PLAY");
refreshPlaying();
}
public void stop ()
{
sendCommand("STOP");
refreshPlaying();
}
public void clear ()
{
sendCommand("CLEAR");
}
public void back ()
{
sendCommand("BACK");
refreshPlaying();
}
public void skip ()
{
sendCommand("SKIP");
refreshPlaying();
}
public void append (int eid, int sid, String trackPath)
{
sendCommand("APPEND " + eid + " " + sid + " " + trackPath);
}
public void remove (int sid)
{
sendCommand("REMOVE " + sid);
refreshPlaying();
}
public void removeGroup (int sid, int count)
{
sendCommand("REMOVEGRP " + sid + " " + count);
refreshPlaying();
}
public void skipto (int sid)
{
sendCommand("SKIPTO " + sid);
refreshPlaying();
}
public int getPlaying ()
{
refreshPlaying();
return _playingSongId;
}
public void refreshPlaying ()
{
String playing = sendCommand("PLAYING");
// figure out if we're paused
_paused = (playing.indexOf("paused") != -1);
// figure out what song is playing
playing = StringUtil.split(playing, ":")[1].trim();
_playingSongId = -1;
if (!playing.equals("<none>")) {
try {
_playingSongId = Integer.parseInt(playing);
} catch (NumberFormatException nfe) {
Log.warning("Unable to parse currently playing id '" +
playing + "'.");
}
}
// let our listeners know about the new info
SwingUtilities.invokeLater(this);
}
public String[] getPlaylist ()
{
String result = sendCommand("PLAYLIST");
ArrayList songs = new ArrayList();
// parse the result string and then read the proper number of
// playlist entries from the output
if (!result.startsWith("200")) {
return null;
}
// the result looks like this:
// 200 Playlist songs: 9 current: /export/.../02.mp3
StringTokenizer tok = new StringTokenizer(result);
// skip the first three tokens to get to the actual count
tok.nextToken(); tok.nextToken(); tok.nextToken();
int count = 0;
try {
count = Integer.parseInt(tok.nextToken());
for (int i = 0; i < count; i++) {
songs.add(_in.readLine());
}
} catch (IOException ioe) {
Log.warning("Error communicating with music server: " + ioe);
return null;
} catch (NumberFormatException nfe) {
Log.warning("Bogus response from music server: " + result);
return null;
}
String[] plist = new String[count];
songs.toArray(plist);
return plist;
}
public void run ()
{
// notify our playing listeners
for (int i = 0; i < _listeners.size(); i++) {
PlayingListener listener = (PlayingListener)_listeners.get(i);
try {
listener.playingUpdated(_playingSongId, _paused);
} catch (Exception e) {
Log.warning("PlayingListener choked during update " +
"[listener=" + listener +
", songid=" + _playingSongId + "].");
Log.logStackTrace(e);
}
}
}
protected String sendCommand (String command)
{
try {
Log.info("Sending: " + command);
_out.println(command);
_out.flush();
String rsp = _in.readLine();
Log.info("Read response: " + rsp);
return rsp;
} catch (IOException ioe) {
Log.warning("Error communicating with server: " + ioe);
return null;
}
}
protected Socket _conn;
protected PrintWriter _out;
protected BufferedReader _in;
/** A list of entities that are informed when the playing song
* changes. */
protected ArrayList _listeners = new ArrayList();
/** The most recently fetched playing song id. */
protected int _playingSongId;
/** The most recently fetched paused state. */
protected boolean _paused;
}
| projects/robodj/src/java/robodj/util/ServerControl.java | //
// $Id: ServerControl.java,v 1.4 2002/02/22 08:37:34 mdb Exp $
package robodj.util;
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.StringTokenizer;
import robodj.Log;
/**
* A simple class used to remotely control the music server through its
* network interface.
*/
public class ServerControl
{
public ServerControl (String host, int port)
throws IOException
{
// create our server connection
_conn = new Socket(host, port);
// create our IO objects
_in = new BufferedReader(new InputStreamReader(
_conn.getInputStream()));
_out = new PrintWriter(_conn.getOutputStream());
}
public void pause ()
{
sendCommand("PAUSE");
}
public void play ()
{
sendCommand("PLAY");
}
public void stop ()
{
sendCommand("STOP");
}
public void clear ()
{
sendCommand("CLEAR");
}
public void skip ()
{
sendCommand("SKIP");
}
public void append (int eid, int sid, String trackPath)
{
sendCommand("APPEND " + eid + " " + sid + " " + trackPath);
}
public void remove (int sid)
{
sendCommand("REMOVE " + sid);
}
public void removeGroup (int sid, int count)
{
sendCommand("REMOVEGRP " + sid + " " + count);
}
public void skipto (int sid)
{
sendCommand("SKIPTO " + sid);
}
public String getPlaying ()
{
return sendCommand("PLAYING");
}
public String[] getPlaylist ()
{
String result = sendCommand("PLAYLIST");
ArrayList songs = new ArrayList();
// parse the result string and then read the proper number of
// playlist entries from the output
if (!result.startsWith("200")) {
return null;
}
// the result looks like this:
// 200 Playlist songs: 9 current: /export/.../02.mp3
StringTokenizer tok = new StringTokenizer(result);
// skip the first three tokens to get to the actual count
tok.nextToken(); tok.nextToken(); tok.nextToken();
int count = 0;
try {
count = Integer.parseInt(tok.nextToken());
for (int i = 0; i < count; i++) {
songs.add(_in.readLine());
}
} catch (IOException ioe) {
Log.warning("Error communicating with music server: " + ioe);
return null;
} catch (NumberFormatException nfe) {
Log.warning("Bogus response from music server: " + result);
return null;
}
String[] plist = new String[count];
songs.toArray(plist);
return plist;
}
protected String sendCommand (String command)
{
try {
Log.info("Sending: " + command);
_out.println(command);
_out.flush();
String rsp = _in.readLine();
Log.info("Read response: " + rsp);
return rsp;
} catch (IOException ioe) {
Log.warning("Error communicating with server: " + ioe);
return null;
}
}
protected Socket _conn;
protected PrintWriter _out;
protected BufferedReader _in;
}
| Added mechanism for reporting the "playing" state of the music server.
Automatically query the playing state after requesting a command that is
likely to modify it.
git-svn-id: 64ebf368729f38804935acb7146e017e0f909c6b@632 6335cc39-0255-0410-8fd6-9bcaacd3b74c
| projects/robodj/src/java/robodj/util/ServerControl.java | Added mechanism for reporting the "playing" state of the music server. Automatically query the playing state after requesting a command that is likely to modify it. | <ide><path>rojects/robodj/src/java/robodj/util/ServerControl.java
<ide> //
<del>// $Id: ServerControl.java,v 1.4 2002/02/22 08:37:34 mdb Exp $
<add>// $Id: ServerControl.java,v 1.5 2002/03/03 17:21:29 mdb Exp $
<ide>
<ide> package robodj.util;
<ide>
<ide> import java.net.*;
<ide> import java.util.ArrayList;
<ide> import java.util.StringTokenizer;
<add>import javax.swing.SwingUtilities;
<add>
<add>import com.samskivert.util.StringUtil;
<ide>
<ide> import robodj.Log;
<ide>
<ide> * network interface.
<ide> */
<ide> public class ServerControl
<add> implements Runnable
<ide> {
<add> /**
<add> * Used to report changes to the playing song.
<add> */
<add> public static interface PlayingListener
<add> {
<add> /**
<add> * Called when the playing song is known to have changed to the
<add> * specified songid.
<add> *
<add> * @param songid the id of the song that's playing or -1 if
<add> * nothing is playing.
<add> * @param paused true if the music daemon is paused.
<add> */
<add> public void playingUpdated (int songid, boolean paused);
<add> }
<add>
<ide> public ServerControl (String host, int port)
<ide> throws IOException
<ide> {
<ide> _out = new PrintWriter(_conn.getOutputStream());
<ide> }
<ide>
<add> public void addPlayingListener (PlayingListener listener)
<add> {
<add> _listeners.add(listener);
<add> }
<add>
<add> public void removePlayingListener (PlayingListener listener)
<add> {
<add> _listeners.remove(listener);
<add> }
<add>
<ide> public void pause ()
<ide> {
<ide> sendCommand("PAUSE");
<add> refreshPlaying();
<ide> }
<ide>
<ide> public void play ()
<ide> {
<ide> sendCommand("PLAY");
<add> refreshPlaying();
<ide> }
<ide>
<ide> public void stop ()
<ide> {
<ide> sendCommand("STOP");
<add> refreshPlaying();
<ide> }
<ide>
<ide> public void clear ()
<ide> sendCommand("CLEAR");
<ide> }
<ide>
<add> public void back ()
<add> {
<add> sendCommand("BACK");
<add> refreshPlaying();
<add> }
<add>
<ide> public void skip ()
<ide> {
<ide> sendCommand("SKIP");
<add> refreshPlaying();
<ide> }
<ide>
<ide> public void append (int eid, int sid, String trackPath)
<ide> public void remove (int sid)
<ide> {
<ide> sendCommand("REMOVE " + sid);
<add> refreshPlaying();
<ide> }
<ide>
<ide> public void removeGroup (int sid, int count)
<ide> {
<ide> sendCommand("REMOVEGRP " + sid + " " + count);
<add> refreshPlaying();
<ide> }
<ide>
<ide> public void skipto (int sid)
<ide> {
<ide> sendCommand("SKIPTO " + sid);
<del> }
<del>
<del> public String getPlaying ()
<del> {
<del> return sendCommand("PLAYING");
<add> refreshPlaying();
<add> }
<add>
<add> public int getPlaying ()
<add> {
<add> refreshPlaying();
<add> return _playingSongId;
<add> }
<add>
<add> public void refreshPlaying ()
<add> {
<add> String playing = sendCommand("PLAYING");
<add>
<add> // figure out if we're paused
<add> _paused = (playing.indexOf("paused") != -1);
<add>
<add> // figure out what song is playing
<add> playing = StringUtil.split(playing, ":")[1].trim();
<add> _playingSongId = -1;
<add> if (!playing.equals("<none>")) {
<add> try {
<add> _playingSongId = Integer.parseInt(playing);
<add> } catch (NumberFormatException nfe) {
<add> Log.warning("Unable to parse currently playing id '" +
<add> playing + "'.");
<add> }
<add> }
<add>
<add> // let our listeners know about the new info
<add> SwingUtilities.invokeLater(this);
<ide> }
<ide>
<ide> public String[] getPlaylist ()
<ide> String[] plist = new String[count];
<ide> songs.toArray(plist);
<ide> return plist;
<add> }
<add>
<add> public void run ()
<add> {
<add> // notify our playing listeners
<add> for (int i = 0; i < _listeners.size(); i++) {
<add> PlayingListener listener = (PlayingListener)_listeners.get(i);
<add> try {
<add> listener.playingUpdated(_playingSongId, _paused);
<add> } catch (Exception e) {
<add> Log.warning("PlayingListener choked during update " +
<add> "[listener=" + listener +
<add> ", songid=" + _playingSongId + "].");
<add> Log.logStackTrace(e);
<add> }
<add> }
<ide> }
<ide>
<ide> protected String sendCommand (String command)
<ide> protected Socket _conn;
<ide> protected PrintWriter _out;
<ide> protected BufferedReader _in;
<add>
<add> /** A list of entities that are informed when the playing song
<add> * changes. */
<add> protected ArrayList _listeners = new ArrayList();
<add>
<add> /** The most recently fetched playing song id. */
<add> protected int _playingSongId;
<add>
<add> /** The most recently fetched paused state. */
<add> protected boolean _paused;
<ide> } |
|
Java | apache-2.0 | 67e1dd180df7ec6a6749922401df3d0d82dae623 | 0 | majorseitan/dataverse,leeper/dataverse-1,quarian/dataverse,quarian/dataverse,ekoi/DANS-DVN-4.6.1,quarian/dataverse,jacksonokuhn/dataverse,quarian/dataverse,leeper/dataverse-1,bmckinney/dataverse-canonical,majorseitan/dataverse,jacksonokuhn/dataverse,jacksonokuhn/dataverse,majorseitan/dataverse,majorseitan/dataverse,JayanthyChengan/dataverse,bmckinney/dataverse-canonical,ekoi/DANS-DVN-4.6.1,jacksonokuhn/dataverse,JayanthyChengan/dataverse,jacksonokuhn/dataverse,ekoi/DANS-DVN-4.6.1,bmckinney/dataverse-canonical,ekoi/DANS-DVN-4.6.1,leeper/dataverse-1,JayanthyChengan/dataverse,quarian/dataverse,ekoi/DANS-DVN-4.6.1,leeper/dataverse-1,quarian/dataverse,ekoi/DANS-DVN-4.6.1,majorseitan/dataverse,ekoi/DANS-DVN-4.6.1,leeper/dataverse-1,majorseitan/dataverse,JayanthyChengan/dataverse,bmckinney/dataverse-canonical,ekoi/DANS-DVN-4.6.1,majorseitan/dataverse,leeper/dataverse-1,bmckinney/dataverse-canonical,bmckinney/dataverse-canonical,JayanthyChengan/dataverse,JayanthyChengan/dataverse,quarian/dataverse,quarian/dataverse,leeper/dataverse-1,jacksonokuhn/dataverse,leeper/dataverse-1,bmckinney/dataverse-canonical,JayanthyChengan/dataverse,JayanthyChengan/dataverse,bmckinney/dataverse-canonical,majorseitan/dataverse,jacksonokuhn/dataverse,jacksonokuhn/dataverse | package edu.harvard.iq.dataverse.util.json;
import edu.harvard.iq.dataverse.DatasetFieldValue;
import java.math.BigDecimal;
import java.math.BigInteger;
import javax.json.Json;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import javax.json.JsonValue;
/**
* A JSON builder that drops any null values. If we didn't drop'em,
* we'd get an NPE from the standard JSON builder. But just omitting them
* makes sense. So there.
*
* @author michael
*/
public class NullSafeJsonBuilder implements JsonObjectBuilder {
public static NullSafeJsonBuilder jsonObjectBuilder() {
return new NullSafeJsonBuilder();
}
private final JsonObjectBuilder delegate;
public NullSafeJsonBuilder() {
delegate = Json.createObjectBuilder();
}
@Override
public NullSafeJsonBuilder add(String name, JsonValue value) {
if ( value!=null ) delegate.add(name, value);
return this;
}
@Override
public NullSafeJsonBuilder add(String name, String value) {
if ( value!=null )
delegate.add(name, value);
return this;
}
@Override
public NullSafeJsonBuilder add(String name, BigInteger value) {
if ( value!=null )
delegate.add(name, value);
return this;
}
@Override
public NullSafeJsonBuilder add(String name, BigDecimal value) {
if ( value!=null )
delegate.add(name, value);
return this;
}
@Override
public NullSafeJsonBuilder add(String name, int value) {
delegate.add(name, value);
return this;
}
@Override
public NullSafeJsonBuilder add(String name, long value) {
delegate.add(name, value);
return this;
}
@Override
public NullSafeJsonBuilder add(String name, double value) {
delegate.add(name, value);
return this;
}
@Override
public NullSafeJsonBuilder add(String name, boolean value) {
delegate.add(name, value);
return this;
}
@Override
public NullSafeJsonBuilder addNull(String name) {
delegate.addNull(name);
return this;
}
@Override
public NullSafeJsonBuilder add(String name, JsonObjectBuilder builder) {
if ( builder!=null )
delegate.add(name, builder);
return this;
}
@Override
public NullSafeJsonBuilder add(String name, JsonArrayBuilder builder) {
if ( builder!=null )
delegate.add(name, builder);
return this;
}
public NullSafeJsonBuilder addStrValue( String name, DatasetFieldValue field ) {
if ( field != null ) {
delegate.add( name, field.getValue() );
}
return this;
}
@Override
public JsonObject build() {
return delegate.build();
}
}
| src/main/java/edu/harvard/iq/dataverse/util/json/NullSafeJsonBuilder.java | package edu.harvard.iq.dataverse.util.json;
import edu.harvard.iq.dataverse.DatasetFieldValue;
import java.math.BigDecimal;
import java.math.BigInteger;
import javax.json.Json;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import javax.json.JsonValue;
/**
* A JSON builder that drops any null values. If we didn't drop'em,
* we'd get an NPE from the standard JSON builder. But just omitting them
* makes sense. So there.
*
* @author michael
*/
public class NullSafeJsonBuilder implements JsonObjectBuilder {
public static NullSafeJsonBuilder jsonObjectBuilder() {
return new NullSafeJsonBuilder();
}
private final JsonObjectBuilder delegate;
public NullSafeJsonBuilder() {
delegate = Json.createObjectBuilder();
}
@Override
public NullSafeJsonBuilder add(String name, JsonValue value) {
if ( value!=null ) delegate.add(name, value);
return this;
}
@Override
public NullSafeJsonBuilder add(String name, String value) {
if ( value!=null )
delegate.add(name, value);
return this;
}
@Override
public NullSafeJsonBuilder add(String name, BigInteger value) {
if ( value!=null )
delegate.add(name, value);
return this;
}
@Override
public NullSafeJsonBuilder add(String name, BigDecimal value) {
if ( value!=null )
delegate.add(name, value);
return this;
}
@Override
public NullSafeJsonBuilder add(String name, int value) {
delegate.add(name, value);
return this;
}
@Override
public NullSafeJsonBuilder add(String name, long value) {
delegate.add(name, value);
return this;
}
@Override
public NullSafeJsonBuilder add(String name, double value) {
delegate.add(name, value);
return this;
}
@Override
public NullSafeJsonBuilder add(String name, boolean value) {
delegate.add(name, value);
return this;
}
@Override
public NullSafeJsonBuilder addNull(String name) {
delegate.addNull(name);
return this;
}
@Override
public NullSafeJsonBuilder add(String name, JsonObjectBuilder builder) {
if ( builder!=null )
delegate.add(name, builder);
return this;
}
@Override
public NullSafeJsonBuilder add(String name, JsonArrayBuilder builder) {
if ( builder!=null )
delegate.add(name, builder);
return this;
}
public NullSafeJsonBuilder addStrValue( String name, DatasetFieldValue field ) {
if ( field != null ) {
delegate.add( name, field.getStrValue() );
}
return this;
}
@Override
public JsonObject build() {
return delegate.build();
}
}
| changed called from getStrValue (deprecated) to getValue | src/main/java/edu/harvard/iq/dataverse/util/json/NullSafeJsonBuilder.java | changed called from getStrValue (deprecated) to getValue | <ide><path>rc/main/java/edu/harvard/iq/dataverse/util/json/NullSafeJsonBuilder.java
<ide>
<ide> public NullSafeJsonBuilder addStrValue( String name, DatasetFieldValue field ) {
<ide> if ( field != null ) {
<del> delegate.add( name, field.getStrValue() );
<add> delegate.add( name, field.getValue() );
<ide> }
<ide> return this;
<ide> } |
|
Java | agpl-3.0 | fce00d3c329b0100bb0e06c1e59defa44a7307ee | 0 | imCodePartnerAB/imcms,imCodePartnerAB/imcms,imCodePartnerAB/imcms | package imcode.server.document;
import imcode.util.Utility;
import imcode.util.io.ExceptionFreeInputStreamSource;
import imcode.util.io.FileInputStreamSource;
import imcode.util.io.InputStreamSource;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.NullArgumentException;
import org.apache.commons.lang.UnhandledException;
import java.io.File;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
/**
* A FileDocumentDomainObject contains a collection files.
* In this context a file is set of attributes associated with a data {@link FileDocumentFile}.
* <p>
* A file is identified by fileId - a string which is unique to a FileDocumentDomainObject.
*/
public class FileDocumentDomainObject extends DocumentDomainObject {
public static final String MIME_TYPE__APPLICATION_OCTET_STREAM = "application/octet-stream";
@SuppressWarnings("unused")
public static final String MIME_TYPE__UNKNOWN_DEFAULT = MIME_TYPE__APPLICATION_OCTET_STREAM;
// key: file id
private Map<String, FileDocumentFile> files = createFilesMap();
private String defaultFileId;
public DocumentTypeDomainObject getDocumentType() {
return DocumentTypeDomainObject.FILE;
}
public void accept(DocumentVisitor documentVisitor) {
documentVisitor.visitFileDocument(this);
}
public void addFile(String fileId, FileDocumentFile file) {
if (null == fileId) {
throw new NullArgumentException("fileId");
}
if (!files.containsKey(defaultFileId)) {
defaultFileId = fileId;
}
FileDocumentFile fileClone = cloneFile(file);
fileClone.setId(fileId);
files.put(fileId, fileClone);
}
/**
* @param file file to clone
* @return file clone or null if provided file is null
*/
private FileDocumentFile cloneFile(FileDocumentFile file) {
if (null == file) {
return null;
}
FileDocumentFile fileClone;
try {
fileClone = file.clone();
} catch (CloneNotSupportedException e) {
throw new UnhandledException(e);
}
return fileClone;
}
public Map<String, FileDocumentFile> getFiles() {
Map<String, FileDocumentFile> map = createFilesMap();
map.putAll(files);
return map;
}
@SuppressWarnings("unchecked")
private Map<String, FileDocumentFile> createFilesMap() {
return MapUtils.orderedMap(new HashMap<String, FileDocumentFile>());
}
public FileDocumentFile getFile(String fileId) {
return cloneFile(files.get(fileId));
}
public FileDocumentFile removeFile(String fileId) {
FileDocumentFile fileDocumentFile = files.remove(fileId);
selectDefaultFileName(fileId);
return fileDocumentFile;
}
private void selectDefaultFileName(String fileId) {
if (files.isEmpty()) {
defaultFileId = null;
} else if (defaultFileId.equals(fileId)) {
defaultFileId = Utility.firstElementOfSetByOrderOf(files.keySet(), String.CASE_INSENSITIVE_ORDER);
}
}
public String getDefaultFileId() {
return defaultFileId;
}
public void setDefaultFileId(String defaultFileId) {
if (!files.containsKey(defaultFileId)) {
throw new IllegalArgumentException("Cannot set defaultFile to non-existant key "
+ defaultFileId);
}
this.defaultFileId = defaultFileId;
}
/**
* @param fileId
* @return file with fileId or default file if fileId is null or there is no file with a such id.
*/
public FileDocumentFile getFileOrDefault(String fileId) {
if (null == fileId) {
return getDefaultFile();
}
FileDocumentFile fileDocumentFile = getFile(fileId);
if (null == fileDocumentFile) {
fileDocumentFile = getDefaultFile();
}
return fileDocumentFile;
}
public FileDocumentFile getDefaultFile() {
return getFile(defaultFileId);
}
@SuppressWarnings("unused")
public void changeFileId(String oldFileId, String newFileId) {
if (null == oldFileId) {
throw new NullArgumentException("oldFileId");
}
if (null == newFileId) {
throw new NullArgumentException("newFileId");
}
if (!files.containsKey(oldFileId)) {
throw new IllegalStateException("There is no file with the id " + oldFileId);
}
if (oldFileId.equals(newFileId)) {
return;
}
if (files.containsKey(newFileId)) {
throw new IllegalStateException("There already is a file with the id " + newFileId);
}
addFile(newFileId, files.remove(oldFileId));
if (defaultFileId.equals(oldFileId)) {
defaultFileId = newFileId;
}
}
/**
* File attributes associated with a data.
*
* @see imcode.util.io.InputStreamSource
*/
public static class FileDocumentFile implements Cloneable, Serializable {
private String id;
/**
* If this object represent a new file then assigned by the system before the file is stored in a FS.
* Otherwise set by the system when FileDocumentDomainObject is initialized.
*/
private String filename;
private String mimeType;
private InputStreamSource inputStreamSource;
private boolean createdAsImage;
public String getFilename() {
return filename;
}
public void setFilename(String v) {
this.filename = v;
}
public String getMimeType() {
return mimeType;
}
public void setMimeType(String mimeType) {
this.mimeType = mimeType;
}
public InputStreamSource getInputStreamSource() {
return new ExceptionFreeInputStreamSource(inputStreamSource);
}
public void setInputStreamSource(InputStreamSource inputStreamSource) {
this.inputStreamSource = inputStreamSource;
}
public boolean isFileInputStreamSource() {
return inputStreamSource instanceof FileInputStreamSource;
}
public boolean isCreatedAsImage() {
return createdAsImage;
}
public void setCreatedAsImage(boolean createdAsImage) {
this.createdAsImage = createdAsImage;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public FileDocumentFile clone() throws CloneNotSupportedException {
return (FileDocumentFile) super.clone();
}
public File getFile() {
return ((FileInputStreamSource) inputStreamSource).getFile();
}
}
} | src/main/java/imcode/server/document/FileDocumentDomainObject.java | package imcode.server.document;
import imcode.util.Utility;
import imcode.util.io.ExceptionFreeInputStreamSource;
import imcode.util.io.FileInputStreamSource;
import imcode.util.io.InputStreamSource;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.NullArgumentException;
import org.apache.commons.lang.UnhandledException;
import java.io.File;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
/**
* A FileDocumentDomainObject contains a collection files.
* In this context a file is set of attributes associated with a data {@link FileDocumentFile}.
* <p>
* A file is identified by fileId - a string which is unique to a FileDocumentDomainObject.
*/
public class FileDocumentDomainObject extends DocumentDomainObject {
public static final String MIME_TYPE__APPLICATION_OCTET_STREAM = "application/octet-stream";
@SuppressWarnings("unused")
public static final String MIME_TYPE__UNKNOWN_DEFAULT = MIME_TYPE__APPLICATION_OCTET_STREAM;
// key: file id
private Map<String, FileDocumentFile> files = createFilesMap();
private String defaultFileId;
public DocumentTypeDomainObject getDocumentType() {
return DocumentTypeDomainObject.FILE;
}
public void accept(DocumentVisitor documentVisitor) {
documentVisitor.visitFileDocument(this);
}
public void addFile(String fileId, FileDocumentFile file) {
if (null == fileId) {
throw new NullArgumentException("fileId");
}
if (!files.containsKey(defaultFileId)) {
defaultFileId = fileId;
}
FileDocumentFile fileClone = cloneFile(file);
fileClone.setId(fileId);
files.put(fileId, fileClone);
}
/**
* @param file file to clone
* @return file clone or null if provided file is null
*/
private FileDocumentFile cloneFile(FileDocumentFile file) {
if (null == file) {
return null;
}
FileDocumentFile fileClone;
try {
fileClone = file.clone();
} catch (CloneNotSupportedException e) {
throw new UnhandledException(e);
}
return fileClone;
}
public Map<String, FileDocumentFile> getFiles() {
Map<String, FileDocumentFile> map = createFilesMap();
map.putAll(files);
return map;
}
@SuppressWarnings("unchecked")
private Map<String, FileDocumentFile> createFilesMap() {
return MapUtils.orderedMap(new HashMap<String, FileDocumentFile>());
}
public FileDocumentFile getFile(String fileId) {
return cloneFile(files.get(fileId));
}
public FileDocumentFile removeFile(String fileId) {
FileDocumentFile fileDocumentFile = files.remove(fileId);
selectDefaultFileName(fileId);
return fileDocumentFile;
}
private void selectDefaultFileName(String fileId) {
if (files.isEmpty()) {
defaultFileId = null;
} else if (defaultFileId.equals(fileId)) {
defaultFileId = Utility.firstElementOfSetByOrderOf(files.keySet(), String.CASE_INSENSITIVE_ORDER);
}
}
public String getDefaultFileId() {
return defaultFileId;
}
public void setDefaultFileId(String defaultFileId) {
if (!files.containsKey(defaultFileId)) {
throw new IllegalArgumentException("Cannot set defaultFileId to non-existant key "
+ defaultFileId);
}
this.defaultFileId = defaultFileId;
}
/**
* @param fileId
* @return file with fileId or default file if fileId is null or there is no file with a such id.
*/
public FileDocumentFile getFileOrDefault(String fileId) {
if (null == fileId) {
return getDefaultFile();
}
FileDocumentFile fileDocumentFile = getFile(fileId);
if (null == fileDocumentFile) {
fileDocumentFile = getDefaultFile();
}
return fileDocumentFile;
}
public FileDocumentFile getDefaultFile() {
return getFile(defaultFileId);
}
@SuppressWarnings("unused")
public void changeFileId(String oldFileId, String newFileId) {
if (null == oldFileId) {
throw new NullArgumentException("oldFileId");
}
if (null == newFileId) {
throw new NullArgumentException("newFileId");
}
if (!files.containsKey(oldFileId)) {
throw new IllegalStateException("There is no file with the id " + oldFileId);
}
if (oldFileId.equals(newFileId)) {
return;
}
if (files.containsKey(newFileId)) {
throw new IllegalStateException("There already is a file with the id " + newFileId);
}
addFile(newFileId, files.remove(oldFileId));
if (defaultFileId.equals(oldFileId)) {
defaultFileId = newFileId;
}
}
/**
* File attributes associated with a data.
*
* @see imcode.util.io.InputStreamSource
*/
public static class FileDocumentFile implements Cloneable, Serializable {
private String id;
/**
* If this object represent a new file then assigned by the system before the file is stored in a FS.
* Otherwise set by the system when FileDocumentDomainObject is initialized.
*/
private String filename;
private String mimeType;
private InputStreamSource inputStreamSource;
private boolean createdAsImage;
public String getFilename() {
return filename;
}
public void setFilename(String v) {
this.filename = v;
}
public String getMimeType() {
return mimeType;
}
public void setMimeType(String mimeType) {
this.mimeType = mimeType;
}
public InputStreamSource getInputStreamSource() {
return new ExceptionFreeInputStreamSource(inputStreamSource);
}
public void setInputStreamSource(InputStreamSource inputStreamSource) {
this.inputStreamSource = inputStreamSource;
}
public boolean isFileInputStreamSource() {
return inputStreamSource instanceof FileInputStreamSource;
}
public boolean isCreatedAsImage() {
return createdAsImage;
}
public void setCreatedAsImage(boolean createdAsImage) {
this.createdAsImage = createdAsImage;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public FileDocumentFile clone() throws CloneNotSupportedException {
return (FileDocumentFile) super.clone();
}
public File getFile() {
return ((FileInputStreamSource) inputStreamSource).getFile();
}
}
} | IMCMS-255 - Upgrade server side to work with new client:
- Naming fixes.
| src/main/java/imcode/server/document/FileDocumentDomainObject.java | IMCMS-255 - Upgrade server side to work with new client: - Naming fixes. | <ide><path>rc/main/java/imcode/server/document/FileDocumentDomainObject.java
<ide>
<ide> public void setDefaultFileId(String defaultFileId) {
<ide> if (!files.containsKey(defaultFileId)) {
<del> throw new IllegalArgumentException("Cannot set defaultFileId to non-existant key "
<add> throw new IllegalArgumentException("Cannot set defaultFile to non-existant key "
<ide> + defaultFileId);
<ide> }
<ide> this.defaultFileId = defaultFileId; |
|
JavaScript | mit | a81cbb1c4899a1c0d826bba2738b199c0071181c | 0 | treykc78/popcorn-js,TwoD/popcorn-js,ryanirelan/popcorn-js,azmenak/popcorn-js,stevemao/popcorn-js,ryanirelan/popcorn-js,Qambar/popcorn-js,josedab/popcorn-js,megomars/popcornjsdemo,stevemao/popcorn-js,Qambar/popcorn-js,cadecairos/popcorn-js,mozilla/popcorn-js,justindelacruz/popcorn-js,pculture/popcorn-js,mozilla/popcorn-js,pculture/popcorn-js,josedab/popcorn-js,azmenak/popcorn-js,ScottDowne/popcorn-js,TwoD/popcorn-js,azmenak/popcorn-js,mbuttu/popcorn-js,megomars/popcornjsdemo,mozilla/popcorn-js,ivesbai/popcorn-js,treykc78/popcorn-js,rwaldron/popcorn-js,ScottDowne/popcorn-js,justindelacruz/popcorn-js,Qambar/popcorn-js,rwaldron/popcorn-js,stevemao/popcorn-js,mbuttu/popcorn-js,ivesbai/popcorn-js,treykc78/popcorn-js,ivesbai/popcorn-js,cadecairos/popcorn-js,pculture/popcorn-js,ryanirelan/popcorn-js,justindelacruz/popcorn-js | (function(global, document) {
// Popcorn.js does not support archaic browsers
if ( !document.addEventListener ) {
global.Popcorn = {};
var methods = ( "removeInstance addInstance getInstanceById removeInstanceById " +
"forEach extend effects error guid sizeOf isArray nop position disable enable destroy " +
"addTrackEvent removeTrackEvent getTrackEvents getTrackEvent getLastTrackEventId " +
"timeUpdate plugin removePlugin compose effect parser xhr getJSONP getScript" ).split(/\s+/);
while( methods.length ) {
global.Popcorn[ methods.shift() ] = function() {};
}
return;
}
var
AP = Array.prototype,
OP = Object.prototype,
forEach = AP.forEach,
slice = AP.slice,
hasOwn = OP.hasOwnProperty,
toString = OP.toString,
// ID string matching
rIdExp = /^(#([\w\-\_\.]+))$/,
// Ready fn cache
readyStack = [],
readyBound = false,
readyFired = false,
// Non-public internal data object
internal = {
events: {
hash: {},
apis: {}
}
},
// Non-public `requestAnimFrame`
// http://paulirish.com/2011/requestanimationframe-for-smart-animating/
requestAnimFrame = (function(){
return global.requestAnimationFrame ||
global.webkitRequestAnimationFrame ||
global.mozRequestAnimationFrame ||
global.oRequestAnimationFrame ||
global.msRequestAnimationFrame ||
function( callback, element ) {
global.setTimeout( callback, 16 );
};
}()),
// Declare constructor
// Returns an instance object.
Popcorn = function( entity, options ) {
// Return new Popcorn object
return new Popcorn.p.init( entity, options || null );
};
// Instance caching
Popcorn.instances = [];
Popcorn.instanceIds = {};
Popcorn.removeInstance = function( instance ) {
// If called prior to any instances being created
// Return early to avoid splicing on nothing
if ( !Popcorn.instances.length ) {
return;
}
// Remove instance from Popcorn.instances
Popcorn.instances.splice( Popcorn.instanceIds[ instance.id ], 1 );
// Delete the instance id key
delete Popcorn.instanceIds[ instance.id ];
// Return current modified instances
return Popcorn.instances;
};
// Addes a Popcorn instance to the Popcorn instance array
Popcorn.addInstance = function( instance ) {
var instanceLen = Popcorn.instances.length,
instanceId = instance.media.id && instance.media.id;
// If the media element has its own `id` use it, otherwise provide one
// Ensure that instances have unique ids and unique entries
// Uses `in` operator to avoid false positives on 0
instance.id = !( instanceId in Popcorn.instanceIds ) && instanceId ||
"__popcorn" + instanceLen;
// Create a reference entry for this instance
Popcorn.instanceIds[ instance.id ] = instanceLen;
// Add this instance to the cache
Popcorn.instances.push( instance );
// Return the current modified instances
return Popcorn.instances;
};
// Request Popcorn object instance by id
Popcorn.getInstanceById = function( id ) {
return Popcorn.instances[ Popcorn.instanceIds[ id ] ];
};
// Remove Popcorn object instance by id
Popcorn.removeInstanceById = function( id ) {
return Popcorn.removeInstance( Popcorn.instances[ Popcorn.instanceIds[ id ] ] );
};
// Declare a shortcut (Popcorn.p) to and a definition of
// the new prototype for our Popcorn constructor
Popcorn.p = Popcorn.prototype = {
init: function( entity, options ) {
var matches;
// Supports Popcorn(function () { /../ })
// Originally proposed by Daniel Brooks
if ( typeof entity === "function" ) {
// If document ready has already fired
if ( document.readyState === "interactive" || document.readyState === "complete" ) {
entity( document, Popcorn );
return;
}
// Add `entity` fn to ready stack
readyStack.push( entity );
// This process should happen once per page load
if ( !readyBound ) {
// set readyBound flag
readyBound = true;
var DOMContentLoaded = function() {
readyFired = true;
// Remove global DOM ready listener
document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
// Execute all ready function in the stack
for ( var i = 0, readyStackLength = readyStack.length; i < readyStackLength; i++ ) {
readyStack[ i ].call( document, Popcorn );
}
// GC readyStack
readyStack = null;
};
// Register global DOM ready listener
document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
}
return;
}
// Check if entity is a valid string id
matches = rIdExp.exec( entity );
// Get media element by id or object reference
this.media = matches && matches.length && matches[ 2 ] ?
document.getElementById( matches[ 2 ] ) :
entity;
// Create an audio or video element property reference
this[ ( this.media.nodeName && this.media.nodeName.toLowerCase() ) || "video" ] = this.media;
// Register new instance
Popcorn.addInstance( this );
this.options = options || {};
this.isDestroyed = false;
this.data = {
// Allows disabling a plugin per instance
disabled: [],
// Stores DOM event queues by type
events: {},
// Stores Special event hooks data
hooks: {},
// Store track event history data
history: [],
// Stores ad-hoc state related data]
state: {
volume: this.media.volume
},
// Store track event object references by trackId
trackRefs: {},
// Playback track event queues
trackEvents: {
byStart: [{
start: -1,
end: -1
}],
byEnd: [{
start: -1,
end: -1
}],
animating: [],
startIndex: 0,
endIndex: 0,
previousUpdateTime: -1
}
};
// Wrap true ready check
var isReady = function( that ) {
var duration, videoDurationPlus, animate;
if ( that.media.readyState >= 2 ) {
// Adding padding to the front and end of the arrays
// this is so we do not fall off either end
duration = that.media.duration;
// Check for no duration info (NaN)
videoDurationPlus = duration != duration ? Number.MAX_VALUE : duration + 1;
Popcorn.addTrackEvent( that, {
start: videoDurationPlus,
end: videoDurationPlus
});
if ( that.options.frameAnimation ) {
// if Popcorn is created with frameAnimation option set to true,
// requestAnimFrame is used instead of "timeupdate" media event.
// This is for greater frame time accuracy, theoretically up to
// 60 frames per second as opposed to ~4 ( ~every 15-250ms)
animate = function () {
Popcorn.timeUpdate( that, {} );
that.trigger( "timeupdate" );
requestAnimFrame( animate );
};
requestAnimFrame( animate );
} else {
that.data.timeUpdateFunction = function( event ) {
Popcorn.timeUpdate( that, event );
};
if ( !that.isDestroyed ) {
that.media.addEventListener( "timeupdate", that.data.timeUpdateFunction, false );
}
}
} else {
global.setTimeout(function() {
isReady( that );
}, 1 );
}
};
isReady( this );
return this;
}
};
// Extend constructor prototype to instance prototype
// Allows chaining methods to instances
Popcorn.p.init.prototype = Popcorn.p;
Popcorn.forEach = function( obj, fn, context ) {
if ( !obj || !fn ) {
return {};
}
context = context || this;
var key, len;
// Use native whenever possible
if ( forEach && obj.forEach === forEach ) {
return obj.forEach( fn, context );
}
if ( toString.call( obj ) === "[object NodeList]" ) {
for ( key = 0, len = obj.length; key < len; key++ ) {
fn.call( context, obj[ key ], key, obj );
}
return obj;
}
for ( key in obj ) {
if ( hasOwn.call( obj, key ) ) {
fn.call( context, obj[ key ], key, obj );
}
}
return obj;
};
Popcorn.extend = function( obj ) {
var dest = obj, src = slice.call( arguments, 1 );
Popcorn.forEach( src, function( copy ) {
for ( var prop in copy ) {
dest[ prop ] = copy[ prop ];
}
});
return dest;
};
// A Few reusable utils, memoized onto Popcorn
Popcorn.extend( Popcorn, {
error: function( msg ) {
throw new Error( msg );
},
guid: function( prefix ) {
Popcorn.guid.counter++;
return ( prefix ? prefix : "" ) + ( +new Date() + Popcorn.guid.counter );
},
sizeOf: function( obj ) {
var size = 0;
for ( var prop in obj ) {
size++;
}
return size;
},
isArray: Array.isArray || function( array ) {
return toString.call( array ) === "[object Array]";
},
nop: function() {},
position: function( elem ) {
var clientRect = elem.getBoundingClientRect(),
bounds = {},
doc = elem.ownerDocument,
docElem = document.documentElement,
body = document.body,
clientTop, clientLeft, scrollTop, scrollLeft, top, left;
// Determine correct clientTop/Left
clientTop = docElem.clientTop || body.clientTop || 0;
clientLeft = docElem.clientLeft || body.clientLeft || 0;
// Determine correct scrollTop/Left
scrollTop = ( global.pageYOffset && docElem.scrollTop || body.scrollTop );
scrollLeft = ( global.pageXOffset && docElem.scrollLeft || body.scrollLeft );
// Temp top/left
top = Math.ceil( clientRect.top + scrollTop - clientTop );
left = Math.ceil( clientRect.left + scrollLeft - clientLeft );
for ( var p in clientRect ) {
bounds[ p ] = Math.round( clientRect[ p ] );
}
return Popcorn.extend({}, bounds, { top: top, left: left });
},
disable: function( instance, plugin ) {
var disabled = instance.data.disabled;
if ( disabled.indexOf( plugin ) === -1 ) {
disabled.push( plugin );
}
return instance;
},
enable: function( instance, plugin ) {
var disabled = instance.data.disabled,
index = disabled.indexOf( plugin );
if ( index > -1 ) {
disabled.splice( index, 1 );
}
return instance;
},
destroy: function( instance ) {
var events = instance.data.events,
singleEvent, item, fn;
// Iterate through all events and remove them
for ( item in events ) {
singleEvent = events[ item ];
for ( fn in singleEvent ) {
delete singleEvent[ fn ];
}
events[ item ] = null;
}
if ( !instance.isDestroyed ) {
instance.media.removeEventListener( "timeupdate", instance.data.timeUpdateFunction, false );
instance.isDestroyed = true;
}
Popcorn.instances.splice( Popcorn.instanceIds[ instance.id ], 1 );
delete Popcorn.instanceIds[ instance.id ];
}
});
// Memoized GUID Counter
Popcorn.guid.counter = 1;
// Factory to implement getters, setters and controllers
// as Popcorn instance methods. The IIFE will create and return
// an object with defined methods
Popcorn.extend(Popcorn.p, (function() {
var methods = "load play pause currentTime playbackRate volume duration preload playbackRate " +
"autoplay loop controls muted buffered readyState seeking paused played seekable ended",
ret = {};
// Build methods, store in object that is returned and passed to extend
Popcorn.forEach( methods.split( /\s+/g ), function( name ) {
ret[ name ] = function( arg ) {
if ( typeof this.media[ name ] === "function" ) {
this.media[ name ]();
return this;
}
if ( arg != null ) {
this.media[ name ] = arg;
return this;
}
return this.media[ name ];
};
});
return ret;
})()
);
Popcorn.forEach( "enable disable".split(" "), function( method ) {
Popcorn.p[ method ] = function( plugin ) {
return Popcorn[ method ]( this, plugin );
};
});
Popcorn.extend(Popcorn.p, {
// Rounded currentTime
roundTime: function() {
return -~this.media.currentTime;
},
// Attach an event to a single point in time
exec: function( time, fn ) {
// Creating a one second track event with an empty end
Popcorn.addTrackEvent( this, {
start: time,
end: time + 1,
_running: false,
_natives: {
start: fn || Popcorn.nop,
end: Popcorn.nop,
type: "exec"
}
});
return this;
},
// Mute the calling media, optionally toggle
mute: function( toggle ) {
var event = toggle == null || toggle === true ? "muted" : "unmuted";
// If `toggle` is explicitly `false`,
// unmute the media and restore the volume level
if ( event === "unmuted" ) {
this.media.muted = false;
this.media.volume = this.data.state.volume;
}
// If `toggle` is either null or undefined,
// save the current volume and mute the media element
if ( event === "muted" ) {
this.data.state.volume = this.media.volume;
this.media.muted = true;
}
// Trigger either muted|unmuted event
this.trigger( event );
return this;
},
// Convenience method, unmute the calling media
unmute: function( toggle ) {
return this.mute( toggle == null ? false : !toggle );
},
// Get the client bounding box of an instance element
position: function() {
return Popcorn.position( this.media );
},
// Toggle a plugin's playback behaviour (on or off) per instance
toggle: function( plugin ) {
return Popcorn[ this.data.disabled.indexOf( plugin ) > -1 ? "enable" : "disable" ]( this, plugin );
},
// Set default values for plugin options objects per instance
defaults: function( plugin, defaults ) {
// If an array of default configurations is provided,
// iterate and apply each to this instance
if ( Popcorn.isArray( plugin ) ) {
Popcorn.forEach( plugin, function( obj ) {
for ( var name in obj ) {
this.defaults( name, obj[ name ] );
}
}, this );
return this;
}
if ( !this.options.defaults ) {
this.options.defaults = {};
}
if ( !this.options.defaults[ plugin ] ) {
this.options.defaults[ plugin ] = {};
}
Popcorn.extend( this.options.defaults[ plugin ], defaults );
return this;
}
});
Popcorn.Events = {
UIEvents: "blur focus focusin focusout load resize scroll unload",
MouseEvents: "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave click dblclick",
Events: "loadstart progress suspend emptied stalled play pause " +
"loadedmetadata loadeddata waiting playing canplay canplaythrough " +
"seeking seeked timeupdate ended ratechange durationchange volumechange"
};
Popcorn.Events.Natives = Popcorn.Events.UIEvents + " " +
Popcorn.Events.MouseEvents + " " +
Popcorn.Events.Events;
internal.events.apiTypes = [ "UIEvents", "MouseEvents", "Events" ];
// Privately compile events table at load time
(function( events, data ) {
var apis = internal.events.apiTypes,
eventsList = events.Natives.split( /\s+/g ),
idx = 0, len = eventsList.length, prop;
for( ; idx < len; idx++ ) {
data.hash[ eventsList[idx] ] = true;
}
apis.forEach(function( val, idx ) {
data.apis[ val ] = {};
var apiEvents = events[ val ].split( /\s+/g ),
len = apiEvents.length,
k = 0;
for ( ; k < len; k++ ) {
data.apis[ val ][ apiEvents[ k ] ] = true;
}
});
})( Popcorn.Events, internal.events );
Popcorn.events = {
isNative: function( type ) {
return !!internal.events.hash[ type ];
},
getInterface: function( type ) {
if ( !Popcorn.events.isNative( type ) ) {
return false;
}
var eventApi = internal.events,
apis = eventApi.apiTypes,
apihash = eventApi.apis,
idx = 0, len = apis.length, api, tmp;
for ( ; idx < len; idx++ ) {
tmp = apis[ idx ];
if ( apihash[ tmp ][ type ] ) {
api = tmp;
break;
}
}
return api;
},
// Compile all native events to single array
all: Popcorn.Events.Natives.split( /\s+/g ),
// Defines all Event handling static functions
fn: {
trigger: function( type, data ) {
var eventInterface, evt;
// setup checks for custom event system
if ( this.data.events[ type ] && Popcorn.sizeOf( this.data.events[ type ] ) ) {
eventInterface = Popcorn.events.getInterface( type );
if ( eventInterface ) {
evt = document.createEvent( eventInterface );
evt.initEvent( type, true, true, global, 1 );
this.media.dispatchEvent( evt );
return this;
}
// Custom events
Popcorn.forEach( this.data.events[ type ], function( obj, key ) {
obj.call( this, data );
}, this );
}
return this;
},
listen: function( type, fn ) {
var self = this,
hasEvents = true,
eventHook = Popcorn.events.hooks[ type ],
origType = type,
tmp;
if ( !this.data.events[ type ] ) {
this.data.events[ type ] = {};
hasEvents = false;
}
// Check and setup event hooks
if ( eventHook ) {
// Execute hook add method if defined
if ( eventHook.add ) {
eventHook.add.call( this, {}, fn );
}
// Reassign event type to our piggyback event type if defined
if ( eventHook.bind ) {
type = eventHook.bind;
}
// Reassign handler if defined
if ( eventHook.handler ) {
tmp = fn;
fn = function wrapper( event ) {
eventHook.handler.call( self, event, tmp );
};
}
// assume the piggy back event is registered
hasEvents = true;
// Setup event registry entry
if ( !this.data.events[ type ] ) {
this.data.events[ type ] = {};
// Toggle if the previous assumption was untrue
hasEvents = false;
}
}
// Register event and handler
this.data.events[ type ][ fn.name || ( fn.toString() + Popcorn.guid() ) ] = fn;
// only attach one event of any type
if ( !hasEvents && Popcorn.events.all.indexOf( type ) > -1 ) {
this.media.addEventListener( type, function( event ) {
Popcorn.forEach( self.data.events[ type ], function( obj, key ) {
if ( typeof obj === "function" ) {
obj.call( self, event );
}
});
}, false);
}
return this;
},
unlisten: function( type, fn ) {
if ( this.data.events[ type ] && this.data.events[ type ][ fn ] ) {
delete this.data.events[ type ][ fn ];
return this;
}
this.data.events[ type ] = null;
return this;
}
},
hooks: {
canplayall: {
bind: "canplaythrough",
add: function( event, callback ) {
var state = false;
if ( this.media.readyState ) {
callback.call( this, event );
state = true;
}
this.data.hooks.canplayall = {
fired: state
};
},
// declare special handling instructions
handler: function canplayall( event, callback ) {
if ( !this.data.hooks.canplayall.fired ) {
// trigger original user callback once
callback.call( this, event );
this.data.hooks.canplayall.fired = true;
}
}
}
}
};
// Extend Popcorn.events.fns (listen, unlisten, trigger) to all Popcorn instances
Popcorn.forEach( [ "trigger", "listen", "unlisten" ], function( key ) {
Popcorn.p[ key ] = Popcorn.events.fn[ key ];
});
// Protected API methods
Popcorn.protect = {
natives: ( "load play pause currentTime playbackRate mute volume duration removePlugin roundTime trigger listen unlisten exec" +
"preload playbackRate autoplay loop controls muted buffered readyState seeking paused played seekable ended" ).toLowerCase().split( /\s+/ )
};
// Internal Only - Adds track events to the instance object
Popcorn.addTrackEvent = function( obj, track ) {
// Determine if this track has default options set for it
// If so, apply them to the track object
if ( track && track._natives && track._natives.type &&
( obj.options.defaults && obj.options.defaults[ track._natives.type ] ) ) {
track = Popcorn.extend( {}, obj.options.defaults[ track._natives.type ], track );
}
if ( track._natives ) {
// Supports user defined track event id
track._id = !track.id ? Popcorn.guid( track._natives.type ) : track.id;
// Push track event ids into the history
obj.data.history.push( track._id );
}
track.start = Popcorn.util.toSeconds( track.start, obj.options.framerate );
track.end = Popcorn.util.toSeconds( track.end, obj.options.framerate );
// Store this definition in an array sorted by times
var byStart = obj.data.trackEvents.byStart,
byEnd = obj.data.trackEvents.byEnd,
idx;
for ( idx = byStart.length - 1; idx >= 0; idx-- ) {
if ( track.start >= byStart[ idx ].start ) {
byStart.splice( idx + 1, 0, track );
break;
}
}
for ( idx = byEnd.length - 1; idx >= 0; idx-- ) {
if ( track.end > byEnd[ idx ].end ) {
byEnd.splice( idx + 1, 0, track );
break;
}
}
// Store references to user added trackevents in ref table
if ( track._id ) {
Popcorn.addTrackEvent.ref( obj, track );
}
};
// Internal Only - Adds track event references to the instance object's trackRefs hash table
Popcorn.addTrackEvent.ref = function( obj, track ) {
obj.data.trackRefs[ track._id ] = track;
return obj;
};
Popcorn.removeTrackEvent = function( obj, trackId ) {
var historyLen = obj.data.history.length,
indexWasAt = 0,
byStart = [],
byEnd = [],
animating = [],
history = [];
Popcorn.forEach( obj.data.trackEvents.byStart, function( o, i, context ) {
// Preserve the original start/end trackEvents
if ( !o._id ) {
byStart.push( obj.data.trackEvents.byStart[i] );
byEnd.push( obj.data.trackEvents.byEnd[i] );
}
// Filter for user track events (vs system track events)
if ( o._id ) {
// Filter for the trackevent to remove
if ( o._id !== trackId ) {
byStart.push( obj.data.trackEvents.byStart[i] );
byEnd.push( obj.data.trackEvents.byEnd[i] );
}
// Capture the position of the track being removed.
if ( o._id === trackId ) {
indexWasAt = i;
o._natives._teardown && o._natives._teardown.call( obj, o );
}
}
});
if ( obj.data.trackEvents.animating.length ) {
Popcorn.forEach( obj.data.trackEvents.animating, function( o, i, context ) {
// Preserve the original start/end trackEvents
if ( !o._id ) {
animating.push( obj.data.trackEvents.animating[i] );
}
// Filter for user track events (vs system track events)
if ( o._id ) {
// Filter for the trackevent to remove
if ( o._id !== trackId ) {
animating.push( obj.data.trackEvents.animating[i] );
}
}
});
}
// Update
if ( indexWasAt <= obj.data.trackEvents.startIndex ) {
obj.data.trackEvents.startIndex--;
}
if ( indexWasAt <= obj.data.trackEvents.endIndex ) {
obj.data.trackEvents.endIndex--;
}
obj.data.trackEvents.byStart = byStart;
obj.data.trackEvents.byEnd = byEnd;
obj.data.trackEvents.animating = animating;
for ( var i = 0; i < historyLen; i++ ) {
if ( obj.data.history[ i ] !== trackId ) {
history.push( obj.data.history[ i ] );
}
}
// Update ordered history array
obj.data.history = history;
// Update track event references
Popcorn.removeTrackEvent.ref( obj, trackId );
};
// Internal Only - Removes track event references from instance object's trackRefs hash table
Popcorn.removeTrackEvent.ref = function( obj, trackId ) {
delete obj.data.trackRefs[ trackId ];
return obj;
};
// Return an array of track events bound to this instance object
Popcorn.getTrackEvents = function( obj ) {
var trackevents = [],
refs = obj.data.trackEvents.byStart,
length = refs.length,
idx = 0,
ref;
for ( ; idx < length; idx++ ) {
ref = refs[ idx ];
// Return only user attributed track event references
if ( ref._id ) {
trackevents.push( ref );
}
}
return trackevents;
};
// Internal Only - Returns an instance object's trackRefs hash table
Popcorn.getTrackEvents.ref = function( obj ) {
return obj.data.trackRefs;
};
// Return a single track event bound to this instance object
Popcorn.getTrackEvent = function( obj, trackId ) {
return obj.data.trackRefs[ trackId ];
};
// Internal Only - Returns an instance object's track reference by track id
Popcorn.getTrackEvent.ref = function( obj, trackId ) {
return obj.data.trackRefs[ trackId ];
};
Popcorn.getLastTrackEventId = function( obj ) {
return obj.data.history[ obj.data.history.length - 1 ];
};
Popcorn.timeUpdate = function( obj, event ) {
var currentTime = obj.media.currentTime,
previousTime = obj.data.trackEvents.previousUpdateTime,
tracks = obj.data.trackEvents,
animating = tracks.animating,
end = tracks.endIndex,
start = tracks.startIndex,
animIndex = 0,
registryByName = Popcorn.registryByName,
byEnd, byStart, byAnimate, natives, type;
// Playbar advancing
if ( previousTime < currentTime ) {
while ( tracks.byEnd[ end ] && tracks.byEnd[ end ].end <= currentTime ) {
byEnd = tracks.byEnd[ end ];
natives = byEnd._natives;
type = natives && natives.type;
// If plugin does not exist on this instance, remove it
if ( !natives ||
( !!registryByName[ type ] ||
!!obj[ type ] ) ) {
if ( byEnd._running === true ) {
byEnd._running = false;
natives.end.call( obj, event, byEnd );
}
end++;
} else {
// remove track event
Popcorn.removeTrackEvent( obj, byEnd._id );
return;
}
}
while ( tracks.byStart[ start ] && tracks.byStart[ start ].start <= currentTime ) {
byStart = tracks.byStart[ start ];
natives = byStart._natives;
type = natives && natives.type;
// If plugin does not exist on this instance, remove it
if ( !natives ||
( !!registryByName[ type ] ||
!!obj[ type ] ) ) {
if ( byStart.end > currentTime &&
byStart._running === false &&
obj.data.disabled.indexOf( type ) === -1 ) {
byStart._running = true;
natives.start.call( obj, event, byStart );
// If the `frameAnimation` option is used,
// push the current byStart object into the `animating` cue
if ( obj.options.frameAnimation &&
( byStart && byStart._running && byStart._natives.frame ) ) {
animating.push( byStart );
}
}
start++;
} else {
// remove track event
Popcorn.removeTrackEvent( obj, byStart._id );
return;
}
}
// If the `frameAnimation` option is used, iterate the animating track
// and execute the `frame` callback
if ( obj.options.frameAnimation ) {
while ( animIndex < animating.length ) {
byAnimate = animating[ animIndex ];
if ( !byAnimate._running ) {
animating.splice( animIndex, 1 );
} else {
byAnimate._natives.frame.call( obj, event, byAnimate, currentTime );
animIndex++;
}
}
}
// Playbar receding
} else if ( previousTime > currentTime ) {
while ( tracks.byStart[ start ] && tracks.byStart[ start ].start > currentTime ) {
byStart = tracks.byStart[ start ];
natives = byStart._natives;
type = natives && natives.type;
// if plugin does not exist on this instance, remove it
if ( !natives ||
( !!registryByName[ type ] ||
!!obj[ type ] ) ) {
if ( byStart._running === true ) {
byStart._running = false;
natives.end.call( obj, event, byStart );
}
start--;
} else {
// remove track event
Popcorn.removeTrackEvent( obj, byStart._id );
return;
}
}
while ( tracks.byEnd[ end ] && tracks.byEnd[ end ].end > currentTime ) {
byEnd = tracks.byEnd[ end ];
natives = byEnd._natives;
type = natives && natives.type;
// if plugin does not exist on this instance, remove it
if ( !natives ||
( !!registryByName[ type ] ||
!!obj[ type ] ) ) {
if ( byEnd.start <= currentTime &&
byEnd._running === false &&
obj.data.disabled.indexOf( type ) === -1 ) {
byEnd._running = true;
natives.start.call( obj, event, byEnd );
// If the `frameAnimation` option is used,
// push the current byEnd object into the `animating` cue
if ( obj.options.frameAnimation &&
( byEnd && byEnd._running && byEnd._natives.frame ) ) {
animating.push( byEnd );
}
}
end--;
} else {
// remove track event
Popcorn.removeTrackEvent( obj, byEnd._id );
return;
}
}
// If the `frameAnimation` option is used, iterate the animating track
// and execute the `frame` callback
if ( obj.options.frameAnimation ) {
while ( animIndex < animating.length ) {
byAnimate = animating[ animIndex ];
if ( !byAnimate._running ) {
animating.splice( animIndex, 1 );
} else {
byAnimate._natives.frame.call( obj, event, byAnimate, currentTime );
animIndex++;
}
}
}
// time bar is not moving ( video is paused )
}
tracks.endIndex = end;
tracks.startIndex = start;
tracks.previousUpdateTime = currentTime;
};
// Map and Extend TrackEvent functions to all Popcorn instances
Popcorn.extend( Popcorn.p, {
getTrackEvents: function() {
return Popcorn.getTrackEvents.call( null, this );
},
getTrackEvent: function( id ) {
return Popcorn.getTrackEvent.call( null, this, id );
},
getLastTrackEventId: function() {
return Popcorn.getLastTrackEventId.call( null, this );
},
removeTrackEvent: function( id ) {
Popcorn.removeTrackEvent.call( null, this, id );
return this;
},
removePlugin: function( name ) {
Popcorn.removePlugin.call( null, this, name );
return this;
},
timeUpdate: function( event ) {
Popcorn.timeUpdate.call( null, this, event );
return this;
},
destroy: function() {
Popcorn.destroy.call( null, this );
return this;
}
});
// Plugin manifests
Popcorn.manifest = {};
// Plugins are registered
Popcorn.registry = [];
Popcorn.registryByName = {};
// An interface for extending Popcorn
// with plugin functionality
Popcorn.plugin = function( name, definition, manifest ) {
if ( Popcorn.protect.natives.indexOf( name.toLowerCase() ) >= 0 ) {
Popcorn.error( "'" + name + "' is a protected function name" );
return;
}
// Provides some sugar, but ultimately extends
// the definition into Popcorn.p
var reserved = [ "start", "end" ],
plugin = {},
setup,
isfn = typeof definition === "function",
methods = [ "_setup", "_teardown", "start", "end", "frame" ];
// combines calls of two function calls into one
var combineFn = function( first, second ) {
first = first || Popcorn.nop;
second = second || Popcorn.nop;
return function() {
first.apply( this, arguments );
second.apply( this, arguments );
};
};
// If `manifest` arg is undefined, check for manifest within the `definition` object
// If no `definition.manifest`, an empty object is a sufficient fallback
Popcorn.manifest[ name ] = manifest = manifest || definition.manifest || {};
// apply safe, and empty default functions
methods.forEach(function( method ) {
definition[ method ] = definition[ method ] || Popcorn.nop;
});
var pluginFn = function( setup, options ) {
if ( !options ) {
return this;
}
// Storing the plugin natives
var natives = options._natives = {},
compose = "",
defaults, originalOpts, manifestOpts, mergedSetupOpts;
Popcorn.extend( natives, setup );
options._natives.type = name;
options._running = false;
// Check for previously set default options
defaults = this.options.defaults && this.options.defaults[ options._natives && options._natives.type ];
// default to an empty string if no effect exists
// split string into an array of effects
options.compose = options.compose && options.compose.split( " " ) || [];
options.effect = options.effect && options.effect.split( " " ) || [];
// join the two arrays together
options.compose = options.compose.concat( options.effect );
options.compose.forEach(function( composeOption ) {
// if the requested compose is garbage, throw it away
compose = Popcorn.compositions[ composeOption ] || {};
// extends previous functions with compose function
methods.forEach(function( method ) {
natives[ method ] = combineFn( natives[ method ], compose[ method ] );
});
});
// Ensure a manifest object, an empty object is a sufficient fallback
options._natives.manifest = manifest;
// Checks for expected properties
if ( !( "start" in options ) ) {
options.start = 0;
}
if ( !( "end" in options ) ) {
options.end = this.duration() || Number.MAX_VALUE;
}
// Merge with defaults if they exist, make sure per call is prioritized
mergedSetupOpts = defaults ? Popcorn.extend( {}, defaults, options ) :
options;
// Resolves 239, 241, 242
if ( !mergedSetupOpts.target ) {
// Sometimes the manifest may be missing entirely
// or it has an options object that doesn't have a `target` property
manifestOpts = "options" in manifest && manifest.options;
mergedSetupOpts.target = manifestOpts && "target" in manifestOpts && manifestOpts.target;
}
// Trigger _setup method if exists
options._natives._setup && options._natives._setup.call( this, mergedSetupOpts );
// Create new track event for this instance
Popcorn.addTrackEvent( this, Popcorn.extend( mergedSetupOpts, options ) );
// Future support for plugin event definitions
// for all of the native events
Popcorn.forEach( setup, function( callback, type ) {
if ( type !== "type" ) {
if ( reserved.indexOf( type ) === -1 ) {
this.listen( type, callback );
}
}
}, this );
return this;
};
// Assign new named definition
plugin[ name ] = function( options ) {
return pluginFn.call( this, isfn ? definition.call( this, options ) : definition,
options );
};
// Extend Popcorn.p with new named definition
Popcorn.extend( Popcorn.p, plugin );
// Push into the registry
var entry = {
fn: plugin[ name ],
definition: definition,
base: definition,
parents: [],
name: name
};
Popcorn.registry.push(
Popcorn.extend( plugin, entry, {
type: name
})
);
Popcorn.registryByName[ name ] = entry;
return plugin;
};
Popcorn.plugin.debug = false;
// removePlugin( type ) removes all tracks of that from all instances of popcorn
// removePlugin( obj, type ) removes all tracks of type from obj, where obj is a single instance of popcorn
Popcorn.removePlugin = function( obj, name ) {
// Check if we are removing plugin from an instance or from all of Popcorn
if ( !name ) {
// Fix the order
name = obj;
obj = Popcorn.p;
if ( Popcorn.protect.natives.indexOf( name.toLowerCase() ) >= 0 ) {
Popcorn.error( "'" + name + "' is a protected function name" );
return;
}
var registryLen = Popcorn.registry.length,
registryIdx;
// remove plugin reference from registry
for ( registryIdx = 0; registryIdx < registryLen; registryIdx++ ) {
if ( Popcorn.registry[ registryIdx ].name === name ) {
Popcorn.registry.splice( registryIdx, 1 );
delete Popcorn.registryByName[ name ];
// delete the plugin
delete obj[ name ];
// plugin found and removed, stop checking, we are done
return;
}
}
}
var byStart = obj.data.trackEvents.byStart,
byEnd = obj.data.trackEvents.byEnd,
animating = obj.data.trackEvents.animating,
idx, sl;
// remove all trackEvents
for ( idx = 0, sl = byStart.length; idx < sl; idx++ ) {
if ( ( byStart[ idx ] && byStart[ idx ]._natives && byStart[ idx ]._natives.type === name ) &&
( byEnd[ idx ] && byEnd[ idx ]._natives && byEnd[ idx ]._natives.type === name ) ) {
byStart[ idx ]._natives._teardown && byStart[ idx ]._natives._teardown.call( obj, byStart[ idx ] );
byStart.splice( idx, 1 );
byEnd.splice( idx, 1 );
// update for loop if something removed, but keep checking
idx--; sl--;
if ( obj.data.trackEvents.startIndex <= idx ) {
obj.data.trackEvents.startIndex--;
obj.data.trackEvents.endIndex--;
}
}
}
//remove all animating events
for ( idx = 0, sl = animating.length; idx < sl; idx++ ) {
if ( animating[ idx ] && animating[ idx ]._natives && animating[ idx ]._natives.type === name ) {
animating.splice( idx, 1 );
// update for loop if something removed, but keep checking
idx--; sl--;
}
}
};
Popcorn.compositions = {};
// Plugin inheritance
Popcorn.compose = function( name, definition, manifest ) {
// If `manifest` arg is undefined, check for manifest within the `definition` object
// If no `definition.manifest`, an empty object is a sufficient fallback
Popcorn.manifest[ name ] = manifest = manifest || definition.manifest || {};
// register the effect by name
Popcorn.compositions[ name ] = definition;
};
Popcorn.plugin.effect = Popcorn.effect = Popcorn.compose;
// stores parsers keyed on filetype
Popcorn.parsers = {};
// An interface for extending Popcorn
// with parser functionality
Popcorn.parser = function( name, type, definition ) {
if ( Popcorn.protect.natives.indexOf( name.toLowerCase() ) >= 0 ) {
Popcorn.error( "'" + name + "' is a protected function name" );
return;
}
// fixes parameters for overloaded function call
if ( typeof type === "function" && !definition ) {
definition = type;
type = "";
}
if ( typeof definition !== "function" || typeof type !== "string" ) {
return;
}
// Provides some sugar, but ultimately extends
// the definition into Popcorn.p
var natives = Popcorn.events.all,
parseFn,
parser = {};
parseFn = function( filename, callback ) {
if ( !filename ) {
return this;
}
var that = this;
Popcorn.xhr({
url: filename,
dataType: type,
success: function( data ) {
var tracksObject = definition( data ),
tracksData,
tracksDataLen,
tracksDef,
idx = 0;
tracksData = tracksObject.data || [];
tracksDataLen = tracksData.length;
tracksDef = null;
// If no tracks to process, return immediately
if ( !tracksDataLen ) {
return;
}
// Create tracks out of parsed object
for ( ; idx < tracksDataLen; idx++ ) {
tracksDef = tracksData[ idx ];
for ( var key in tracksDef ) {
if ( hasOwn.call( tracksDef, key ) && !!that[ key ] ) {
that[ key ]( tracksDef[ key ] );
}
}
}
if ( callback ) {
callback();
}
}
});
return this;
};
// Assign new named definition
parser[ name ] = parseFn;
// Extend Popcorn.p with new named definition
Popcorn.extend( Popcorn.p, parser );
// keys the function name by filetype extension
//Popcorn.parsers[ name ] = true;
return parser;
};
// Cache references to reused RegExps
var rparams = /\?/,
// XHR Setup object
setup = {
url: "",
data: "",
dataType: "",
success: Popcorn.nop,
type: "GET",
async: true,
xhr: function() {
return new global.XMLHttpRequest();
}
};
Popcorn.xhr = function( options ) {
options.dataType = options.dataType && options.dataType.toLowerCase() || null;
if ( options.dataType &&
( options.dataType === "jsonp" || options.dataType === "script" ) ) {
Popcorn.xhr.getJSONP(
options.url,
options.success,
options.dataType === "script"
);
return;
}
var settings = Popcorn.extend( {}, setup, options );
// Create new XMLHttpRequest object
settings.ajax = settings.xhr();
if ( settings.ajax ) {
if ( settings.type === "GET" && settings.data ) {
// append query string
settings.url += ( rparams.test( settings.url ) ? "&" : "?" ) + settings.data;
// Garbage collect and reset settings.data
settings.data = null;
}
settings.ajax.open( settings.type, settings.url, settings.async );
settings.ajax.send( settings.data || null );
return Popcorn.xhr.httpData( settings );
}
};
Popcorn.xhr.httpData = function( settings ) {
var data, json = null;
settings.ajax.onreadystatechange = function() {
if ( settings.ajax.readyState === 4 ) {
try {
json = JSON.parse( settings.ajax.responseText );
} catch( e ) {
//suppress
}
data = {
xml: settings.ajax.responseXML,
text: settings.ajax.responseText,
json: json
};
// If a dataType was specified, return that type of data
if ( settings.dataType ) {
data = data[ settings.dataType ];
}
settings.success.call( settings.ajax, data );
}
};
return data;
};
Popcorn.xhr.getJSONP = function( url, success, isScript ) {
var head = document.head || document.getElementsByTagName( "head" )[ 0 ] || document.documentElement,
script = document.createElement( "script" ),
paramStr = url.split( "?" )[ 1 ],
isFired = false,
params = [],
callback, parts, callparam;
if ( paramStr && !isScript ) {
params = paramStr.split( "&" );
}
if ( params.length ) {
parts = params[ params.length - 1 ].split( "=" );
}
callback = params.length ? ( parts[ 1 ] ? parts[ 1 ] : parts[ 0 ] ) : "jsonp";
if ( !paramStr && !isScript ) {
url += "?callback=" + callback;
}
if ( callback && !isScript ) {
// If a callback name already exists
if ( !!window[ callback ] ) {
// Create a new unique callback name
callback = Popcorn.guid( callback );
}
// Define the JSONP success callback globally
window[ callback ] = function( data ) {
// Fire success callbacks
success && success( data );
isFired = true;
};
// Replace callback param and callback name
url = url.replace( parts.join( "=" ), parts[ 0 ] + "=" + callback );
}
script.onload = function() {
// Handling remote script loading callbacks
if ( isScript ) {
// getScript
success && success();
}
// Executing for JSONP requests
if ( isFired ) {
// Garbage collect the callback
delete window[ callback ];
}
// Garbage collect the script resource
head.removeChild( script );
};
script.src = url;
head.insertBefore( script, head.firstChild );
return;
};
Popcorn.getJSONP = Popcorn.xhr.getJSONP;
Popcorn.getScript = Popcorn.xhr.getScript = function( url, success ) {
return Popcorn.xhr.getJSONP( url, success, true );
};
Popcorn.util = {
// Simple function to parse a timestamp into seconds
// Acceptable formats are:
// HH:MM:SS.MMM
// HH:MM:SS;FF
// Hours and minutes are optional. They default to 0
toSeconds: function( timeStr, framerate ) {
// Hours and minutes are optional
// Seconds must be specified
// Seconds can be followed by milliseconds OR by the frame information
var validTimeFormat = /^([0-9]+:){0,2}[0-9]+([.;][0-9]+)?$/,
errorMessage = "Invalid time format",
digitPairs, lastIndex, lastPair, firstPair,
frameInfo, frameTime;
if ( typeof timeStr === "number" ) {
return timeStr;
}
if ( typeof timeStr === "string" &&
!validTimeFormat.test( timeStr ) ) {
Popcorn.error( errorMessage );
}
digitPairs = timeStr.split( ":" );
lastIndex = digitPairs.length - 1;
lastPair = digitPairs[ lastIndex ];
// Fix last element:
if ( lastPair.indexOf( ";" ) > -1 ) {
frameInfo = lastPair.split( ";" );
frameTime = 0;
if ( framerate && ( typeof framerate === "number" ) ) {
frameTime = parseFloat( frameInfo[ 1 ], 10 ) / framerate;
}
digitPairs[ lastIndex ] = parseInt( frameInfo[ 0 ], 10 ) + frameTime;
}
firstPair = digitPairs[ 0 ];
return {
1: parseFloat( firstPair, 10 ),
2: ( parseInt( firstPair, 10 ) * 60 ) +
parseFloat( digitPairs[ 1 ], 10 ),
3: ( parseInt( firstPair, 10 ) * 3600 ) +
( parseInt( digitPairs[ 1 ], 10 ) * 60 ) +
parseFloat( digitPairs[ 2 ], 10 )
}[ digitPairs.length || 1 ];
}
};
// Initialize locale data
// Based on http://en.wikipedia.org/wiki/Language_localisation#Language_tags_and_codes
function initLocale( arg ) {
var locale = typeof arg === "string" ? arg : [ arg.language, arg.region ].join( "-" ),
parts = locale.split( "-" );
// Setup locale data table
return {
iso6391: locale,
language: parts[ 0 ] || "",
region: parts[ 1 ] || ""
};
}
// Declare locale data table
var localeData = initLocale( global.navigator.userLanguage || global.navigator.language );
Popcorn.locale = {
// Popcorn.locale.get()
// returns reference to privately
// defined localeData
get: function() {
return localeData;
},
// Popcorn.locale.set( string|object );
set: function( arg ) {
localeData = initLocale( arg );
Popcorn.locale.broadcast();
return localeData;
},
// Popcorn.locale.broadcast( type )
// Sends events to all popcorn media instances that are
// listening for locale events
broadcast: function( type ) {
var instances = Popcorn.instances,
length = instances.length,
idx = 0,
instance;
type = type || "locale:changed";
// Iterate all current instances
for ( ; idx < length; idx++ ) {
instance = instances[ idx ];
// For those instances with locale event listeners,
// trigger a locale change event
if ( type in instance.data.events ) {
instance.trigger( type );
}
}
}
};
// alias for exec function
Popcorn.p.cue = Popcorn.p.exec;
// Exposes Popcorn to global context
global.Popcorn = Popcorn;
document.addEventListener( "DOMContentLoaded", function() {
// Supports non-specific elements
var dataAttr = "data-timeline-sources",
medias = document.querySelectorAll( "[" + dataAttr + "]" );
Popcorn.forEach( medias, function( idx, key ) {
var media = medias[ key ],
hasDataSources = false,
dataSources, data, popcornMedia;
// Ensure that the DOM has an id
if ( !media.id ) {
media.id = Popcorn.guid( "__popcorn" );
}
// Ensure we're looking at a dom node
if ( media.nodeType && media.nodeType === 1 ) {
popcornMedia = Popcorn( "#" + media.id );
dataSources = ( media.getAttribute( dataAttr ) || "" ).split( "," );
if ( dataSources[ 0 ] ) {
Popcorn.forEach( dataSources, function( source ) {
// split the parser and data as parser!file
data = source.split( "!" );
// if no parser is defined for the file, assume "parse" + file extension
if ( data.length === 1 ) {
data = source.split( "." );
data[ 0 ] = "parse" + data[ data.length - 1 ].toUpperCase();
data[ 1 ] = source;
}
// If the media has data sources and the correct parser is registered, continue to load
if ( dataSources[ 0 ] && popcornMedia[ data[ 0 ] ] ) {
// Set up the media and load in the datasources
popcornMedia[ data[ 0 ] ]( data[ 1 ] );
}
});
}
// Only play the media if it was specified to do so
if ( !!popcornMedia.autoplay ) {
popcornMedia.play();
}
}
});
}, false );
})(window, window.document);
| popcorn.js | (function(global, document) {
// Popcorn.js does not support archaic browsers
if ( !document.addEventListener ) {
global.Popcorn = {};
var methods = ( "removeInstance addInstance getInstanceById removeInstanceById " +
"forEach extend effects error guid sizeOf isArray nop position disable enable destroy " +
"addTrackEvent removeTrackEvent getTrackEvents getTrackEvent getLastTrackEventId " +
"timeUpdate plugin removePlugin compose effect parser xhr getJSONP getScript" ).split(/\s+/);
while( methods.length ) {
global.Popcorn[ methods.shift() ] = function() {};
}
return;
}
var
AP = Array.prototype,
OP = Object.prototype,
forEach = AP.forEach,
slice = AP.slice,
hasOwn = OP.hasOwnProperty,
toString = OP.toString,
// ID string matching
rIdExp = /^(#([\w\-\_\.]+))$/,
// Ready fn cache
readyStack = [],
readyBound = false,
readyFired = false,
// Non-public internal data object
internal = {
events: {
hash: {},
apis: {}
}
},
// Non-public `requestAnimFrame`
// http://paulirish.com/2011/requestanimationframe-for-smart-animating/
requestAnimFrame = (function(){
return global.requestAnimationFrame ||
global.webkitRequestAnimationFrame ||
global.mozRequestAnimationFrame ||
global.oRequestAnimationFrame ||
global.msRequestAnimationFrame ||
function( callback, element ) {
global.setTimeout( callback, 16 );
};
}()),
// Declare constructor
// Returns an instance object.
Popcorn = function( entity, options ) {
// Return new Popcorn object
return new Popcorn.p.init( entity, options || null );
};
// Instance caching
Popcorn.instances = [];
Popcorn.instanceIds = {};
Popcorn.removeInstance = function( instance ) {
// If called prior to any instances being created
// Return early to avoid splicing on nothing
if ( !Popcorn.instances.length ) {
return;
}
// Remove instance from Popcorn.instances
Popcorn.instances.splice( Popcorn.instanceIds[ instance.id ], 1 );
// Delete the instance id key
delete Popcorn.instanceIds[ instance.id ];
// Return current modified instances
return Popcorn.instances;
};
// Addes a Popcorn instance to the Popcorn instance array
Popcorn.addInstance = function( instance ) {
var instanceLen = Popcorn.instances.length,
instanceId = instance.media.id && instance.media.id;
// If the media element has its own `id` use it, otherwise provide one
// Ensure that instances have unique ids and unique entries
// Uses `in` operator to avoid false positives on 0
instance.id = !( instanceId in Popcorn.instanceIds ) && instanceId ||
"__popcorn" + instanceLen;
// Create a reference entry for this instance
Popcorn.instanceIds[ instance.id ] = instanceLen;
// Add this instance to the cache
Popcorn.instances.push( instance );
// Return the current modified instances
return Popcorn.instances;
};
// Request Popcorn object instance by id
Popcorn.getInstanceById = function( id ) {
return Popcorn.instances[ Popcorn.instanceIds[ id ] ];
};
// Remove Popcorn object instance by id
Popcorn.removeInstanceById = function( id ) {
return Popcorn.removeInstance( Popcorn.instances[ Popcorn.instanceIds[ id ] ] );
};
// Declare a shortcut (Popcorn.p) to and a definition of
// the new prototype for our Popcorn constructor
Popcorn.p = Popcorn.prototype = {
init: function( entity, options ) {
var matches;
// Supports Popcorn(function () { /../ })
// Originally proposed by Daniel Brooks
if ( typeof entity === "function" ) {
// If document ready has already fired
if ( document.readyState === "interactive" || document.readyState === "complete" ) {
entity( document, Popcorn );
return;
}
// Add `entity` fn to ready stack
readyStack.push( entity );
// This process should happen once per page load
if ( !readyBound ) {
// set readyBound flag
readyBound = true;
var DOMContentLoaded = function() {
readyFired = true;
// Remove global DOM ready listener
document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
// Execute all ready function in the stack
for ( var i = 0, readyStackLength = readyStack.length; i < readyStackLength; i++ ) {
readyStack[ i ].call( document, Popcorn );
}
// GC readyStack
readyStack = null;
};
// Register global DOM ready listener
document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
}
return;
}
// Check if entity is a valid string id
matches = rIdExp.exec( entity );
// Get media element by id or object reference
this.media = matches && matches.length && matches[ 2 ] ?
document.getElementById( matches[ 2 ] ) :
entity;
// Create an audio or video element property reference
this[ ( this.media.nodeName && this.media.nodeName.toLowerCase() ) || "video" ] = this.media;
// Register new instance
Popcorn.addInstance( this );
this.options = options || {};
this.isDestroyed = false;
this.data = {
// Allows disabling a plugin per instance
disabled: [],
// Stores DOM event queues by type
events: {},
// Stores Special event hooks data
hooks: {},
// Store track event history data
history: [],
// Stores ad-hoc state related data]
state: {
volume: this.media.volume
},
// Store track event object references by trackId
trackRefs: {},
// Playback track event queues
trackEvents: {
byStart: [{
start: -1,
end: -1
}],
byEnd: [{
start: -1,
end: -1
}],
animating: [],
startIndex: 0,
endIndex: 0,
previousUpdateTime: -1
}
};
// Wrap true ready check
var isReady = function( that ) {
var duration, videoDurationPlus, animate;
if ( that.media.readyState >= 2 ) {
// Adding padding to the front and end of the arrays
// this is so we do not fall off either end
duration = that.media.duration;
// Check for no duration info (NaN)
videoDurationPlus = duration != duration ? Number.MAX_VALUE : duration + 1;
Popcorn.addTrackEvent( that, {
start: videoDurationPlus,
end: videoDurationPlus
});
if ( that.options.frameAnimation ) {
// if Popcorn is created with frameAnimation option set to true,
// requestAnimFrame is used instead of "timeupdate" media event.
// This is for greater frame time accuracy, theoretically up to
// 60 frames per second as opposed to ~4 ( ~every 15-250ms)
animate = function () {
Popcorn.timeUpdate( that, {} );
that.trigger( "timeupdate" );
requestAnimFrame( animate );
};
requestAnimFrame( animate );
} else {
that.data.timeUpdateFunction = function( event ) {
Popcorn.timeUpdate( that, event );
}
if ( !that.isDestroyed ) {
that.media.addEventListener( "timeupdate", that.data.timeUpdateFunction, false );
}
}
} else {
global.setTimeout(function() {
isReady( that );
}, 1 );
}
};
isReady( this );
return this;
}
};
// Extend constructor prototype to instance prototype
// Allows chaining methods to instances
Popcorn.p.init.prototype = Popcorn.p;
Popcorn.forEach = function( obj, fn, context ) {
if ( !obj || !fn ) {
return {};
}
context = context || this;
var key, len;
// Use native whenever possible
if ( forEach && obj.forEach === forEach ) {
return obj.forEach( fn, context );
}
if ( toString.call( obj ) === "[object NodeList]" ) {
for ( key = 0, len = obj.length; key < len; key++ ) {
fn.call( context, obj[ key ], key, obj );
}
return obj;
}
for ( key in obj ) {
if ( hasOwn.call( obj, key ) ) {
fn.call( context, obj[ key ], key, obj );
}
}
return obj;
};
Popcorn.extend = function( obj ) {
var dest = obj, src = slice.call( arguments, 1 );
Popcorn.forEach( src, function( copy ) {
for ( var prop in copy ) {
dest[ prop ] = copy[ prop ];
}
});
return dest;
};
// A Few reusable utils, memoized onto Popcorn
Popcorn.extend( Popcorn, {
error: function( msg ) {
throw new Error( msg );
},
guid: function( prefix ) {
Popcorn.guid.counter++;
return ( prefix ? prefix : "" ) + ( +new Date() + Popcorn.guid.counter );
},
sizeOf: function( obj ) {
var size = 0;
for ( var prop in obj ) {
size++;
}
return size;
},
isArray: Array.isArray || function( array ) {
return toString.call( array ) === "[object Array]";
},
nop: function() {},
position: function( elem ) {
var clientRect = elem.getBoundingClientRect(),
bounds = {},
doc = elem.ownerDocument,
docElem = document.documentElement,
body = document.body,
clientTop, clientLeft, scrollTop, scrollLeft, top, left;
// Determine correct clientTop/Left
clientTop = docElem.clientTop || body.clientTop || 0;
clientLeft = docElem.clientLeft || body.clientLeft || 0;
// Determine correct scrollTop/Left
scrollTop = ( global.pageYOffset && docElem.scrollTop || body.scrollTop );
scrollLeft = ( global.pageXOffset && docElem.scrollLeft || body.scrollLeft );
// Temp top/left
top = Math.ceil( clientRect.top + scrollTop - clientTop );
left = Math.ceil( clientRect.left + scrollLeft - clientLeft );
for ( var p in clientRect ) {
bounds[ p ] = Math.round( clientRect[ p ] );
}
return Popcorn.extend({}, bounds, { top: top, left: left });
},
disable: function( instance, plugin ) {
var disabled = instance.data.disabled;
if ( disabled.indexOf( plugin ) === -1 ) {
disabled.push( plugin );
}
return instance;
},
enable: function( instance, plugin ) {
var disabled = instance.data.disabled,
index = disabled.indexOf( plugin );
if ( index > -1 ) {
disabled.splice( index, 1 );
}
return instance;
},
destroy: function( instance ) {
var events = instance.data.events,
singleEvent, item, fn;
// Iterate through all events and remove them
for ( item in events ) {
singleEvent = events[ item ];
for ( fn in singleEvent ) {
delete singleEvent[ fn ];
}
events[ item ] = null;
}
if ( !instance.isDestroyed ) {
instance.media.removeEventListener( "timeupdate", instance.data.timeUpdateFunction, false );
instance.isDestroyed = true;
}
Popcorn.removeInstance( instance );
}
});
// Memoized GUID Counter
Popcorn.guid.counter = 1;
// Factory to implement getters, setters and controllers
// as Popcorn instance methods. The IIFE will create and return
// an object with defined methods
Popcorn.extend(Popcorn.p, (function() {
var methods = "load play pause currentTime playbackRate volume duration preload playbackRate " +
"autoplay loop controls muted buffered readyState seeking paused played seekable ended",
ret = {};
// Build methods, store in object that is returned and passed to extend
Popcorn.forEach( methods.split( /\s+/g ), function( name ) {
ret[ name ] = function( arg ) {
if ( typeof this.media[ name ] === "function" ) {
this.media[ name ]();
return this;
}
if ( arg != null ) {
this.media[ name ] = arg;
return this;
}
return this.media[ name ];
};
});
return ret;
})()
);
Popcorn.forEach( "enable disable".split(" "), function( method ) {
Popcorn.p[ method ] = function( plugin ) {
return Popcorn[ method ]( this, plugin );
};
});
Popcorn.extend(Popcorn.p, {
// Rounded currentTime
roundTime: function() {
return -~this.media.currentTime;
},
// Attach an event to a single point in time
exec: function( time, fn ) {
// Creating a one second track event with an empty end
Popcorn.addTrackEvent( this, {
start: time,
end: time + 1,
_running: false,
_natives: {
start: fn || Popcorn.nop,
end: Popcorn.nop,
type: "exec"
}
});
return this;
},
// Mute the calling media, optionally toggle
mute: function( toggle ) {
var event = toggle == null || toggle === true ? "muted" : "unmuted";
// If `toggle` is explicitly `false`,
// unmute the media and restore the volume level
if ( event === "unmuted" ) {
this.media.muted = false;
this.media.volume = this.data.state.volume;
}
// If `toggle` is either null or undefined,
// save the current volume and mute the media element
if ( event === "muted" ) {
this.data.state.volume = this.media.volume;
this.media.muted = true;
}
// Trigger either muted|unmuted event
this.trigger( event );
return this;
},
// Convenience method, unmute the calling media
unmute: function( toggle ) {
return this.mute( toggle == null ? false : !toggle );
},
// Get the client bounding box of an instance element
position: function() {
return Popcorn.position( this.media );
},
// Toggle a plugin's playback behaviour (on or off) per instance
toggle: function( plugin ) {
return Popcorn[ this.data.disabled.indexOf( plugin ) > -1 ? "enable" : "disable" ]( this, plugin );
},
// Set default values for plugin options objects per instance
defaults: function( plugin, defaults ) {
// If an array of default configurations is provided,
// iterate and apply each to this instance
if ( Popcorn.isArray( plugin ) ) {
Popcorn.forEach( plugin, function( obj ) {
for ( var name in obj ) {
this.defaults( name, obj[ name ] );
}
}, this );
return this;
}
if ( !this.options.defaults ) {
this.options.defaults = {};
}
if ( !this.options.defaults[ plugin ] ) {
this.options.defaults[ plugin ] = {};
}
Popcorn.extend( this.options.defaults[ plugin ], defaults );
return this;
}
});
Popcorn.Events = {
UIEvents: "blur focus focusin focusout load resize scroll unload",
MouseEvents: "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave click dblclick",
Events: "loadstart progress suspend emptied stalled play pause " +
"loadedmetadata loadeddata waiting playing canplay canplaythrough " +
"seeking seeked timeupdate ended ratechange durationchange volumechange"
};
Popcorn.Events.Natives = Popcorn.Events.UIEvents + " " +
Popcorn.Events.MouseEvents + " " +
Popcorn.Events.Events;
internal.events.apiTypes = [ "UIEvents", "MouseEvents", "Events" ];
// Privately compile events table at load time
(function( events, data ) {
var apis = internal.events.apiTypes,
eventsList = events.Natives.split( /\s+/g ),
idx = 0, len = eventsList.length, prop;
for( ; idx < len; idx++ ) {
data.hash[ eventsList[idx] ] = true;
}
apis.forEach(function( val, idx ) {
data.apis[ val ] = {};
var apiEvents = events[ val ].split( /\s+/g ),
len = apiEvents.length,
k = 0;
for ( ; k < len; k++ ) {
data.apis[ val ][ apiEvents[ k ] ] = true;
}
});
})( Popcorn.Events, internal.events );
Popcorn.events = {
isNative: function( type ) {
return !!internal.events.hash[ type ];
},
getInterface: function( type ) {
if ( !Popcorn.events.isNative( type ) ) {
return false;
}
var eventApi = internal.events,
apis = eventApi.apiTypes,
apihash = eventApi.apis,
idx = 0, len = apis.length, api, tmp;
for ( ; idx < len; idx++ ) {
tmp = apis[ idx ];
if ( apihash[ tmp ][ type ] ) {
api = tmp;
break;
}
}
return api;
},
// Compile all native events to single array
all: Popcorn.Events.Natives.split( /\s+/g ),
// Defines all Event handling static functions
fn: {
trigger: function( type, data ) {
var eventInterface, evt;
// setup checks for custom event system
if ( this.data.events[ type ] && Popcorn.sizeOf( this.data.events[ type ] ) ) {
eventInterface = Popcorn.events.getInterface( type );
if ( eventInterface ) {
evt = document.createEvent( eventInterface );
evt.initEvent( type, true, true, global, 1 );
this.media.dispatchEvent( evt );
return this;
}
// Custom events
Popcorn.forEach( this.data.events[ type ], function( obj, key ) {
obj.call( this, data );
}, this );
}
return this;
},
listen: function( type, fn ) {
var self = this,
hasEvents = true,
eventHook = Popcorn.events.hooks[ type ],
origType = type,
tmp;
if ( !this.data.events[ type ] ) {
this.data.events[ type ] = {};
hasEvents = false;
}
// Check and setup event hooks
if ( eventHook ) {
// Execute hook add method if defined
if ( eventHook.add ) {
eventHook.add.call( this, {}, fn );
}
// Reassign event type to our piggyback event type if defined
if ( eventHook.bind ) {
type = eventHook.bind;
}
// Reassign handler if defined
if ( eventHook.handler ) {
tmp = fn;
fn = function wrapper( event ) {
eventHook.handler.call( self, event, tmp );
};
}
// assume the piggy back event is registered
hasEvents = true;
// Setup event registry entry
if ( !this.data.events[ type ] ) {
this.data.events[ type ] = {};
// Toggle if the previous assumption was untrue
hasEvents = false;
}
}
// Register event and handler
this.data.events[ type ][ fn.name || ( fn.toString() + Popcorn.guid() ) ] = fn;
// only attach one event of any type
if ( !hasEvents && Popcorn.events.all.indexOf( type ) > -1 ) {
this.media.addEventListener( type, function( event ) {
Popcorn.forEach( self.data.events[ type ], function( obj, key ) {
if ( typeof obj === "function" ) {
obj.call( self, event );
}
});
}, false);
}
return this;
},
unlisten: function( type, fn ) {
if ( this.data.events[ type ] && this.data.events[ type ][ fn ] ) {
delete this.data.events[ type ][ fn ];
return this;
}
this.data.events[ type ] = null;
return this;
}
},
hooks: {
canplayall: {
bind: "canplaythrough",
add: function( event, callback ) {
var state = false;
if ( this.media.readyState ) {
callback.call( this, event );
state = true;
}
this.data.hooks.canplayall = {
fired: state
};
},
// declare special handling instructions
handler: function canplayall( event, callback ) {
if ( !this.data.hooks.canplayall.fired ) {
// trigger original user callback once
callback.call( this, event );
this.data.hooks.canplayall.fired = true;
}
}
}
}
};
// Extend Popcorn.events.fns (listen, unlisten, trigger) to all Popcorn instances
Popcorn.forEach( [ "trigger", "listen", "unlisten" ], function( key ) {
Popcorn.p[ key ] = Popcorn.events.fn[ key ];
});
// Protected API methods
Popcorn.protect = {
natives: ( "load play pause currentTime playbackRate mute volume duration removePlugin roundTime trigger listen unlisten exec" +
"preload playbackRate autoplay loop controls muted buffered readyState seeking paused played seekable ended" ).toLowerCase().split( /\s+/ )
};
// Internal Only - Adds track events to the instance object
Popcorn.addTrackEvent = function( obj, track ) {
// Determine if this track has default options set for it
// If so, apply them to the track object
if ( track && track._natives && track._natives.type &&
( obj.options.defaults && obj.options.defaults[ track._natives.type ] ) ) {
track = Popcorn.extend( {}, obj.options.defaults[ track._natives.type ], track );
}
if ( track._natives ) {
// Supports user defined track event id
track._id = !track.id ? Popcorn.guid( track._natives.type ) : track.id;
// Push track event ids into the history
obj.data.history.push( track._id );
}
track.start = Popcorn.util.toSeconds( track.start, obj.options.framerate );
track.end = Popcorn.util.toSeconds( track.end, obj.options.framerate );
// Store this definition in an array sorted by times
var byStart = obj.data.trackEvents.byStart,
byEnd = obj.data.trackEvents.byEnd,
idx;
for ( idx = byStart.length - 1; idx >= 0; idx-- ) {
if ( track.start >= byStart[ idx ].start ) {
byStart.splice( idx + 1, 0, track );
break;
}
}
for ( idx = byEnd.length - 1; idx >= 0; idx-- ) {
if ( track.end > byEnd[ idx ].end ) {
byEnd.splice( idx + 1, 0, track );
break;
}
}
// Store references to user added trackevents in ref table
if ( track._id ) {
Popcorn.addTrackEvent.ref( obj, track );
}
};
// Internal Only - Adds track event references to the instance object's trackRefs hash table
Popcorn.addTrackEvent.ref = function( obj, track ) {
obj.data.trackRefs[ track._id ] = track;
return obj;
};
Popcorn.removeTrackEvent = function( obj, trackId ) {
var historyLen = obj.data.history.length,
indexWasAt = 0,
byStart = [],
byEnd = [],
animating = [],
history = [];
Popcorn.forEach( obj.data.trackEvents.byStart, function( o, i, context ) {
// Preserve the original start/end trackEvents
if ( !o._id ) {
byStart.push( obj.data.trackEvents.byStart[i] );
byEnd.push( obj.data.trackEvents.byEnd[i] );
}
// Filter for user track events (vs system track events)
if ( o._id ) {
// Filter for the trackevent to remove
if ( o._id !== trackId ) {
byStart.push( obj.data.trackEvents.byStart[i] );
byEnd.push( obj.data.trackEvents.byEnd[i] );
}
// Capture the position of the track being removed.
if ( o._id === trackId ) {
indexWasAt = i;
o._natives._teardown && o._natives._teardown.call( obj, o );
}
}
});
if ( obj.data.trackEvents.animating.length ) {
Popcorn.forEach( obj.data.trackEvents.animating, function( o, i, context ) {
// Preserve the original start/end trackEvents
if ( !o._id ) {
animating.push( obj.data.trackEvents.animating[i] );
}
// Filter for user track events (vs system track events)
if ( o._id ) {
// Filter for the trackevent to remove
if ( o._id !== trackId ) {
animating.push( obj.data.trackEvents.animating[i] );
}
}
});
}
// Update
if ( indexWasAt <= obj.data.trackEvents.startIndex ) {
obj.data.trackEvents.startIndex--;
}
if ( indexWasAt <= obj.data.trackEvents.endIndex ) {
obj.data.trackEvents.endIndex--;
}
obj.data.trackEvents.byStart = byStart;
obj.data.trackEvents.byEnd = byEnd;
obj.data.trackEvents.animating = animating;
for ( var i = 0; i < historyLen; i++ ) {
if ( obj.data.history[ i ] !== trackId ) {
history.push( obj.data.history[ i ] );
}
}
// Update ordered history array
obj.data.history = history;
// Update track event references
Popcorn.removeTrackEvent.ref( obj, trackId );
};
// Internal Only - Removes track event references from instance object's trackRefs hash table
Popcorn.removeTrackEvent.ref = function( obj, trackId ) {
delete obj.data.trackRefs[ trackId ];
return obj;
};
// Return an array of track events bound to this instance object
Popcorn.getTrackEvents = function( obj ) {
var trackevents = [],
refs = obj.data.trackEvents.byStart,
length = refs.length,
idx = 0,
ref;
for ( ; idx < length; idx++ ) {
ref = refs[ idx ];
// Return only user attributed track event references
if ( ref._id ) {
trackevents.push( ref );
}
}
return trackevents;
};
// Internal Only - Returns an instance object's trackRefs hash table
Popcorn.getTrackEvents.ref = function( obj ) {
return obj.data.trackRefs;
};
// Return a single track event bound to this instance object
Popcorn.getTrackEvent = function( obj, trackId ) {
return obj.data.trackRefs[ trackId ];
};
// Internal Only - Returns an instance object's track reference by track id
Popcorn.getTrackEvent.ref = function( obj, trackId ) {
return obj.data.trackRefs[ trackId ];
};
Popcorn.getLastTrackEventId = function( obj ) {
return obj.data.history[ obj.data.history.length - 1 ];
};
Popcorn.timeUpdate = function( obj, event ) {
var currentTime = obj.media.currentTime,
previousTime = obj.data.trackEvents.previousUpdateTime,
tracks = obj.data.trackEvents,
animating = tracks.animating,
end = tracks.endIndex,
start = tracks.startIndex,
animIndex = 0,
registryByName = Popcorn.registryByName,
byEnd, byStart, byAnimate, natives, type;
// Playbar advancing
if ( previousTime < currentTime ) {
while ( tracks.byEnd[ end ] && tracks.byEnd[ end ].end <= currentTime ) {
byEnd = tracks.byEnd[ end ];
natives = byEnd._natives;
type = natives && natives.type;
// If plugin does not exist on this instance, remove it
if ( !natives ||
( !!registryByName[ type ] ||
!!obj[ type ] ) ) {
if ( byEnd._running === true ) {
byEnd._running = false;
natives.end.call( obj, event, byEnd );
}
end++;
} else {
// remove track event
Popcorn.removeTrackEvent( obj, byEnd._id );
return;
}
}
while ( tracks.byStart[ start ] && tracks.byStart[ start ].start <= currentTime ) {
byStart = tracks.byStart[ start ];
natives = byStart._natives;
type = natives && natives.type;
// If plugin does not exist on this instance, remove it
if ( !natives ||
( !!registryByName[ type ] ||
!!obj[ type ] ) ) {
if ( byStart.end > currentTime &&
byStart._running === false &&
obj.data.disabled.indexOf( type ) === -1 ) {
byStart._running = true;
natives.start.call( obj, event, byStart );
// If the `frameAnimation` option is used,
// push the current byStart object into the `animating` cue
if ( obj.options.frameAnimation &&
( byStart && byStart._running && byStart._natives.frame ) ) {
animating.push( byStart );
}
}
start++;
} else {
// remove track event
Popcorn.removeTrackEvent( obj, byStart._id );
return;
}
}
// If the `frameAnimation` option is used, iterate the animating track
// and execute the `frame` callback
if ( obj.options.frameAnimation ) {
while ( animIndex < animating.length ) {
byAnimate = animating[ animIndex ];
if ( !byAnimate._running ) {
animating.splice( animIndex, 1 );
} else {
byAnimate._natives.frame.call( obj, event, byAnimate, currentTime );
animIndex++;
}
}
}
// Playbar receding
} else if ( previousTime > currentTime ) {
while ( tracks.byStart[ start ] && tracks.byStart[ start ].start > currentTime ) {
byStart = tracks.byStart[ start ];
natives = byStart._natives;
type = natives && natives.type;
// if plugin does not exist on this instance, remove it
if ( !natives ||
( !!registryByName[ type ] ||
!!obj[ type ] ) ) {
if ( byStart._running === true ) {
byStart._running = false;
natives.end.call( obj, event, byStart );
}
start--;
} else {
// remove track event
Popcorn.removeTrackEvent( obj, byStart._id );
return;
}
}
while ( tracks.byEnd[ end ] && tracks.byEnd[ end ].end > currentTime ) {
byEnd = tracks.byEnd[ end ];
natives = byEnd._natives;
type = natives && natives.type;
// if plugin does not exist on this instance, remove it
if ( !natives ||
( !!registryByName[ type ] ||
!!obj[ type ] ) ) {
if ( byEnd.start <= currentTime &&
byEnd._running === false &&
obj.data.disabled.indexOf( type ) === -1 ) {
byEnd._running = true;
natives.start.call( obj, event, byEnd );
// If the `frameAnimation` option is used,
// push the current byEnd object into the `animating` cue
if ( obj.options.frameAnimation &&
( byEnd && byEnd._running && byEnd._natives.frame ) ) {
animating.push( byEnd );
}
}
end--;
} else {
// remove track event
Popcorn.removeTrackEvent( obj, byEnd._id );
return;
}
}
// If the `frameAnimation` option is used, iterate the animating track
// and execute the `frame` callback
if ( obj.options.frameAnimation ) {
while ( animIndex < animating.length ) {
byAnimate = animating[ animIndex ];
if ( !byAnimate._running ) {
animating.splice( animIndex, 1 );
} else {
byAnimate._natives.frame.call( obj, event, byAnimate, currentTime );
animIndex++;
}
}
}
// time bar is not moving ( video is paused )
}
tracks.endIndex = end;
tracks.startIndex = start;
tracks.previousUpdateTime = currentTime;
};
// Map and Extend TrackEvent functions to all Popcorn instances
Popcorn.extend( Popcorn.p, {
getTrackEvents: function() {
return Popcorn.getTrackEvents.call( null, this );
},
getTrackEvent: function( id ) {
return Popcorn.getTrackEvent.call( null, this, id );
},
getLastTrackEventId: function() {
return Popcorn.getLastTrackEventId.call( null, this );
},
removeTrackEvent: function( id ) {
Popcorn.removeTrackEvent.call( null, this, id );
return this;
},
removePlugin: function( name ) {
Popcorn.removePlugin.call( null, this, name );
return this;
},
timeUpdate: function( event ) {
Popcorn.timeUpdate.call( null, this, event );
return this;
},
destroy: function() {
Popcorn.destroy.call( null, this );
return this;
}
});
// Plugin manifests
Popcorn.manifest = {};
// Plugins are registered
Popcorn.registry = [];
Popcorn.registryByName = {};
// An interface for extending Popcorn
// with plugin functionality
Popcorn.plugin = function( name, definition, manifest ) {
if ( Popcorn.protect.natives.indexOf( name.toLowerCase() ) >= 0 ) {
Popcorn.error( "'" + name + "' is a protected function name" );
return;
}
// Provides some sugar, but ultimately extends
// the definition into Popcorn.p
var reserved = [ "start", "end" ],
plugin = {},
setup,
isfn = typeof definition === "function",
methods = [ "_setup", "_teardown", "start", "end", "frame" ];
// combines calls of two function calls into one
var combineFn = function( first, second ) {
first = first || Popcorn.nop;
second = second || Popcorn.nop;
return function() {
first.apply( this, arguments );
second.apply( this, arguments );
};
};
// If `manifest` arg is undefined, check for manifest within the `definition` object
// If no `definition.manifest`, an empty object is a sufficient fallback
Popcorn.manifest[ name ] = manifest = manifest || definition.manifest || {};
// apply safe, and empty default functions
methods.forEach(function( method ) {
definition[ method ] = definition[ method ] || Popcorn.nop;
});
var pluginFn = function( setup, options ) {
if ( !options ) {
return this;
}
// Storing the plugin natives
var natives = options._natives = {},
compose = "",
defaults, originalOpts, manifestOpts, mergedSetupOpts;
Popcorn.extend( natives, setup );
options._natives.type = name;
options._running = false;
// Check for previously set default options
defaults = this.options.defaults && this.options.defaults[ options._natives && options._natives.type ];
// default to an empty string if no effect exists
// split string into an array of effects
options.compose = options.compose && options.compose.split( " " ) || [];
options.effect = options.effect && options.effect.split( " " ) || [];
// join the two arrays together
options.compose = options.compose.concat( options.effect );
options.compose.forEach(function( composeOption ) {
// if the requested compose is garbage, throw it away
compose = Popcorn.compositions[ composeOption ] || {};
// extends previous functions with compose function
methods.forEach(function( method ) {
natives[ method ] = combineFn( natives[ method ], compose[ method ] );
});
});
// Ensure a manifest object, an empty object is a sufficient fallback
options._natives.manifest = manifest;
// Checks for expected properties
if ( !( "start" in options ) ) {
options.start = 0;
}
if ( !( "end" in options ) ) {
options.end = this.duration() || Number.MAX_VALUE;
}
// Merge with defaults if they exist, make sure per call is prioritized
mergedSetupOpts = defaults ? Popcorn.extend( {}, defaults, options ) :
options;
// Resolves 239, 241, 242
if ( !mergedSetupOpts.target ) {
// Sometimes the manifest may be missing entirely
// or it has an options object that doesn't have a `target` property
manifestOpts = "options" in manifest && manifest.options;
mergedSetupOpts.target = manifestOpts && "target" in manifestOpts && manifestOpts.target;
}
// Trigger _setup method if exists
options._natives._setup && options._natives._setup.call( this, mergedSetupOpts );
// Create new track event for this instance
Popcorn.addTrackEvent( this, Popcorn.extend( mergedSetupOpts, options ) );
// Future support for plugin event definitions
// for all of the native events
Popcorn.forEach( setup, function( callback, type ) {
if ( type !== "type" ) {
if ( reserved.indexOf( type ) === -1 ) {
this.listen( type, callback );
}
}
}, this );
return this;
};
// Assign new named definition
plugin[ name ] = function( options ) {
return pluginFn.call( this, isfn ? definition.call( this, options ) : definition,
options );
};
// Extend Popcorn.p with new named definition
Popcorn.extend( Popcorn.p, plugin );
// Push into the registry
var entry = {
fn: plugin[ name ],
definition: definition,
base: definition,
parents: [],
name: name
};
Popcorn.registry.push(
Popcorn.extend( plugin, entry, {
type: name
})
);
Popcorn.registryByName[ name ] = entry;
return plugin;
};
Popcorn.plugin.debug = false;
// removePlugin( type ) removes all tracks of that from all instances of popcorn
// removePlugin( obj, type ) removes all tracks of type from obj, where obj is a single instance of popcorn
Popcorn.removePlugin = function( obj, name ) {
// Check if we are removing plugin from an instance or from all of Popcorn
if ( !name ) {
// Fix the order
name = obj;
obj = Popcorn.p;
if ( Popcorn.protect.natives.indexOf( name.toLowerCase() ) >= 0 ) {
Popcorn.error( "'" + name + "' is a protected function name" );
return;
}
var registryLen = Popcorn.registry.length,
registryIdx;
// remove plugin reference from registry
for ( registryIdx = 0; registryIdx < registryLen; registryIdx++ ) {
if ( Popcorn.registry[ registryIdx ].name === name ) {
Popcorn.registry.splice( registryIdx, 1 );
delete Popcorn.registryByName[ name ];
// delete the plugin
delete obj[ name ];
// plugin found and removed, stop checking, we are done
return;
}
}
}
var byStart = obj.data.trackEvents.byStart,
byEnd = obj.data.trackEvents.byEnd,
animating = obj.data.trackEvents.animating,
idx, sl;
// remove all trackEvents
for ( idx = 0, sl = byStart.length; idx < sl; idx++ ) {
if ( ( byStart[ idx ] && byStart[ idx ]._natives && byStart[ idx ]._natives.type === name ) &&
( byEnd[ idx ] && byEnd[ idx ]._natives && byEnd[ idx ]._natives.type === name ) ) {
byStart[ idx ]._natives._teardown && byStart[ idx ]._natives._teardown.call( obj, byStart[ idx ] );
byStart.splice( idx, 1 );
byEnd.splice( idx, 1 );
// update for loop if something removed, but keep checking
idx--; sl--;
if ( obj.data.trackEvents.startIndex <= idx ) {
obj.data.trackEvents.startIndex--;
obj.data.trackEvents.endIndex--;
}
}
}
//remove all animating events
for ( idx = 0, sl = animating.length; idx < sl; idx++ ) {
if ( animating[ idx ] && animating[ idx ]._natives && animating[ idx ]._natives.type === name ) {
animating.splice( idx, 1 );
// update for loop if something removed, but keep checking
idx--; sl--;
}
}
};
Popcorn.compositions = {};
// Plugin inheritance
Popcorn.compose = function( name, definition, manifest ) {
// If `manifest` arg is undefined, check for manifest within the `definition` object
// If no `definition.manifest`, an empty object is a sufficient fallback
Popcorn.manifest[ name ] = manifest = manifest || definition.manifest || {};
// register the effect by name
Popcorn.compositions[ name ] = definition;
};
Popcorn.plugin.effect = Popcorn.effect = Popcorn.compose;
// stores parsers keyed on filetype
Popcorn.parsers = {};
// An interface for extending Popcorn
// with parser functionality
Popcorn.parser = function( name, type, definition ) {
if ( Popcorn.protect.natives.indexOf( name.toLowerCase() ) >= 0 ) {
Popcorn.error( "'" + name + "' is a protected function name" );
return;
}
// fixes parameters for overloaded function call
if ( typeof type === "function" && !definition ) {
definition = type;
type = "";
}
if ( typeof definition !== "function" || typeof type !== "string" ) {
return;
}
// Provides some sugar, but ultimately extends
// the definition into Popcorn.p
var natives = Popcorn.events.all,
parseFn,
parser = {};
parseFn = function( filename, callback ) {
if ( !filename ) {
return this;
}
var that = this;
Popcorn.xhr({
url: filename,
dataType: type,
success: function( data ) {
var tracksObject = definition( data ),
tracksData,
tracksDataLen,
tracksDef,
idx = 0;
tracksData = tracksObject.data || [];
tracksDataLen = tracksData.length;
tracksDef = null;
// If no tracks to process, return immediately
if ( !tracksDataLen ) {
return;
}
// Create tracks out of parsed object
for ( ; idx < tracksDataLen; idx++ ) {
tracksDef = tracksData[ idx ];
for ( var key in tracksDef ) {
if ( hasOwn.call( tracksDef, key ) && !!that[ key ] ) {
that[ key ]( tracksDef[ key ] );
}
}
}
if ( callback ) {
callback();
}
}
});
return this;
};
// Assign new named definition
parser[ name ] = parseFn;
// Extend Popcorn.p with new named definition
Popcorn.extend( Popcorn.p, parser );
// keys the function name by filetype extension
//Popcorn.parsers[ name ] = true;
return parser;
};
// Cache references to reused RegExps
var rparams = /\?/,
// XHR Setup object
setup = {
url: "",
data: "",
dataType: "",
success: Popcorn.nop,
type: "GET",
async: true,
xhr: function() {
return new global.XMLHttpRequest();
}
};
Popcorn.xhr = function( options ) {
options.dataType = options.dataType && options.dataType.toLowerCase() || null;
if ( options.dataType &&
( options.dataType === "jsonp" || options.dataType === "script" ) ) {
Popcorn.xhr.getJSONP(
options.url,
options.success,
options.dataType === "script"
);
return;
}
var settings = Popcorn.extend( {}, setup, options );
// Create new XMLHttpRequest object
settings.ajax = settings.xhr();
if ( settings.ajax ) {
if ( settings.type === "GET" && settings.data ) {
// append query string
settings.url += ( rparams.test( settings.url ) ? "&" : "?" ) + settings.data;
// Garbage collect and reset settings.data
settings.data = null;
}
settings.ajax.open( settings.type, settings.url, settings.async );
settings.ajax.send( settings.data || null );
return Popcorn.xhr.httpData( settings );
}
};
Popcorn.xhr.httpData = function( settings ) {
var data, json = null;
settings.ajax.onreadystatechange = function() {
if ( settings.ajax.readyState === 4 ) {
try {
json = JSON.parse( settings.ajax.responseText );
} catch( e ) {
//suppress
}
data = {
xml: settings.ajax.responseXML,
text: settings.ajax.responseText,
json: json
};
// If a dataType was specified, return that type of data
if ( settings.dataType ) {
data = data[ settings.dataType ];
}
settings.success.call( settings.ajax, data );
}
};
return data;
};
Popcorn.xhr.getJSONP = function( url, success, isScript ) {
var head = document.head || document.getElementsByTagName( "head" )[ 0 ] || document.documentElement,
script = document.createElement( "script" ),
paramStr = url.split( "?" )[ 1 ],
isFired = false,
params = [],
callback, parts, callparam;
if ( paramStr && !isScript ) {
params = paramStr.split( "&" );
}
if ( params.length ) {
parts = params[ params.length - 1 ].split( "=" );
}
callback = params.length ? ( parts[ 1 ] ? parts[ 1 ] : parts[ 0 ] ) : "jsonp";
if ( !paramStr && !isScript ) {
url += "?callback=" + callback;
}
if ( callback && !isScript ) {
// If a callback name already exists
if ( !!window[ callback ] ) {
// Create a new unique callback name
callback = Popcorn.guid( callback );
}
// Define the JSONP success callback globally
window[ callback ] = function( data ) {
// Fire success callbacks
success && success( data );
isFired = true;
};
// Replace callback param and callback name
url = url.replace( parts.join( "=" ), parts[ 0 ] + "=" + callback );
}
script.onload = function() {
// Handling remote script loading callbacks
if ( isScript ) {
// getScript
success && success();
}
// Executing for JSONP requests
if ( isFired ) {
// Garbage collect the callback
delete window[ callback ];
}
// Garbage collect the script resource
head.removeChild( script );
};
script.src = url;
head.insertBefore( script, head.firstChild );
return;
};
Popcorn.getJSONP = Popcorn.xhr.getJSONP;
Popcorn.getScript = Popcorn.xhr.getScript = function( url, success ) {
return Popcorn.xhr.getJSONP( url, success, true );
};
Popcorn.util = {
// Simple function to parse a timestamp into seconds
// Acceptable formats are:
// HH:MM:SS.MMM
// HH:MM:SS;FF
// Hours and minutes are optional. They default to 0
toSeconds: function( timeStr, framerate ) {
// Hours and minutes are optional
// Seconds must be specified
// Seconds can be followed by milliseconds OR by the frame information
var validTimeFormat = /^([0-9]+:){0,2}[0-9]+([.;][0-9]+)?$/,
errorMessage = "Invalid time format",
digitPairs, lastIndex, lastPair, firstPair,
frameInfo, frameTime;
if ( typeof timeStr === "number" ) {
return timeStr;
}
if ( typeof timeStr === "string" &&
!validTimeFormat.test( timeStr ) ) {
Popcorn.error( errorMessage );
}
digitPairs = timeStr.split( ":" );
lastIndex = digitPairs.length - 1;
lastPair = digitPairs[ lastIndex ];
// Fix last element:
if ( lastPair.indexOf( ";" ) > -1 ) {
frameInfo = lastPair.split( ";" );
frameTime = 0;
if ( framerate && ( typeof framerate === "number" ) ) {
frameTime = parseFloat( frameInfo[ 1 ], 10 ) / framerate;
}
digitPairs[ lastIndex ] = parseInt( frameInfo[ 0 ], 10 ) + frameTime;
}
firstPair = digitPairs[ 0 ];
return {
1: parseFloat( firstPair, 10 ),
2: ( parseInt( firstPair, 10 ) * 60 ) +
parseFloat( digitPairs[ 1 ], 10 ),
3: ( parseInt( firstPair, 10 ) * 3600 ) +
( parseInt( digitPairs[ 1 ], 10 ) * 60 ) +
parseFloat( digitPairs[ 2 ], 10 )
}[ digitPairs.length || 1 ];
}
};
// Initialize locale data
// Based on http://en.wikipedia.org/wiki/Language_localisation#Language_tags_and_codes
function initLocale( arg ) {
var locale = typeof arg === "string" ? arg : [ arg.language, arg.region ].join( "-" ),
parts = locale.split( "-" );
// Setup locale data table
return {
iso6391: locale,
language: parts[ 0 ] || "",
region: parts[ 1 ] || ""
};
}
// Declare locale data table
var localeData = initLocale( global.navigator.userLanguage || global.navigator.language );
Popcorn.locale = {
// Popcorn.locale.get()
// returns reference to privately
// defined localeData
get: function() {
return localeData;
},
// Popcorn.locale.set( string|object );
set: function( arg ) {
localeData = initLocale( arg );
Popcorn.locale.broadcast();
return localeData;
},
// Popcorn.locale.broadcast( type )
// Sends events to all popcorn media instances that are
// listening for locale events
broadcast: function( type ) {
var instances = Popcorn.instances,
length = instances.length,
idx = 0,
instance;
type = type || "locale:changed";
// Iterate all current instances
for ( ; idx < length; idx++ ) {
instance = instances[ idx ];
// For those instances with locale event listeners,
// trigger a locale change event
if ( type in instance.data.events ) {
instance.trigger( type );
}
}
}
};
// alias for exec function
Popcorn.p.cue = Popcorn.p.exec;
// Exposes Popcorn to global context
global.Popcorn = Popcorn;
document.addEventListener( "DOMContentLoaded", function() {
// Supports non-specific elements
var dataAttr = "data-timeline-sources",
medias = document.querySelectorAll( "[" + dataAttr + "]" );
Popcorn.forEach( medias, function( idx, key ) {
var media = medias[ key ],
hasDataSources = false,
dataSources, data, popcornMedia;
// Ensure that the DOM has an id
if ( !media.id ) {
media.id = Popcorn.guid( "__popcorn" );
}
// Ensure we're looking at a dom node
if ( media.nodeType && media.nodeType === 1 ) {
popcornMedia = Popcorn( "#" + media.id );
dataSources = ( media.getAttribute( dataAttr ) || "" ).split( "," );
if ( dataSources[ 0 ] ) {
Popcorn.forEach( dataSources, function( source ) {
// split the parser and data as parser!file
data = source.split( "!" );
// if no parser is defined for the file, assume "parse" + file extension
if ( data.length === 1 ) {
data = source.split( "." );
data[ 0 ] = "parse" + data[ data.length - 1 ].toUpperCase();
data[ 1 ] = source;
}
// If the media has data sources and the correct parser is registered, continue to load
if ( dataSources[ 0 ] && popcornMedia[ data[ 0 ] ] ) {
// Set up the media and load in the datasources
popcornMedia[ data[ 0 ] ]( data[ 1 ] );
}
});
}
// Only play the media if it was specified to do so
if ( !!popcornMedia.autoplay ) {
popcornMedia.play();
}
}
});
}, false );
})(window, window.document);
| Fixed linting error and remove any leftover reference to the instance methods
| popcorn.js | Fixed linting error and remove any leftover reference to the instance methods | <ide><path>opcorn.js
<ide>
<ide> that.data.timeUpdateFunction = function( event ) {
<ide> Popcorn.timeUpdate( that, event );
<del> }
<add> };
<ide>
<ide> if ( !that.isDestroyed ) {
<ide> that.media.addEventListener( "timeupdate", that.data.timeUpdateFunction, false );
<ide> instance.isDestroyed = true;
<ide> }
<ide>
<del> Popcorn.removeInstance( instance );
<add> Popcorn.instances.splice( Popcorn.instanceIds[ instance.id ], 1 );
<add>
<add> delete Popcorn.instanceIds[ instance.id ];
<ide> }
<ide> });
<ide> |
|
Java | apache-2.0 | 68d146eac64bfd70f992d0310b39388b82fc0bd4 | 0 | philchand/mpdroid-2014,philchand/mpdroid-2014,joansmith/dmix,abarisain/dmix,0359xiaodong/dmix,abarisain/dmix,0359xiaodong/dmix,hurzl/dmix,philchand/mpdroid-2014,hurzl/dmix,philchand/mpdroid-2014,jcnoir/dmix,jcnoir/dmix,joansmith/dmix | package com.namelessdev.mpdroid.fragments;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.*;
import android.view.MenuItem.OnMenuItemClickListener;
import android.widget.*;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import com.namelessdev.mpdroid.MPDApplication;
import com.namelessdev.mpdroid.R;
import com.namelessdev.mpdroid.adapters.ArrayIndexerAdapter;
import com.namelessdev.mpdroid.helpers.MPDAsyncHelper.AsyncExecListener;
import org.a0z.mpd.Item;
import org.a0z.mpd.exception.MPDServerException;
import java.util.List;
public abstract class BrowseFragment extends Fragment implements OnMenuItemClickListener, AsyncExecListener, OnItemClickListener {
protected int iJobID = -1;
public static final int MAIN = 0;
public static final int PLAYLIST = 3;
public static final int ADD = 0;
public static final int ADDNREPLACE = 1;
public static final int ADDNREPLACEPLAY = 4;
public static final int ADDNPLAY = 2;
public static final int ADD_TO_PLAYLIST = 3;
protected List<? extends Item> items = null;
protected MPDApplication app = null;
protected View loadingView;
protected TextView loadingTextView;
protected View noResultView;
protected AbsListView list;
private boolean firstUpdateDone = false;
String context;
int irAdd, irAdded;
public BrowseFragment(int rAdd, int rAdded, String pContext) {
super();
irAdd = rAdd;
irAdded = rAdded;
context = pContext;
setHasOptionsMenu(false);
}
@TargetApi(11)
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
app = (MPDApplication) getActivity().getApplicationContext();
try {
Activity activity = this.getActivity();
ActionBar actionBar = activity.getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
} catch (NoClassDefFoundError e) {
// Older android
} catch (NullPointerException e) {
} catch (NoSuchMethodError e) {
}
}
@Override
public void onStart() {
super.onStart();
app.setActivity(getActivity());
if(!firstUpdateDone) {
firstUpdateDone = true;
UpdateList();
}
}
@Override
public void onStop() {
super.onStop();
app.unsetActivity(getActivity());
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.browse, container, false);
list = (ListView) view.findViewById(R.id.list);
registerForContextMenu(list);
list.setOnItemClickListener(this);
if (android.os.Build.VERSION.SDK_INT == 19)
list.setFastScrollAlwaysVisible(true);
loadingView = view.findViewById(R.id.loadingLayout);
loadingTextView = (TextView) view.findViewById(R.id.loadingText);
noResultView = view.findViewById(R.id.noResultLayout);
loadingTextView.setText(getLoadingText());
return view;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if(items != null) {
list.setAdapter(getCustomListAdapter());
}
}
@Override
public void onDestroyView() {
// help out the GC; imitated from ListFragment source
loadingView = null;
loadingTextView = null;
noResultView = null;
super.onDestroyView();
}
/*
* Override this to display a custom activity title
*/
public String getTitle() {
return "";
}
/*
* Override this to display a custom loading text
*/
public int getLoadingText() {
return R.string.loading;
}
public void setActivityTitle(String title) {
getActivity().setTitle(title);
}
public void UpdateList() {
list.setAdapter(null);
noResultView.setVisibility(View.GONE);
loadingView.setVisibility(View.VISIBLE);
// Loading Artists asynchronous...
app.oMPDAsyncHelper.addAsyncExecListener(this);
iJobID = app.oMPDAsyncHelper.execAsync(new Runnable() {
@Override
public void run() {
asyncUpdate();
}
});
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
int index = (int) info.id;
if (index >= 0 && items.size() > index ) {
menu.setHeaderTitle(items.get((int) info.id).toString());
android.view.MenuItem addItem = menu.add(ADD, ADD, 0, getResources().getString(irAdd));
addItem.setOnMenuItemClickListener(this);
android.view.MenuItem addAndReplaceItem = menu.add(ADDNREPLACE, ADDNREPLACE, 0, R.string.addAndReplace);
addAndReplaceItem.setOnMenuItemClickListener(this);
android.view.MenuItem addAndReplacePlayItem = menu.add(ADDNREPLACEPLAY, ADDNREPLACEPLAY, 0, R.string.addAndReplacePlay);
addAndReplacePlayItem.setOnMenuItemClickListener(this);
android.view.MenuItem addAndPlayItem = menu.add(ADDNPLAY, ADDNPLAY, 0, R.string.addAndPlay);
addAndPlayItem.setOnMenuItemClickListener(this);
if (R.string.addPlaylist!=irAdd && R.string.addStream!=irAdd) {
int id=0;
SubMenu playlistMenu=menu.addSubMenu(R.string.addToPlaylist);
android.view.MenuItem item=playlistMenu.add(ADD_TO_PLAYLIST, id++, (int)info.id, R.string.newPlaylist);
item.setOnMenuItemClickListener(this);
try {
List<Item> playlists=((MPDApplication) getActivity().getApplication()).oMPDAsyncHelper.oMPD.getPlaylists();
if (null!=playlists) {
for (Item pl : playlists) {
item = playlistMenu.add(ADD_TO_PLAYLIST, id++, (int) info.id, pl.getName());
item.setOnMenuItemClickListener(this);
}
}
} catch (MPDServerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
protected abstract void add(Item item, boolean replace, boolean play);
protected abstract void add(Item item, String playlist);
@Override
public boolean onMenuItemClick(final android.view.MenuItem item) {
final AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getGroupId()) {
case ADDNREPLACEPLAY:
case ADDNREPLACE:
case ADD:
case ADDNPLAY:
app.oMPDAsyncHelper.execAsync(new Runnable() {
@Override
public void run() {
boolean replace = false;
boolean play = false;
switch (item.getGroupId()) {
case ADDNREPLACEPLAY:
replace = true;
play = true;
break;
case ADDNREPLACE:
replace = true;
break;
case ADDNPLAY:
play = true;
break;
}
add(items.get((int) info.id), replace, play);
}
});
break;
case ADD_TO_PLAYLIST: {
final EditText input = new EditText(getActivity());
final int id = (int) item.getOrder();
if (item.getItemId() == 0) {
new AlertDialog.Builder(getActivity())
.setTitle(R.string.playlistName)
.setMessage(R.string.newPlaylistPrompt)
.setView(input)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
final String name = input.getText().toString().trim();
if (null != name && name.length() > 0) {
app.oMPDAsyncHelper.execAsync(new Runnable() {
@Override
public void run() {
add(items.get(id), name);
}
});
}
}
}).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Do nothing.
}
}).show();
} else {
add(items.get(id), item.getTitle().toString());
}
break;
}
default:
final String name = item.getTitle().toString();
final int id = (int) item.getOrder();
app.oMPDAsyncHelper.execAsync(new Runnable() {
@Override
public void run() {
add(items.get(id), name);
}
});
break;
}
return false;
}
protected void asyncUpdate() {
}
/**
* Update the view from the items list if items is set.
*/
public void updateFromItems() {
if (getView() == null) {
// The view has been destroyed, bail.
return;
}
if (items != null) {
list.setAdapter(getCustomListAdapter());
try {
if (forceEmptyView() || ((list instanceof ListView) && ((ListView) list).getHeaderViewsCount() == 0))
list.setEmptyView(noResultView);
loadingView.setVisibility(View.GONE);
} catch (Exception e) {}
}
}
protected ListAdapter getCustomListAdapter() {
return new ArrayIndexerAdapter(getActivity(), R.layout.simple_list_item_1, items);
}
//Override if you want setEmptyView to be called on the list even if you have a header
protected boolean forceEmptyView() {
return false;
}
@Override
public void asyncExecSucceeded(int jobID) {
if (iJobID == jobID) {
updateFromItems();
}
}
public void scrollToTop() {
try {
list.setSelection(-1);
} catch (Exception e) {
// What if the list is empty or some other bug ? I don't want any crashes because of that
}
}
}
| MPDroid/src/com/namelessdev/mpdroid/fragments/BrowseFragment.java | package com.namelessdev.mpdroid.fragments;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.*;
import android.view.MenuItem.OnMenuItemClickListener;
import android.widget.*;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import com.namelessdev.mpdroid.MPDApplication;
import com.namelessdev.mpdroid.R;
import com.namelessdev.mpdroid.adapters.ArrayIndexerAdapter;
import com.namelessdev.mpdroid.helpers.MPDAsyncHelper.AsyncExecListener;
import org.a0z.mpd.Item;
import org.a0z.mpd.exception.MPDServerException;
import java.util.List;
public abstract class BrowseFragment extends Fragment implements OnMenuItemClickListener, AsyncExecListener, OnItemClickListener {
protected int iJobID = -1;
public static final int MAIN = 0;
public static final int PLAYLIST = 3;
public static final int ADD = 0;
public static final int ADDNREPLACE = 1;
public static final int ADDNREPLACEPLAY = 4;
public static final int ADDNPLAY = 2;
public static final int ADD_TO_PLAYLIST = 3;
protected List<? extends Item> items = null;
protected MPDApplication app = null;
protected View loadingView;
protected TextView loadingTextView;
protected View noResultView;
protected AbsListView list;
private boolean firstUpdateDone = false;
String context;
int irAdd, irAdded;
public BrowseFragment(int rAdd, int rAdded, String pContext) {
super();
irAdd = rAdd;
irAdded = rAdded;
context = pContext;
setHasOptionsMenu(false);
}
@TargetApi(11)
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
app = (MPDApplication) getActivity().getApplicationContext();
try {
Activity activity = this.getActivity();
ActionBar actionBar = activity.getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
} catch (NoClassDefFoundError e) {
// Older android
} catch (NullPointerException e) {
} catch (NoSuchMethodError e) {
}
}
@Override
public void onStart() {
super.onStart();
app.setActivity(getActivity());
if(!firstUpdateDone) {
firstUpdateDone = true;
UpdateList();
}
}
@Override
public void onStop() {
super.onStop();
app.unsetActivity(getActivity());
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.browse, container, false);
list = (ListView) view.findViewById(R.id.list);
registerForContextMenu(list);
list.setOnItemClickListener(this);
loadingView = view.findViewById(R.id.loadingLayout);
loadingTextView = (TextView) view.findViewById(R.id.loadingText);
noResultView = view.findViewById(R.id.noResultLayout);
loadingTextView.setText(getLoadingText());
return view;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if(items != null) {
list.setAdapter(getCustomListAdapter());
}
}
@Override
public void onDestroyView() {
// help out the GC; imitated from ListFragment source
loadingView = null;
loadingTextView = null;
noResultView = null;
super.onDestroyView();
}
/*
* Override this to display a custom activity title
*/
public String getTitle() {
return "";
}
/*
* Override this to display a custom loading text
*/
public int getLoadingText() {
return R.string.loading;
}
public void setActivityTitle(String title) {
getActivity().setTitle(title);
}
public void UpdateList() {
list.setAdapter(null);
noResultView.setVisibility(View.GONE);
loadingView.setVisibility(View.VISIBLE);
// Loading Artists asynchronous...
app.oMPDAsyncHelper.addAsyncExecListener(this);
iJobID = app.oMPDAsyncHelper.execAsync(new Runnable() {
@Override
public void run() {
asyncUpdate();
}
});
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
int index = (int) info.id;
if (index >= 0 && items.size() > index ) {
menu.setHeaderTitle(items.get((int) info.id).toString());
android.view.MenuItem addItem = menu.add(ADD, ADD, 0, getResources().getString(irAdd));
addItem.setOnMenuItemClickListener(this);
android.view.MenuItem addAndReplaceItem = menu.add(ADDNREPLACE, ADDNREPLACE, 0, R.string.addAndReplace);
addAndReplaceItem.setOnMenuItemClickListener(this);
android.view.MenuItem addAndReplacePlayItem = menu.add(ADDNREPLACEPLAY, ADDNREPLACEPLAY, 0, R.string.addAndReplacePlay);
addAndReplacePlayItem.setOnMenuItemClickListener(this);
android.view.MenuItem addAndPlayItem = menu.add(ADDNPLAY, ADDNPLAY, 0, R.string.addAndPlay);
addAndPlayItem.setOnMenuItemClickListener(this);
if (R.string.addPlaylist!=irAdd && R.string.addStream!=irAdd) {
int id=0;
SubMenu playlistMenu=menu.addSubMenu(R.string.addToPlaylist);
android.view.MenuItem item=playlistMenu.add(ADD_TO_PLAYLIST, id++, (int)info.id, R.string.newPlaylist);
item.setOnMenuItemClickListener(this);
try {
List<Item> playlists=((MPDApplication) getActivity().getApplication()).oMPDAsyncHelper.oMPD.getPlaylists();
if (null!=playlists) {
for (Item pl : playlists) {
item = playlistMenu.add(ADD_TO_PLAYLIST, id++, (int) info.id, pl.getName());
item.setOnMenuItemClickListener(this);
}
}
} catch (MPDServerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
protected abstract void add(Item item, boolean replace, boolean play);
protected abstract void add(Item item, String playlist);
@Override
public boolean onMenuItemClick(final android.view.MenuItem item) {
final AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getGroupId()) {
case ADDNREPLACEPLAY:
case ADDNREPLACE:
case ADD:
case ADDNPLAY:
app.oMPDAsyncHelper.execAsync(new Runnable() {
@Override
public void run() {
boolean replace = false;
boolean play = false;
switch (item.getGroupId()) {
case ADDNREPLACEPLAY:
replace = true;
play = true;
break;
case ADDNREPLACE:
replace = true;
break;
case ADDNPLAY:
play = true;
break;
}
add(items.get((int) info.id), replace, play);
}
});
break;
case ADD_TO_PLAYLIST: {
final EditText input = new EditText(getActivity());
final int id = (int) item.getOrder();
if (item.getItemId() == 0) {
new AlertDialog.Builder(getActivity())
.setTitle(R.string.playlistName)
.setMessage(R.string.newPlaylistPrompt)
.setView(input)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
final String name = input.getText().toString().trim();
if (null != name && name.length() > 0) {
app.oMPDAsyncHelper.execAsync(new Runnable() {
@Override
public void run() {
add(items.get(id), name);
}
});
}
}
}).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Do nothing.
}
}).show();
} else {
add(items.get(id), item.getTitle().toString());
}
break;
}
default:
final String name = item.getTitle().toString();
final int id = (int) item.getOrder();
app.oMPDAsyncHelper.execAsync(new Runnable() {
@Override
public void run() {
add(items.get(id), name);
}
});
break;
}
return false;
}
protected void asyncUpdate() {
}
/**
* Update the view from the items list if items is set.
*/
public void updateFromItems() {
if (getView() == null) {
// The view has been destroyed, bail.
return;
}
if (items != null) {
list.setAdapter(getCustomListAdapter());
try {
if (forceEmptyView() || ((list instanceof ListView) && ((ListView) list).getHeaderViewsCount() == 0))
list.setEmptyView(noResultView);
loadingView.setVisibility(View.GONE);
} catch (Exception e) {}
}
}
protected ListAdapter getCustomListAdapter() {
return new ArrayIndexerAdapter(getActivity(), R.layout.simple_list_item_1, items);
}
//Override if you want setEmptyView to be called on the list even if you have a header
protected boolean forceEmptyView() {
return false;
}
@Override
public void asyncExecSucceeded(int jobID) {
if (iJobID == jobID) {
updateFromItems();
}
}
public void scrollToTop() {
try {
list.setSelection(-1);
} catch (Exception e) {
// What if the list is empty or some other bug ? I don't want any crashes because of that
}
}
}
| Always show fast scroll for 4.4
Workaround for fast scroll not being visible on 4.4 devices.
| MPDroid/src/com/namelessdev/mpdroid/fragments/BrowseFragment.java | Always show fast scroll for 4.4 | <ide><path>PDroid/src/com/namelessdev/mpdroid/fragments/BrowseFragment.java
<ide> list = (ListView) view.findViewById(R.id.list);
<ide> registerForContextMenu(list);
<ide> list.setOnItemClickListener(this);
<add> if (android.os.Build.VERSION.SDK_INT == 19)
<add> list.setFastScrollAlwaysVisible(true);
<ide> loadingView = view.findViewById(R.id.loadingLayout);
<ide> loadingTextView = (TextView) view.findViewById(R.id.loadingText);
<ide> noResultView = view.findViewById(R.id.noResultLayout); |
|
Java | mit | error: pathspec 'src/test/java/me/jamiemansfield/lorenz/test/model/jar/TypeTest.java' did not match any file(s) known to git
| 35fa0c841ddea31cbe721fb5fa812131c127880c | 1 | jamiemansfield/Lorenz,Lexteam/Lorenz | /*
* This file is part of Lorenz, licensed under the MIT License (MIT).
*
* Copyright (c) Jamie Mansfield <https://www.jamierocks.uk/>
* Copyright (c) contributors
*
* 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 me.jamiemansfield.lorenz.test.model.jar;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import me.jamiemansfield.lorenz.model.jar.ArrayType;
import me.jamiemansfield.lorenz.model.jar.MethodDescriptor;
import me.jamiemansfield.lorenz.model.jar.ObjectType;
import me.jamiemansfield.lorenz.model.jar.PrimitiveType;
import me.jamiemansfield.lorenz.model.jar.Type;
import org.junit.Test;
/**
* A variety of unit tests pertaining to the de-obfuscation
* pertaining to {@link MethodDescriptor}.
*/
public final class TypeTest {
@Test
public void arrayType() {
final String raw = "[[I";
final Type type = Type.of(raw);
assertTrue("Type should be an ArrayType!", type instanceof ArrayType);
assertEquals(raw, type.getObfuscated());
final ArrayType array = (ArrayType) type;
assertEquals(2, array.getDimCount());
assertEquals(PrimitiveType.INT, array.getComponent());
}
@Test
public void objectTest() {
final String raw = "Lme/jamiemansfield/Test;";
final Type type = Type.of(raw);
assertTrue("Type should be an ObjectType!", type instanceof ObjectType);
assertEquals(raw, type.getObfuscated());
}
@Test
public void primtiveTest() {
final String raw = "Z";
final Type type = Type.of(raw);
assertTrue("Type should be an PrimitiveType!", type instanceof PrimitiveType);
assertEquals(PrimitiveType.BOOLEAN, type);
assertEquals(raw, type.getObfuscated());
}
}
| src/test/java/me/jamiemansfield/lorenz/test/model/jar/TypeTest.java | Add unit tests for type models
| src/test/java/me/jamiemansfield/lorenz/test/model/jar/TypeTest.java | Add unit tests for type models | <ide><path>rc/test/java/me/jamiemansfield/lorenz/test/model/jar/TypeTest.java
<add>/*
<add> * This file is part of Lorenz, licensed under the MIT License (MIT).
<add> *
<add> * Copyright (c) Jamie Mansfield <https://www.jamierocks.uk/>
<add> * Copyright (c) contributors
<add> *
<add> * Permission is hereby granted, free of charge, to any person obtaining a copy
<add> * of this software and associated documentation files (the "Software"), to deal
<add> * in the Software without restriction, including without limitation the rights
<add> * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
<add> * copies of the Software, and to permit persons to whom the Software is
<add> * furnished to do so, subject to the following conditions:
<add> *
<add> * The above copyright notice and this permission notice shall be included in
<add> * all copies or substantial portions of the Software.
<add> *
<add> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
<add> * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
<add> * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
<add> * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
<add> * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
<add> * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
<add> * THE SOFTWARE.
<add> */
<add>
<add>package me.jamiemansfield.lorenz.test.model.jar;
<add>
<add>import static org.junit.Assert.assertEquals;
<add>import static org.junit.Assert.assertTrue;
<add>
<add>import me.jamiemansfield.lorenz.model.jar.ArrayType;
<add>import me.jamiemansfield.lorenz.model.jar.MethodDescriptor;
<add>import me.jamiemansfield.lorenz.model.jar.ObjectType;
<add>import me.jamiemansfield.lorenz.model.jar.PrimitiveType;
<add>import me.jamiemansfield.lorenz.model.jar.Type;
<add>import org.junit.Test;
<add>
<add>/**
<add> * A variety of unit tests pertaining to the de-obfuscation
<add> * pertaining to {@link MethodDescriptor}.
<add> */
<add>public final class TypeTest {
<add>
<add> @Test
<add> public void arrayType() {
<add> final String raw = "[[I";
<add> final Type type = Type.of(raw);
<add> assertTrue("Type should be an ArrayType!", type instanceof ArrayType);
<add> assertEquals(raw, type.getObfuscated());
<add> final ArrayType array = (ArrayType) type;
<add> assertEquals(2, array.getDimCount());
<add> assertEquals(PrimitiveType.INT, array.getComponent());
<add> }
<add>
<add> @Test
<add> public void objectTest() {
<add> final String raw = "Lme/jamiemansfield/Test;";
<add> final Type type = Type.of(raw);
<add> assertTrue("Type should be an ObjectType!", type instanceof ObjectType);
<add> assertEquals(raw, type.getObfuscated());
<add> }
<add>
<add> @Test
<add> public void primtiveTest() {
<add> final String raw = "Z";
<add> final Type type = Type.of(raw);
<add> assertTrue("Type should be an PrimitiveType!", type instanceof PrimitiveType);
<add> assertEquals(PrimitiveType.BOOLEAN, type);
<add> assertEquals(raw, type.getObfuscated());
<add> }
<add>
<add>} |
|
JavaScript | mit | 5028eeb57908916d98d9e7c82d59ad958ee8f611 | 0 | DeviaVir/ShowNotify,DeviaVir/ShowNotify | /**
* Module dependencies.
*/
var app = require('../app');
var http = require('http');
var xml = require('xml2js').parseString;
var colors = require('colors');
var secrets = require('../config/secrets');
var Show = require('../models/Show');
var User = require('../models/User');
var nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport("SMTP", {
service: 'gmail',
auth: {
user: secrets.email.username,
pass: secrets.email.password
}
});
if (!Date.now) {
Date.now = function now() {
return new Date().getTime();
};
}
function pad(a,b) { return(1e15+a+"").slice(-b); }
var tomorrowDate = new Date(new Date().getTime() + 24 * 60 * 60 * 1000),
yesterdayDate = new Date(new Date().getTime() - 24 * 60 * 60 * 1000);
var tomorrow = tomorrowDate.getFullYear() + '-' + ( tomorrowDate.getMonth() + 1 ) + '-' + tomorrowDate.getDate(),
yesterday = yesterdayDate.getFullYear() + '-' + ( yesterdayDate.getMonth() + 1 ) + '-' + yesterdayDate.getDate();
Show.find({}, function(err, shows) {
if(err === null) {
shows.forEach(function(show) {
var tomorrows = 'http://www.thetvdb.com/api/GetEpisodeByAirDate.php?apikey=' + secrets.thetvdb.apiKey + '&seriesid=' + show.id + '&airdate=' + tomorrow,
yesterdays = 'http://www.thetvdb.com/api/GetEpisodeByAirDate.php?apikey=' + secrets.thetvdb.apiKey + '&seriesid=' + show.id + '&airdate=' + yesterday;
// Get tomorrow
http.get(tomorrows, function(res) {
res.setEncoding('utf8');
res.on('data', function (body) {
xml(body, function(err, obj) {
if(obj && ('Data' in obj) && obj.Data && ('Error' in obj.Data) && obj.Data.Error) {
console.info('Skipping tomorrow (' + tomorrow + '), no relevant airDate'.green, show.id);
}
else {
show.users.forEach(function(userId) {
User.find(userId, function(err, user) {
if(err === null) {
user = user[0];
var mailOptions = {
from: 'ShowNotify ✔ <' + secrets.email.username + '>',
to: user.email,
subject: show.name + ' returns tomorrow - ShowNotify',
text: 'Look sharp! ' + show.name + ' returns tomorrow with season ' + pad(obj.Data.Episode[0].SeasonNumber, 2) + ' episode ' + pad(obj.Data.Episode[0].EpisodeNumber, 2) + ' (s' + pad(obj.Data.Episode[0].SeasonNumber, 2) + 'e' + pad(obj.Data.Episode[0].EpisodeNumber, 2) + ') it has been called "' + obj.Data.Episode[0].EpisodeName[0] + '" and this is a short overview: ' + obj.Data.Episode[0].Overview[0],
html: 'Look sharp! <br /><br />' +
'<strong>' + show.name + '</strong> returns tomorrow with season ' + pad(obj.Data.Episode[0].SeasonNumber, 2) + ' episode ' + pad(obj.Data.Episode[0].EpisodeNumber, 2) + ' (s' + pad(obj.Data.Episode[0].SeasonNumber, 2) + 'e' + pad(obj.Data.Episode[0].EpisodeNumber, 2) + ').<br /><br />' +
'<strong>"' + obj.Data.Episode[0].EpisodeName[0] + '"</strong><br />' + obj.Data.Episode[0].Overview[0]
};
transporter.sendMail(mailOptions, function(error, info){
console.log(error, info);
});
}
});
});
}
});
});
}).on('error', function(e) {
console.error('Got http error: ' + e.message + ''.underline.red);
});
// Get yesterday
http.get(yesterdays, function(res) {
res.setEncoding('utf8');
res.on('data', function (body) {
xml(body, function(err, obj) {
if(obj && ('Data' in obj) && obj.Data && ('Error' in obj.Data) && obj.Data.Error) {
console.info('Skipping yesterday (' + yesterday + '), no relevant airDate'.green, show.id);
}
else {
show.users.forEach(function(userId) {
User.find(userId, function(err, user) {
if(err === null) {
user = user[0];
var mailOptions = {
from: 'ShowNotify ✔ <' + secrets.email.username + '>',
to: user.email,
subject: show.name + ' returned yesterday - ShowNotify',
text: 'Look sharp! ' + show.name + ' returned yesterday with season ' + pad(obj.Data.Episode[0].SeasonNumber, 2) + ' episode ' + pad(obj.Data.Episode[0].EpisodeNumber, 2) + ' (s' + pad(obj.Data.Episode[0].SeasonNumber, 2) + 'e' + pad(obj.Data.Episode[0].EpisodeNumber, 2) + ') it has been called "' + obj.Data.Episode[0].EpisodeName[0] + '" and this is a short overview: ' + obj.Data.Episode[0].Overview[0],
html: 'Look sharp! <br /><br />' +
'<strong>' + show.name + '</strong> returned yesterday with season ' + pad(obj.Data.Episode[0].SeasonNumber, 2) + ' episode ' + pad(obj.Data.Episode[0].EpisodeNumber, 2) + ' (s' + pad(obj.Data.Episode[0].SeasonNumber, 2) + 'e' + pad(obj.Data.Episode[0].EpisodeNumber, 2) + ').<br /><br />' +
'<strong>"' + obj.Data.Episode[0].EpisodeName[0] + '"</strong><br />' + obj.Data.Episode[0].Overview[0]
};
transporter.sendMail(mailOptions, function(error, info){
console.log(error, info);
});
}
});
});
}
});
});
}).on('error', function(e) {
console.error('Got http error: ' + e.message + ''.underline.red);
});
});
}
setTimeout(function() {
process.exit(0);
}, 30000);
});
| scripts/notifier.js | var app = require('../app');
var http = require('http');
var xml = require('xml2js').parseString;
var colors = require('colors');
var secrets = require('../config/secrets');
var Show = require('../models/Show');
var User = require('../models/User');
var nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport("SMTP", {
service: 'gmail',
auth: {
user: secrets.email.username,
pass: secrets.email.password
}
});
if (!Date.now) {
Date.now = function now() {
return new Date().getTime();
};
}
function pad(a,b) { return(1e15+a+"").slice(-b); }
var tomorrowDate = new Date(new Date().getTime() + 24 * 60 * 60 * 1000),
yesterdayDate = new Date(new Date().getTime() - 24 * 60 * 60 * 1000);
var tomorrow = tomorrowDate.getFullYear() + '-' + ( tomorrowDate.getMonth() + 1 ) + '-' + tomorrowDate.getDate(),
yesterday = yesterdayDate.getFullYear() + '-' + ( yesterdayDate.getMonth() + 1 ) + '-' + yesterdayDate.getDate();
Show.find({}, function(err, shows) {
if(err === null) {
shows.forEach(function(show) {
var tomorrows = 'http://www.thetvdb.com/api/GetEpisodeByAirDate.php?apikey=' + secrets.thetvdb.apiKey + '&seriesid=' + show.id + '&airdate=' + tomorrow,
yesterdays = 'http://www.thetvdb.com/api/GetEpisodeByAirDate.php?apikey=' + secrets.thetvdb.apiKey + '&seriesid=' + show.id + '&airdate=' + yesterday;
// Get tomorrow
http.get(tomorrows, function(res) {
res.setEncoding('utf8');
res.on('data', function (body) {
xml(body, function(err, obj) {
if(obj.Data && ('Error' in obj.Data) && obj.Data.Error) {
console.info('Skipping tomorrow, no relevant airDate'.green, show.id);
}
else {
show.users.forEach(function(userId) {
User.findById(userId, function(user) {
var mailOptions = {
from: 'ShowNotify ✔ <' + secrets.email.username + '>',
to: user.email,
subject: show.name + ' returns tomorrow - ShowNotify',
text: 'Look sharp! ' + show.name + ' returns tomorrow with season ' + pad(obj.Data.Episode[0].SeasonNumber, 2) + ' episode ' + pad(obj.Data.Episode[0].EpImgFlag, 2) + ' (s' + pad(obj.Data.Episode[0].SeasonNumber, 2) + 'e' + pad(obj.Data.Episode[0].EpImgFlag, 2) + ') it has been called "' + obj.Data.Episode[0].EpisodeName[0] + '" and this is a short overview: ' + obj.Data.Episode[0].Overview[0],
html: 'Look sharp! <br /><br />' +
'<strong>' + show.name + '</strong> returns tomorrow with season ' + pad(obj.Data.Episode[0].SeasonNumber, 2) + ' episode ' + pad(obj.Data.Episode[0].EpImgFlag, 2) + ' (s' + pad(obj.Data.Episode[0].SeasonNumber, 2) + 'e' + pad(obj.Data.Episode[0].EpImgFlag, 2) + ').<br /><br />' +
'<strong>"' + obj.Data.Episode[0].EpisodeName[0] + '"</strong><br />' + obj.Data.Episode[0].Overview[0]
};
transporter.sendMail(mailOptions, function(error, info){
console.log(error, info);
});
});
});
}
});
});
}).on('error', function(e) {
console.error('Got http error: ' + e.message + ''.underline.red);
});
// Get yesterday
http.get(yesterdays, function(res) {
res.setEncoding('utf8');
res.on('data', function (body) {
xml(body, function(err, obj) {
if(obj.Data && ('Error' in obj.Data) && obj.Data.Error) {
console.info('Skipping yesterday, no relevant airDate'.green, show.id);
}
else {
show.users.forEach(function(userId) {
User.findById(userId, function(err, user) {
var mailOptions = {
from: 'ShowNotify ✔ <' + secrets.email.username + '>',
to: user.email,
subject: show.name + ' returned yesterday - ShowNotify',
text: 'Look sharp! ' + show.name + ' returned yesterday with season ' + pad(obj.Data.Episode[0].SeasonNumber, 2) + ' episode ' + pad(obj.Data.Episode[0].EpImgFlag, 2) + ' (s' + pad(obj.Data.Episode[0].SeasonNumber, 2) + 'e' + pad(obj.Data.Episode[0].EpImgFlag, 2) + ') it has been called "' + obj.Data.Episode[0].EpisodeName[0] + '" and this is a short overview: ' + obj.Data.Episode[0].Overview[0],
html: 'Look sharp! <br /><br />' +
'<strong>' + show.name + '</strong> returned yesterday with season ' + pad(obj.Data.Episode[0].SeasonNumber, 2) + ' episode ' + pad(obj.Data.Episode[0].EpImgFlag, 2) + ' (s' + pad(obj.Data.Episode[0].SeasonNumber, 2) + 'e' + pad(obj.Data.Episode[0].EpImgFlag, 2) + ').<br /><br />' +
'<strong>"' + obj.Data.Episode[0].EpisodeName[0] + '"</strong><br />' + obj.Data.Episode[0].Overview[0]
};
transporter.sendMail(mailOptions, function(error, info){
console.log(error, info);
});
});
});
}
});
});
}).on('error', function(e) {
console.error('Got http error: ' + e.message + ''.underline.red);
});
});
}
setTimeout(function() {
process.exit(0);
}, 30000);
});
| Fix bug with the notifier script
| scripts/notifier.js | Fix bug with the notifier script | <ide><path>cripts/notifier.js
<add>/**
<add> * Module dependencies.
<add> */
<ide> var app = require('../app');
<ide> var http = require('http');
<ide> var xml = require('xml2js').parseString;
<ide> res.setEncoding('utf8');
<ide> res.on('data', function (body) {
<ide> xml(body, function(err, obj) {
<del> if(obj.Data && ('Error' in obj.Data) && obj.Data.Error) {
<del> console.info('Skipping tomorrow, no relevant airDate'.green, show.id);
<add> if(obj && ('Data' in obj) && obj.Data && ('Error' in obj.Data) && obj.Data.Error) {
<add> console.info('Skipping tomorrow (' + tomorrow + '), no relevant airDate'.green, show.id);
<ide> }
<ide> else {
<ide> show.users.forEach(function(userId) {
<del> User.findById(userId, function(user) {
<del> var mailOptions = {
<del> from: 'ShowNotify ✔ <' + secrets.email.username + '>',
<del> to: user.email,
<del> subject: show.name + ' returns tomorrow - ShowNotify',
<del> text: 'Look sharp! ' + show.name + ' returns tomorrow with season ' + pad(obj.Data.Episode[0].SeasonNumber, 2) + ' episode ' + pad(obj.Data.Episode[0].EpImgFlag, 2) + ' (s' + pad(obj.Data.Episode[0].SeasonNumber, 2) + 'e' + pad(obj.Data.Episode[0].EpImgFlag, 2) + ') it has been called "' + obj.Data.Episode[0].EpisodeName[0] + '" and this is a short overview: ' + obj.Data.Episode[0].Overview[0],
<del> html: 'Look sharp! <br /><br />' +
<del> '<strong>' + show.name + '</strong> returns tomorrow with season ' + pad(obj.Data.Episode[0].SeasonNumber, 2) + ' episode ' + pad(obj.Data.Episode[0].EpImgFlag, 2) + ' (s' + pad(obj.Data.Episode[0].SeasonNumber, 2) + 'e' + pad(obj.Data.Episode[0].EpImgFlag, 2) + ').<br /><br />' +
<del> '<strong>"' + obj.Data.Episode[0].EpisodeName[0] + '"</strong><br />' + obj.Data.Episode[0].Overview[0]
<del> };
<del> transporter.sendMail(mailOptions, function(error, info){
<del> console.log(error, info);
<del> });
<add> User.find(userId, function(err, user) {
<add> if(err === null) {
<add> user = user[0];
<add> var mailOptions = {
<add> from: 'ShowNotify ✔ <' + secrets.email.username + '>',
<add> to: user.email,
<add> subject: show.name + ' returns tomorrow - ShowNotify',
<add> text: 'Look sharp! ' + show.name + ' returns tomorrow with season ' + pad(obj.Data.Episode[0].SeasonNumber, 2) + ' episode ' + pad(obj.Data.Episode[0].EpisodeNumber, 2) + ' (s' + pad(obj.Data.Episode[0].SeasonNumber, 2) + 'e' + pad(obj.Data.Episode[0].EpisodeNumber, 2) + ') it has been called "' + obj.Data.Episode[0].EpisodeName[0] + '" and this is a short overview: ' + obj.Data.Episode[0].Overview[0],
<add> html: 'Look sharp! <br /><br />' +
<add> '<strong>' + show.name + '</strong> returns tomorrow with season ' + pad(obj.Data.Episode[0].SeasonNumber, 2) + ' episode ' + pad(obj.Data.Episode[0].EpisodeNumber, 2) + ' (s' + pad(obj.Data.Episode[0].SeasonNumber, 2) + 'e' + pad(obj.Data.Episode[0].EpisodeNumber, 2) + ').<br /><br />' +
<add> '<strong>"' + obj.Data.Episode[0].EpisodeName[0] + '"</strong><br />' + obj.Data.Episode[0].Overview[0]
<add> };
<add> transporter.sendMail(mailOptions, function(error, info){
<add> console.log(error, info);
<add> });
<add> }
<ide> });
<ide> });
<ide> }
<ide> res.setEncoding('utf8');
<ide> res.on('data', function (body) {
<ide> xml(body, function(err, obj) {
<del> if(obj.Data && ('Error' in obj.Data) && obj.Data.Error) {
<del> console.info('Skipping yesterday, no relevant airDate'.green, show.id);
<add> if(obj && ('Data' in obj) && obj.Data && ('Error' in obj.Data) && obj.Data.Error) {
<add> console.info('Skipping yesterday (' + yesterday + '), no relevant airDate'.green, show.id);
<ide> }
<ide> else {
<ide> show.users.forEach(function(userId) {
<del> User.findById(userId, function(err, user) {
<del> var mailOptions = {
<del> from: 'ShowNotify ✔ <' + secrets.email.username + '>',
<del> to: user.email,
<del> subject: show.name + ' returned yesterday - ShowNotify',
<del> text: 'Look sharp! ' + show.name + ' returned yesterday with season ' + pad(obj.Data.Episode[0].SeasonNumber, 2) + ' episode ' + pad(obj.Data.Episode[0].EpImgFlag, 2) + ' (s' + pad(obj.Data.Episode[0].SeasonNumber, 2) + 'e' + pad(obj.Data.Episode[0].EpImgFlag, 2) + ') it has been called "' + obj.Data.Episode[0].EpisodeName[0] + '" and this is a short overview: ' + obj.Data.Episode[0].Overview[0],
<del> html: 'Look sharp! <br /><br />' +
<del> '<strong>' + show.name + '</strong> returned yesterday with season ' + pad(obj.Data.Episode[0].SeasonNumber, 2) + ' episode ' + pad(obj.Data.Episode[0].EpImgFlag, 2) + ' (s' + pad(obj.Data.Episode[0].SeasonNumber, 2) + 'e' + pad(obj.Data.Episode[0].EpImgFlag, 2) + ').<br /><br />' +
<del> '<strong>"' + obj.Data.Episode[0].EpisodeName[0] + '"</strong><br />' + obj.Data.Episode[0].Overview[0]
<del> };
<del> transporter.sendMail(mailOptions, function(error, info){
<del> console.log(error, info);
<del> });
<add> User.find(userId, function(err, user) {
<add> if(err === null) {
<add> user = user[0];
<add> var mailOptions = {
<add> from: 'ShowNotify ✔ <' + secrets.email.username + '>',
<add> to: user.email,
<add> subject: show.name + ' returned yesterday - ShowNotify',
<add> text: 'Look sharp! ' + show.name + ' returned yesterday with season ' + pad(obj.Data.Episode[0].SeasonNumber, 2) + ' episode ' + pad(obj.Data.Episode[0].EpisodeNumber, 2) + ' (s' + pad(obj.Data.Episode[0].SeasonNumber, 2) + 'e' + pad(obj.Data.Episode[0].EpisodeNumber, 2) + ') it has been called "' + obj.Data.Episode[0].EpisodeName[0] + '" and this is a short overview: ' + obj.Data.Episode[0].Overview[0],
<add> html: 'Look sharp! <br /><br />' +
<add> '<strong>' + show.name + '</strong> returned yesterday with season ' + pad(obj.Data.Episode[0].SeasonNumber, 2) + ' episode ' + pad(obj.Data.Episode[0].EpisodeNumber, 2) + ' (s' + pad(obj.Data.Episode[0].SeasonNumber, 2) + 'e' + pad(obj.Data.Episode[0].EpisodeNumber, 2) + ').<br /><br />' +
<add> '<strong>"' + obj.Data.Episode[0].EpisodeName[0] + '"</strong><br />' + obj.Data.Episode[0].Overview[0]
<add> };
<add> transporter.sendMail(mailOptions, function(error, info){
<add> console.log(error, info);
<add> });
<add> }
<ide> });
<ide> });
<ide> } |
|
Java | bsd-2-clause | 93c0d63c3121b96e0653f4d2298c6b6bd97a2027 | 0 | scenerygraphics/SciView,scenerygraphics/SciView | /*-
* #%L
* Scenery-backed 3D visualization package for ImageJ.
* %%
* Copyright (C) 2016 - 2018 SciView developers.
* %%
* 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.
* #L%
*/
package sc.iview;
import cleargl.GLTypeEnum;
import cleargl.GLVector;
import com.bulenkov.darcula.DarculaLaf;
import com.jogamp.opengl.math.Quaternion;
import com.sun.javafx.application.PlatformImpl;
import coremem.enums.NativeTypeEnum;
import graphics.scenery.Box;
import graphics.scenery.*;
import graphics.scenery.backends.Renderer;
import graphics.scenery.backends.vulkan.VulkanRenderer;
import graphics.scenery.controls.InputHandler;
import graphics.scenery.controls.OpenVRHMD;
import graphics.scenery.controls.TrackerInput;
import graphics.scenery.controls.behaviours.ArcballCameraControl;
import graphics.scenery.controls.behaviours.FPSCameraControl;
import graphics.scenery.controls.behaviours.MovementCommand;
import graphics.scenery.controls.behaviours.SelectCommand;
import graphics.scenery.utils.SceneryFXPanel;
import graphics.scenery.utils.SceneryJPanel;
import graphics.scenery.utils.SceneryPanel;
import graphics.scenery.utils.Statistics;
import graphics.scenery.volumes.TransferFunction;
import graphics.scenery.volumes.Volume;
import graphics.scenery.volumes.bdv.BDVVolume;
import javafx.animation.FadeTransition;
import javafx.animation.Interpolator;
import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.geometry.Insets;
import javafx.geometry.*;
import javafx.scene.control.Label;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseButton;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.paint.Paint;
import javafx.scene.text.TextAlignment;
import javafx.util.Duration;
import kotlin.Unit;
import kotlin.jvm.functions.Function1;
import net.imagej.Dataset;
import net.imagej.lut.LUTService;
import net.imagej.ops.OpService;
import net.imglib2.Cursor;
import net.imglib2.IterableInterval;
import net.imglib2.RealLocalizable;
import net.imglib2.RealPoint;
import net.imglib2.display.ColorTable;
import net.imglib2.type.numeric.RealType;
import net.imglib2.type.numeric.integer.UnsignedByteType;
import net.imglib2.type.numeric.integer.UnsignedShortType;
import net.imglib2.type.numeric.real.FloatType;
import net.imglib2.view.Views;
import org.scijava.Context;
import org.scijava.display.Display;
import org.scijava.display.DisplayService;
import org.scijava.event.EventService;
import org.scijava.io.IOService;
import org.scijava.log.LogService;
import org.scijava.menu.MenuService;
import org.scijava.plugin.Parameter;
import org.scijava.thread.ThreadService;
import org.scijava.ui.behaviour.ClickBehaviour;
import org.scijava.ui.behaviour.InputTrigger;
import org.scijava.ui.swing.menu.SwingJMenuBarCreator;
import org.scijava.util.ColorRGB;
import org.scijava.util.ColorRGBA;
import org.scijava.util.Colors;
import sc.iview.commands.view.NodePropertyEditor;
import sc.iview.controls.behaviours.CameraTranslateControl;
import sc.iview.controls.behaviours.NodeTranslateControl;
import sc.iview.event.NodeActivatedEvent;
import sc.iview.event.NodeAddedEvent;
import sc.iview.event.NodeRemovedEvent;
import sc.iview.javafx.JavaFXMenuCreator;
import sc.iview.process.MeshConverter;
import sc.iview.vector.ClearGLVector3;
import sc.iview.vector.Vector3;
import tpietzsch.example2.VolumeViewerOptions;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.plaf.basic.BasicLookAndFeel;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.util.List;
import java.util.Queue;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;
import java.util.function.Predicate;
import java.util.function.Supplier;
public class SciView extends SceneryBase {
public static final ColorRGB DEFAULT_COLOR = Colors.LIGHTGRAY;
@Parameter
private LogService log;
@Parameter
private MenuService menus;
@Parameter
private IOService io;
@Parameter
private OpService ops;
@Parameter
private EventService eventService;
@Parameter
private DisplayService displayService;
@Parameter
private LUTService lutService;
@Parameter
private ThreadService threadService;
/**
* Queue keeps track of the currently running animations
**/
private Queue<Future> animations;
/**
* Animation pause tracking
**/
private boolean animating;
/**
* This tracks the actively selected Node in the scene
*/
private Node activeNode = null;
/**
* Mouse controls for FPS movement and Arcball rotation
*/
protected ArcballCameraControl targetArcball;
protected FPSCameraControl fpsControl;
/**
* The primary camera/observer in the scene
*/
Camera camera = null;
/**
* JavaFX UI
*/
private boolean useJavaFX = false;
/**
* Speeds for input controls
*/
private float fpsScrollSpeed = 3.0f;
private float mouseSpeedMult = 0.25f;
private Display<?> scijavaDisplay;
/**
* The floor that orients the user in the scene
*/
protected Node floor;
private Label statusLabel;
private Label loadingLabel;
private JLabel splashLabel;
private SceneryJPanel panel;
private StackPane stackPane;
private MenuBar menuBar;
private JSplitPane mainSplitPane;
private final SceneryPanel[] sceneryPanel = { null };
private JSplitPane inspector;
private NodePropertyEditor nodePropertyEditor;
public SciView( Context context ) {
super( "SciView", 1280, 720, false, context );
context.inject( this );
}
public SciView( String applicationName, int windowWidth, int windowHeight ) {
super( applicationName, windowWidth, windowHeight, false );
}
public InputHandler publicGetInputHandler() {
return getInputHandler();
}
public class TransparentSlider extends JSlider {
public TransparentSlider() {
// Important, we taking over the filling of the
// component...
setOpaque(false);
setBackground(java.awt.Color.DARK_GRAY);
setForeground(java.awt.Color.LIGHT_GRAY);
}
@Override
protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(getBackground());
g2d.setComposite(AlphaComposite.SrcOver.derive(0.9f));
g2d.fillRect(0, 0, getWidth(), getHeight());
g2d.dispose();
super.paintComponent(g);
}
}
@SuppressWarnings("restriction") @Override public void init() {
if(Boolean.parseBoolean(System.getProperty("sciview.useDarcula", "false"))) {
try {
BasicLookAndFeel darcula = new DarculaLaf();
UIManager.setLookAndFeel(darcula);
} catch (Exception e) {
System.err.println("Could not load Darcula Look and Feel");
}
}
int x, y;
try {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
x = screenSize.width/2 - getWindowWidth()/2;
y = screenSize.height/2 - getWindowHeight()/2;
} catch(HeadlessException e) {
x = 10;
y = 10;
}
JFrame frame = new JFrame("SciView");
frame.setLayout(new BorderLayout(0, 0));
frame.setSize(getWindowWidth(), getWindowHeight());
frame.setLocation(x, y);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
nodePropertyEditor = new NodePropertyEditor( this );
if( useJavaFX ) {
final JFXPanel fxPanel = new JFXPanel();
frame.add(fxPanel);
CountDownLatch latch = new CountDownLatch( 1 );
PlatformImpl.startup( () -> {
} );
Platform.runLater( () -> {
stackPane = new StackPane();
stackPane.setBackground(
new Background( new BackgroundFill( Color.TRANSPARENT, CornerRadii.EMPTY, Insets.EMPTY ) ) );
GridPane pane = new GridPane();
statusLabel = new Label( "SciView - press U for usage help" );
statusLabel.setVisible(false);
final SceneryFXPanel panel = new SceneryFXPanel(100, 100);
Image loadingImage = new Image(this.getClass().getResourceAsStream("sciview-logo.png"), 600, 200, true, true);
ImageView loadingImageView = new ImageView(loadingImage);
loadingLabel = new Label("SciView is starting.");
loadingLabel.setStyle(
"-fx-background-color: rgb(50,48,47);" +
"-fx-opacity: 1.0;" +
"-fx-font-weight: 400; " +
"-fx-font-size: 2.2em; " +
"-fx-text-fill: white;");
loadingLabel.setTextFill(Paint.valueOf("white"));
loadingLabel.setGraphic(loadingImageView);
loadingLabel.setGraphicTextGap(40.0);
loadingLabel.setContentDisplay(ContentDisplay.TOP);
loadingLabel.prefHeightProperty().bind(pane.heightProperty());
loadingLabel.prefWidthProperty().bind(pane.widthProperty());
loadingLabel.setAlignment(Pos.CENTER);
GridPane.setHgrow( panel, Priority.ALWAYS );
GridPane.setVgrow( panel, Priority.ALWAYS );
GridPane.setFillHeight( panel, true );
GridPane.setFillWidth( panel, true );
GridPane.setHgrow( statusLabel, Priority.ALWAYS );
GridPane.setHalignment( statusLabel, HPos.CENTER );
GridPane.setValignment( statusLabel, VPos.BOTTOM );
statusLabel.maxWidthProperty().bind( pane.widthProperty() );
pane.setStyle( "-fx-background-color: rgb(50,48,47);" +
"-fx-font-family: Helvetica Neue, Helvetica, Segoe, Proxima Nova, Arial, sans-serif;" +
"-fx-font-weight: 400;" + "-fx-font-size: 1.2em;" + "-fx-text-fill: white;" +
"-fx-text-alignment: center;" );
statusLabel.setStyle( "-fx-padding: 0.2em;" + "-fx-text-fill: white;" );
statusLabel.setTextAlignment( TextAlignment.CENTER );
menuBar = new MenuBar();
pane.add( menuBar, 1, 1 );
pane.add( panel, 1, 2 );
pane.add( statusLabel, 1, 3 );
stackPane.getChildren().addAll(pane, loadingLabel);
final ContextMenu contextMenu = new ContextMenu();
final MenuItem title = new MenuItem("Node");
final MenuItem position = new MenuItem("Position");
title.setDisable(true);
position.setDisable(true);
contextMenu.getItems().addAll(title, position);
panel.setOnContextMenuRequested(event -> {
final Point2D localPosition = panel.sceneToLocal(event.getSceneX(), event.getSceneY());
final List<Scene.RaycastResult> matches = camera.getNodesForScreenSpacePosition((int)localPosition.getX(), (int)localPosition.getY());
if(matches.size() > 0) {
final Node firstMatch = matches.get(0).getNode();
title.setText("Node: " + firstMatch.getName() + " (" + firstMatch.getClass().getSimpleName() + ")");
position.setText(firstMatch.getPosition().toString());
} else {
title.setText("(no matches)");
position.setText("");
}
contextMenu.show(panel, event.getScreenX(), event.getScreenY());
});
panel.setOnMouseClicked(event -> {
if(event.getButton() == MouseButton.PRIMARY) {
contextMenu.hide();
}
});
sceneryPanel[0] = panel;
javafx.scene.Scene scene = new javafx.scene.Scene( stackPane );
fxPanel.setScene(scene);
// scene.addEventHandler(MouseEvent.ANY, event -> getLogger().info("Mouse event: " + event.toString()));
// sceneryPanel[0].addEventHandler(MouseEvent.ANY, event -> getLogger().info("PANEL Mouse event: " + event.toString()));
frame.setVisible(true);
// stage.setScene( scene );
// stage.setOnCloseRequest( event -> {
// getDisplay().close();
// this.close();
// } );
// stage.focusedProperty().addListener( ( ov, t, t1 ) -> {
// if( t1 )// If you just gained focus
// displayService.setActiveDisplay( getDisplay() );
// } );
new JavaFXMenuCreator().createMenus( menus.getMenu( "SciView" ), menuBar );
// stage.show();
latch.countDown();
} );
try {
latch.await();
} catch( InterruptedException e1 ) {
e1.printStackTrace();
}
// window width and window height get ignored by the renderer if it is embedded.
// dimensions are determined from the SceneryFXPanel, then.
setRenderer( Renderer.createRenderer( getHub(), getApplicationName(), getScene(),
getWindowWidth(), getWindowHeight(),
sceneryPanel[0] ) );
} else {
final JPanel p = new JPanel(new BorderLayout(0, 0));
panel = new SceneryJPanel();
JPopupMenu.setDefaultLightWeightPopupEnabled(false);
final JMenuBar swingMenuBar = new JMenuBar();
new SwingJMenuBarCreator().createMenus(menus.getMenu("SciView"), swingMenuBar);
frame.setJMenuBar(swingMenuBar);
BufferedImage splashImage;
try {
splashImage = ImageIO.read(this.getClass().getResourceAsStream("sciview-logo.png"));
} catch (IOException e) {
getLogger().warn("Could not read splash image 'sciview-logo.png'");
splashImage = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
}
final String sceneryVersion = SceneryBase.class.getPackage().getImplementationVersion();
final String sciviewVersion = SciView.class.getPackage().getImplementationVersion();
final String versionString;
if(sceneryVersion == null || sciviewVersion == null) {
versionString = "";
} else {
versionString = "\n\nsciview " + sciviewVersion + " / scenery " + sceneryVersion;
}
splashLabel = new JLabel(versionString,
new ImageIcon(splashImage.getScaledInstance(500, 200, java.awt.Image.SCALE_SMOOTH)),
SwingConstants.CENTER);
splashLabel.setBackground(new java.awt.Color(50, 48, 47));
splashLabel.setForeground(new java.awt.Color(78, 76, 75));
splashLabel.setOpaque(true);
splashLabel.setVerticalTextPosition(JLabel.BOTTOM);
splashLabel.setHorizontalTextPosition(JLabel.CENTER);
p.setLayout(new OverlayLayout(p));
p.setBackground(new java.awt.Color(50, 48, 47));
p.add(panel, BorderLayout.CENTER);
panel.setVisible(true);
nodePropertyEditor.getComponent(); // Initialize node property panel
JTree inspectorTree = nodePropertyEditor.getTree();
JPanel inspectorProperties = nodePropertyEditor.getProps();
inspector = new JSplitPane(JSplitPane.VERTICAL_SPLIT, //
new JScrollPane( inspectorTree ),
new JScrollPane( inspectorProperties ));
inspector.setDividerLocation( getWindowHeight() / 3 );
inspector.setContinuousLayout(true);
inspector.setBorder(BorderFactory.createEmptyBorder());
mainSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, //
p,
inspector
);
mainSplitPane.setDividerLocation( getWindowWidth()/3 * 2 );
mainSplitPane.setBorder(BorderFactory.createEmptyBorder());
frame.add(mainSplitPane, BorderLayout.CENTER);
frame.setGlassPane(splashLabel);
frame.getGlassPane().setVisible(true);
// frame.getGlassPane().setBackground(new java.awt.Color(50, 48, 47, 255));
frame.setVisible(true);
sceneryPanel[0] = panel;
setRenderer( Renderer.createRenderer( getHub(), getApplicationName(), getScene(),
getWindowWidth(), getWindowHeight(),
sceneryPanel[0]) );
}
// Enable push rendering by default
getRenderer().setPushMode( true );
getHub().add( SceneryElement.Renderer, getRenderer() );
GLVector[] tetrahedron = new GLVector[4];
tetrahedron[0] = new GLVector( 1.0f, 0f, -1.0f/(float)Math.sqrt(2.0f) );
tetrahedron[1] = new GLVector( -1.0f,0f,-1.0f/(float)Math.sqrt(2.0) );
tetrahedron[2] = new GLVector( 0.0f,1.0f,1.0f/(float)Math.sqrt(2.0) );
tetrahedron[3] = new GLVector( 0.0f,-1.0f,1.0f/(float)Math.sqrt(2.0) );
PointLight[] lights = new PointLight[4];
for( int i = 0; i < lights.length; i++ ) {
lights[i] = new PointLight( 150.0f );
lights[i].setPosition( tetrahedron[i].times(25.0f) );
lights[i].setEmissionColor( new GLVector( 1.0f, 1.0f, 1.0f ) );
lights[i].setIntensity( 100.0f );
getScene().addChild( lights[i] );
}
Camera cam = new DetachedHeadCamera();
cam.setPosition( new GLVector( 0.0f, 5.0f, 5.0f ) );
cam.perspectiveCamera( 50.0f, getWindowWidth(), getWindowHeight(), 0.1f, 1000.0f );
//cam.setTarget( new GLVector( 0, 0, 0 ) );
//cam.setTargeted( true );
cam.setActive( true );
getScene().addChild( cam );
this.camera = cam;
floor = new Box( new GLVector( 500f, 0.2f, 500f ) );
floor.setName( "Floor" );
floor.setPosition( new GLVector( 0f, -1f, 0f ) );
floor.getMaterial().setDiffuse( new GLVector( 1.0f, 1.0f, 1.0f ) );
getScene().addChild( floor );
animations = new LinkedList<>();
if(useJavaFX) {
Platform.runLater(() -> {
while (!getRenderer().getFirstImageReady()) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// fade out loading screen, show status bar
FadeTransition ft = new FadeTransition(Duration.millis(500), loadingLabel);
ft.setFromValue(1.0);
ft.setToValue(0.0);
ft.setCycleCount(1);
ft.setInterpolator(Interpolator.EASE_OUT);
ft.setOnFinished(event -> {
loadingLabel.setVisible(false);
statusLabel.setVisible(true);
});
ft.play();
});
} else {
SwingUtilities.invokeLater(() -> {
try {
while (!getSceneryRenderer().getFirstImageReady()) {
getLogger().info("Waiting for renderer");
Thread.sleep(100);
}
Thread.sleep(200);
} catch (InterruptedException e) {
}
nodePropertyEditor.rebuildTree();
frame.getGlassPane().setVisible(false);
getLogger().info("Done initializing SciView");
});
}
}
public void setStatusText(String text) {
statusLabel.setText(text);
}
public void setFloor( Node n ) {
floor = n;
}
public Node getFloor() {
return floor;
}
private float getFloory() {
return floor.getPosition().y();
}
private void setFloory( float new_pos ) {
float temp_pos = 0f;
temp_pos = new_pos;
if( temp_pos < -100f ) temp_pos = -100f;
else if( new_pos > 5f ) temp_pos = 5f;
floor.getPosition().set( 1, temp_pos );
}
public boolean isInitialized() {
return sceneInitialized();
}
public Camera getCamera() {
return camera;
}
public void setDisplay( Display<?> display ) {
scijavaDisplay = display;
}
public Display<?> getDisplay() {
return scijavaDisplay;
}
public void centerOnNode( Node currentNode ) {
if( currentNode == null ) return;
Node.OrientedBoundingBox bb = currentNode.generateBoundingBox();
getCamera().setTarget( currentNode.getPosition() );
getCamera().setTargeted( true );
// Set forward direction to point from camera at active node
getCamera().setForward( bb.getBoundingSphere().getOrigin().minus( getCamera().getPosition() ).normalize().times( -1 ) );
float distance = (float) (bb.getBoundingSphere().getRadius() / Math.tan( getCamera().getFov() / 360 * java.lang.Math.PI ));
// Solve for the proper rotation
Quaternion rotation = new Quaternion().setLookAt( getCamera().getForward().toFloatArray(),
new GLVector(0,1,0).toFloatArray(),
new GLVector(1,0,0).toFloatArray(),
new GLVector( 0,1,0).toFloatArray(),
new GLVector( 0, 0, 1).toFloatArray() );
getCamera().setRotation( rotation.normalize() );
getCamera().setPosition( bb.getBoundingSphere().getOrigin().plus( getCamera().getForward().times( distance * -1 ) ) );
getCamera().setDirty(true);
getCamera().setNeedsUpdate(true);
}
public void setFPSSpeed( float newspeed ) {
if( newspeed < 0.30f ) newspeed = 0.3f;
else if( newspeed > 30.0f ) newspeed = 30.0f;
fpsScrollSpeed = newspeed;
log.debug( "FPS scroll speed: " + fpsScrollSpeed );
}
public float getFPSSpeed() {
return fpsScrollSpeed;
}
public void setMouseSpeed( float newspeed ) {
if( newspeed < 0.30f ) newspeed = 0.3f;
else if( newspeed > 3.0f ) newspeed = 3.0f;
mouseSpeedMult = newspeed;
log.debug( "Mouse speed: " + mouseSpeedMult );
}
public float getMouseSpeed() {
return mouseSpeedMult;
}
public void resetFPSInputs() {
getInputHandler().addBehaviour( "move_forward_scroll",
new MovementCommand( "move_forward", "forward", () -> getScene().findObserver(),
getFPSSpeed() ) );
getInputHandler().addBehaviour( "move_forward",
new MovementCommand( "move_forward", "forward", () -> getScene().findObserver(),
getFPSSpeed() ) );
getInputHandler().addBehaviour( "move_back",
new MovementCommand( "move_back", "back", () -> getScene().findObserver(),
getFPSSpeed() ) );
getInputHandler().addBehaviour( "move_left",
new MovementCommand( "move_left", "left", () -> getScene().findObserver(),
getFPSSpeed() ) );
getInputHandler().addBehaviour( "move_right",
new MovementCommand( "move_right", "right", () -> getScene().findObserver(),
getFPSSpeed() ) );
getInputHandler().addBehaviour( "move_up",
new MovementCommand( "move_up", "up", () -> getScene().findObserver(),
getFPSSpeed() ) );
getInputHandler().addBehaviour( "move_down",
new MovementCommand( "move_down", "down", () -> getScene().findObserver(),
getFPSSpeed() ) );
}
class enableIncrease implements ClickBehaviour {
@Override public void click( int x, int y ) {
setFPSSpeed( getFPSSpeed() + 0.5f );
setMouseSpeed( getMouseSpeed() + 0.05f );
log.debug( "Increasing FPS scroll Speed" );
resetFPSInputs();
}
}
class enableDecrease implements ClickBehaviour {
@Override public void click( int x, int y ) {
setFPSSpeed( getFPSSpeed() - 0.1f );
setMouseSpeed( getMouseSpeed() - 0.05f );
log.debug( "Decreasing FPS scroll Speed" );
resetFPSInputs();
}
}
class showHelpDisplay implements ClickBehaviour {
@Override public void click( int x, int y ) {
String helpString = "SciView help:\n\n";
for( InputTrigger trigger : getInputHandler().getAllBindings().keySet() ) {
helpString += trigger + "\t-\t" + getInputHandler().getAllBindings().get( trigger ) + "\n";
}
// HACK: Make the console pop via stderr.
// Later, we will use a nicer dialog box or some such.
log.warn( helpString );
}
}
@Override public void inputSetup() {
Function1<? super List<Scene.RaycastResult>, Unit> selectAction = nearest -> {
if( !nearest.isEmpty() ) {
setActiveNode( nearest.get( 0 ).getNode() );
log.debug( "Selected node: " + getActiveNode().getName() );
}
return Unit.INSTANCE;
};
List<Class<? extends Object>> ignoredObjects = new ArrayList<>();
ignoredObjects.add( BoundingGrid.class );
getInputHandler().useDefaultBindings( "" );
// Mouse controls
getInputHandler().addBehaviour( "object_selection_mode",
new SelectCommand( "objectSelector", getRenderer(), getScene(),
() -> getScene().findObserver(), false, ignoredObjects,
selectAction ) );
getInputHandler().addKeyBinding( "object_selection_mode", "double-click button1" );
enableArcBallControl();
enableFPSControl();
getInputHandler().addBehaviour( "mouse_control_nodetranslate", new NodeTranslateControl( this, 0.002f ) );
getInputHandler().addKeyBinding( "mouse_control_nodetranslate", "shift button2" );
// Extra keyboard controls
getInputHandler().addBehaviour( "show_help", new showHelpDisplay() );
getInputHandler().addKeyBinding( "show_help", "U" );
getInputHandler().addBehaviour( "enable_decrease", new enableDecrease() );
getInputHandler().addKeyBinding( "enable_decrease", "M" );
getInputHandler().addBehaviour( "enable_increase", new enableIncrease() );
getInputHandler().addKeyBinding( "enable_increase", "N" );
}
private void enableArcBallControl() {
GLVector target;
if( getActiveNode() == null ) {
target = new GLVector( 0, 0, 0 );
} else {
target = getActiveNode().getPosition();
}
float mouseSpeed = 0.25f;
mouseSpeed = getMouseSpeed();
Supplier<Camera> cameraSupplier = () -> getScene().findObserver();
targetArcball = new ArcballCameraControl( "mouse_control_arcball", cameraSupplier,
getRenderer().getWindow().getWidth(),
getRenderer().getWindow().getHeight(), target );
targetArcball.setMaximumDistance( Float.MAX_VALUE );
targetArcball.setMouseSpeedMultiplier( mouseSpeed );
targetArcball.setScrollSpeedMultiplier( 0.05f );
targetArcball.setDistance( getCamera().getPosition().minus( target ).magnitude() );
getInputHandler().addBehaviour( "mouse_control_arcball", targetArcball );
getInputHandler().addKeyBinding( "mouse_control_arcball", "shift button1" );
getInputHandler().addBehaviour( "scroll_arcball", targetArcball );
getInputHandler().addKeyBinding( "scroll_arcball", "shift scroll" );
}
private void enableFPSControl() {
Supplier<Camera> cameraSupplier = () -> getScene().findObserver();
fpsControl = new FPSCameraControl( "mouse_control", cameraSupplier, getRenderer().getWindow().getWidth(),
getRenderer().getWindow().getHeight() );
getInputHandler().addBehaviour( "mouse_control", fpsControl );
getInputHandler().addKeyBinding( "mouse_control", "button1" );
getInputHandler().addBehaviour( "mouse_control_cameratranslate", new CameraTranslateControl( this, 0.002f ) );
getInputHandler().addKeyBinding( "mouse_control_cameratranslate", "button2" );
resetFPSInputs();
getInputHandler().addKeyBinding( "move_forward_scroll", "scroll" );
}
public Node addBox() {
return addBox( new ClearGLVector3( 0.0f, 0.0f, 0.0f ) );
}
public Node addBox( Vector3 position ) {
return addBox( position, new ClearGLVector3( 1.0f, 1.0f, 1.0f ) );
}
public Node addBox( Vector3 position, Vector3 size ) {
return addBox( position, size, DEFAULT_COLOR, false );
}
public Node addBox( final Vector3 position, final Vector3 size, final ColorRGB color,
final boolean inside ) {
// TODO: use a material from the current palate by default
final Material boxmaterial = new Material();
boxmaterial.setAmbient( new GLVector( 1.0f, 0.0f, 0.0f ) );
boxmaterial.setDiffuse( vector( color ) );
boxmaterial.setSpecular( new GLVector( 1.0f, 1.0f, 1.0f ) );
final Box box = new Box( ClearGLVector3.convert( size ), inside );
box.setMaterial( boxmaterial );
box.setPosition( ClearGLVector3.convert( position ) );
return addNode( box );
}
public Node addSphere() {
return addSphere( new ClearGLVector3( 0.0f, 0.0f, 0.0f ), 1 );
}
public Node addSphere( Vector3 position, float radius ) {
return addSphere( position, radius, DEFAULT_COLOR );
}
public Node addSphere( final Vector3 position, final float radius, final ColorRGB color ) {
final Material material = new Material();
material.setAmbient( new GLVector( 1.0f, 0.0f, 0.0f ) );
material.setDiffuse( vector( color ) );
material.setSpecular( new GLVector( 1.0f, 1.0f, 1.0f ) );
final Sphere sphere = new Sphere( radius, 20 );
sphere.setMaterial( material );
sphere.setPosition( ClearGLVector3.convert( position ) );
return addNode( sphere );
}
public Node addLine() {
return addLine( new ClearGLVector3( 0.0f, 0.0f, 0.0f ), new ClearGLVector3( 0.0f, 0.0f, 0.0f ) );
}
public Node addLine( Vector3 start, Vector3 stop ) {
return addLine( start, stop, DEFAULT_COLOR );
}
public Node addLine( Vector3 start, Vector3 stop, ColorRGB color ) {
return addLine( new Vector3[] { start, stop }, color, 0.1f );
}
public Node addLine( final Vector3[] points, final ColorRGB color, final double edgeWidth ) {
final Material material = new Material();
material.setAmbient( new GLVector( 1.0f, 1.0f, 1.0f ) );
material.setDiffuse( vector( color ) );
material.setSpecular( new GLVector( 1.0f, 1.0f, 1.0f ) );
final Line line = new Line( points.length );
for( final Vector3 pt : points ) {
line.addPoint( ClearGLVector3.convert( pt ) );
}
line.setEdgeWidth( ( float ) edgeWidth );
line.setMaterial( material );
line.setPosition( ClearGLVector3.convert( points[0] ) );
return addNode( line );
}
public Node addPointLight() {
final Material material = new Material();
material.setAmbient( new GLVector( 1.0f, 0.0f, 0.0f ) );
material.setDiffuse( new GLVector( 0.0f, 1.0f, 0.0f ) );
material.setSpecular( new GLVector( 1.0f, 1.0f, 1.0f ) );
final PointLight light = new PointLight( 5.0f );
light.setMaterial( material );
light.setPosition( new GLVector( 0.0f, 0.0f, 0.0f ) );
return addNode( light );
}
public void writeSCMesh( String filename, Mesh scMesh ) {
File f = new File( filename );
BufferedOutputStream out;
try {
out = new BufferedOutputStream( new FileOutputStream( f ) );
out.write( "solid STL generated by FIJI\n".getBytes() );
FloatBuffer normalsFB = scMesh.getNormals();
FloatBuffer verticesFB = scMesh.getVertices();
while( verticesFB.hasRemaining() && normalsFB.hasRemaining() ) {
out.write( ( "facet normal " + normalsFB.get() + " " + normalsFB.get() + " " + normalsFB.get() +
"\n" ).getBytes() );
out.write( "outer loop\n".getBytes() );
for( int v = 0; v < 3; v++ ) {
out.write( ( "vertex\t" + verticesFB.get() + " " + verticesFB.get() + " " + verticesFB.get() +
"\n" ).getBytes() );
}
out.write( "endloop\n".getBytes() );
out.write( "endfacet\n".getBytes() );
}
out.write( "endsolid vcg\n".getBytes() );
out.close();
} catch( FileNotFoundException e ) {
e.printStackTrace();
} catch( IOException e ) {
e.printStackTrace();
}
}
public float getDefaultPointSize() {
return 0.025f;
}
public float[] makeNormalsFromVertices( ArrayList<RealPoint> verts ) {
float[] normals = new float[verts.size()];// div3 * 3coords
for( int k = 0; k < verts.size(); k += 3 ) {
GLVector v1 = new GLVector( verts.get( k ).getFloatPosition( 0 ), //
verts.get( k ).getFloatPosition( 1 ), //
verts.get( k ).getFloatPosition( 2 ) );
GLVector v2 = new GLVector( verts.get( k + 1 ).getFloatPosition( 0 ),
verts.get( k + 1 ).getFloatPosition( 1 ),
verts.get( k + 1 ).getFloatPosition( 2 ) );
GLVector v3 = new GLVector( verts.get( k + 2 ).getFloatPosition( 0 ),
verts.get( k + 2 ).getFloatPosition( 1 ),
verts.get( k + 2 ).getFloatPosition( 2 ) );
GLVector a = v2.minus( v1 );
GLVector b = v3.minus( v1 );
GLVector n = a.cross( b ).getNormalized();
normals[k / 3] = n.get( 0 );
normals[k / 3 + 1] = n.get( 1 );
normals[k / 3 + 2] = n.get( 2 );
}
return normals;
}
public void open( final String source ) throws IOException {
if(source.endsWith(".xml")) {
addBDVVolume(source);
return;
}
final Object data = io.open( source );
if( data instanceof net.imagej.mesh.Mesh ) addMesh( ( net.imagej.mesh.Mesh ) data );
else if( data instanceof graphics.scenery.Mesh ) addMesh( ( graphics.scenery.Mesh ) data );
else if( data instanceof graphics.scenery.PointCloud ) addPointCloud( ( graphics.scenery.PointCloud ) data );
else if( data instanceof Dataset ) addVolume( ( Dataset ) data );
else if( data instanceof IterableInterval ) addVolume( ( ( IterableInterval ) data ), source );
else if( data instanceof List ) {
final List<?> list = ( List<?> ) data;
if( list.isEmpty() ) {
throw new IllegalArgumentException( "Data source '" + source + "' appears empty." );
}
final Object element = list.get( 0 );
if( element instanceof RealLocalizable ) {
// NB: For now, we assume all elements will be RealLocalizable.
// Highly likely to be the case, barring antagonistic importers.
@SuppressWarnings("unchecked") final List<? extends RealLocalizable> points = ( List<? extends RealLocalizable> ) list;
addPointCloud( points, source );
} else {
final String type = element == null ? "<null>" : element.getClass().getName();
throw new IllegalArgumentException( "Data source '" + source + //
"' contains elements of unknown type '" + type + "'" );
}
} else {
final String type = data == null ? "<null>" : data.getClass().getName();
throw new IllegalArgumentException( "Data source '" + source + //
"' contains data of unknown type '" + type + "'" );
}
}
public Node addPointCloud( Collection<? extends RealLocalizable> points ) {
return addPointCloud( points, "PointCloud" );
}
public Node addPointCloud( final Collection<? extends RealLocalizable> points,
final String name ) {
final float[] flatVerts = new float[points.size() * 3];
int k = 0;
for( final RealLocalizable point : points ) {
flatVerts[k * 3] = point.getFloatPosition( 0 );
flatVerts[k * 3 + 1] = point.getFloatPosition( 1 );
flatVerts[k * 3 + 2] = point.getFloatPosition( 2 );
k++;
}
final PointCloud pointCloud = new PointCloud( getDefaultPointSize(), name );
final Material material = new Material();
final FloatBuffer vBuffer = ByteBuffer.allocateDirect( flatVerts.length * 4 ) //
.order( ByteOrder.nativeOrder() ).asFloatBuffer();
final FloatBuffer nBuffer = ByteBuffer.allocateDirect( 0 ) //
.order( ByteOrder.nativeOrder() ).asFloatBuffer();
vBuffer.put( flatVerts );
vBuffer.flip();
pointCloud.setVertices( vBuffer );
pointCloud.setNormals( nBuffer );
pointCloud.setIndices( ByteBuffer.allocateDirect( 0 ) //
.order( ByteOrder.nativeOrder() ).asIntBuffer() );
pointCloud.setupPointCloud();
material.setAmbient( new GLVector( 1.0f, 1.0f, 1.0f ) );
material.setDiffuse( new GLVector( 1.0f, 1.0f, 1.0f ) );
material.setSpecular( new GLVector( 1.0f, 1.0f, 1.0f ) );
pointCloud.setMaterial( material );
pointCloud.setPosition( new GLVector( 0f, 0f, 0f ) );
return addNode( pointCloud );
}
public Node addPointCloud( final PointCloud pointCloud ) {
pointCloud.setupPointCloud();
pointCloud.getMaterial().setAmbient( new GLVector( 1.0f, 1.0f, 1.0f ) );
pointCloud.getMaterial().setDiffuse( new GLVector( 1.0f, 1.0f, 1.0f ) );
pointCloud.getMaterial().setSpecular( new GLVector( 1.0f, 1.0f, 1.0f ) );
pointCloud.setPosition( new GLVector( 0f, 0f, 0f ) );
return addNode( pointCloud );
}
public Node addNode( final Node n ) {
getScene().addChild( n );
setActiveNode( n );
updateFloorPosition();
eventService.publish( new NodeAddedEvent( n ) );
return n;
}
public Node addMesh( final Mesh scMesh ) {
final Material material = new Material();
material.setAmbient( new GLVector( 1.0f, 0.0f, 0.0f ) );
material.setDiffuse( new GLVector( 0.0f, 1.0f, 0.0f ) );
material.setSpecular( new GLVector( 1.0f, 1.0f, 1.0f ) );
scMesh.setMaterial( material );
scMesh.setPosition( new GLVector( 0.0f, 0.0f, 0.0f ) );
return addNode( scMesh );
}
public Node addMesh( net.imagej.mesh.Mesh mesh ) {
Mesh scMesh = MeshConverter.toScenery( mesh );
return addMesh( scMesh );
}
public void removeMesh( Mesh scMesh ) {
getScene().removeChild( scMesh );
}
public Node getActiveNode() {
return activeNode;
}
public Node setActiveNode( Node n ) {
if( activeNode == n ) return activeNode;
activeNode = n;
targetArcball.setTarget( n == null ? () -> new GLVector( 0, 0, 0 ) : n::getPosition);
eventService.publish( new NodeActivatedEvent( activeNode ) );
nodePropertyEditor.rebuildTree();
getScene().getOnNodePropertiesChanged().put("updateInspector",
node -> { if(node == activeNode) {
nodePropertyEditor.updateProperties(activeNode);
}
return null;
});
return activeNode;
}
public void toggleInspectorWindow()
{
boolean currentlyVisible = inspector.isVisible();
if(currentlyVisible) {
inspector.setVisible(false);
mainSplitPane.setDividerLocation(getWindowWidth());
}
else {
inspector.setVisible(true);
mainSplitPane.setDividerLocation(getWindowWidth()/4 * 3);
}
}
public synchronized void animate( int fps, Runnable action ) {
// TODO: Make animation speed less laggy and more accurate.
final int delay = 1000 / fps;
animations.add( threadService.run( () -> {
while( animating ) {
action.run();
try {
Thread.sleep( delay );
} catch( InterruptedException e ) {
break;
}
}
} ) );
animating = true;
}
public synchronized void stopAnimation() {
animating = false;
while( !animations.isEmpty() ) {
animations.peek().cancel( true );
animations.remove();
}
}
public void takeScreenshot() {
getRenderer().screenshot();
}
public void takeScreenshot( String path ) {
getRenderer().screenshot( path, false );
}
public Node[] getSceneNodes() {
return getSceneNodes( n -> !( n instanceof Camera ) && !( n instanceof PointLight ) );
}
public Node[] getSceneNodes( Predicate<? super Node> filter ) {
return getScene().getChildren().stream().filter( filter ).toArray( Node[]::new );
}
public Node[] getAllSceneNodes() {
return getSceneNodes( n -> true );
}
public void deleteActiveNode() {
deleteNode( getActiveNode() );
}
public void deleteNode( Node node ) {
node.getParent().removeChild( node );
eventService.publish( new NodeRemovedEvent( node ) );
if( activeNode == node ) setActiveNode( null );
}
public void dispose() {
this.close();
}
public void moveCamera( float[] position ) {
getCamera().setPosition( new GLVector( position[0], position[1], position[2] ) );
}
public void moveCamera( double[] position ) {
getCamera().setPosition( new GLVector( ( float ) position[0], ( float ) position[1], ( float ) position[2] ) );
}
public String getName() {
return getApplicationName();
}
public void addChild( Node node ) {
getScene().addChild( node );
}
public Node addVolume( Dataset image ) {
float[] voxelDims = new float[image.numDimensions()];
for( int d = 0; d < voxelDims.length; d++ ) {
voxelDims[d] = ( float ) image.axis( d ).averageScale( 0, 1 );
}
return addVolume( image, voxelDims );
}
public Node addBDVVolume( String source ) {
final VolumeViewerOptions opts = new VolumeViewerOptions();
opts.maxCacheSizeInMB(Integer.parseInt(System.getProperty("scenery.BDVVolume.maxCacheSize", "512")));
final BDVVolume v = new BDVVolume(source, opts);
v.setScale(new GLVector(0.01f, 0.01f, 0.01f));
getScene().addChild(v);
setActiveNode(v);
v.goToTimePoint(0);
return v;
}
@SuppressWarnings({ "rawtypes", "unchecked" }) public Node addVolume( Dataset image,
float[] voxelDimensions ) {
return addVolume( ( IterableInterval ) Views.flatIterable( image.getImgPlus() ), image.getName(),
voxelDimensions );
}
public <T extends RealType<T>> Node addVolume( IterableInterval<T> image ) {
return addVolume( image, "Volume" );
}
public <T extends RealType<T>> Node addVolume( IterableInterval<T> image, String name ) {
return addVolume( image, name, 1, 1, 1 );
}
public void setColormap( Node n, ColorTable colorTable ) {
final int copies = 16;
final ByteBuffer byteBuffer = ByteBuffer.allocateDirect(
4 * colorTable.getLength() * copies );// Num bytes * num components * color map length * height of color map texture
final byte[] tmp = new byte[4 * colorTable.getLength()];
for( int k = 0; k < colorTable.getLength(); k++ ) {
for( int c = 0; c < colorTable.getComponentCount(); c++ ) {
// TODO this assumes numBits is 8, could be 16
tmp[4 * k + c] = ( byte ) colorTable.get( c, k );
}
if( colorTable.getComponentCount() == 3 ) {
tmp[4 * k + 3] = (byte)255;
}
}
for( int i = 0; i < copies; i++ ) {
byteBuffer.put(tmp);
}
byteBuffer.flip();
n.getMetadata().put("sciviewColormap", colorTable);
if(n instanceof Volume) {
((Volume) n).getColormaps().put("sciviewColormap", new Volume.Colormap.ColormapBuffer(new GenericTexture("colorTable",
new GLVector(colorTable.getLength(),
copies, 1.0f), 4,
GLTypeEnum.UnsignedByte,
byteBuffer)));
((Volume) n).setColormap("sciviewColormap");
}
}
public <T extends RealType<T>> Node addVolume( IterableInterval<T> image, String name,
float... voxelDimensions ) {
log.debug( "Add Volume" );
long dimensions[] = new long[3];
image.dimensions( dimensions );
Volume v = new Volume();
getScene().addChild( v );
@SuppressWarnings("unchecked") Class<T> voxelType = ( Class<T> ) image.firstElement().getClass();
float minVal, maxVal;
if( voxelType == UnsignedByteType.class ) {
minVal = 0;
maxVal = 255;
} else if( voxelType == UnsignedShortType.class ) {
minVal = 0;
maxVal = 65535;
} else if( voxelType == FloatType.class ) {
minVal = 0;
maxVal = 1;
} else {
log.debug( "Type: " + voxelType +
" cannot be displayed as a volume. Convert to UnsignedByteType, UnsignedShortType, or FloatType." );
return null;
}
updateVolume( image, name, voxelDimensions, v );
GLVector scaleVec = new GLVector( 0.5f * dimensions[0], //
0.5f * dimensions[1], //
0.5f * dimensions[2] );
v.setScale( scaleVec );// TODO maybe dont do this
// TODO: This translation should probably be accounted for in scenery; volumes use a corner-origin and
// meshes use center-origin coordinate systems.
v.setPosition( v.getPosition().plus( new GLVector( 0.5f * dimensions[0] - 0.5f, 0.5f * dimensions[1] - 0.5f,
0.5f * dimensions[2] - 0.5f ) ) );
v.setTrangemin( minVal );
v.setTrangemax( maxVal );
v.setTransferFunction(TransferFunction.ramp(0.0f, 0.4f));
try {
setColormap( v, lutService.loadLUT( lutService.findLUTs().get( "WCIF/ICA.lut" ) ) );
} catch( IOException e ) {
e.printStackTrace();
}
setActiveNode( v );
return v;
}
public <T extends RealType<T>> Node updateVolume( IterableInterval<T> image, String name,
float[] voxelDimensions, Volume v ) {
log.debug( "Update Volume" );
long dimensions[] = new long[3];
image.dimensions( dimensions );
@SuppressWarnings("unchecked") Class<T> voxelType = ( Class<T> ) image.firstElement().getClass();
int bytesPerVoxel = image.firstElement().getBitsPerPixel() / 8;
NativeTypeEnum nType;
if( voxelType == UnsignedByteType.class ) {
nType = NativeTypeEnum.UnsignedByte;
} else if( voxelType == UnsignedShortType.class ) {
nType = NativeTypeEnum.UnsignedShort;
} else if( voxelType == FloatType.class ) {
nType = NativeTypeEnum.Float;
} else {
log.debug( "Type: " + voxelType +
" cannot be displayed as a volume. Convert to UnsignedByteType, UnsignedShortType, or FloatType." );
return null;
}
// Make and populate a ByteBuffer with the content of the Dataset
ByteBuffer byteBuffer = ByteBuffer.allocateDirect(
( int ) ( bytesPerVoxel * dimensions[0] * dimensions[1] * dimensions[2] ) );
Cursor<T> cursor = image.cursor();
while( cursor.hasNext() ) {
cursor.fwd();
if( voxelType == UnsignedByteType.class ) {
byteBuffer.put( ( byte ) ( ( ( UnsignedByteType ) cursor.get() ).get() ) );
} else if( voxelType == UnsignedShortType.class ) {
byteBuffer.putShort( ( short ) Math.abs( ( ( UnsignedShortType ) cursor.get() ).getShort() ) );
} else if( voxelType == FloatType.class ) {
byteBuffer.putFloat( ( ( FloatType ) cursor.get() ).get() );
}
}
byteBuffer.flip();
v.readFromBuffer( name, byteBuffer, dimensions[0], dimensions[1], dimensions[2], voxelDimensions[0],
voxelDimensions[1], voxelDimensions[2], nType, bytesPerVoxel );
v.setDirty( true );
v.setNeedsUpdate( true );
v.setNeedsUpdateWorld( true );
return v;
}
private static GLVector vector( ColorRGB color ) {
if( color instanceof ColorRGBA ) {
return new GLVector( color.getRed() / 255f, //
color.getGreen() / 255f, //
color.getBlue() / 255f, //
color.getAlpha() / 255f );
}
return new GLVector( color.getRed() / 255f, //
color.getGreen() / 255f, //
color.getBlue() / 255f );
}
public boolean getPushMode() {
return getRenderer().getPushMode();
}
public boolean setPushMode( boolean push ) {
getRenderer().setPushMode( push );
return getRenderer().getPushMode();
}
public ArcballCameraControl getTargetArcball() {
return targetArcball;
}
@Override
protected void finalize() {
stopAnimation();
}
private void updateFloorPosition() {
// Lower the floor below the active node, as needed.
final Node currentNode = getActiveNode();
if( currentNode != null ) {
final Node.OrientedBoundingBox bb = currentNode.generateBoundingBox();
final Node.BoundingSphere bs = bb.getBoundingSphere();
final float neededFloor = bb.getMin().y() - Math.max( bs.getRadius(), 1 );
if( neededFloor < getFloory() ) setFloory( neededFloor );
}
floor.setPosition( new GLVector( 0f, getFloory(), 0f ) );
}
public Settings getScenerySettings() {
return this.getSettings();
}
public Statistics getSceneryStats() {
return this.getStats();
}
public Renderer getSceneryRenderer() {
return this.getRenderer();
}
protected boolean vrActive = false;
public void toggleVRRendering() {
vrActive = !vrActive;
Camera cam = getScene().getActiveObserver();
if(!(cam instanceof DetachedHeadCamera)) {
return;
}
TrackerInput ti = null;
if (!getHub().has(SceneryElement.HMDInput)) {
try {
final OpenVRHMD hmd = new OpenVRHMD(false, true);
getHub().add(SceneryElement.HMDInput, hmd);
ti = hmd;
// we need to force reloading the renderer as the HMD might require device or instance extensions
if(getRenderer() instanceof VulkanRenderer) {
replaceRenderer(getRenderer().getClass().getSimpleName(), true);
Thread.sleep(1000);
}
} catch (Exception e) {
getLogger().error("Could not add OpenVRHMD: " + e.toString());
}
} else {
ti = getHub().getWorkingHMD();
}
if(vrActive && ti != null) {
((DetachedHeadCamera) cam).setTracker(ti);
} else {
((DetachedHeadCamera) cam).setTracker(null);
}
while(getRenderer().getInitialized() == false) {
getLogger().info("Waiting for renderer");
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
getRenderer().toggleVR();
}
}
| src/main/java/sc/iview/SciView.java | /*-
* #%L
* Scenery-backed 3D visualization package for ImageJ.
* %%
* Copyright (C) 2016 - 2018 SciView developers.
* %%
* 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.
* #L%
*/
package sc.iview;
import cleargl.GLTypeEnum;
import cleargl.GLVector;
import com.bulenkov.darcula.DarculaLaf;
import com.jogamp.opengl.math.Quaternion;
import com.sun.javafx.application.PlatformImpl;
import coremem.enums.NativeTypeEnum;
import graphics.scenery.Box;
import graphics.scenery.*;
import graphics.scenery.backends.Renderer;
import graphics.scenery.backends.vulkan.VulkanRenderer;
import graphics.scenery.controls.InputHandler;
import graphics.scenery.controls.OpenVRHMD;
import graphics.scenery.controls.TrackerInput;
import graphics.scenery.controls.behaviours.ArcballCameraControl;
import graphics.scenery.controls.behaviours.FPSCameraControl;
import graphics.scenery.controls.behaviours.MovementCommand;
import graphics.scenery.controls.behaviours.SelectCommand;
import graphics.scenery.utils.SceneryFXPanel;
import graphics.scenery.utils.SceneryJPanel;
import graphics.scenery.utils.SceneryPanel;
import graphics.scenery.utils.Statistics;
import graphics.scenery.volumes.TransferFunction;
import graphics.scenery.volumes.Volume;
import graphics.scenery.volumes.bdv.BDVVolume;
import javafx.animation.FadeTransition;
import javafx.animation.Interpolator;
import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.geometry.Insets;
import javafx.geometry.*;
import javafx.scene.control.Label;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseButton;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.paint.Paint;
import javafx.scene.text.TextAlignment;
import javafx.util.Duration;
import kotlin.Unit;
import kotlin.jvm.functions.Function1;
import net.imagej.Dataset;
import net.imagej.lut.LUTService;
import net.imagej.ops.OpService;
import net.imglib2.Cursor;
import net.imglib2.IterableInterval;
import net.imglib2.RealLocalizable;
import net.imglib2.RealPoint;
import net.imglib2.display.ColorTable;
import net.imglib2.type.numeric.RealType;
import net.imglib2.type.numeric.integer.UnsignedByteType;
import net.imglib2.type.numeric.integer.UnsignedShortType;
import net.imglib2.type.numeric.real.FloatType;
import net.imglib2.view.Views;
import org.scijava.Context;
import org.scijava.display.Display;
import org.scijava.display.DisplayService;
import org.scijava.event.EventService;
import org.scijava.io.IOService;
import org.scijava.log.LogService;
import org.scijava.menu.MenuService;
import org.scijava.plugin.Parameter;
import org.scijava.thread.ThreadService;
import org.scijava.ui.behaviour.ClickBehaviour;
import org.scijava.ui.behaviour.InputTrigger;
import org.scijava.ui.swing.menu.SwingJMenuBarCreator;
import org.scijava.util.ColorRGB;
import org.scijava.util.ColorRGBA;
import org.scijava.util.Colors;
import sc.iview.commands.view.NodePropertyEditor;
import sc.iview.controls.behaviours.CameraTranslateControl;
import sc.iview.controls.behaviours.NodeTranslateControl;
import sc.iview.event.NodeActivatedEvent;
import sc.iview.event.NodeAddedEvent;
import sc.iview.event.NodeRemovedEvent;
import sc.iview.javafx.JavaFXMenuCreator;
import sc.iview.process.MeshConverter;
import sc.iview.vector.ClearGLVector3;
import sc.iview.vector.Vector3;
import tpietzsch.example2.VolumeViewerOptions;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.event.ChangeListener;
import javax.swing.plaf.basic.BasicLookAndFeel;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.util.List;
import java.util.Queue;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;
import java.util.function.Predicate;
import java.util.function.Supplier;
public class SciView extends SceneryBase {
public static final ColorRGB DEFAULT_COLOR = Colors.LIGHTGRAY;
@Parameter
private LogService log;
@Parameter
private MenuService menus;
@Parameter
private IOService io;
@Parameter
private OpService ops;
@Parameter
private EventService eventService;
@Parameter
private DisplayService displayService;
@Parameter
private LUTService lutService;
@Parameter
private ThreadService threadService;
/**
* Queue keeps track of the currently running animations
**/
private Queue<Future> animations;
/**
* Animation pause tracking
**/
private boolean animating;
/**
* This tracks the actively selected Node in the scene
*/
private Node activeNode = null;
/**
* Mouse controls for FPS movement and Arcball rotation
*/
protected ArcballCameraControl targetArcball;
protected FPSCameraControl fpsControl;
/**
* The primary camera/observer in the scene
*/
Camera camera = null;
/**
* JavaFX UI
*/
private boolean useJavaFX = false;
/**
* Speeds for input controls
*/
private float fpsScrollSpeed = 3.0f;
private float mouseSpeedMult = 0.25f;
private Display<?> scijavaDisplay;
/**
* The floor that orients the user in the scene
*/
protected Node floor;
private Label statusLabel;
private Label loadingLabel;
private JLabel splashLabel;
private SceneryJPanel panel;
private StackPane stackPane;
private MenuBar menuBar;
private JSplitPane mainSplitPane;
private final SceneryPanel[] sceneryPanel = { null };
private JSplitPane inspector;
private NodePropertyEditor nodePropertyEditor;
public SciView( Context context ) {
super( "SciView", 1280, 720, false, context );
context.inject( this );
}
public SciView( String applicationName, int windowWidth, int windowHeight ) {
super( applicationName, windowWidth, windowHeight, false );
}
public InputHandler publicGetInputHandler() {
return getInputHandler();
}
public class TransparentSlider extends JSlider {
public TransparentSlider() {
// Important, we taking over the filling of the
// component...
setOpaque(false);
setBackground(java.awt.Color.DARK_GRAY);
setForeground(java.awt.Color.LIGHT_GRAY);
}
@Override
protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(getBackground());
g2d.setComposite(AlphaComposite.SrcOver.derive(0.9f));
g2d.fillRect(0, 0, getWidth(), getHeight());
g2d.dispose();
super.paintComponent(g);
}
}
@SuppressWarnings("restriction") @Override public void init() {
if(Boolean.parseBoolean(System.getProperty("sciview.useDarcula", "false"))) {
try {
BasicLookAndFeel darcula = new DarculaLaf();
UIManager.setLookAndFeel(darcula);
} catch (Exception e) {
System.err.println("Could not load Darcula Look and Feel");
}
}
int x, y;
try {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
x = screenSize.width/2 - getWindowWidth()/2;
y = screenSize.height/2 - getWindowHeight()/2;
} catch(HeadlessException e) {
x = 10;
y = 10;
}
JFrame frame = new JFrame("SciView");
frame.setLayout(new BorderLayout(0, 0));
frame.setSize(getWindowWidth(), getWindowHeight());
frame.setLocation(x, y);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
nodePropertyEditor = new NodePropertyEditor( this );
if( useJavaFX ) {
final JFXPanel fxPanel = new JFXPanel();
frame.add(fxPanel);
CountDownLatch latch = new CountDownLatch( 1 );
PlatformImpl.startup( () -> {
} );
Platform.runLater( () -> {
stackPane = new StackPane();
stackPane.setBackground(
new Background( new BackgroundFill( Color.TRANSPARENT, CornerRadii.EMPTY, Insets.EMPTY ) ) );
GridPane pane = new GridPane();
statusLabel = new Label( "SciView - press U for usage help" );
statusLabel.setVisible(false);
final SceneryFXPanel panel = new SceneryFXPanel(100, 100);
Image loadingImage = new Image(this.getClass().getResourceAsStream("sciview-logo.png"), 600, 200, true, true);
ImageView loadingImageView = new ImageView(loadingImage);
loadingLabel = new Label("SciView is starting.");
loadingLabel.setStyle(
"-fx-background-color: rgb(50,48,47);" +
"-fx-opacity: 1.0;" +
"-fx-font-weight: 400; " +
"-fx-font-size: 2.2em; " +
"-fx-text-fill: white;");
loadingLabel.setTextFill(Paint.valueOf("white"));
loadingLabel.setGraphic(loadingImageView);
loadingLabel.setGraphicTextGap(40.0);
loadingLabel.setContentDisplay(ContentDisplay.TOP);
loadingLabel.prefHeightProperty().bind(pane.heightProperty());
loadingLabel.prefWidthProperty().bind(pane.widthProperty());
loadingLabel.setAlignment(Pos.CENTER);
GridPane.setHgrow( panel, Priority.ALWAYS );
GridPane.setVgrow( panel, Priority.ALWAYS );
GridPane.setFillHeight( panel, true );
GridPane.setFillWidth( panel, true );
GridPane.setHgrow( statusLabel, Priority.ALWAYS );
GridPane.setHalignment( statusLabel, HPos.CENTER );
GridPane.setValignment( statusLabel, VPos.BOTTOM );
statusLabel.maxWidthProperty().bind( pane.widthProperty() );
pane.setStyle( "-fx-background-color: rgb(50,48,47);" +
"-fx-font-family: Helvetica Neue, Helvetica, Segoe, Proxima Nova, Arial, sans-serif;" +
"-fx-font-weight: 400;" + "-fx-font-size: 1.2em;" + "-fx-text-fill: white;" +
"-fx-text-alignment: center;" );
statusLabel.setStyle( "-fx-padding: 0.2em;" + "-fx-text-fill: white;" );
statusLabel.setTextAlignment( TextAlignment.CENTER );
menuBar = new MenuBar();
pane.add( menuBar, 1, 1 );
pane.add( panel, 1, 2 );
pane.add( statusLabel, 1, 3 );
stackPane.getChildren().addAll(pane, loadingLabel);
final ContextMenu contextMenu = new ContextMenu();
final MenuItem title = new MenuItem("Node");
final MenuItem position = new MenuItem("Position");
title.setDisable(true);
position.setDisable(true);
contextMenu.getItems().addAll(title, position);
panel.setOnContextMenuRequested(event -> {
final Point2D localPosition = panel.sceneToLocal(event.getSceneX(), event.getSceneY());
final List<Scene.RaycastResult> matches = camera.getNodesForScreenSpacePosition((int)localPosition.getX(), (int)localPosition.getY());
if(matches.size() > 0) {
final Node firstMatch = matches.get(0).getNode();
title.setText("Node: " + firstMatch.getName() + " (" + firstMatch.getClass().getSimpleName() + ")");
position.setText(firstMatch.getPosition().toString());
} else {
title.setText("(no matches)");
position.setText("");
}
contextMenu.show(panel, event.getScreenX(), event.getScreenY());
});
panel.setOnMouseClicked(event -> {
if(event.getButton() == MouseButton.PRIMARY) {
contextMenu.hide();
}
});
sceneryPanel[0] = panel;
javafx.scene.Scene scene = new javafx.scene.Scene( stackPane );
fxPanel.setScene(scene);
// scene.addEventHandler(MouseEvent.ANY, event -> getLogger().info("Mouse event: " + event.toString()));
// sceneryPanel[0].addEventHandler(MouseEvent.ANY, event -> getLogger().info("PANEL Mouse event: " + event.toString()));
frame.setVisible(true);
// stage.setScene( scene );
// stage.setOnCloseRequest( event -> {
// getDisplay().close();
// this.close();
// } );
// stage.focusedProperty().addListener( ( ov, t, t1 ) -> {
// if( t1 )// If you just gained focus
// displayService.setActiveDisplay( getDisplay() );
// } );
new JavaFXMenuCreator().createMenus( menus.getMenu( "SciView" ), menuBar );
// stage.show();
latch.countDown();
} );
try {
latch.await();
} catch( InterruptedException e1 ) {
e1.printStackTrace();
}
// window width and window height get ignored by the renderer if it is embedded.
// dimensions are determined from the SceneryFXPanel, then.
setRenderer( Renderer.createRenderer( getHub(), getApplicationName(), getScene(),
getWindowWidth(), getWindowHeight(),
sceneryPanel[0] ) );
} else {
final JPanel p = new JPanel(new BorderLayout(0, 0));
panel = new SceneryJPanel();
JPopupMenu.setDefaultLightWeightPopupEnabled(false);
final JMenuBar swingMenuBar = new JMenuBar();
new SwingJMenuBarCreator().createMenus(menus.getMenu("SciView"), swingMenuBar);
frame.setJMenuBar(swingMenuBar);
BufferedImage splashImage;
try {
splashImage = ImageIO.read(this.getClass().getResourceAsStream("sciview-logo.png"));
} catch (IOException e) {
getLogger().warn("Could not read splash image 'sciview-logo.png'");
splashImage = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
}
splashLabel = new JLabel(new ImageIcon(splashImage.getScaledInstance(500, 200, java.awt.Image.SCALE_SMOOTH)));
splashLabel.setBackground(new java.awt.Color(50, 48, 47));
splashLabel.setOpaque(true);
p.setLayout(new OverlayLayout(p));
p.setBackground(new java.awt.Color(50, 48, 47));
p.add(panel, BorderLayout.CENTER);
panel.setVisible(true);
nodePropertyEditor.getComponent(); // Initialize node property panel
JTree inspectorTree = nodePropertyEditor.getTree();
JPanel inspectorProperties = nodePropertyEditor.getProps();
inspector = new JSplitPane(JSplitPane.VERTICAL_SPLIT, //
new JScrollPane( inspectorTree ),
new JScrollPane( inspectorProperties ));
inspector.setDividerLocation( getWindowHeight() / 3 );
inspector.setContinuousLayout(true);
inspector.setBorder(BorderFactory.createEmptyBorder());
mainSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, //
p,
inspector
);
mainSplitPane.setDividerLocation( getWindowWidth()/3 * 2 );
mainSplitPane.setBorder(BorderFactory.createEmptyBorder());
frame.add(mainSplitPane, BorderLayout.CENTER);
frame.setGlassPane(splashLabel);
frame.getGlassPane().setVisible(true);
// frame.getGlassPane().setBackground(new java.awt.Color(50, 48, 47, 255));
frame.setVisible(true);
sceneryPanel[0] = panel;
setRenderer( Renderer.createRenderer( getHub(), getApplicationName(), getScene(),
getWindowWidth(), getWindowHeight(),
sceneryPanel[0]) );
}
// Enable push rendering by default
getRenderer().setPushMode( true );
getHub().add( SceneryElement.Renderer, getRenderer() );
GLVector[] tetrahedron = new GLVector[4];
tetrahedron[0] = new GLVector( 1.0f, 0f, -1.0f/(float)Math.sqrt(2.0f) );
tetrahedron[1] = new GLVector( -1.0f,0f,-1.0f/(float)Math.sqrt(2.0) );
tetrahedron[2] = new GLVector( 0.0f,1.0f,1.0f/(float)Math.sqrt(2.0) );
tetrahedron[3] = new GLVector( 0.0f,-1.0f,1.0f/(float)Math.sqrt(2.0) );
PointLight[] lights = new PointLight[4];
for( int i = 0; i < lights.length; i++ ) {
lights[i] = new PointLight( 150.0f );
lights[i].setPosition( tetrahedron[i].times(25.0f) );
lights[i].setEmissionColor( new GLVector( 1.0f, 1.0f, 1.0f ) );
lights[i].setIntensity( 100.0f );
getScene().addChild( lights[i] );
}
Camera cam = new DetachedHeadCamera();
cam.setPosition( new GLVector( 0.0f, 5.0f, 5.0f ) );
cam.perspectiveCamera( 50.0f, getWindowWidth(), getWindowHeight(), 0.1f, 1000.0f );
//cam.setTarget( new GLVector( 0, 0, 0 ) );
//cam.setTargeted( true );
cam.setActive( true );
getScene().addChild( cam );
this.camera = cam;
floor = new Box( new GLVector( 500f, 0.2f, 500f ) );
floor.setName( "Floor" );
floor.setPosition( new GLVector( 0f, -1f, 0f ) );
floor.getMaterial().setDiffuse( new GLVector( 1.0f, 1.0f, 1.0f ) );
getScene().addChild( floor );
animations = new LinkedList<>();
if(useJavaFX) {
Platform.runLater(() -> {
while (!getRenderer().getFirstImageReady()) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// fade out loading screen, show status bar
FadeTransition ft = new FadeTransition(Duration.millis(500), loadingLabel);
ft.setFromValue(1.0);
ft.setToValue(0.0);
ft.setCycleCount(1);
ft.setInterpolator(Interpolator.EASE_OUT);
ft.setOnFinished(event -> {
loadingLabel.setVisible(false);
statusLabel.setVisible(true);
});
ft.play();
});
} else {
SwingUtilities.invokeLater(() -> {
try {
while (!getSceneryRenderer().getFirstImageReady()) {
getLogger().info("Waiting for renderer");
Thread.sleep(100);
}
Thread.sleep(200);
} catch (InterruptedException e) {
}
nodePropertyEditor.rebuildTree();
frame.getGlassPane().setVisible(false);
getLogger().info("Done initializing SciView");
});
}
}
public void setStatusText(String text) {
statusLabel.setText(text);
}
public void setFloor( Node n ) {
floor = n;
}
public Node getFloor() {
return floor;
}
private float getFloory() {
return floor.getPosition().y();
}
private void setFloory( float new_pos ) {
float temp_pos = 0f;
temp_pos = new_pos;
if( temp_pos < -100f ) temp_pos = -100f;
else if( new_pos > 5f ) temp_pos = 5f;
floor.getPosition().set( 1, temp_pos );
}
public boolean isInitialized() {
return sceneInitialized();
}
public Camera getCamera() {
return camera;
}
public void setDisplay( Display<?> display ) {
scijavaDisplay = display;
}
public Display<?> getDisplay() {
return scijavaDisplay;
}
public void centerOnNode( Node currentNode ) {
if( currentNode == null ) return;
Node.OrientedBoundingBox bb = currentNode.generateBoundingBox();
getCamera().setTarget( currentNode.getPosition() );
getCamera().setTargeted( true );
// Set forward direction to point from camera at active node
getCamera().setForward( bb.getBoundingSphere().getOrigin().minus( getCamera().getPosition() ).normalize().times( -1 ) );
float distance = (float) (bb.getBoundingSphere().getRadius() / Math.tan( getCamera().getFov() / 360 * java.lang.Math.PI ));
// Solve for the proper rotation
Quaternion rotation = new Quaternion().setLookAt( getCamera().getForward().toFloatArray(),
new GLVector(0,1,0).toFloatArray(),
new GLVector(1,0,0).toFloatArray(),
new GLVector( 0,1,0).toFloatArray(),
new GLVector( 0, 0, 1).toFloatArray() );
getCamera().setRotation( rotation.normalize() );
getCamera().setPosition( bb.getBoundingSphere().getOrigin().plus( getCamera().getForward().times( distance * -1 ) ) );
getCamera().setDirty(true);
getCamera().setNeedsUpdate(true);
}
public void setFPSSpeed( float newspeed ) {
if( newspeed < 0.30f ) newspeed = 0.3f;
else if( newspeed > 30.0f ) newspeed = 30.0f;
fpsScrollSpeed = newspeed;
log.debug( "FPS scroll speed: " + fpsScrollSpeed );
}
public float getFPSSpeed() {
return fpsScrollSpeed;
}
public void setMouseSpeed( float newspeed ) {
if( newspeed < 0.30f ) newspeed = 0.3f;
else if( newspeed > 3.0f ) newspeed = 3.0f;
mouseSpeedMult = newspeed;
log.debug( "Mouse speed: " + mouseSpeedMult );
}
public float getMouseSpeed() {
return mouseSpeedMult;
}
public void resetFPSInputs() {
getInputHandler().addBehaviour( "move_forward_scroll",
new MovementCommand( "move_forward", "forward", () -> getScene().findObserver(),
getFPSSpeed() ) );
getInputHandler().addBehaviour( "move_forward",
new MovementCommand( "move_forward", "forward", () -> getScene().findObserver(),
getFPSSpeed() ) );
getInputHandler().addBehaviour( "move_back",
new MovementCommand( "move_back", "back", () -> getScene().findObserver(),
getFPSSpeed() ) );
getInputHandler().addBehaviour( "move_left",
new MovementCommand( "move_left", "left", () -> getScene().findObserver(),
getFPSSpeed() ) );
getInputHandler().addBehaviour( "move_right",
new MovementCommand( "move_right", "right", () -> getScene().findObserver(),
getFPSSpeed() ) );
getInputHandler().addBehaviour( "move_up",
new MovementCommand( "move_up", "up", () -> getScene().findObserver(),
getFPSSpeed() ) );
getInputHandler().addBehaviour( "move_down",
new MovementCommand( "move_down", "down", () -> getScene().findObserver(),
getFPSSpeed() ) );
}
class enableIncrease implements ClickBehaviour {
@Override public void click( int x, int y ) {
setFPSSpeed( getFPSSpeed() + 0.5f );
setMouseSpeed( getMouseSpeed() + 0.05f );
log.debug( "Increasing FPS scroll Speed" );
resetFPSInputs();
}
}
class enableDecrease implements ClickBehaviour {
@Override public void click( int x, int y ) {
setFPSSpeed( getFPSSpeed() - 0.1f );
setMouseSpeed( getMouseSpeed() - 0.05f );
log.debug( "Decreasing FPS scroll Speed" );
resetFPSInputs();
}
}
class showHelpDisplay implements ClickBehaviour {
@Override public void click( int x, int y ) {
String helpString = "SciView help:\n\n";
for( InputTrigger trigger : getInputHandler().getAllBindings().keySet() ) {
helpString += trigger + "\t-\t" + getInputHandler().getAllBindings().get( trigger ) + "\n";
}
// HACK: Make the console pop via stderr.
// Later, we will use a nicer dialog box or some such.
log.warn( helpString );
}
}
@Override public void inputSetup() {
Function1<? super List<Scene.RaycastResult>, Unit> selectAction = nearest -> {
if( !nearest.isEmpty() ) {
setActiveNode( nearest.get( 0 ).getNode() );
log.debug( "Selected node: " + getActiveNode().getName() );
}
return Unit.INSTANCE;
};
List<Class<? extends Object>> ignoredObjects = new ArrayList<>();
ignoredObjects.add( BoundingGrid.class );
getInputHandler().useDefaultBindings( "" );
// Mouse controls
getInputHandler().addBehaviour( "object_selection_mode",
new SelectCommand( "objectSelector", getRenderer(), getScene(),
() -> getScene().findObserver(), false, ignoredObjects,
selectAction ) );
getInputHandler().addKeyBinding( "object_selection_mode", "double-click button1" );
enableArcBallControl();
enableFPSControl();
getInputHandler().addBehaviour( "mouse_control_nodetranslate", new NodeTranslateControl( this, 0.002f ) );
getInputHandler().addKeyBinding( "mouse_control_nodetranslate", "shift button2" );
// Extra keyboard controls
getInputHandler().addBehaviour( "show_help", new showHelpDisplay() );
getInputHandler().addKeyBinding( "show_help", "U" );
getInputHandler().addBehaviour( "enable_decrease", new enableDecrease() );
getInputHandler().addKeyBinding( "enable_decrease", "M" );
getInputHandler().addBehaviour( "enable_increase", new enableIncrease() );
getInputHandler().addKeyBinding( "enable_increase", "N" );
}
private void enableArcBallControl() {
GLVector target;
if( getActiveNode() == null ) {
target = new GLVector( 0, 0, 0 );
} else {
target = getActiveNode().getPosition();
}
float mouseSpeed = 0.25f;
mouseSpeed = getMouseSpeed();
Supplier<Camera> cameraSupplier = () -> getScene().findObserver();
targetArcball = new ArcballCameraControl( "mouse_control_arcball", cameraSupplier,
getRenderer().getWindow().getWidth(),
getRenderer().getWindow().getHeight(), target );
targetArcball.setMaximumDistance( Float.MAX_VALUE );
targetArcball.setMouseSpeedMultiplier( mouseSpeed );
targetArcball.setScrollSpeedMultiplier( 0.05f );
targetArcball.setDistance( getCamera().getPosition().minus( target ).magnitude() );
getInputHandler().addBehaviour( "mouse_control_arcball", targetArcball );
getInputHandler().addKeyBinding( "mouse_control_arcball", "shift button1" );
getInputHandler().addBehaviour( "scroll_arcball", targetArcball );
getInputHandler().addKeyBinding( "scroll_arcball", "shift scroll" );
}
private void enableFPSControl() {
Supplier<Camera> cameraSupplier = () -> getScene().findObserver();
fpsControl = new FPSCameraControl( "mouse_control", cameraSupplier, getRenderer().getWindow().getWidth(),
getRenderer().getWindow().getHeight() );
getInputHandler().addBehaviour( "mouse_control", fpsControl );
getInputHandler().addKeyBinding( "mouse_control", "button1" );
getInputHandler().addBehaviour( "mouse_control_cameratranslate", new CameraTranslateControl( this, 0.002f ) );
getInputHandler().addKeyBinding( "mouse_control_cameratranslate", "button2" );
resetFPSInputs();
getInputHandler().addKeyBinding( "move_forward_scroll", "scroll" );
}
public Node addBox() {
return addBox( new ClearGLVector3( 0.0f, 0.0f, 0.0f ) );
}
public Node addBox( Vector3 position ) {
return addBox( position, new ClearGLVector3( 1.0f, 1.0f, 1.0f ) );
}
public Node addBox( Vector3 position, Vector3 size ) {
return addBox( position, size, DEFAULT_COLOR, false );
}
public Node addBox( final Vector3 position, final Vector3 size, final ColorRGB color,
final boolean inside ) {
// TODO: use a material from the current palate by default
final Material boxmaterial = new Material();
boxmaterial.setAmbient( new GLVector( 1.0f, 0.0f, 0.0f ) );
boxmaterial.setDiffuse( vector( color ) );
boxmaterial.setSpecular( new GLVector( 1.0f, 1.0f, 1.0f ) );
final Box box = new Box( ClearGLVector3.convert( size ), inside );
box.setMaterial( boxmaterial );
box.setPosition( ClearGLVector3.convert( position ) );
return addNode( box );
}
public Node addSphere() {
return addSphere( new ClearGLVector3( 0.0f, 0.0f, 0.0f ), 1 );
}
public Node addSphere( Vector3 position, float radius ) {
return addSphere( position, radius, DEFAULT_COLOR );
}
public Node addSphere( final Vector3 position, final float radius, final ColorRGB color ) {
final Material material = new Material();
material.setAmbient( new GLVector( 1.0f, 0.0f, 0.0f ) );
material.setDiffuse( vector( color ) );
material.setSpecular( new GLVector( 1.0f, 1.0f, 1.0f ) );
final Sphere sphere = new Sphere( radius, 20 );
sphere.setMaterial( material );
sphere.setPosition( ClearGLVector3.convert( position ) );
return addNode( sphere );
}
public Node addLine() {
return addLine( new ClearGLVector3( 0.0f, 0.0f, 0.0f ), new ClearGLVector3( 0.0f, 0.0f, 0.0f ) );
}
public Node addLine( Vector3 start, Vector3 stop ) {
return addLine( start, stop, DEFAULT_COLOR );
}
public Node addLine( Vector3 start, Vector3 stop, ColorRGB color ) {
return addLine( new Vector3[] { start, stop }, color, 0.1f );
}
public Node addLine( final Vector3[] points, final ColorRGB color, final double edgeWidth ) {
final Material material = new Material();
material.setAmbient( new GLVector( 1.0f, 1.0f, 1.0f ) );
material.setDiffuse( vector( color ) );
material.setSpecular( new GLVector( 1.0f, 1.0f, 1.0f ) );
final Line line = new Line( points.length );
for( final Vector3 pt : points ) {
line.addPoint( ClearGLVector3.convert( pt ) );
}
line.setEdgeWidth( ( float ) edgeWidth );
line.setMaterial( material );
line.setPosition( ClearGLVector3.convert( points[0] ) );
return addNode( line );
}
public Node addPointLight() {
final Material material = new Material();
material.setAmbient( new GLVector( 1.0f, 0.0f, 0.0f ) );
material.setDiffuse( new GLVector( 0.0f, 1.0f, 0.0f ) );
material.setSpecular( new GLVector( 1.0f, 1.0f, 1.0f ) );
final PointLight light = new PointLight( 5.0f );
light.setMaterial( material );
light.setPosition( new GLVector( 0.0f, 0.0f, 0.0f ) );
return addNode( light );
}
public void writeSCMesh( String filename, Mesh scMesh ) {
File f = new File( filename );
BufferedOutputStream out;
try {
out = new BufferedOutputStream( new FileOutputStream( f ) );
out.write( "solid STL generated by FIJI\n".getBytes() );
FloatBuffer normalsFB = scMesh.getNormals();
FloatBuffer verticesFB = scMesh.getVertices();
while( verticesFB.hasRemaining() && normalsFB.hasRemaining() ) {
out.write( ( "facet normal " + normalsFB.get() + " " + normalsFB.get() + " " + normalsFB.get() +
"\n" ).getBytes() );
out.write( "outer loop\n".getBytes() );
for( int v = 0; v < 3; v++ ) {
out.write( ( "vertex\t" + verticesFB.get() + " " + verticesFB.get() + " " + verticesFB.get() +
"\n" ).getBytes() );
}
out.write( "endloop\n".getBytes() );
out.write( "endfacet\n".getBytes() );
}
out.write( "endsolid vcg\n".getBytes() );
out.close();
} catch( FileNotFoundException e ) {
e.printStackTrace();
} catch( IOException e ) {
e.printStackTrace();
}
}
public float getDefaultPointSize() {
return 0.025f;
}
public float[] makeNormalsFromVertices( ArrayList<RealPoint> verts ) {
float[] normals = new float[verts.size()];// div3 * 3coords
for( int k = 0; k < verts.size(); k += 3 ) {
GLVector v1 = new GLVector( verts.get( k ).getFloatPosition( 0 ), //
verts.get( k ).getFloatPosition( 1 ), //
verts.get( k ).getFloatPosition( 2 ) );
GLVector v2 = new GLVector( verts.get( k + 1 ).getFloatPosition( 0 ),
verts.get( k + 1 ).getFloatPosition( 1 ),
verts.get( k + 1 ).getFloatPosition( 2 ) );
GLVector v3 = new GLVector( verts.get( k + 2 ).getFloatPosition( 0 ),
verts.get( k + 2 ).getFloatPosition( 1 ),
verts.get( k + 2 ).getFloatPosition( 2 ) );
GLVector a = v2.minus( v1 );
GLVector b = v3.minus( v1 );
GLVector n = a.cross( b ).getNormalized();
normals[k / 3] = n.get( 0 );
normals[k / 3 + 1] = n.get( 1 );
normals[k / 3 + 2] = n.get( 2 );
}
return normals;
}
public void open( final String source ) throws IOException {
if(source.endsWith(".xml")) {
addBDVVolume(source);
return;
}
final Object data = io.open( source );
if( data instanceof net.imagej.mesh.Mesh ) addMesh( ( net.imagej.mesh.Mesh ) data );
else if( data instanceof graphics.scenery.Mesh ) addMesh( ( graphics.scenery.Mesh ) data );
else if( data instanceof graphics.scenery.PointCloud ) addPointCloud( ( graphics.scenery.PointCloud ) data );
else if( data instanceof Dataset ) addVolume( ( Dataset ) data );
else if( data instanceof IterableInterval ) addVolume( ( ( IterableInterval ) data ), source );
else if( data instanceof List ) {
final List<?> list = ( List<?> ) data;
if( list.isEmpty() ) {
throw new IllegalArgumentException( "Data source '" + source + "' appears empty." );
}
final Object element = list.get( 0 );
if( element instanceof RealLocalizable ) {
// NB: For now, we assume all elements will be RealLocalizable.
// Highly likely to be the case, barring antagonistic importers.
@SuppressWarnings("unchecked") final List<? extends RealLocalizable> points = ( List<? extends RealLocalizable> ) list;
addPointCloud( points, source );
} else {
final String type = element == null ? "<null>" : element.getClass().getName();
throw new IllegalArgumentException( "Data source '" + source + //
"' contains elements of unknown type '" + type + "'" );
}
} else {
final String type = data == null ? "<null>" : data.getClass().getName();
throw new IllegalArgumentException( "Data source '" + source + //
"' contains data of unknown type '" + type + "'" );
}
}
public Node addPointCloud( Collection<? extends RealLocalizable> points ) {
return addPointCloud( points, "PointCloud" );
}
public Node addPointCloud( final Collection<? extends RealLocalizable> points,
final String name ) {
final float[] flatVerts = new float[points.size() * 3];
int k = 0;
for( final RealLocalizable point : points ) {
flatVerts[k * 3] = point.getFloatPosition( 0 );
flatVerts[k * 3 + 1] = point.getFloatPosition( 1 );
flatVerts[k * 3 + 2] = point.getFloatPosition( 2 );
k++;
}
final PointCloud pointCloud = new PointCloud( getDefaultPointSize(), name );
final Material material = new Material();
final FloatBuffer vBuffer = ByteBuffer.allocateDirect( flatVerts.length * 4 ) //
.order( ByteOrder.nativeOrder() ).asFloatBuffer();
final FloatBuffer nBuffer = ByteBuffer.allocateDirect( 0 ) //
.order( ByteOrder.nativeOrder() ).asFloatBuffer();
vBuffer.put( flatVerts );
vBuffer.flip();
pointCloud.setVertices( vBuffer );
pointCloud.setNormals( nBuffer );
pointCloud.setIndices( ByteBuffer.allocateDirect( 0 ) //
.order( ByteOrder.nativeOrder() ).asIntBuffer() );
pointCloud.setupPointCloud();
material.setAmbient( new GLVector( 1.0f, 1.0f, 1.0f ) );
material.setDiffuse( new GLVector( 1.0f, 1.0f, 1.0f ) );
material.setSpecular( new GLVector( 1.0f, 1.0f, 1.0f ) );
pointCloud.setMaterial( material );
pointCloud.setPosition( new GLVector( 0f, 0f, 0f ) );
return addNode( pointCloud );
}
public Node addPointCloud( final PointCloud pointCloud ) {
pointCloud.setupPointCloud();
pointCloud.getMaterial().setAmbient( new GLVector( 1.0f, 1.0f, 1.0f ) );
pointCloud.getMaterial().setDiffuse( new GLVector( 1.0f, 1.0f, 1.0f ) );
pointCloud.getMaterial().setSpecular( new GLVector( 1.0f, 1.0f, 1.0f ) );
pointCloud.setPosition( new GLVector( 0f, 0f, 0f ) );
return addNode( pointCloud );
}
public Node addNode( final Node n ) {
getScene().addChild( n );
setActiveNode( n );
updateFloorPosition();
eventService.publish( new NodeAddedEvent( n ) );
return n;
}
public Node addMesh( final Mesh scMesh ) {
final Material material = new Material();
material.setAmbient( new GLVector( 1.0f, 0.0f, 0.0f ) );
material.setDiffuse( new GLVector( 0.0f, 1.0f, 0.0f ) );
material.setSpecular( new GLVector( 1.0f, 1.0f, 1.0f ) );
scMesh.setMaterial( material );
scMesh.setPosition( new GLVector( 0.0f, 0.0f, 0.0f ) );
return addNode( scMesh );
}
public Node addMesh( net.imagej.mesh.Mesh mesh ) {
Mesh scMesh = MeshConverter.toScenery( mesh );
return addMesh( scMesh );
}
public void removeMesh( Mesh scMesh ) {
getScene().removeChild( scMesh );
}
public Node getActiveNode() {
return activeNode;
}
public Node setActiveNode( Node n ) {
if( activeNode == n ) return activeNode;
activeNode = n;
targetArcball.setTarget( n == null ? () -> new GLVector( 0, 0, 0 ) : n::getPosition);
eventService.publish( new NodeActivatedEvent( activeNode ) );
nodePropertyEditor.rebuildTree();
getScene().getOnNodePropertiesChanged().put("updateInspector",
node -> { if(node == activeNode) {
nodePropertyEditor.updateProperties(activeNode);
}
return null;
});
return activeNode;
}
public void toggleInspectorWindow()
{
boolean currentlyVisible = inspector.isVisible();
if(currentlyVisible) {
inspector.setVisible(false);
mainSplitPane.setDividerLocation(getWindowWidth());
}
else {
inspector.setVisible(true);
mainSplitPane.setDividerLocation(getWindowWidth()/4 * 3);
}
}
public synchronized void animate( int fps, Runnable action ) {
// TODO: Make animation speed less laggy and more accurate.
final int delay = 1000 / fps;
animations.add( threadService.run( () -> {
while( animating ) {
action.run();
try {
Thread.sleep( delay );
} catch( InterruptedException e ) {
break;
}
}
} ) );
animating = true;
}
public synchronized void stopAnimation() {
animating = false;
while( !animations.isEmpty() ) {
animations.peek().cancel( true );
animations.remove();
}
}
public void takeScreenshot() {
getRenderer().screenshot();
}
public void takeScreenshot( String path ) {
getRenderer().screenshot( path, false );
}
public Node[] getSceneNodes() {
return getSceneNodes( n -> !( n instanceof Camera ) && !( n instanceof PointLight ) );
}
public Node[] getSceneNodes( Predicate<? super Node> filter ) {
return getScene().getChildren().stream().filter( filter ).toArray( Node[]::new );
}
public Node[] getAllSceneNodes() {
return getSceneNodes( n -> true );
}
public void deleteActiveNode() {
deleteNode( getActiveNode() );
}
public void deleteNode( Node node ) {
node.getParent().removeChild( node );
eventService.publish( new NodeRemovedEvent( node ) );
if( activeNode == node ) setActiveNode( null );
}
public void dispose() {
this.close();
}
public void moveCamera( float[] position ) {
getCamera().setPosition( new GLVector( position[0], position[1], position[2] ) );
}
public void moveCamera( double[] position ) {
getCamera().setPosition( new GLVector( ( float ) position[0], ( float ) position[1], ( float ) position[2] ) );
}
public String getName() {
return getApplicationName();
}
public void addChild( Node node ) {
getScene().addChild( node );
}
public Node addVolume( Dataset image ) {
float[] voxelDims = new float[image.numDimensions()];
for( int d = 0; d < voxelDims.length; d++ ) {
voxelDims[d] = ( float ) image.axis( d ).averageScale( 0, 1 );
}
return addVolume( image, voxelDims );
}
public Node addBDVVolume( String source ) {
final VolumeViewerOptions opts = new VolumeViewerOptions();
opts.maxCacheSizeInMB(Integer.parseInt(System.getProperty("scenery.BDVVolume.maxCacheSize", "512")));
final BDVVolume v = new BDVVolume(source, opts);
v.setScale(new GLVector(0.01f, 0.01f, 0.01f));
getScene().addChild(v);
setActiveNode(v);
v.goToTimePoint(0);
return v;
}
@SuppressWarnings({ "rawtypes", "unchecked" }) public Node addVolume( Dataset image,
float[] voxelDimensions ) {
return addVolume( ( IterableInterval ) Views.flatIterable( image.getImgPlus() ), image.getName(),
voxelDimensions );
}
public <T extends RealType<T>> Node addVolume( IterableInterval<T> image ) {
return addVolume( image, "Volume" );
}
public <T extends RealType<T>> Node addVolume( IterableInterval<T> image, String name ) {
return addVolume( image, name, 1, 1, 1 );
}
public void setColormap( Node n, ColorTable colorTable ) {
final int copies = 16;
final ByteBuffer byteBuffer = ByteBuffer.allocateDirect(
4 * colorTable.getLength() * copies );// Num bytes * num components * color map length * height of color map texture
final byte[] tmp = new byte[4 * colorTable.getLength()];
for( int k = 0; k < colorTable.getLength(); k++ ) {
for( int c = 0; c < colorTable.getComponentCount(); c++ ) {
// TODO this assumes numBits is 8, could be 16
tmp[4 * k + c] = ( byte ) colorTable.get( c, k );
}
if( colorTable.getComponentCount() == 3 ) {
tmp[4 * k + 3] = (byte)255;
}
}
for( int i = 0; i < copies; i++ ) {
byteBuffer.put(tmp);
}
byteBuffer.flip();
n.getMetadata().put("sciviewColormap", colorTable);
if(n instanceof Volume) {
((Volume) n).getColormaps().put("sciviewColormap", new Volume.Colormap.ColormapBuffer(new GenericTexture("colorTable",
new GLVector(colorTable.getLength(),
copies, 1.0f), 4,
GLTypeEnum.UnsignedByte,
byteBuffer)));
((Volume) n).setColormap("sciviewColormap");
}
}
public <T extends RealType<T>> Node addVolume( IterableInterval<T> image, String name,
float... voxelDimensions ) {
log.debug( "Add Volume" );
long dimensions[] = new long[3];
image.dimensions( dimensions );
Volume v = new Volume();
getScene().addChild( v );
@SuppressWarnings("unchecked") Class<T> voxelType = ( Class<T> ) image.firstElement().getClass();
float minVal, maxVal;
if( voxelType == UnsignedByteType.class ) {
minVal = 0;
maxVal = 255;
} else if( voxelType == UnsignedShortType.class ) {
minVal = 0;
maxVal = 65535;
} else if( voxelType == FloatType.class ) {
minVal = 0;
maxVal = 1;
} else {
log.debug( "Type: " + voxelType +
" cannot be displayed as a volume. Convert to UnsignedByteType, UnsignedShortType, or FloatType." );
return null;
}
updateVolume( image, name, voxelDimensions, v );
GLVector scaleVec = new GLVector( 0.5f * dimensions[0], //
0.5f * dimensions[1], //
0.5f * dimensions[2] );
v.setScale( scaleVec );// TODO maybe dont do this
// TODO: This translation should probably be accounted for in scenery; volumes use a corner-origin and
// meshes use center-origin coordinate systems.
v.setPosition( v.getPosition().plus( new GLVector( 0.5f * dimensions[0] - 0.5f, 0.5f * dimensions[1] - 0.5f,
0.5f * dimensions[2] - 0.5f ) ) );
v.setTrangemin( minVal );
v.setTrangemax( maxVal );
v.setTransferFunction(TransferFunction.ramp(0.0f, 0.4f));
try {
setColormap( v, lutService.loadLUT( lutService.findLUTs().get( "WCIF/ICA.lut" ) ) );
} catch( IOException e ) {
e.printStackTrace();
}
setActiveNode( v );
return v;
}
public <T extends RealType<T>> Node updateVolume( IterableInterval<T> image, String name,
float[] voxelDimensions, Volume v ) {
log.debug( "Update Volume" );
long dimensions[] = new long[3];
image.dimensions( dimensions );
@SuppressWarnings("unchecked") Class<T> voxelType = ( Class<T> ) image.firstElement().getClass();
int bytesPerVoxel = image.firstElement().getBitsPerPixel() / 8;
NativeTypeEnum nType;
if( voxelType == UnsignedByteType.class ) {
nType = NativeTypeEnum.UnsignedByte;
} else if( voxelType == UnsignedShortType.class ) {
nType = NativeTypeEnum.UnsignedShort;
} else if( voxelType == FloatType.class ) {
nType = NativeTypeEnum.Float;
} else {
log.debug( "Type: " + voxelType +
" cannot be displayed as a volume. Convert to UnsignedByteType, UnsignedShortType, or FloatType." );
return null;
}
// Make and populate a ByteBuffer with the content of the Dataset
ByteBuffer byteBuffer = ByteBuffer.allocateDirect(
( int ) ( bytesPerVoxel * dimensions[0] * dimensions[1] * dimensions[2] ) );
Cursor<T> cursor = image.cursor();
while( cursor.hasNext() ) {
cursor.fwd();
if( voxelType == UnsignedByteType.class ) {
byteBuffer.put( ( byte ) ( ( ( UnsignedByteType ) cursor.get() ).get() ) );
} else if( voxelType == UnsignedShortType.class ) {
byteBuffer.putShort( ( short ) Math.abs( ( ( UnsignedShortType ) cursor.get() ).getShort() ) );
} else if( voxelType == FloatType.class ) {
byteBuffer.putFloat( ( ( FloatType ) cursor.get() ).get() );
}
}
byteBuffer.flip();
v.readFromBuffer( name, byteBuffer, dimensions[0], dimensions[1], dimensions[2], voxelDimensions[0],
voxelDimensions[1], voxelDimensions[2], nType, bytesPerVoxel );
v.setDirty( true );
v.setNeedsUpdate( true );
v.setNeedsUpdateWorld( true );
return v;
}
private static GLVector vector( ColorRGB color ) {
if( color instanceof ColorRGBA ) {
return new GLVector( color.getRed() / 255f, //
color.getGreen() / 255f, //
color.getBlue() / 255f, //
color.getAlpha() / 255f );
}
return new GLVector( color.getRed() / 255f, //
color.getGreen() / 255f, //
color.getBlue() / 255f );
}
public boolean getPushMode() {
return getRenderer().getPushMode();
}
public boolean setPushMode( boolean push ) {
getRenderer().setPushMode( push );
return getRenderer().getPushMode();
}
public ArcballCameraControl getTargetArcball() {
return targetArcball;
}
@Override
protected void finalize() {
stopAnimation();
}
private void updateFloorPosition() {
// Lower the floor below the active node, as needed.
final Node currentNode = getActiveNode();
if( currentNode != null ) {
final Node.OrientedBoundingBox bb = currentNode.generateBoundingBox();
final Node.BoundingSphere bs = bb.getBoundingSphere();
final float neededFloor = bb.getMin().y() - Math.max( bs.getRadius(), 1 );
if( neededFloor < getFloory() ) setFloory( neededFloor );
}
floor.setPosition( new GLVector( 0f, getFloory(), 0f ) );
}
public Settings getScenerySettings() {
return this.getSettings();
}
public Statistics getSceneryStats() {
return this.getStats();
}
public Renderer getSceneryRenderer() {
return this.getRenderer();
}
protected boolean vrActive = false;
public void toggleVRRendering() {
vrActive = !vrActive;
Camera cam = getScene().getActiveObserver();
if(!(cam instanceof DetachedHeadCamera)) {
return;
}
TrackerInput ti = null;
if (!getHub().has(SceneryElement.HMDInput)) {
try {
final OpenVRHMD hmd = new OpenVRHMD(false, true);
getHub().add(SceneryElement.HMDInput, hmd);
ti = hmd;
// we need to force reloading the renderer as the HMD might require device or instance extensions
if(getRenderer() instanceof VulkanRenderer) {
replaceRenderer(getRenderer().getClass().getSimpleName(), true);
Thread.sleep(1000);
}
} catch (Exception e) {
getLogger().error("Could not add OpenVRHMD: " + e.toString());
}
} else {
ti = getHub().getWorkingHMD();
}
if(vrActive && ti != null) {
((DetachedHeadCamera) cam).setTracker(ti);
} else {
((DetachedHeadCamera) cam).setTracker(null);
}
while(getRenderer().getInitialized() == false) {
getLogger().info("Waiting for renderer");
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
getRenderer().toggleVR();
}
}
| SciView: Show scenery and sciview version number in splash screen if it can be retrieved from JAR manifest
| src/main/java/sc/iview/SciView.java | SciView: Show scenery and sciview version number in splash screen if it can be retrieved from JAR manifest | <ide><path>rc/main/java/sc/iview/SciView.java
<ide>
<ide> import javax.imageio.ImageIO;
<ide> import javax.swing.*;
<del>import javax.swing.event.ChangeListener;
<ide> import javax.swing.plaf.basic.BasicLookAndFeel;
<ide> import java.awt.*;
<ide> import java.awt.image.BufferedImage;
<ide> getLogger().warn("Could not read splash image 'sciview-logo.png'");
<ide> splashImage = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
<ide> }
<del> splashLabel = new JLabel(new ImageIcon(splashImage.getScaledInstance(500, 200, java.awt.Image.SCALE_SMOOTH)));
<add>
<add> final String sceneryVersion = SceneryBase.class.getPackage().getImplementationVersion();
<add> final String sciviewVersion = SciView.class.getPackage().getImplementationVersion();
<add> final String versionString;
<add>
<add> if(sceneryVersion == null || sciviewVersion == null) {
<add> versionString = "";
<add> } else {
<add> versionString = "\n\nsciview " + sciviewVersion + " / scenery " + sceneryVersion;
<add> }
<add>
<add> splashLabel = new JLabel(versionString,
<add> new ImageIcon(splashImage.getScaledInstance(500, 200, java.awt.Image.SCALE_SMOOTH)),
<add> SwingConstants.CENTER);
<ide> splashLabel.setBackground(new java.awt.Color(50, 48, 47));
<add> splashLabel.setForeground(new java.awt.Color(78, 76, 75));
<ide> splashLabel.setOpaque(true);
<add> splashLabel.setVerticalTextPosition(JLabel.BOTTOM);
<add> splashLabel.setHorizontalTextPosition(JLabel.CENTER);
<ide>
<ide> p.setLayout(new OverlayLayout(p));
<ide> p.setBackground(new java.awt.Color(50, 48, 47)); |
|
Java | apache-2.0 | a1b05198fa6d63980870b51d32c0408e0e41c90d | 0 | mystdeim/vertx-web,mystdeim/vertx-web,vert-x3/vertx-web,vert-x3/vertx-web,InfoSec812/vertx-web,InfoSec812/vertx-web,vert-x3/vertx-web,vert-x3/vertx-web,InfoSec812/vertx-web,InfoSec812/vertx-web,aesteve/vertx-web,mystdeim/vertx-web,InfoSec812/vertx-web,vert-x3/vertx-web,aesteve/vertx-web,InfoSec812/vertx-web,mystdeim/vertx-web,mystdeim/vertx-web,aesteve/vertx-web,aesteve/vertx-web,aesteve/vertx-web,mystdeim/vertx-web | package io.vertx.ext.web.client;
import java.io.File;
import java.net.ConnectException;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import io.vertx.core.http.HttpConnection;
import org.junit.Test;
import io.vertx.core.Handler;
import io.vertx.core.MultiMap;
import io.vertx.core.VertxException;
import io.vertx.core.VertxOptions;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.dns.AddressResolverOptions;
import io.vertx.core.file.AsyncFile;
import io.vertx.core.file.OpenOptions;
import io.vertx.core.http.HttpClientOptions;
import io.vertx.core.http.HttpHeaders;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.HttpServerOptions;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.json.DecodeException;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.core.net.ProxyOptions;
import io.vertx.core.net.ProxyType;
import io.vertx.core.streams.ReadStream;
import io.vertx.core.streams.WriteStream;
import io.vertx.ext.web.client.impl.HttpContext;
import io.vertx.ext.web.client.jackson.WineAndCheese;
import io.vertx.ext.web.codec.BodyCodec;
import io.vertx.test.core.HttpTestBase;
import io.vertx.test.core.TestUtils;
import io.vertx.test.core.tls.Cert;
/**
* @author <a href="mailto:[email protected]">Julien Viet</a>
*/
public class WebClientTest extends HttpTestBase {
private WebClient client;
@Override
protected VertxOptions getOptions() {
return super.getOptions().setAddressResolverOptions(new AddressResolverOptions().
setHostsValue(Buffer.buffer(
"127.0.0.1 somehost\n" +
"127.0.0.1 localhost")));
}
@Override
public void setUp() throws Exception {
super.setUp();
super.client = vertx.createHttpClient(new HttpClientOptions().setDefaultPort(8080).setDefaultHost("localhost"));
client = WebClient.wrap(super.client);
server.close();
server = vertx.createHttpServer(new HttpServerOptions().setPort(DEFAULT_HTTP_PORT).setHost(DEFAULT_HTTP_HOST));
}
@Test
public void testDefaultHostAndPort() throws Exception {
testRequest(client -> client.get("somepath"), req -> {
assertEquals("localhost:8080", req.host());
});
}
@Test
public void testDefaultPort() throws Exception {
testRequest(client -> client.get("somehost", "somepath"), req -> {
assertEquals("somehost:8080", req.host());
});
}
@Test
public void testDefaultUserAgent() throws Exception {
testRequest(client -> client.get("somehost", "somepath"), req -> {
String ua = req.headers().get(HttpHeaders.USER_AGENT);
assertTrue("Was expecting use agent header " + ua + " to start with Vert.x-WebClient/", ua.startsWith("Vert.x-WebClient/"));
});
}
@Test
public void testCustomUserAgent() throws Exception {
client = WebClient.wrap(super.client, new WebClientOptions().setUserAgent("smith"));
testRequest(client -> client.get("somehost", "somepath"), req -> {
assertEquals(Collections.singletonList("smith"), req.headers().getAll(HttpHeaders.USER_AGENT));
});
}
@Test
public void testUserAgentDisabled() throws Exception {
client = WebClient.wrap(super.client, new WebClientOptions().setUserAgentEnabled(false));
testRequest(client -> client.get("somehost", "somepath"), req -> {
assertEquals(Collections.emptyList(), req.headers().getAll(HttpHeaders.USER_AGENT));
});
}
@Test
public void testUserAgentHeaderOverride() throws Exception {
testRequest(client -> client.get("somehost", "somepath").putHeader(HttpHeaders.USER_AGENT.toString(), "smith"), req -> {
assertEquals(Collections.singletonList("smith"), req.headers().getAll(HttpHeaders.USER_AGENT));
});
}
@Test
public void testUserAgentHeaderRemoved() throws Exception {
testRequest(client -> {
HttpRequest<Buffer> request = client.get("somehost", "somepath");
request.headers().remove(HttpHeaders.USER_AGENT);
return request;
}, req -> {
assertEquals(Collections.emptyList(), req.headers().getAll(HttpHeaders.USER_AGENT));
});
}
@Test
public void testGet() throws Exception {
testRequest(HttpMethod.GET);
}
@Test
public void testHead() throws Exception {
testRequest(HttpMethod.HEAD);
}
@Test
public void testDelete() throws Exception {
testRequest(HttpMethod.DELETE);
}
private void testRequest(HttpMethod method) throws Exception {
testRequest(client -> {
switch (method) {
case GET:
return client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
case HEAD:
return client.head(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
case DELETE:
return client.delete(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
default:
fail("Invalid HTTP method");
return null;
}
}, req -> assertEquals(method, req.method()));
}
private void testRequest(Function<WebClient, HttpRequest<Buffer>> reqFactory, Consumer<HttpServerRequest> reqChecker) throws Exception {
waitFor(4);
server.requestHandler(req -> {
try {
reqChecker.accept(req);
complete();
} finally {
req.response().end();
}
});
startServer();
HttpRequest<Buffer> builder = reqFactory.apply(client);
builder.send(onSuccess(resp -> {
complete();
}));
builder.send(onSuccess(resp -> {
complete();
}));
await();
}
@Test
public void testPost() throws Exception {
testRequestWithBody(HttpMethod.POST, false);
}
@Test
public void testPostChunked() throws Exception {
testRequestWithBody(HttpMethod.POST, true);
}
@Test
public void testPut() throws Exception {
testRequestWithBody(HttpMethod.PUT, false);
}
@Test
public void testPutChunked() throws Exception {
testRequestWithBody(HttpMethod.PUT, true);
}
@Test
public void testPatch() throws Exception {
testRequestWithBody(HttpMethod.PATCH, false);
}
private void testRequestWithBody(HttpMethod method, boolean chunked) throws Exception {
String expected = TestUtils.randomAlphaString(1024 * 1024);
File f = File.createTempFile("vertx", ".data");
f.deleteOnExit();
Files.write(f.toPath(), expected.getBytes());
waitFor(2);
server.requestHandler(req -> req.bodyHandler(buff -> {
assertEquals(method, req.method());
assertEquals(Buffer.buffer(expected), buff);
complete();
req.response().end();
}));
startServer();
vertx.runOnContext(v -> {
AsyncFile asyncFile = vertx.fileSystem().openBlocking(f.getAbsolutePath(), new OpenOptions());
HttpRequest<Buffer> builder = null;
switch (method) {
case POST:
builder = client.post(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
break;
case PUT:
builder = client.put(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
break;
case PATCH:
builder = client.patch(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
break;
default:
fail("Invalid HTTP method");
}
if (!chunked) {
builder = builder.putHeader("Content-Length", "" + expected.length());
}
builder.sendStream(asyncFile, onSuccess(resp -> {
assertEquals(200, resp.statusCode());
complete();
}));
});
await();
}
@Test
public void testSendJsonObjectBody() throws Exception {
JsonObject body = new JsonObject().put("wine", "Chateauneuf Du Pape").put("cheese", "roquefort");
testSendBody(body, (contentType, buff) -> {
assertEquals("application/json", contentType);
assertEquals(body, buff.toJsonObject());
});
}
@Test
public void testSendJsonPojoBody() throws Exception {
testSendBody(new WineAndCheese().setCheese("roquefort").setWine("Chateauneuf Du Pape"),
(contentType, buff) -> {
assertEquals("application/json", contentType);
assertEquals(new JsonObject().put("wine", "Chateauneuf Du Pape").put("cheese", "roquefort"), buff.toJsonObject());
});
}
@Test
public void testSendJsonArrayBody() throws Exception {
JsonArray body = new JsonArray().add(0).add(1).add(2);
testSendBody(body, (contentType, buff) -> {
assertEquals("application/json", contentType);
assertEquals(body, buff.toJsonArray());
});
}
@Test
public void testSendBufferBody() throws Exception {
Buffer body = TestUtils.randomBuffer(2048);
testSendBody(body, (contentType, buff) -> assertEquals(body, buff));
}
private void testSendBody(Object body, BiConsumer<String, Buffer> checker) throws Exception {
waitFor(2);
server.requestHandler(req -> {
req.bodyHandler(buff -> {
checker.accept(req.getHeader("content-type"), buff);
complete();
req.response().end();
});
});
startServer();
HttpRequest<Buffer> post = client.post(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
if (body instanceof Buffer) {
post.sendBuffer((Buffer) body, onSuccess(resp -> {
complete();
}));
} else if (body instanceof JsonObject) {
post.sendJsonObject((JsonObject) body, onSuccess(resp -> {
complete();
}));
} else {
post.sendJson(body, onSuccess(resp -> {
complete();
}));
}
await();
}
@Test
public void testConnectError() throws Exception {
HttpRequest<Buffer> get = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
get.send(onFailure(err -> {
assertTrue(err instanceof ConnectException);
complete();
}));
await();
}
@Test
public void testRequestSendError() throws Exception {
HttpRequest<Buffer> post = client.post(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
CountDownLatch latch = new CountDownLatch(1);
AtomicReference<HttpConnection> conn = new AtomicReference<>();
server.requestHandler(req -> {
conn.set(req.connection());
req.pause();
latch.countDown();
});
startServer();
AtomicReference<Handler<Buffer>> dataHandler = new AtomicReference<>();
AtomicReference<Handler<Void>> endHandler = new AtomicReference<>();
AtomicBoolean paused = new AtomicBoolean();
post.sendStream(new ReadStream<Buffer>() {
@Override
public ReadStream<Buffer> exceptionHandler(Handler<Throwable> handler) {
return this;
}
@Override
public ReadStream<Buffer> handler(Handler<Buffer> handler) {
dataHandler.set(handler);
return this;
}
@Override
public ReadStream<Buffer> pause() {
paused.set(true);
return this;
}
@Override
public ReadStream<Buffer> resume() {
paused.set(false);
return this;
}
@Override
public ReadStream<Buffer> endHandler(Handler<Void> handler) {
endHandler.set(handler);
return this;
}
}, onFailure(err -> {
// Should be a connection reset by peer or closed
assertNull(endHandler.get());
assertNull(dataHandler.get());
assertFalse(paused.get());
complete();
}));
assertWaitUntil(() -> dataHandler.get() != null);
dataHandler.get().handle(TestUtils.randomBuffer(1024));
awaitLatch(latch);
while (!paused.get()) {
dataHandler.get().handle(TestUtils.randomBuffer(1024));
}
conn.get().close();
await();
}
@Test
public void testRequestPumpError() throws Exception {
waitFor(2);
HttpRequest<Buffer> post = client.post(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
CompletableFuture<Void> done = new CompletableFuture<>();
server.requestHandler(req -> {
req.response().closeHandler(v -> {
complete();
});
req.handler(buff -> {
done.complete(null);
});
});
Throwable cause = new Throwable();
startServer();
post.sendStream(new ReadStream<Buffer>() {
@Override
public ReadStream<Buffer> exceptionHandler(Handler<Throwable> handler) {
if (handler != null) {
done.thenAccept(v -> {
handler.handle(cause);
});
}
return this;
}
@Override
public ReadStream<Buffer> handler(Handler<Buffer> handler) {
if (handler != null) {
handler.handle(TestUtils.randomBuffer(1024));
}
return this;
}
@Override
public ReadStream<Buffer> pause() {
return this;
}
@Override
public ReadStream<Buffer> resume() {
return this;
}
@Override
public ReadStream<Buffer> endHandler(Handler<Void> endHandler) {
return this;
}
}, onFailure(err -> {
assertSame(cause, err);
complete();
}));
await();
}
@Test
public void testRequestPumpErrorNotYetConnected() throws Exception {
HttpRequest<Buffer> post = client.post(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
server.requestHandler(req -> {
fail();
});
Throwable cause = new Throwable();
startServer();
post.sendStream(new ReadStream<Buffer>() {
Handler<Throwable> exceptionHandler;
@Override
public ReadStream<Buffer> exceptionHandler(Handler<Throwable> handler) {
exceptionHandler = handler;
return this;
}
@Override
public ReadStream<Buffer> handler(Handler<Buffer> handler) {
if (handler != null) {
handler.handle(TestUtils.randomBuffer(1024));
vertx.runOnContext(v -> {
exceptionHandler.handle(cause);
});
}
return this;
}
@Override
public ReadStream<Buffer> pause() {
return this;
}
@Override
public ReadStream<Buffer> resume() {
return this;
}
@Override
public ReadStream<Buffer> endHandler(Handler<Void> endHandler) {
return this;
}
}, onFailure(err -> {
assertSame(cause, err);
testComplete();
}));
await();
}
@Test
public void testResponseBodyAsBuffer() throws Exception {
Buffer expected = TestUtils.randomBuffer(2000);
server.requestHandler(req -> {
req.response().end(expected);
});
startServer();
HttpRequest<Buffer> get = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
get.send(onSuccess(resp -> {
assertEquals(200, resp.statusCode());
assertEquals(expected, resp.body());
testComplete();
}));
await();
}
@Test
public void testResponseBodyAsAsJsonObject() throws Exception {
JsonObject expected = new JsonObject().put("cheese", "Goat Cheese").put("wine", "Condrieu");
server.requestHandler(req -> {
req.response().end(expected.encode());
});
startServer();
HttpRequest<Buffer> get = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
get
.as(BodyCodec.jsonObject())
.send(onSuccess(resp -> {
assertEquals(200, resp.statusCode());
assertEquals(expected, resp.body());
testComplete();
}));
await();
}
@Test
public void testResponseBodyAsAsJsonMapped() throws Exception {
JsonObject expected = new JsonObject().put("cheese", "Goat Cheese").put("wine", "Condrieu");
server.requestHandler(req -> {
req.response().end(expected.encode());
});
startServer();
HttpRequest<Buffer> get = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
get
.as(BodyCodec.json(WineAndCheese.class))
.send(onSuccess(resp -> {
assertEquals(200, resp.statusCode());
assertEquals(new WineAndCheese().setCheese("Goat Cheese").setWine("Condrieu"), resp.body());
testComplete();
}));
await();
}
@Test
public void testResponseBodyAsAsJsonArray() throws Exception {
JsonArray expected = new JsonArray().add("cheese").add("wine");
server.requestHandler(req -> {
req.response().end(expected.encode());
});
startServer();
HttpRequest<Buffer> get = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
get
.as(BodyCodec.jsonArray())
.send(onSuccess(resp -> {
assertEquals(200, resp.statusCode());
assertEquals(expected, resp.body());
testComplete();
}));
await();
}
@Test
public void testResponseBodyAsAsJsonArrayMapped() throws Exception {
JsonArray expected = new JsonArray().add("cheese").add("wine");
server.requestHandler(req -> {
req.response().end(expected.encode());
});
startServer();
HttpRequest<Buffer> get = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
get
.as(BodyCodec.json(List.class))
.send(onSuccess(resp -> {
assertEquals(200, resp.statusCode());
assertEquals(expected.getList(), resp.body());
testComplete();
}));
await();
}
@Test
public void testResponseBodyDiscarded() throws Exception {
server.requestHandler(req -> {
req.response().end(TestUtils.randomAlphaString(1024));
});
startServer();
HttpRequest<Buffer> get = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
get
.as(BodyCodec.none())
.send(onSuccess(resp -> {
assertEquals(200, resp.statusCode());
assertEquals(null, resp.body());
testComplete();
}));
await();
}
@Test
public void testResponseUnknownContentTypeBodyAsJsonObject() throws Exception {
JsonObject expected = new JsonObject().put("cheese", "Goat Cheese").put("wine", "Condrieu");
server.requestHandler(req -> {
req.response().end(expected.encode());
});
startServer();
HttpRequest<Buffer> get = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
get.send(onSuccess(resp -> {
assertEquals(200, resp.statusCode());
assertEquals(expected, resp.bodyAsJsonObject());
testComplete();
}));
await();
}
@Test
public void testResponseUnknownContentTypeBodyAsJsonArray() throws Exception {
JsonArray expected = new JsonArray().add("cheese").add("wine");
server.requestHandler(req -> {
req.response().end(expected.encode());
});
startServer();
HttpRequest<Buffer> get = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
get.send(onSuccess(resp -> {
assertEquals(200, resp.statusCode());
assertEquals(expected, resp.bodyAsJsonArray());
testComplete();
}));
await();
}
@Test
public void testResponseUnknownContentTypeBodyAsJsonMapped() throws Exception {
JsonObject expected = new JsonObject().put("cheese", "Goat Cheese").put("wine", "Condrieu");
server.requestHandler(req -> {
req.response().end(expected.encode());
});
startServer();
HttpRequest<Buffer> get = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
get.send(onSuccess(resp -> {
assertEquals(200, resp.statusCode());
assertEquals(new WineAndCheese().setCheese("Goat Cheese").setWine("Condrieu"), resp.bodyAsJson(WineAndCheese.class));
testComplete();
}));
await();
}
@Test
public void testResponseBodyUnmarshallingError() throws Exception {
server.requestHandler(req -> {
req.response().end("not-json-object");
});
startServer();
HttpRequest<Buffer> get = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
get
.as(BodyCodec.jsonObject())
.send(onFailure(err -> {
assertTrue(err instanceof DecodeException);
testComplete();
}));
await();
}
@Test
public void testResponseBodyStream() throws Exception {
AtomicBoolean paused = new AtomicBoolean();
server.requestHandler(req -> {
HttpServerResponse resp = req.response();
resp.setChunked(true);
vertx.setPeriodic(1, id -> {
if (!resp.writeQueueFull()) {
resp.write(TestUtils.randomAlphaString(1024));
} else {
resp.drainHandler(v -> {
resp.end();
});
paused.set(true);
vertx.cancelTimer(id);
}
});
});
startServer();
CompletableFuture<Void> resume = new CompletableFuture<>();
AtomicInteger size = new AtomicInteger();
AtomicBoolean ended = new AtomicBoolean();
WriteStream<Buffer> stream = new WriteStream<Buffer>() {
boolean paused = true;
Handler<Void> drainHandler;
{
resume.thenAccept(v -> {
paused = false;
if (drainHandler != null) {
drainHandler.handle(null);
}
});
}
@Override
public WriteStream<Buffer> exceptionHandler(Handler<Throwable> handler) {
return this;
}
@Override
public WriteStream<Buffer> write(Buffer data) {
size.addAndGet(data.length());
return this;
}
@Override
public void end() {
ended.set(true);
}
@Override
public WriteStream<Buffer> setWriteQueueMaxSize(int maxSize) {
return this;
}
@Override
public boolean writeQueueFull() {
return paused;
}
@Override
public WriteStream<Buffer> drainHandler(Handler<Void> handler) {
drainHandler = handler;
return this;
}
};
HttpRequest<Buffer> get = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
get
.as(BodyCodec.pipe(stream))
.send(onSuccess(resp -> {
assertTrue(ended.get());
assertEquals(200, resp.statusCode());
assertEquals(null, resp.body());
testComplete();
}));
assertWaitUntil(paused::get);
resume.complete(null);
await();
}
@Test
public void testResponseBodyStreamError() throws Exception {
CompletableFuture<Void> fail = new CompletableFuture<>();
server.requestHandler(req -> {
HttpServerResponse resp = req.response();
resp.setChunked(true);
resp.write(TestUtils.randomBuffer(2048));
fail.thenAccept(v -> {
resp.close();
});
});
startServer();
AtomicInteger received = new AtomicInteger();
WriteStream<Buffer> stream = new WriteStream<Buffer>() {
@Override
public WriteStream<Buffer> exceptionHandler(Handler<Throwable> handler) {
return this;
}
@Override
public WriteStream<Buffer> write(Buffer data) {
received.addAndGet(data.length());
return this;
}
@Override
public void end() {
}
@Override
public WriteStream<Buffer> setWriteQueueMaxSize(int maxSize) {
return this;
}
@Override
public boolean writeQueueFull() {
return false;
}
@Override
public WriteStream<Buffer> drainHandler(Handler<Void> handler) {
return this;
}
};
HttpRequest<Buffer> get = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
get
.as(BodyCodec.pipe(stream))
.send(onFailure(err -> {
testComplete();
}));
assertWaitUntil(() -> received.get() == 2048);
fail.complete(null);
await();
}
@Test
public void testResponseBodyCodecError() throws Exception {
server.requestHandler(req -> {
HttpServerResponse resp = req.response();
resp.setChunked(true);
resp.end(TestUtils.randomBuffer(2048));
});
startServer();
RuntimeException cause = new RuntimeException();
WriteStream<Buffer> stream = new WriteStream<Buffer>() {
Handler<Throwable> exceptionHandler;
@Override
public WriteStream<Buffer> exceptionHandler(Handler<Throwable> handler) {
exceptionHandler = handler;
return this;
}
@Override
public WriteStream<Buffer> write(Buffer data) {
exceptionHandler.handle(cause);
return this;
}
@Override
public void end() {
}
@Override
public WriteStream<Buffer> setWriteQueueMaxSize(int maxSize) {
return this;
}
@Override
public boolean writeQueueFull() {
return false;
}
@Override
public WriteStream<Buffer> drainHandler(Handler<Void> handler) {
return this;
}
};
HttpRequest<Buffer> get = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
get
.as(BodyCodec.pipe(stream))
.send(onFailure(err -> {
assertSame(cause, err);
testComplete();
}));
await();
}
@Test
public void testResponseJsonObjectMissingBody() throws Exception {
testResponseMissingBody(BodyCodec.jsonObject());
}
@Test
public void testResponseJsonMissingBody() throws Exception {
testResponseMissingBody(BodyCodec.json(WineAndCheese.class));
}
@Test
public void testResponseWriteStreamMissingBody() throws Exception {
AtomicInteger length = new AtomicInteger();
AtomicBoolean ended = new AtomicBoolean();
WriteStream<Buffer> stream = new WriteStream<Buffer>() {
@Override
public WriteStream<Buffer> exceptionHandler(Handler<Throwable> handler) {
return this;
}
@Override
public WriteStream<Buffer> write(Buffer data) {
length.addAndGet(data.length());
return this;
}
@Override
public void end() {
ended.set(true);
}
@Override
public WriteStream<Buffer> setWriteQueueMaxSize(int maxSize) {
return this;
}
@Override
public boolean writeQueueFull() {
return false;
}
@Override
public WriteStream<Buffer> drainHandler(Handler<Void> handler) {
return this;
}
};
testResponseMissingBody(BodyCodec.pipe(stream));
assertTrue(ended.get());
assertEquals(0, length.get());
}
private <R> void testResponseMissingBody(BodyCodec<R> codec) throws Exception {
server.requestHandler(req -> {
req.response().setStatusCode(403).end();
});
startServer();
HttpRequest<Buffer> get = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
get
.as(codec)
.send(onSuccess(resp -> {
assertEquals(403, resp.statusCode());
assertNull(resp.body());
testComplete();
}));
await();
}
@Test
public void testHttpResponseError() throws Exception {
server.requestHandler(req -> {
req.response().setChunked(true).write(Buffer.buffer("some-data")).close();
});
startServer();
HttpRequest<Buffer> get = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
get
.as(BodyCodec.jsonObject())
.send(onFailure(err -> {
assertTrue(err instanceof VertxException);
testComplete();
}));
await();
}
@Test
public void testTimeout() throws Exception {
AtomicInteger count = new AtomicInteger();
server.requestHandler(req -> {
count.incrementAndGet();
});
startServer();
HttpRequest<Buffer> get = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
get.timeout(50).send(onFailure(err -> {
assertEquals(err.getClass(), TimeoutException.class);
testComplete();
}));
await();
}
@Test
public void testQueryParam() throws Exception {
testRequest(client -> client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/").addQueryParam("param", "param_value"), req -> {
assertEquals("param=param_value", req.query());
assertEquals("param_value", req.getParam("param"));
});
}
@Test
public void testQueryParamMulti() throws Exception {
testRequest(client -> client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/").addQueryParam("param", "param_value1").addQueryParam("param", "param_value2"), req -> {
assertEquals("param=param_value1¶m=param_value2", req.query());
assertEquals(Arrays.asList("param_value1", "param_value2"), req.params().getAll("param"));
});
}
@Test
public void testQueryParamAppend() throws Exception {
testRequest(client -> client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/?param1=param1_value1").addQueryParam("param1", "param1_value2").addQueryParam("param2", "param2_value"), req -> {
assertEquals("param1=param1_value1¶m1=param1_value2¶m2=param2_value", req.query());
assertEquals("param1_value2", req.getParam("param1"));
assertEquals("param2_value", req.getParam("param2"));
});
}
@Test
public void testOverwriteQueryParams() throws Exception {
testRequest(client -> client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/?param=param_value1").setQueryParam("param", "param_value2"), req -> {
assertEquals("param=param_value2", req.query());
assertEquals("param_value2", req.getParam("param"));
});
}
@Test
public void testQueryParamEncoding() throws Exception {
testRequest(client -> client
.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/")
.addQueryParam("param1", " ")
.addQueryParam("param2", "\u20AC"), req -> {
assertEquals("param1=%20¶m2=%E2%82%AC", req.query());
assertEquals(" ", req.getParam("param1"));
assertEquals("\u20AC", req.getParam("param2"));
});
}
@Test
public void testFormUrlEncoded() throws Exception {
server.requestHandler(req -> {
req.setExpectMultipart(true);
req.endHandler(v -> {
assertEquals("param1_value", req.getFormAttribute("param1"));
req.response().end();
});
});
startServer();
MultiMap form = MultiMap.caseInsensitiveMultiMap();
form.add("param1", "param1_value");
HttpRequest<Buffer> builder = client.post("/somepath");
builder.sendForm(form, onSuccess(resp -> {
complete();
}));
await();
}
@Test
public void testFormMultipart() throws Exception {
server.requestHandler(req -> {
req.setExpectMultipart(true);
req.endHandler(v -> {
assertEquals("param1_value", req.getFormAttribute("param1"));
req.response().end();
});
});
startServer();
MultiMap form = MultiMap.caseInsensitiveMultiMap();
form.add("param1", "param1_value");
HttpRequest<Buffer> builder = client.post("/somepath");
builder.putHeader("content-type", "multipart/form-data");
builder.sendForm(form, onSuccess(resp -> {
complete();
}));
await();
}
@Test
public void testDefaultFollowRedirects() throws Exception {
testFollowRedirects(null, true);
}
@Test
public void testFollowRedirects() throws Exception {
testFollowRedirects(true, true);
}
@Test
public void testDoNotFollowRedirects() throws Exception {
testFollowRedirects(false, false);
}
private void testFollowRedirects(Boolean set, boolean expect) throws Exception {
waitFor(2);
String location = "http://" + DEFAULT_HTTP_HOST + ":" + DEFAULT_HTTP_PORT + "/ok";
server.requestHandler(req -> {
if (req.path().equals("/redirect")) {
req.response().setStatusCode(301).putHeader("Location", location).end();
if (!expect) {
complete();
}
} else {
req.response().end(req.path());
if (expect) {
complete();
}
}
});
startServer();
HttpRequest<Buffer> builder = client.get("/redirect");
if (set != null) {
builder = builder.followRedirects(set);
}
builder.send(onSuccess(resp -> {
if (expect) {
assertEquals(200, resp.statusCode());
assertEquals("/ok", resp.body().toString());
} else {
assertEquals(301, resp.statusCode());
assertEquals(location, resp.getHeader("location"));
}
complete();
}));
await();
}
@Test
public void testTLSEnabled() throws Exception {
testTLS(true, true, client -> client.get("/"));
}
@Test
public void testTLSEnabledDisableRequestTLS() throws Exception {
testTLS(true, false, client -> client.get("/").ssl(false));
}
@Test
public void testTLSEnabledEnableRequestTLS() throws Exception {
testTLS(true, true, client -> client.get("/").ssl(true));
}
@Test
public void testTLSDisabledDisableRequestTLS() throws Exception {
testTLS(false, false, client -> client.get("/").ssl(false));
}
@Test
public void testTLSDisabledEnableRequestTLS() throws Exception {
testTLS(false, true, client -> client.get("/").ssl(true));
}
@Test
public void testTLSEnabledDisableRequestTLSAbsURI() throws Exception {
testTLS(true, false, client -> client.getAbs("http://" + DEFAULT_HTTPS_HOST + ":" + DEFAULT_HTTPS_PORT));
}
@Test
public void testTLSEnabledEnableRequestTLSAbsURI() throws Exception {
testTLS(true, true, client -> client.getAbs("https://" + DEFAULT_HTTPS_HOST + ":" + DEFAULT_HTTPS_PORT));
}
@Test
public void testTLSDisabledDisableRequestTLSAbsURI() throws Exception {
testTLS(false, false, client -> client.getAbs("http://" + DEFAULT_HTTPS_HOST + ":" + DEFAULT_HTTPS_PORT));
}
@Test
public void testTLSDisabledEnableRequestTLSAbsURI() throws Exception {
testTLS(false, true, client -> client.getAbs("https://" + DEFAULT_HTTPS_HOST + ":" + DEFAULT_HTTPS_PORT));
}
/**
* Regression test for issue #563 (https://github.com/vert-x3/vertx-web/issues/563)
* <p>
* Only occurred when {@link WebClientOptions#isSsl()} was false for an SSL request.
*/
@Test
public void testTLSQueryParametersIssue563() throws Exception {
testTLS(false, true,
client -> client.getAbs("https://" + DEFAULT_HTTPS_HOST + ":" + DEFAULT_HTTPS_PORT)
.addQueryParam("query1", "value1")
.addQueryParam("query2", "value2"),
serverRequest -> assertEquals("query1=value1&query2=value2", serverRequest.query()));
}
private void testTLS(boolean clientSSL, boolean serverSSL, Function<WebClient, HttpRequest<Buffer>> requestProvider) throws Exception {
testTLS(clientSSL, serverSSL, requestProvider, null);
}
private void testTLS(boolean clientSSL, boolean serverSSL, Function<WebClient, HttpRequest<Buffer>> requestProvider, Consumer<HttpServerRequest> serverAssertions) throws Exception {
WebClient sslClient = WebClient.create(vertx, new WebClientOptions()
.setSsl(clientSSL)
.setTrustAll(true)
.setDefaultHost(DEFAULT_HTTPS_HOST)
.setDefaultPort(DEFAULT_HTTPS_PORT));
HttpServer sslServer = vertx.createHttpServer(new HttpServerOptions()
.setSsl(serverSSL)
.setKeyStoreOptions(Cert.CLIENT_JKS.get())
.setPort(DEFAULT_HTTPS_PORT)
.setHost(DEFAULT_HTTPS_HOST));
sslServer.requestHandler(req -> {
assertEquals(serverSSL, req.isSSL());
if (serverAssertions != null) {
serverAssertions.accept(req);
}
req.response().end();
});
try {
startServer(sslServer);
HttpRequest<Buffer> builder = requestProvider.apply(sslClient);
builder.send(onSuccess(resp -> {
testComplete();
}));
await();
} finally {
sslClient.close();
sslServer.close();
}
}
@Test
public void testHttpProxyFtpRequest() throws Exception {
startProxy(null, ProxyType.HTTP);
proxy.setForceUri("http://" + DEFAULT_HTTP_HOST + ":" + DEFAULT_HTTP_PORT);
server.requestHandler(req -> {
req.response().setStatusCode(200).end();
});
startServer();
WebClientOptions options = new WebClientOptions();
options.setProxyOptions(new ProxyOptions().setPort(proxy.getPort()));
WebClient client = WebClient.create(vertx, options);
client
.getAbs("ftp://ftp.gnu.org/gnu/")
.send(ar -> {
if (ar.succeeded()) {
// Obtain response
HttpResponse<Buffer> response = ar.result();
assertEquals(200, response.statusCode());
assertEquals("ftp://ftp.gnu.org/gnu/", proxy.getLastUri());
testComplete();
} else {
fail(ar.cause());
}
});
await();
}
@Test
public void testStreamHttpServerRequest() throws Exception {
Buffer expected = TestUtils.randomBuffer(10000);
HttpServer server2 = vertx.createHttpServer(new HttpServerOptions().setPort(8081)).requestHandler(req -> {
req.bodyHandler(body -> {
assertEquals(body, expected);
req.response().end();
});
});
startServer(server2);
WebClient webClient = WebClient.create(vertx);
try {
server.requestHandler(req -> {
webClient.postAbs("http://localhost:8081/")
.sendStream(req, onSuccess(resp -> {
req.response().end("ok");
}));
});
startServer();
webClient.post(8080, "localhost", "/").sendBuffer(expected, onSuccess(resp -> {
assertEquals("ok", resp.bodyAsString());
complete();
}));
await();
} finally {
server2.close();
}
}
}
| vertx-web-client/src/test/java/io/vertx/ext/web/client/WebClientTest.java | package io.vertx.ext.web.client;
import java.io.File;
import java.net.ConnectException;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import io.vertx.core.http.HttpConnection;
import org.junit.Test;
import io.vertx.core.Handler;
import io.vertx.core.MultiMap;
import io.vertx.core.VertxException;
import io.vertx.core.VertxOptions;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.dns.AddressResolverOptions;
import io.vertx.core.file.AsyncFile;
import io.vertx.core.file.OpenOptions;
import io.vertx.core.http.HttpClientOptions;
import io.vertx.core.http.HttpHeaders;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.HttpServerOptions;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.json.DecodeException;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.core.net.ProxyOptions;
import io.vertx.core.net.ProxyType;
import io.vertx.core.streams.ReadStream;
import io.vertx.core.streams.WriteStream;
import io.vertx.ext.web.client.impl.HttpContext;
import io.vertx.ext.web.client.jackson.WineAndCheese;
import io.vertx.ext.web.codec.BodyCodec;
import io.vertx.test.core.HttpTestBase;
import io.vertx.test.core.TestUtils;
import io.vertx.test.core.tls.Cert;
/**
* @author <a href="mailto:[email protected]">Julien Viet</a>
*/
public class WebClientTest extends HttpTestBase {
private WebClient client;
@Override
protected VertxOptions getOptions() {
return super.getOptions().setAddressResolverOptions(new AddressResolverOptions().
setHostsValue(Buffer.buffer(
"127.0.0.1 somehost\n" +
"127.0.0.1 localhost")));
}
@Override
public void setUp() throws Exception {
super.setUp();
super.client = vertx.createHttpClient(new HttpClientOptions().setDefaultPort(8080).setDefaultHost("localhost"));
client = WebClient.wrap(super.client);
server.close();
server = vertx.createHttpServer(new HttpServerOptions().setPort(DEFAULT_HTTP_PORT).setHost(DEFAULT_HTTP_HOST));
}
@Test
public void testDefaultHostAndPort() throws Exception {
testRequest(client -> client.get("somepath"), req -> {
assertEquals("localhost:8080", req.host());
});
}
@Test
public void testDefaultPort() throws Exception {
testRequest(client -> client.get("somehost", "somepath"), req -> {
assertEquals("somehost:8080", req.host());
});
}
@Test
public void testDefaultUserAgent() throws Exception {
testRequest(client -> client.get("somehost", "somepath"), req -> {
String ua = req.headers().get(HttpHeaders.USER_AGENT);
assertTrue("Was expecting use agent header " + ua + " to start with Vert.x-WebClient/", ua.startsWith("Vert.x-WebClient/"));
});
}
@Test
public void testCustomUserAgent() throws Exception {
client = WebClient.wrap(super.client, new WebClientOptions().setUserAgent("smith"));
testRequest(client -> client.get("somehost", "somepath"), req -> {
assertEquals(Collections.singletonList("smith"), req.headers().getAll(HttpHeaders.USER_AGENT));
});
}
@Test
public void testUserAgentDisabled() throws Exception {
client = WebClient.wrap(super.client, new WebClientOptions().setUserAgentEnabled(false));
testRequest(client -> client.get("somehost", "somepath"), req -> {
assertEquals(Collections.emptyList(), req.headers().getAll(HttpHeaders.USER_AGENT));
});
}
@Test
public void testUserAgentHeaderOverride() throws Exception {
testRequest(client -> client.get("somehost", "somepath").putHeader(HttpHeaders.USER_AGENT.toString(), "smith"), req -> {
assertEquals(Collections.singletonList("smith"), req.headers().getAll(HttpHeaders.USER_AGENT));
});
}
@Test
public void testUserAgentHeaderRemoved() throws Exception {
testRequest(client -> {
HttpRequest<Buffer> request = client.get("somehost", "somepath");
request.headers().remove(HttpHeaders.USER_AGENT);
return request;
}, req -> {
assertEquals(Collections.emptyList(), req.headers().getAll(HttpHeaders.USER_AGENT));
});
}
@Test
public void testGet() throws Exception {
testRequest(HttpMethod.GET);
}
@Test
public void testHead() throws Exception {
testRequest(HttpMethod.HEAD);
}
@Test
public void testDelete() throws Exception {
testRequest(HttpMethod.DELETE);
}
private void testRequest(HttpMethod method) throws Exception {
testRequest(client -> {
switch (method) {
case GET:
return client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
case HEAD:
return client.head(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
case DELETE:
return client.delete(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
default:
fail("Invalid HTTP method");
return null;
}
}, req -> assertEquals(method, req.method()));
}
private void testRequest(Function<WebClient, HttpRequest<Buffer>> reqFactory, Consumer<HttpServerRequest> reqChecker) throws Exception {
waitFor(4);
server.requestHandler(req -> {
try {
reqChecker.accept(req);
complete();
} finally {
req.response().end();
}
});
startServer();
HttpRequest<Buffer> builder = reqFactory.apply(client);
builder.send(onSuccess(resp -> {
complete();
}));
builder.send(onSuccess(resp -> {
complete();
}));
await();
}
@Test
public void testPost() throws Exception {
testRequestWithBody(HttpMethod.POST, false);
}
@Test
public void testPostChunked() throws Exception {
testRequestWithBody(HttpMethod.POST, true);
}
@Test
public void testPut() throws Exception {
testRequestWithBody(HttpMethod.PUT, false);
}
@Test
public void testPutChunked() throws Exception {
testRequestWithBody(HttpMethod.PUT, true);
}
@Test
public void testPatch() throws Exception {
testRequestWithBody(HttpMethod.PATCH, false);
}
private void testRequestWithBody(HttpMethod method, boolean chunked) throws Exception {
String expected = TestUtils.randomAlphaString(1024 * 1024);
File f = File.createTempFile("vertx", ".data");
f.deleteOnExit();
Files.write(f.toPath(), expected.getBytes());
waitFor(2);
server.requestHandler(req -> req.bodyHandler(buff -> {
assertEquals(method, req.method());
assertEquals(Buffer.buffer(expected), buff);
complete();
req.response().end();
}));
startServer();
vertx.runOnContext(v -> {
AsyncFile asyncFile = vertx.fileSystem().openBlocking(f.getAbsolutePath(), new OpenOptions());
HttpRequest<Buffer> builder = null;
switch (method) {
case POST:
builder = client.post(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
break;
case PUT:
builder = client.put(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
break;
case PATCH:
builder = client.patch(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
break;
default:
fail("Invalid HTTP method");
}
if (!chunked) {
builder = builder.putHeader("Content-Length", "" + expected.length());
}
builder.sendStream(asyncFile, onSuccess(resp -> {
assertEquals(200, resp.statusCode());
complete();
}));
});
await();
}
@Test
public void testSendJsonObjectBody() throws Exception {
JsonObject body = new JsonObject().put("wine", "Chateauneuf Du Pape").put("cheese", "roquefort");
testSendBody(body, (contentType, buff) -> {
assertEquals("application/json", contentType);
assertEquals(body, buff.toJsonObject());
});
}
@Test
public void testSendJsonPojoBody() throws Exception {
testSendBody(new WineAndCheese().setCheese("roquefort").setWine("Chateauneuf Du Pape"),
(contentType, buff) -> {
assertEquals("application/json", contentType);
assertEquals(new JsonObject().put("wine", "Chateauneuf Du Pape").put("cheese", "roquefort"), buff.toJsonObject());
});
}
@Test
public void testSendJsonArrayBody() throws Exception {
JsonArray body = new JsonArray().add(0).add(1).add(2);
testSendBody(body, (contentType, buff) -> {
assertEquals("application/json", contentType);
assertEquals(body, buff.toJsonArray());
});
}
@Test
public void testSendBufferBody() throws Exception {
Buffer body = TestUtils.randomBuffer(2048);
testSendBody(body, (contentType, buff) -> assertEquals(body, buff));
}
private void testSendBody(Object body, BiConsumer<String, Buffer> checker) throws Exception {
waitFor(2);
server.requestHandler(req -> {
req.bodyHandler(buff -> {
checker.accept(req.getHeader("content-type"), buff);
complete();
req.response().end();
});
});
startServer();
HttpRequest<Buffer> post = client.post(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
if (body instanceof Buffer) {
post.sendBuffer((Buffer) body, onSuccess(resp -> {
complete();
}));
} else if (body instanceof JsonObject) {
post.sendJsonObject((JsonObject) body, onSuccess(resp -> {
complete();
}));
} else {
post.sendJson(body, onSuccess(resp -> {
complete();
}));
}
await();
}
@Test
public void testConnectError() throws Exception {
HttpRequest<Buffer> get = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
get.send(onFailure(err -> {
assertTrue(err instanceof ConnectException);
complete();
}));
await();
}
@Test
public void testRequestSendError() throws Exception {
HttpRequest<Buffer> post = client.post(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
CountDownLatch latch = new CountDownLatch(1);
AtomicReference<HttpConnection> conn = new AtomicReference<>();
server.requestHandler(req -> {
conn.set(req.connection());
req.pause();
latch.countDown();
});
startServer();
AtomicReference<Handler<Buffer>> dataHandler = new AtomicReference<>();
AtomicReference<Handler<Void>> endHandler = new AtomicReference<>();
AtomicBoolean paused = new AtomicBoolean();
post.sendStream(new ReadStream<Buffer>() {
@Override
public ReadStream<Buffer> exceptionHandler(Handler<Throwable> handler) {
return this;
}
@Override
public ReadStream<Buffer> handler(Handler<Buffer> handler) {
dataHandler.set(handler);
return this;
}
@Override
public ReadStream<Buffer> pause() {
paused.set(true);
return this;
}
@Override
public ReadStream<Buffer> resume() {
paused.set(false);
return this;
}
@Override
public ReadStream<Buffer> endHandler(Handler<Void> handler) {
endHandler.set(handler);
return this;
}
}, onFailure(err -> {
// Should be a connection reset by peer or closed
assertNull(endHandler.get());
assertNull(dataHandler.get());
assertFalse(paused.get());
complete();
}));
assertWaitUntil(() -> dataHandler.get() != null);
dataHandler.get().handle(TestUtils.randomBuffer(1024));
awaitLatch(latch);
while (!paused.get()) {
dataHandler.get().handle(TestUtils.randomBuffer(1024));
}
conn.get().close();
await();
}
@Test
public void testRequestPumpError() throws Exception {
waitFor(2);
HttpRequest<Buffer> post = client.post(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
CompletableFuture<Void> done = new CompletableFuture<>();
server.requestHandler(req -> {
req.response().closeHandler(v -> {
complete();
});
req.handler(buff -> {
done.complete(null);
});
});
Throwable cause = new Throwable();
startServer();
post.sendStream(new ReadStream<Buffer>() {
@Override
public ReadStream<Buffer> exceptionHandler(Handler<Throwable> handler) {
if (handler != null) {
done.thenAccept(v -> {
handler.handle(cause);
});
}
return this;
}
@Override
public ReadStream<Buffer> handler(Handler<Buffer> handler) {
if (handler != null) {
handler.handle(TestUtils.randomBuffer(1024));
}
return this;
}
@Override
public ReadStream<Buffer> pause() {
return this;
}
@Override
public ReadStream<Buffer> resume() {
return this;
}
@Override
public ReadStream<Buffer> endHandler(Handler<Void> endHandler) {
return this;
}
}, onFailure(err -> {
assertSame(cause, err);
complete();
}));
await();
}
@Test
public void testRequestPumpErrorNotYetConnected() throws Exception {
HttpRequest<Buffer> post = client.post(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
server.requestHandler(req -> {
fail();
});
Throwable cause = new Throwable();
startServer();
post.sendStream(new ReadStream<Buffer>() {
Handler<Throwable> exceptionHandler;
@Override
public ReadStream<Buffer> exceptionHandler(Handler<Throwable> handler) {
exceptionHandler = handler;
return this;
}
@Override
public ReadStream<Buffer> handler(Handler<Buffer> handler) {
if (handler != null) {
handler.handle(TestUtils.randomBuffer(1024));
vertx.runOnContext(v -> {
exceptionHandler.handle(cause);
});
}
return this;
}
@Override
public ReadStream<Buffer> pause() {
return this;
}
@Override
public ReadStream<Buffer> resume() {
return this;
}
@Override
public ReadStream<Buffer> endHandler(Handler<Void> endHandler) {
return this;
}
}, onFailure(err -> {
assertSame(cause, err);
testComplete();
}));
await();
}
@Test
public void testResponseBodyAsBuffer() throws Exception {
Buffer expected = TestUtils.randomBuffer(2000);
server.requestHandler(req -> {
req.response().end(expected);
});
startServer();
HttpRequest<Buffer> get = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
get.send(onSuccess(resp -> {
assertEquals(200, resp.statusCode());
assertEquals(expected, resp.body());
testComplete();
}));
await();
}
@Test
public void testResponseBodyAsAsJsonObject() throws Exception {
JsonObject expected = new JsonObject().put("cheese", "Goat Cheese").put("wine", "Condrieu");
server.requestHandler(req -> {
req.response().end(expected.encode());
});
startServer();
HttpRequest<Buffer> get = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
get
.as(BodyCodec.jsonObject())
.send(onSuccess(resp -> {
assertEquals(200, resp.statusCode());
assertEquals(expected, resp.body());
testComplete();
}));
await();
}
@Test
public void testResponseBodyAsAsJsonMapped() throws Exception {
JsonObject expected = new JsonObject().put("cheese", "Goat Cheese").put("wine", "Condrieu");
server.requestHandler(req -> {
req.response().end(expected.encode());
});
startServer();
HttpRequest<Buffer> get = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
get
.as(BodyCodec.json(WineAndCheese.class))
.send(onSuccess(resp -> {
assertEquals(200, resp.statusCode());
assertEquals(new WineAndCheese().setCheese("Goat Cheese").setWine("Condrieu"), resp.body());
testComplete();
}));
await();
}
@Test
public void testResponseBodyAsAsJsonArray() throws Exception {
JsonArray expected = new JsonArray().add("cheese").add("wine");
server.requestHandler(req -> {
req.response().end(expected.encode());
});
startServer();
HttpRequest<Buffer> get = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
get
.as(BodyCodec.jsonArray())
.send(onSuccess(resp -> {
assertEquals(200, resp.statusCode());
assertEquals(expected, resp.body());
testComplete();
}));
await();
}
@Test
public void testResponseBodyAsAsJsonArrayMapped() throws Exception {
JsonArray expected = new JsonArray().add("cheese").add("wine");
server.requestHandler(req -> {
req.response().end(expected.encode());
});
startServer();
HttpRequest<Buffer> get = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
get
.as(BodyCodec.json(List.class))
.send(onSuccess(resp -> {
assertEquals(200, resp.statusCode());
assertEquals(expected.getList(), resp.body());
testComplete();
}));
await();
}
@Test
public void testResponseBodyDiscarded() throws Exception {
server.requestHandler(req -> {
req.response().end(TestUtils.randomAlphaString(1024));
});
startServer();
HttpRequest<Buffer> get = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
get
.as(BodyCodec.none())
.send(onSuccess(resp -> {
assertEquals(200, resp.statusCode());
assertEquals(null, resp.body());
testComplete();
}));
await();
}
@Test
public void testResponseUnknownContentTypeBodyAsJsonObject() throws Exception {
JsonObject expected = new JsonObject().put("cheese", "Goat Cheese").put("wine", "Condrieu");
server.requestHandler(req -> {
req.response().end(expected.encode());
});
startServer();
HttpRequest<Buffer> get = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
get.send(onSuccess(resp -> {
assertEquals(200, resp.statusCode());
assertEquals(expected, resp.bodyAsJsonObject());
testComplete();
}));
await();
}
@Test
public void testResponseUnknownContentTypeBodyAsJsonArray() throws Exception {
JsonArray expected = new JsonArray().add("cheese").add("wine");
server.requestHandler(req -> {
req.response().end(expected.encode());
});
startServer();
HttpRequest<Buffer> get = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
get.send(onSuccess(resp -> {
assertEquals(200, resp.statusCode());
assertEquals(expected, resp.bodyAsJsonArray());
testComplete();
}));
await();
}
@Test
public void testResponseUnknownContentTypeBodyAsJsonMapped() throws Exception {
JsonObject expected = new JsonObject().put("cheese", "Goat Cheese").put("wine", "Condrieu");
server.requestHandler(req -> {
req.response().end(expected.encode());
});
startServer();
HttpRequest<Buffer> get = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
get.send(onSuccess(resp -> {
assertEquals(200, resp.statusCode());
assertEquals(new WineAndCheese().setCheese("Goat Cheese").setWine("Condrieu"), resp.bodyAsJson(WineAndCheese.class));
testComplete();
}));
await();
}
@Test
public void testResponseBodyUnmarshallingError() throws Exception {
server.requestHandler(req -> {
req.response().end("not-json-object");
});
startServer();
HttpRequest<Buffer> get = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
get
.as(BodyCodec.jsonObject())
.send(onFailure(err -> {
assertTrue(err instanceof DecodeException);
testComplete();
}));
await();
}
@Test
public void testResponseBodyStream() throws Exception {
AtomicBoolean paused = new AtomicBoolean();
server.requestHandler(req -> {
HttpServerResponse resp = req.response();
resp.setChunked(true);
vertx.setPeriodic(1, id -> {
if (!resp.writeQueueFull()) {
resp.write(TestUtils.randomAlphaString(1024));
} else {
resp.drainHandler(v -> {
resp.end();
});
paused.set(true);
vertx.cancelTimer(id);
}
});
});
startServer();
CompletableFuture<Void> resume = new CompletableFuture<>();
AtomicInteger size = new AtomicInteger();
AtomicBoolean ended = new AtomicBoolean();
WriteStream<Buffer> stream = new WriteStream<Buffer>() {
boolean paused = true;
Handler<Void> drainHandler;
{
resume.thenAccept(v -> {
paused = false;
if (drainHandler != null) {
drainHandler.handle(null);
}
});
}
@Override
public WriteStream<Buffer> exceptionHandler(Handler<Throwable> handler) {
return this;
}
@Override
public WriteStream<Buffer> write(Buffer data) {
size.addAndGet(data.length());
return this;
}
@Override
public void end() {
ended.set(true);
}
@Override
public WriteStream<Buffer> setWriteQueueMaxSize(int maxSize) {
return this;
}
@Override
public boolean writeQueueFull() {
return paused;
}
@Override
public WriteStream<Buffer> drainHandler(Handler<Void> handler) {
drainHandler = handler;
return this;
}
};
HttpRequest<Buffer> get = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
get
.as(BodyCodec.pipe(stream))
.send(onSuccess(resp -> {
assertTrue(ended.get());
assertEquals(200, resp.statusCode());
assertEquals(null, resp.body());
testComplete();
}));
assertWaitUntil(paused::get);
resume.complete(null);
await();
}
@Test
public void testResponseBodyStreamError() throws Exception {
CompletableFuture<Void> fail = new CompletableFuture<>();
server.requestHandler(req -> {
HttpServerResponse resp = req.response();
resp.setChunked(true);
resp.write(TestUtils.randomBuffer(2048));
fail.thenAccept(v -> {
resp.close();
});
});
startServer();
AtomicInteger received = new AtomicInteger();
WriteStream<Buffer> stream = new WriteStream<Buffer>() {
@Override
public WriteStream<Buffer> exceptionHandler(Handler<Throwable> handler) {
return this;
}
@Override
public WriteStream<Buffer> write(Buffer data) {
received.addAndGet(data.length());
return this;
}
@Override
public void end() {
}
@Override
public WriteStream<Buffer> setWriteQueueMaxSize(int maxSize) {
return this;
}
@Override
public boolean writeQueueFull() {
return false;
}
@Override
public WriteStream<Buffer> drainHandler(Handler<Void> handler) {
return this;
}
};
HttpRequest<Buffer> get = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
get
.as(BodyCodec.pipe(stream))
.send(onFailure(err -> {
testComplete();
}));
assertWaitUntil(() -> received.get() == 2048);
fail.complete(null);
await();
}
@Test
public void testResponseBodyCodecError() throws Exception {
server.requestHandler(req -> {
HttpServerResponse resp = req.response();
resp.setChunked(true);
resp.end(TestUtils.randomBuffer(2048));
});
startServer();
RuntimeException cause = new RuntimeException();
WriteStream<Buffer> stream = new WriteStream<Buffer>() {
Handler<Throwable> exceptionHandler;
@Override
public WriteStream<Buffer> exceptionHandler(Handler<Throwable> handler) {
exceptionHandler = handler;
return this;
}
@Override
public WriteStream<Buffer> write(Buffer data) {
exceptionHandler.handle(cause);
return this;
}
@Override
public void end() {
}
@Override
public WriteStream<Buffer> setWriteQueueMaxSize(int maxSize) {
return this;
}
@Override
public boolean writeQueueFull() {
return false;
}
@Override
public WriteStream<Buffer> drainHandler(Handler<Void> handler) {
return this;
}
};
HttpRequest<Buffer> get = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
get
.as(BodyCodec.pipe(stream))
.send(onFailure(err -> {
assertSame(cause, err);
testComplete();
}));
await();
}
@Test
public void testResponseJsonObjectMissingBody() throws Exception {
testResponseMissingBody(BodyCodec.jsonObject());
}
@Test
public void testResponseJsonMissingBody() throws Exception {
testResponseMissingBody(BodyCodec.json(WineAndCheese.class));
}
@Test
public void testResponseWriteStreamMissingBody() throws Exception {
AtomicInteger length = new AtomicInteger();
AtomicBoolean ended = new AtomicBoolean();
WriteStream<Buffer> stream = new WriteStream<Buffer>() {
@Override
public WriteStream<Buffer> exceptionHandler(Handler<Throwable> handler) {
return this;
}
@Override
public WriteStream<Buffer> write(Buffer data) {
length.addAndGet(data.length());
return this;
}
@Override
public void end() {
ended.set(true);
}
@Override
public WriteStream<Buffer> setWriteQueueMaxSize(int maxSize) {
return this;
}
@Override
public boolean writeQueueFull() {
return false;
}
@Override
public WriteStream<Buffer> drainHandler(Handler<Void> handler) {
return this;
}
};
testResponseMissingBody(BodyCodec.pipe(stream));
assertTrue(ended.get());
assertEquals(0, length.get());
}
private <R> void testResponseMissingBody(BodyCodec<R> codec) throws Exception {
server.requestHandler(req -> {
req.response().setStatusCode(403).end();
});
startServer();
HttpRequest<Buffer> get = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
get
.as(codec)
.send(onSuccess(resp -> {
assertEquals(403, resp.statusCode());
assertNull(resp.body());
testComplete();
}));
await();
}
@Test
public void testHttpResponseError() throws Exception {
server.requestHandler(req -> {
req.response().setChunked(true).write(Buffer.buffer("some-data")).close();
});
startServer();
HttpRequest<Buffer> get = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
get
.as(BodyCodec.jsonObject())
.send(onFailure(err -> {
assertTrue(err instanceof VertxException);
testComplete();
}));
await();
}
@Test
public void testTimeout() throws Exception {
AtomicInteger count = new AtomicInteger();
server.requestHandler(req -> {
count.incrementAndGet();
});
startServer();
HttpRequest<Buffer> get = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
get.timeout(50).send(onFailure(err -> {
assertEquals(err.getClass(), TimeoutException.class);
testComplete();
}));
await();
}
@Test
public void testQueryParam() throws Exception {
testRequest(client -> client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/").addQueryParam("param", "param_value"), req -> {
assertEquals("param=param_value", req.query());
assertEquals("param_value", req.getParam("param"));
});
}
@Test
public void testQueryParamMulti() throws Exception {
testRequest(client -> client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/").addQueryParam("param", "param_value1").addQueryParam("param", "param_value2"), req -> {
assertEquals("param=param_value1¶m=param_value2", req.query());
assertEquals(Arrays.asList("param_value1", "param_value2"), req.params().getAll("param"));
});
}
@Test
public void testQueryParamAppend() throws Exception {
testRequest(client -> client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/?param1=param1_value1").addQueryParam("param1", "param1_value2").addQueryParam("param2", "param2_value"), req -> {
assertEquals("param1=param1_value1¶m1=param1_value2¶m2=param2_value", req.query());
assertEquals("param1_value2", req.getParam("param1"));
assertEquals("param2_value", req.getParam("param2"));
});
}
@Test
public void testOverwriteQueryParams() throws Exception {
testRequest(client -> client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/?param=param_value1").setQueryParam("param", "param_value2"), req -> {
assertEquals("param=param_value2", req.query());
assertEquals("param_value2", req.getParam("param"));
});
}
@Test
public void testQueryParamEncoding() throws Exception {
testRequest(client -> client
.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/")
.addQueryParam("param1", " ")
.addQueryParam("param2", "\u20AC"), req -> {
assertEquals("param1=%20¶m2=%E2%82%AC", req.query());
assertEquals(" ", req.getParam("param1"));
assertEquals("\u20AC", req.getParam("param2"));
});
}
@Test
public void testFormUrlEncoded() throws Exception {
server.requestHandler(req -> {
req.setExpectMultipart(true);
req.endHandler(v -> {
assertEquals("param1_value", req.getFormAttribute("param1"));
req.response().end();
});
});
startServer();
MultiMap form = MultiMap.caseInsensitiveMultiMap();
form.add("param1", "param1_value");
HttpRequest<Buffer> builder = client.post("/somepath");
builder.sendForm(form, onSuccess(resp -> {
complete();
}));
await();
}
@Test
public void testFormMultipart() throws Exception {
server.requestHandler(req -> {
req.setExpectMultipart(true);
req.endHandler(v -> {
assertEquals("param1_value", req.getFormAttribute("param1"));
req.response().end();
});
});
startServer();
MultiMap form = MultiMap.caseInsensitiveMultiMap();
form.add("param1", "param1_value");
HttpRequest<Buffer> builder = client.post("/somepath");
builder.putHeader("content-type", "multipart/form-data");
builder.sendForm(form, onSuccess(resp -> {
complete();
}));
await();
}
@Test
public void testDefaultFollowRedirects() throws Exception {
testFollowRedirects(null, true);
}
@Test
public void testFollowRedirects() throws Exception {
testFollowRedirects(true, true);
}
@Test
public void testDoNotFollowRedirects() throws Exception {
testFollowRedirects(false, false);
}
private void testFollowRedirects(Boolean set, boolean expect) throws Exception {
waitFor(2);
String location = "http://" + DEFAULT_HTTP_HOST + ":" + DEFAULT_HTTP_PORT + "/ok";
server.requestHandler(req -> {
if (req.path().equals("/redirect")) {
req.response().setStatusCode(301).putHeader("Location", location).end();
if (!expect) {
complete();
}
} else {
req.response().end(req.path());
if (expect) {
complete();
}
}
});
startServer();
HttpRequest<Buffer> builder = client.get("/redirect");
if (set != null) {
builder = builder.followRedirects(set);
}
builder.send(onSuccess(resp -> {
if (expect) {
assertEquals(200, resp.statusCode());
assertEquals("/ok", resp.body().toString());
} else {
assertEquals(301, resp.statusCode());
assertEquals(location, resp.getHeader("location"));
}
complete();
}));
await();
}
@Test
public void testTLSEnabled() throws Exception {
testTLS(true, true, client -> client.get("/"));
}
@Test
public void testTLSEnabledDisableRequestTLS() throws Exception {
testTLS(true, false, client -> client.get("/").ssl(false));
}
@Test
public void testTLSEnabledEnableRequestTLS() throws Exception {
testTLS(true, true, client -> client.get("/").ssl(true));
}
@Test
public void testTLSDisabledDisableRequestTLS() throws Exception {
testTLS(false, false, client -> client.get("/").ssl(false));
}
@Test
public void testTLSDisabledEnableRequestTLS() throws Exception {
testTLS(false, true, client -> client.get("/").ssl(true));
}
@Test
public void testTLSEnabledDisableRequestTLSAbsURI() throws Exception {
testTLS(true, false, client -> client.getAbs("http://" + DEFAULT_HTTPS_HOST + ":" + DEFAULT_HTTPS_PORT));
}
@Test
public void testTLSEnabledEnableRequestTLSAbsURI() throws Exception {
testTLS(true, true, client -> client.getAbs("https://" + DEFAULT_HTTPS_HOST + ":" + DEFAULT_HTTPS_PORT));
}
@Test
public void testTLSDisabledDisableRequestTLSAbsURI() throws Exception {
testTLS(false, false, client -> client.getAbs("http://" + DEFAULT_HTTPS_HOST + ":" + DEFAULT_HTTPS_PORT));
}
@Test
public void testTLSDisabledEnableRequestTLSAbsURI() throws Exception {
testTLS(false, true, client -> client.getAbs("https://" + DEFAULT_HTTPS_HOST + ":" + DEFAULT_HTTPS_PORT));
}
/**
* Regression test for issue #563 (https://github.com/vert-x3/vertx-web/issues/563)
* <p>
* Only occurred when {@link WebClientOptions#isSsl()} was false for an SSL request.
*/
@Test
public void testTLSQueryParametersIssue563() throws Exception {
testTLS(false, true,
client -> client.getAbs("https://" + DEFAULT_HTTPS_HOST + ":" + DEFAULT_HTTPS_PORT)
.addQueryParam("query1", "value1")
.addQueryParam("query2", "value2"),
serverRequest -> assertEquals("query1=value1&query2=value2", serverRequest.query()));
}
private void testTLS(boolean clientSSL, boolean serverSSL, Function<WebClient, HttpRequest<Buffer>> requestProvider) throws Exception {
testTLS(clientSSL, serverSSL, requestProvider, null);
}
private void testTLS(boolean clientSSL, boolean serverSSL, Function<WebClient, HttpRequest<Buffer>> requestProvider, Consumer<HttpServerRequest> serverAssertions) throws Exception {
WebClient sslClient = WebClient.create(vertx, new WebClientOptions()
.setSsl(clientSSL)
.setTrustAll(true)
.setDefaultHost(DEFAULT_HTTPS_HOST)
.setDefaultPort(DEFAULT_HTTPS_PORT));
HttpServer sslServer = vertx.createHttpServer(new HttpServerOptions()
.setSsl(serverSSL)
.setKeyStoreOptions(Cert.CLIENT_JKS.get())
.setPort(DEFAULT_HTTPS_PORT)
.setHost(DEFAULT_HTTPS_HOST));
sslServer.requestHandler(req -> {
assertEquals(serverSSL, req.isSSL());
if (serverAssertions != null) {
serverAssertions.accept(req);
}
req.response().end();
});
try {
startServer(sslServer);
HttpRequest<Buffer> builder = requestProvider.apply(sslClient);
builder.send(onSuccess(resp -> {
testComplete();
}));
await();
} finally {
sslClient.close();
sslServer.close();
}
}
@Test
public void testHttpProxyFtpRequest() throws Exception {
startProxy(null, ProxyType.HTTP);
proxy.setForceUri("http://" + DEFAULT_HTTP_HOST + ":" + DEFAULT_HTTP_PORT);
server.requestHandler(req -> {
req.response().setStatusCode(200).end();
});
startServer();
WebClientOptions options = new WebClientOptions();
options.setProxyOptions(new ProxyOptions().setPort(proxy.getPort()));
WebClient client = WebClient.create(vertx, options);
client
.getAbs("ftp://ftp.gnu.org/gnu/")
.send(ar -> {
if (ar.succeeded()) {
// Obtain response
HttpResponse<Buffer> response = ar.result();
assertEquals(200, response.statusCode());
assertEquals("ftp://ftp.gnu.org/gnu/", proxy.getLastUri());
testComplete();
} else {
fail(ar.cause());
}
});
await();
}
private <R> void handleMutateRequest(HttpContext context) {
context.request().host("localhost");
context.request().port(8080);
context.next();
}
}
| Add a test with a real HttpServerRequest sent to a backend server
| vertx-web-client/src/test/java/io/vertx/ext/web/client/WebClientTest.java | Add a test with a real HttpServerRequest sent to a backend server | <ide><path>ertx-web-client/src/test/java/io/vertx/ext/web/client/WebClientTest.java
<ide> await();
<ide> }
<ide>
<del> private <R> void handleMutateRequest(HttpContext context) {
<del> context.request().host("localhost");
<del> context.request().port(8080);
<del> context.next();
<add> @Test
<add> public void testStreamHttpServerRequest() throws Exception {
<add> Buffer expected = TestUtils.randomBuffer(10000);
<add> HttpServer server2 = vertx.createHttpServer(new HttpServerOptions().setPort(8081)).requestHandler(req -> {
<add> req.bodyHandler(body -> {
<add> assertEquals(body, expected);
<add> req.response().end();
<add> });
<add> });
<add> startServer(server2);
<add> WebClient webClient = WebClient.create(vertx);
<add> try {
<add> server.requestHandler(req -> {
<add> webClient.postAbs("http://localhost:8081/")
<add> .sendStream(req, onSuccess(resp -> {
<add> req.response().end("ok");
<add> }));
<add> });
<add> startServer();
<add> webClient.post(8080, "localhost", "/").sendBuffer(expected, onSuccess(resp -> {
<add> assertEquals("ok", resp.bodyAsString());
<add> complete();
<add> }));
<add> await();
<add> } finally {
<add> server2.close();
<add> }
<ide> }
<ide> } |
|
JavaScript | mit | 4c1ce29b6a7d3f2e774d71b331e5fc8e680cb9ee | 0 | atomizejs/atomize-examples | // atomize-translate unittests.js unittests-compat.js atomize '$(document)' NiceException Error
var URL = "http://localhost:9999/atomize";
function NiceException() {};
NiceException.prototype = Error.prototype;
var niceException = new NiceException();
function withAtomize (clientsAry, test) {
var atomize = new Atomize(URL);
atomize.onAuthenticated = function () {
atomize.atomically(function () {
var key = Date();
atomize.root[key] = atomize.lift({});
return key;
}, function (key) {
var i;
for (i = 0; i < clientsAry.length; i += 1) {
clientsAry[i] = new Atomize(URL);
if (0 === i) {
clientsAry[i].onAuthenticated = function () {
test(key, clientsAry, function () {
for (i = 0; i < clientsAry.length; i += 1) {
clientsAry[i].close();
clientsAry[i] = undefined;
}
atomize.atomically(function () {
delete atomize.root[key];
}, function () {
atomize.close();
});
});
};
} else {
(function () {
var j = i - 1;
clientsAry[i].onAuthenticated = function () {
clientsAry[j].connect();
}
})();
}
}
clientsAry[clientsAry.length - 1].connect();
});
};
atomize.connect();
}
function clients (n) {
var ary = [];
ary.length = n;
return ary;
}
function contAndStart (cont) {
cont();
start();
}
function Semaphore (cont) {
this.count = 0;
this.cont = cont;
}
Semaphore.prototype = {
fired: false,
up: function () {
if (this.fired) {
throw "Semaphore Already Fired";
}
this.count += 1;
},
down: function () {
if (this.fired) {
throw "Semaphore Already Fired";
}
this.count -= 1;
if (0 === this.count) {
this.fired = true;
this.cont()
}
}
};
$(document).ready(function(){
asyncTest("Empty transaction", 2, function () {
withAtomize(clients(1), function (key, clients, cont) {
var c1 = clients[0];
c1.atomically(function () {
ok(true, "This txn has no read or writes so should run once");
}, function () {
ok(true, "The continuation should be run");
contAndStart(cont);
});
});
});
asyncTest("Await private empty root", 2, function () {
withAtomize(clients(1), function (key, clients, cont) {
var c1 = clients[0];
c1.atomically(function () {
if (undefined === c1.root[key]) {
ok(true, "We should retry at least once");
c1.retry();
}
return Object.keys(c1.root[key]).length;
}, function (fieldCount) {
strictEqual(fieldCount, 0, "Root object should be empty");
contAndStart(cont);
});
});
});
asyncTest("Set Primitive", 1, function () {
withAtomize(clients(1), function (key, clients, cont) {
var c1 = clients[0],
value = 5;
c1.atomically(function () {
if (undefined === c1.root[key]) {
c1.retry();
} else if (undefined !== c1.root[key].field) {
throw "Found existing field!";
}
c1.root[key].field = value;
return c1.root[key].field;
}, function (result) {
strictEqual(result, value, "Should have got back value");
contAndStart(cont);
});
});
});
asyncTest("Set Empty Object", 1, function () {
withAtomize(clients(1), function (key, clients, cont) {
var c1 = clients[0],
value = {};
c1.atomically(function () {
if (undefined === c1.root[key]) {
c1.retry();
} else if (undefined !== c1.root[key].field) {
throw "Found existing field!";
}
c1.root[key].field = c1.lift(value);
return c1.root[key].field;
}, function (result) {
deepEqual(result, value, "Should have got back value");
contAndStart(cont);
});
});
});
asyncTest("Set Complex Object", 1, function () {
withAtomize(clients(1), function (key, clients, cont) {
var c1 = clients[0],
value = {a: "hello", b: true, c: 5, d: {}};
value.e = value; // add loop
value.f = value.d; // add non-loop alias
c1.atomically(function () {
if (undefined === c1.root[key]) {
c1.retry();
} else if (undefined !== c1.root[key].field) {
throw "Found existing field!";
}
c1.root[key].field = c1.lift(value);
return c1.root[key].field;
}, function (result) {
deepEqual(result, value, "Should have got back value");
contAndStart(cont);
});
});
});
asyncTest("Trigger (add field)", 1, function () {
withAtomize(clients(2), function (key, clients, cont) {
var c1 = clients[0],
c2 = clients[1],
trigger = "pop!";
c1.atomically(function () {
if (undefined === c1.root[key] ||
undefined === c1.root[key].trigger) {
c1.retry();
}
return c1.root[key].trigger;
}, function (result) {
strictEqual(trigger, result, "Should have received the trigger");
contAndStart(cont);
});
c2.atomically(function () {
if (undefined === c2.root[key]) {
c2.retry();
}
if (undefined === c2.root[key].trigger) {
c2.root[key].trigger = trigger;
} else {
throw "Found existing trigger!";
}
}); // no need for a continuation here
});
});
asyncTest("Trigger (add and change field)", 3, function () {
withAtomize(clients(2), function (key, clients, cont) {
var c1 = clients[0],
c2 = clients[1],
trigger1 = "pop!",
trigger2 = "!pop";
c1.atomically(function () {
if (undefined === c1.root[key] ||
undefined === c1.root[key].trigger) {
c1.retry();
}
if (c1.root[key].trigger == trigger1) {
c1.root[key].trigger = trigger2;
return true;
} else {
return false;
}
}, function (success) {
ok(success, "Reached 1");
});
c2.atomically(function () {
if (undefined === c2.root[key]) {
c2.retry();
}
if (undefined === c2.root[key].trigger) {
c2.root[key].trigger = trigger1;
} else {
throw "Found existing trigger!";
}
}, function () {
ok(true, "Reached 2");
c2.atomically(function () {
if (trigger2 != c2.root[key].trigger) {
c2.retry();
}
}, function () {
ok(true, "Reached 3");
contAndStart(cont);
});
});
});
});
asyncTest("Trigger (add and remove field)", 3, function () {
withAtomize(clients(2), function (key, clients, cont) {
var c1 = clients[0],
c2 = clients[1],
trigger = "pop!";
c1.atomically(function () {
if (undefined === c1.root[key] ||
undefined === c1.root[key].trigger) {
c1.retry();
}
delete c1.root[key].trigger;
}, function () {
ok(true, "Reached 1");
});
c2.atomically(function () {
if (undefined === c2.root[key]) {
c2.retry();
}
if (undefined === c2.root[key].trigger) {
c2.root[key].trigger = trigger;
} else {
throw "Found existing trigger!";
}
}, function () {
ok(true, "Reached 2");
c2.atomically(function () {
if (undefined !== c2.root[key].trigger) {
c2.retry();
}
}, function () {
ok(true, "Reached 3");
contAndStart(cont);
});
});
});
});
asyncTest("Send Primitive", 1, function () {
withAtomize(clients(2), function (key, clients, cont) {
var c1 = clients[0],
c2 = clients[1],
value = 5;
c1.atomically(function () {
if (undefined === c1.root[key]) {
c1.retry();
} else if (undefined !== c1.root[key].field) {
throw "Found existing field!";
}
c1.root[key].field = value;
});
c2.atomically(function () {
if (undefined === c2.root[key] ||
undefined === c2.root[key].field) {
c2.retry();
}
return c2.root[key].field;
}, function (result) {
strictEqual(result, value, "Should have got back value");
contAndStart(cont);
});
});
});
asyncTest("Send Empty Object", 1, function () {
withAtomize(clients(2), function (key, clients, cont) {
var c1 = clients[0],
c2 = clients[1],
value = {};
c1.atomically(function () {
if (undefined === c1.root[key]) {
c1.retry();
} else if (undefined !== c1.root[key].field) {
throw "Found existing field!";
}
c1.root[key].field = c1.lift(value);
});
c2.atomically(function () {
if (undefined === c2.root[key] ||
undefined === c2.root[key].field) {
c2.retry();
}
return c2.root[key].field;
}, function (result) {
deepEqual(result, value, "Should have got back value");
contAndStart(cont);
});
});
});
asyncTest("Send Complex Object", 1, function () {
withAtomize(clients(2), function (key, clients, cont) {
var c1 = clients[0],
c2 = clients[1],
value = {a: "hello", b: true, c: 5, d: {}};
value.e = value; // add loop
value.f = value.d; // add non-loop alias
c1.atomically(function () {
if (undefined === c1.root[key]) {
c1.retry();
} else if (undefined !== c1.root[key].field) {
throw "Found existing field!";
}
c1.root[key].field = c1.lift(value);
});
c2.atomically(function () {
if (undefined === c2.root[key] ||
undefined === c2.root[key].field) {
c2.retry();
}
return c2.root[key].field;
}, function (result) {
deepEqual(result, value, "Should have got back value");
contAndStart(cont);
});
});
});
// For some reason, the current Proxy thing suggests all
// descriptors should be configurable. Thus we don't test for the
// 'configurable' meta-property here. This issue should go away
// once "direct proxies" arrive.
asyncTest("Keys, Enumerate, etc", 10, function () {
withAtomize(clients(2), function (key, clients, cont) {
var c1 = clients[0],
c2 = clients[1],
descriptors = {a: {value: 1,
writable: true,
enumerable: true},
b: {value: 2,
writable: false,
enumerable: true},
c: {value: 3,
writable: true,
enumerable: false},
d: {value: 4,
writable: false,
enumerable: false}};
c1.atomically(function () {
if (undefined === c1.root[key]) {
c1.retry();
}
var keys = Object.keys(descriptors),
x, field, descriptor;
for (x = 0; x < keys.length; x += 1) {
field = keys[x];
descriptor = descriptors[field];
Object.defineProperty(c1.root[key], field, descriptor);
}
c1.root[key].done = true;
});
c2.atomically(function () {
if (undefined === c2.root[key] ||
undefined === c2.root[key].done) {
c2.retry();
}
delete c2.root[key].done;
var keys = Object.keys(c2.root[key]),
names = Object.getOwnPropertyNames(c2.root[key]),
enumerable = [],
descriptors = {},
field, x;
for (field in c2.root[key]) {
enumerable.push(field);
}
for (x = 0; x < names.length; x += 1) {
field = names[x];
descriptors[field] = Object.getOwnPropertyDescriptor(c2.root[key], field);
delete descriptors[field].configurable; // see comment above
}
return {keys: keys.sort(),
names: names.sort(),
enumerable: enumerable.sort(),
descriptors: descriptors,
hasA: 'a' in c2.root[key],
hasC: 'c' in c2.root[key],
hasZ: 'z' in c2.root[key],
hasOwnA: ({}).hasOwnProperty.call(c2.root[key], 'a'),
hasOwnC: ({}).hasOwnProperty.call(c2.root[key], 'c'),
hasOwnZ: ({}).hasOwnProperty.call(c2.root[key], 'z')};
}, function (result) {
deepEqual(result.keys, ['a', 'b'],
"Keys should have found enumerable fields");
deepEqual(result.enumerable, ['a', 'b'],
"Enumeration should have found enumerable fields");
deepEqual(result.names, ['a', 'b', 'c', 'd'],
"Should have found field names 'a' to 'd'");
deepEqual(result.descriptors, descriptors,
"Should have got same descriptors back");
ok(result.hasA, "Should have found field 'a'");
ok(result.hasC, "Should have found field 'c'");
ok(! result.hasZ, "Should not have found field 'z'");
ok(result.hasOwnA, "Should have found own field 'a'");
ok(result.hasOwnC, "Should have found own field 'c'");
ok(! result.hasOwnZ, "Should not have found own field 'z'");
contAndStart(cont);
});
});
});
asyncTest("Triggers: Multiple concurrent retries, multiple clients", 6, function () {
withAtomize(clients(2), function (key, clients, cont) {
var c1 = clients[0],
c2 = clients[1];
c1.atomically(function () {
if (undefined === c1.root[key] ||
undefined === c1.root[key].ready) {
c1.retry();
}
c1.root[key].ready = ! c1.root[key].ready; // 2. Flip it false to true
}, function () {
ok(true, "Reached 1");
});
// We do the 'gone' thing because otherwise c1's txns can
// create and remove it, before c2 spots its
// existence. I.e. classic race condition.
c1.atomically(function () {
if (undefined === c1.root[key] ||
undefined === c1.root[key].ready ||
! c1.root[key].ready) {
c1.retry();
}
delete c1.root[key].ready; // 3. Delete it
c1.root[key].gone = true;
}, function () {
ok(true, "Reached 2");
});
c2.atomically(function () {
if (undefined === c2.root[key] ||
(undefined === c2.root[key].ready &&
undefined === c2.root[key].gone)) {
c2.retry(); // A. Await its existence
}
}, function () {
ok(true, "Reached 3");
c2.atomically(function () {
if (Object.hasOwnProperty.call(c2.root[key], 'ready')) {
c2.retry(); // B. Await its disappearance
}
ok(c2.root[key].gone, "If 'ready' has gone, 'gone' must be truth");
delete c2.root[key].gone;
}, function () {
ok(true, "Reached 4");
contAndStart(cont); // C. All done
});
});
c2.atomically(function () {
if (undefined === c2.root[key]) {
c2.retry();
}
c2.root[key].ready = false; // 1. Create it as false
}, function () {
ok(true, "Reached 5");
});
});
});
asyncTest("OrElse", 4, function () {
withAtomize(clients(2), function (key, clients, cont) {
var c1 = clients[0],
c2 = clients[1],
fun;
fun = function (sum) {
ok(true, "Reached 1"); // should reach this 4 times
if (10 === sum) { // 10 === 1+2+3+4
contAndStart(cont);
return;
}
c1.orElse(
[function () {
if (undefined === c1.root[key] ||
undefined === c1.root[key].a) {
c1.retry();
}
c1.root[key].b = c1.root[key].a + 2;
delete c1.root[key].a;
return c1.root[key].b;
}, function () {
if (undefined === c1.root[key] ||
undefined === c1.root[key].b) {
c1.retry();
}
c1.root[key].c = c1.root[key].b + 3;
delete c1.root[key].b;
return c1.root[key].c;
}, function () {
if (undefined === c1.root[key] ||
undefined === c1.root[key].c) {
c1.retry();
}
c1.root[key].d = c1.root[key].c + 4;
delete c1.root[key].c;
return c1.root[key].d;
}], fun);
};
fun(0);
c2.atomically(function () {
if (undefined === c2.root[key]) {
c2.retry();
}
c2.root[key].a = 1;
});
});
});
asyncTest("OrElse - observing order", 4, function () {
// Same as before, but drop the deletes, and invert the order
// of the orElse statements. As its deterministic choice,
// should do the same as before.
withAtomize(clients(2), function (key, clients, cont) {
var c1 = clients[0],
c2 = clients[1],
fun;
fun = function (sum) {
ok(true, "Reached 1"); // should reach this 4 times
if (10 === sum) { // 10 === 1+2+3+4
contAndStart(cont);
return;
}
c1.orElse(
[function () {
if (undefined === c1.root[key] ||
undefined === c1.root[key].c) {
c1.retry();
}
c1.root[key].d = c1.root[key].c + 4;
return c1.root[key].d;
}, function () {
if (undefined === c1.root[key] ||
undefined === c1.root[key].b) {
c1.retry();
}
c1.root[key].c = c1.root[key].b + 3;
return c1.root[key].c;
}, function () {
if (undefined === c1.root[key] ||
undefined === c1.root[key].a) {
c1.retry();
}
c1.root[key].b = c1.root[key].a + 2;
return c1.root[key].b;
}], fun);
};
fun(0);
c2.atomically(function () {
if (undefined === c2.root[key]) {
c2.retry();
}
c2.root[key].a = 1;
});
});
});
(function () {
var clientCount = 6,
clientConcurrency = 10,
txnCount = 10;
asyncTest("Rampaging Transactions 1 (this takes a while)",
((clientCount - 1) * clientConcurrency * txnCount) -1, function () {
withAtomize(clients(clientCount), function (key, clients, cont) {
var semaphore = new Semaphore(function () { contAndStart(cont); }),
fun, x, y;
fun = function (c) {
c.atomically(function () {
if (undefined === c.root[key] ||
undefined === c.root[key].obj) {
c.retry();
}
var keys = Object.keys(c.root[key].obj),
max = 0,
x, field, n, obj;
for (x = 0; x < keys.length; x += 1) {
field = parseInt(keys[x]);
max = field > max ? field : max;
if (undefined === n) {
n = c.root[key].obj[field].num;
if (0 === n) {
return n;
}
} else if (n !== c.root[key].obj[field].num) {
throw ("All fields should have the same number: " +
n + " vs " + c.root[key].obj[field].num);
}
if (0.75 < Math.random()) {
obj = c.lift({});
obj.num = n;
c.root[key].obj[field] = obj;
}
c.root[key].obj[field].num -= 1;
}
n -= 1;
max += 1;
if (0.75 < Math.random()) {
c.root[key].obj[max] = c.lift({num: n});
delete c.root[key].obj[keys[0]];
}
return n;
}, function (n) {
if (n > 0) {
ok(true, "Reached");
fun(c);
} else {
semaphore.down();
}
});
};
// We use all but one client, and each of those gets 10
// txns concurrently
for (x = 1; x < clients.length; x += 1) {
clients[x].stm.prefix = "(" + x + "): ";
for (y = 0; y < clientConcurrency; y += 1) {
semaphore.up();
fun(clients[x]);
}
}
x = clients[0];
x.atomically(function () {
if (undefined === x.root[key]) {
x.retry();
}
var obj = x.lift({});
for (y = 0; y < 5; y += 1) {
obj[y] = x.lift({num: (clientCount - 1) * clientConcurrency * txnCount});
}
x.root[key].obj = obj;
});
});
});
}());
(function () {
var clientCount = 6,
clientConcurrency = 6,
txnCount = 10;
asyncTest("Rampaging Transactions 2 (this takes a while)",
(clientCount - 1) * clientConcurrency * txnCount, function () {
withAtomize(clients(clientCount), function (key, clients, cont) {
var semaphore = new Semaphore(function () { contAndStart(cont); }),
fun;
fun = function (c, n) {
c.atomically(function () {
if (undefined === c.root[key] ||
undefined === c.root[key].obj) {
c.retry();
}
var ops, names, secret, x, name, op;
// First verify the old thing
ops = c.root[key].obj.log;
if (undefined !== ops) {
secret = ops.secret;
names = Object.keys(ops);
for (x = 0; x < names.length; x += 1) {
name = names[x];
if ('secret' === name) {
continue;
} else if ('delete' === ops[name]) {
if (({}).hasOwnProperty.call(c.root[key].obj, name)) {
throw ("Found field which should be deleted: " + name)
}
} else if ('modify' === ops[name]) {
if (! ({}).hasOwnProperty.call(c.root[key].obj, name)) {
throw ("Failed to find field: " + name);
}
if (secret !== c.root[key].obj[name].modified.value) {
throw ("Found the wrong modified value in field: " + name);
}
} else if ('create' === ops[name]) {
if (! ({}).hasOwnProperty.call(c.root[key].obj, name)) {
throw ("Failed to find field: " + name);
}
if (secret !== c.root[key].obj[name].created.value) {
throw ("Found the wrong created value in field: " + name);
}
} else {
throw ("Found unknown op: " + ops[name]);
}
}
}
secret = Math.random();
ops = {secret: secret};
for (x = 0; x < 20; x += 1) {
name = Math.round(Math.random() * 50);
op = Math.random();
if (op > 0.9) {
delete c.root[key].obj[name];
ops[name] = 'delete';
} else if (op > 0.1 && ({}).hasOwnProperty.call(c.root[key].obj, name)) {
c.root[key].obj[name].modified.value = secret;
ops[name] = 'modify';
} else {
c.root[key].obj[name] = c.lift({});
c.root[key].obj[name].created = c.lift({value: secret});
c.root[key].obj[name].modified = c.lift({value: secret});
ops[name] = 'create';
}
}
c.root[key].obj.log = c.lift(ops);
}, function () {
ok(true, "Reached");
n += 1;
if (10 === n) {
semaphore.down();
} else {
fun(c, n);
}
});
};
// We use all but one client, and each of those gets 10
// txns concurrently
for (x = 1; x < clients.length; x += 1) {
clients[x].stm.prefix = "(" + x + "): ";
for (y = 0; y < clientConcurrency; y += 1) {
semaphore.up();
fun(clients[x], 0);
}
}
x = clients[0];
x.atomically(function () {
if (undefined === x.root[key]) {
x.retry();
}
x.root[key].obj = x.lift({});
});
});
});
}());
});
| test/unittests.js | // atomize-translate unittests.js unittests-compat.js atomize '$(document)' NiceException Error
var URL = "http://localhost:9999/atomize";
function NiceException() {};
NiceException.prototype = Error.prototype;
var niceException = new NiceException();
function withAtomize (clientsAry, test) {
var atomize = new Atomize(URL);
atomize.onAuthenticated = function () {
atomize.atomically(function () {
var key = Date();
atomize.root[key] = atomize.lift({});
return key;
}, function (key) {
var i;
for (i = 0; i < clientsAry.length; i += 1) {
clientsAry[i] = new Atomize(URL);
if (0 === i) {
clientsAry[i].onAuthenticated = function () {
test(key, clientsAry, function () {
for (i = 0; i < clientsAry.length; i += 1) {
clientsAry[i].close();
clientsAry[i] = undefined;
}
atomize.atomically(function () {
delete atomize.root[key];
}, function () {
atomize.close();
});
});
};
} else {
(function () {
var j = i - 1;
clientsAry[i].onAuthenticated = function () {
clientsAry[j].connect();
}
})();
}
}
clientsAry[clientsAry.length - 1].connect();
});
};
atomize.connect();
}
function clients (n) {
var ary = [];
ary.length = n;
return ary;
}
function contAndStart (cont) {
cont();
start();
}
function Semaphore (cont) {
this.count = 0;
this.cont = cont;
}
Semaphore.prototype = {
fired: false,
up: function () {
if (this.fired) {
throw "Semaphore Already Fired";
}
this.count += 1;
},
down: function () {
if (this.fired) {
throw "Semaphore Already Fired";
}
this.count -= 1;
if (0 === this.count) {
this.fired = true;
this.cont()
}
}
};
$(document).ready(function(){
asyncTest("Empty transaction", 2, function () {
withAtomize(clients(1), function (key, clients, cont) {
var c1 = clients[0];
c1.atomically(function () {
ok(true, "This txn has no read or writes so should run once");
}, function () {
ok(true, "The continuation should be run");
contAndStart(cont);
});
});
});
asyncTest("Await private empty root", 2, function () {
withAtomize(clients(1), function (key, clients, cont) {
var c1 = clients[0];
c1.atomically(function () {
if (undefined === c1.root[key]) {
ok(true, "We should retry at least once");
c1.retry();
}
return Object.keys(c1.root[key]).length;
}, function (fieldCount) {
strictEqual(fieldCount, 0, "Root object should be empty");
contAndStart(cont);
});
});
});
asyncTest("Set Primitive", 1, function () {
withAtomize(clients(1), function (key, clients, cont) {
var c1 = clients[0],
value = 5;
c1.atomically(function () {
if (undefined === c1.root[key]) {
c1.retry();
} else if (undefined !== c1.root[key].field) {
throw "Found existing field!";
}
c1.root[key].field = value;
return c1.root[key].field;
}, function (result) {
strictEqual(result, value, "Should have got back value");
contAndStart(cont);
});
});
});
asyncTest("Set Empty Object", 1, function () {
withAtomize(clients(1), function (key, clients, cont) {
var c1 = clients[0],
value = {};
c1.atomically(function () {
if (undefined === c1.root[key]) {
c1.retry();
} else if (undefined !== c1.root[key].field) {
throw "Found existing field!";
}
c1.root[key].field = c1.lift(value);
return c1.root[key].field;
}, function (result) {
deepEqual(result, value, "Should have got back value");
contAndStart(cont);
});
});
});
asyncTest("Set Complex Object", 1, function () {
withAtomize(clients(1), function (key, clients, cont) {
var c1 = clients[0],
value = {a: "hello", b: true, c: 5, d: {}};
value.e = value; // add loop
value.f = value.d; // add non-loop alias
c1.atomically(function () {
if (undefined === c1.root[key]) {
c1.retry();
} else if (undefined !== c1.root[key].field) {
throw "Found existing field!";
}
c1.root[key].field = c1.lift(value);
return c1.root[key].field;
}, function (result) {
deepEqual(result, value, "Should have got back value");
contAndStart(cont);
});
});
});
asyncTest("Trigger (add field)", 1, function () {
withAtomize(clients(2), function (key, clients, cont) {
var c1 = clients[0],
c2 = clients[1],
trigger = "pop!";
c1.atomically(function () {
if (undefined === c1.root[key] ||
undefined === c1.root[key].trigger) {
c1.retry();
}
return c1.root[key].trigger;
}, function (result) {
strictEqual(trigger, result, "Should have received the trigger");
contAndStart(cont);
});
c2.atomically(function () {
if (undefined === c2.root[key]) {
c2.retry();
}
if (undefined === c2.root[key].trigger) {
c2.root[key].trigger = trigger;
} else {
throw "Found existing trigger!";
}
}); // no need for a continuation here
});
});
asyncTest("Trigger (add and change field)", 3, function () {
withAtomize(clients(2), function (key, clients, cont) {
var c1 = clients[0],
c2 = clients[1],
trigger1 = "pop!",
trigger2 = "!pop";
c1.atomically(function () {
if (undefined === c1.root[key] ||
undefined === c1.root[key].trigger) {
c1.retry();
}
if (c1.root[key].trigger == trigger1) {
c1.root[key].trigger = trigger2;
return true;
} else {
return false;
}
}, function (success) {
ok(success, "Reached 1");
});
c2.atomically(function () {
if (undefined === c2.root[key]) {
c2.retry();
}
if (undefined === c2.root[key].trigger) {
c2.root[key].trigger = trigger1;
} else {
throw "Found existing trigger!";
}
}, function () {
ok(true, "Reached 2");
c2.atomically(function () {
if (trigger2 != c2.root[key].trigger) {
c2.retry();
}
}, function () {
ok(true, "Reached 3");
contAndStart(cont);
});
});
});
});
asyncTest("Trigger (add and remove field)", 3, function () {
withAtomize(clients(2), function (key, clients, cont) {
var c1 = clients[0],
c2 = clients[1],
trigger = "pop!";
c1.atomically(function () {
if (undefined === c1.root[key] ||
undefined === c1.root[key].trigger) {
c1.retry();
}
delete c1.root[key].trigger;
}, function () {
ok(true, "Reached 1");
});
c2.atomically(function () {
if (undefined === c2.root[key]) {
c2.retry();
}
if (undefined === c2.root[key].trigger) {
c2.root[key].trigger = trigger;
} else {
throw "Found existing trigger!";
}
}, function () {
ok(true, "Reached 2");
c2.atomically(function () {
if (undefined !== c2.root[key].trigger) {
c2.retry();
}
}, function () {
ok(true, "Reached 3");
contAndStart(cont);
});
});
});
});
asyncTest("Send Primitive", 1, function () {
withAtomize(clients(2), function (key, clients, cont) {
var c1 = clients[0],
c2 = clients[1],
value = 5;
c1.atomically(function () {
if (undefined === c1.root[key]) {
c1.retry();
} else if (undefined !== c1.root[key].field) {
throw "Found existing field!";
}
c1.root[key].field = value;
});
c2.atomically(function () {
if (undefined === c2.root[key] ||
undefined === c2.root[key].field) {
c2.retry();
}
return c2.root[key].field;
}, function (result) {
strictEqual(result, value, "Should have got back value");
contAndStart(cont);
});
});
});
asyncTest("Send Empty Object", 1, function () {
withAtomize(clients(2), function (key, clients, cont) {
var c1 = clients[0],
c2 = clients[1],
value = {};
c1.atomically(function () {
if (undefined === c1.root[key]) {
c1.retry();
} else if (undefined !== c1.root[key].field) {
throw "Found existing field!";
}
c1.root[key].field = c1.lift(value);
});
c2.atomically(function () {
if (undefined === c2.root[key] ||
undefined === c2.root[key].field) {
c2.retry();
}
return c2.root[key].field;
}, function (result) {
deepEqual(result, value, "Should have got back value");
contAndStart(cont);
});
});
});
asyncTest("Send Complex Object", 1, function () {
withAtomize(clients(2), function (key, clients, cont) {
var c1 = clients[0],
c2 = clients[1],
value = {a: "hello", b: true, c: 5, d: {}};
value.e = value; // add loop
value.f = value.d; // add non-loop alias
c1.atomically(function () {
if (undefined === c1.root[key]) {
c1.retry();
} else if (undefined !== c1.root[key].field) {
throw "Found existing field!";
}
c1.root[key].field = c1.lift(value);
});
c2.atomically(function () {
if (undefined === c2.root[key] ||
undefined === c2.root[key].field) {
c2.retry();
}
return c2.root[key].field;
}, function (result) {
deepEqual(result, value, "Should have got back value");
contAndStart(cont);
});
});
});
// For some reason, the current Proxy thing suggests all
// descriptors should be configurable. Thus we don't test for the
// 'configurable' meta-property here. This issue should go away
// once "direct proxies" arrive.
asyncTest("Keys, Enumerate, etc", 10, function () {
withAtomize(clients(2), function (key, clients, cont) {
var c1 = clients[0],
c2 = clients[1],
descriptors = {a: {value: 1,
writable: true,
enumerable: true},
b: {value: 2,
writable: false,
enumerable: true},
c: {value: 3,
writable: true,
enumerable: false},
d: {value: 4,
writable: false,
enumerable: false}};
c1.atomically(function () {
if (undefined === c1.root[key]) {
c1.retry();
}
var keys = Object.keys(descriptors),
x, field, descriptor;
for (x = 0; x < keys.length; x += 1) {
field = keys[x];
descriptor = descriptors[field];
Object.defineProperty(c1.root[key], field, descriptor);
}
c1.root[key].done = true;
});
c2.atomically(function () {
if (undefined === c2.root[key] ||
undefined === c2.root[key].done) {
c2.retry();
}
delete c2.root[key].done;
var keys = Object.keys(c2.root[key]),
names = Object.getOwnPropertyNames(c2.root[key]),
enumerable = [],
descriptors = {},
field, x;
for (field in c2.root[key]) {
enumerable.push(field);
}
for (x = 0; x < names.length; x += 1) {
field = names[x];
descriptors[field] = Object.getOwnPropertyDescriptor(c2.root[key], field);
delete descriptors[field].configurable; // see comment above
}
return {keys: keys.sort(),
names: names.sort(),
enumerable: enumerable.sort(),
descriptors: descriptors,
hasA: 'a' in c2.root[key],
hasC: 'c' in c2.root[key],
hasZ: 'z' in c2.root[key],
hasOwnA: ({}).hasOwnProperty.call(c2.root[key], 'a'),
hasOwnC: ({}).hasOwnProperty.call(c2.root[key], 'c'),
hasOwnZ: ({}).hasOwnProperty.call(c2.root[key], 'z')};
}, function (result) {
deepEqual(result.keys, ['a', 'b'],
"Keys should have found enumerable fields");
deepEqual(result.enumerable, ['a', 'b'],
"Enumeration should have found enumerable fields");
deepEqual(result.names, ['a', 'b', 'c', 'd'],
"Should have found field names 'a' to 'd'");
deepEqual(result.descriptors, descriptors,
"Should have got same descriptors back");
ok(result.hasA, "Should have found field 'a'");
ok(result.hasC, "Should have found field 'c'");
ok(! result.hasZ, "Should not have found field 'z'");
ok(result.hasOwnA, "Should have found own field 'a'");
ok(result.hasOwnC, "Should have found own field 'c'");
ok(! result.hasOwnZ, "Should not have found own field 'z'");
contAndStart(cont);
});
});
});
asyncTest("Triggers: Multiple concurrent retries, multiple clients", 6, function () {
withAtomize(clients(2), function (key, clients, cont) {
var c1 = clients[0],
c2 = clients[1];
c1.atomically(function () {
if (undefined === c1.root[key] ||
undefined === c1.root[key].ready) {
c1.retry();
}
c1.root[key].ready = ! c1.root[key].ready; // 2. Flip it false to true
}, function () {
ok(true, "Reached 1");
});
// We do the 'gone' thing because otherwise c1's txns can
// create and remove it, before c2 spots its
// existence. I.e. classic race condition.
c1.atomically(function () {
if (undefined === c1.root[key] ||
undefined === c1.root[key].ready ||
! c1.root[key].ready) {
c1.retry();
}
delete c1.root[key].ready; // 3. Delete it
c1.root[key].gone = true;
}, function () {
ok(true, "Reached 2");
});
c2.atomically(function () {
if (undefined === c2.root[key] ||
(undefined === c2.root[key].ready &&
undefined === c2.root[key].gone)) {
c2.retry(); // A. Await its existence
}
}, function () {
ok(true, "Reached 3");
c2.atomically(function () {
if (Object.hasOwnProperty.call(c2.root[key], 'ready')) {
c2.retry(); // B. Await its disappearance
}
ok(c2.root[key].gone, "If 'ready' has gone, 'gone' must be truth");
delete c2.root[key].gone;
}, function () {
ok(true, "Reached 4");
contAndStart(cont); // C. All done
});
});
c2.atomically(function () {
if (undefined === c2.root[key]) {
c2.retry();
}
c2.root[key].ready = false; // 1. Create it as false
}, function () {
ok(true, "Reached 5");
});
});
});
asyncTest("OrElse", 4, function () {
withAtomize(clients(2), function (key, clients, cont) {
var c1 = clients[0],
c2 = clients[1],
fun;
fun = function (sum) {
ok(true, "Reached 1"); // should reach this 4 times
if (10 === sum) { // 10 === 1+2+3+4
contAndStart(cont);
return;
}
c1.orElse(
[function () {
if (undefined === c1.root[key] ||
undefined === c1.root[key].a) {
c1.retry();
}
c1.root[key].b = c1.root[key].a + 2;
delete c1.root[key].a;
return c1.root[key].b;
}, function () {
if (undefined === c1.root[key] ||
undefined === c1.root[key].b) {
c1.retry();
}
c1.root[key].c = c1.root[key].b + 3;
delete c1.root[key].b;
return c1.root[key].c;
}, function () {
if (undefined === c1.root[key] ||
undefined === c1.root[key].c) {
c1.retry();
}
c1.root[key].d = c1.root[key].c + 4;
delete c1.root[key].c;
return c1.root[key].d;
}], fun);
};
fun(0);
c2.atomically(function () {
if (undefined === c2.root[key]) {
c2.retry();
}
c2.root[key].a = 1;
});
});
});
asyncTest("OrElse - observing order", 4, function () {
// Same as before, but drop the deletes, and invert the order
// of the orElse statements. As its deterministic choice,
// should do the same as before.
withAtomize(clients(2), function (key, clients, cont) {
var c1 = clients[0],
c2 = clients[1],
fun;
fun = function (sum) {
ok(true, "Reached 1"); // should reach this 4 times
if (10 === sum) { // 10 === 1+2+3+4
contAndStart(cont);
return;
}
c1.orElse(
[function () {
if (undefined === c1.root[key] ||
undefined === c1.root[key].c) {
c1.retry();
}
c1.root[key].d = c1.root[key].c + 4;
return c1.root[key].d;
}, function () {
if (undefined === c1.root[key] ||
undefined === c1.root[key].b) {
c1.retry();
}
c1.root[key].c = c1.root[key].b + 3;
return c1.root[key].c;
}, function () {
if (undefined === c1.root[key] ||
undefined === c1.root[key].a) {
c1.retry();
}
c1.root[key].b = c1.root[key].a + 2;
return c1.root[key].b;
}], fun);
};
fun(0);
c2.atomically(function () {
if (undefined === c2.root[key]) {
c2.retry();
}
c2.root[key].a = 1;
});
});
});
(function () {
var clientCount = 6,
clientConcurrency = 10,
txnCount = 10;
asyncTest("Rampaging Transactions 1 (this takes a while)",
((clientCount - 1) * clientConcurrency * txnCount) -1, function () {
withAtomize(clients(clientCount), function (key, clients, cont) {
var semaphore = new Semaphore(function () { contAndStart(cont); }),
fun, x, y;
fun = function (c) {
c.atomically(function () {
if (undefined === c.root[key] ||
undefined === c.root[key].obj) {
c.retry();
}
var keys = Object.keys(c.root[key].obj),
max = 0,
x, field, n, obj;
for (x = 0; x < keys.length; x += 1) {
field = parseInt(keys[x]);
max = field > max ? field : max;
if (undefined === n) {
n = c.root[key].obj[field].num;
if (0 === n) {
return n;
}
} else if (n !== c.root[key].obj[field].num) {
throw ("All fields should have the same number: " +
n + " vs " + c.root[key].obj[field].num);
}
if (0.75 < Math.random()) {
obj = c.lift({});
obj.num = n;
c.root[key].obj[field] = obj;
}
c.root[key].obj[field].num -= 1;
}
n -= 1;
max += 1;
if (0.75 < Math.random()) {
c.root[key].obj[max] = c.lift({num: n});
delete c.root[key].obj[keys[0]];
}
return n;
}, function (n) {
if (n > 0) {
ok(true, "Reached");
fun(c);
} else {
semaphore.down();
}
});
};
// We use all but one client, and each of those gets 10
// txns concurrently
for (x = 1; x < clients.length; x += 1) {
clients[x].stm.prefix = "(" + x + "): ";
for (y = 0; y < clientConcurrency; y += 1) {
semaphore.up();
fun(clients[x]);
}
}
x = clients[0];
x.atomically(function () {
if (undefined === x.root[key]) {
x.retry();
}
var obj = x.lift({});
for (y = 0; y < 5; y += 1) {
obj[y] = x.lift({num: (clientCount - 1) * clientConcurrency * txnCount});
}
x.root[key].obj = obj;
});
});
});
}());
(function () {
var clientCount = 6,
clientConcurrency = 5,
txnCount = 10;
asyncTest("Rampaging Transactions 2 (this takes a while)",
(clientCount - 1) * clientConcurrency * txnCount, function () {
withAtomize(clients(clientCount), function (key, clients, cont) {
var semaphore = new Semaphore(function () { contAndStart(cont); }),
fun;
fun = function (c, n) {
c.atomically(function () {
if (undefined === c.root[key] ||
undefined === c.root[key].obj) {
c.retry();
}
var ops, names, secret, x, name, op;
// First verify the old thing
ops = c.root[key].obj.log;
if (undefined !== ops) {
secret = ops.secret;
names = Object.keys(ops);
for (x = 0; x < names.length; x += 1) {
name = names[x];
if ('secret' === name) {
continue;
} else if ('delete' === ops[name]) {
if (({}).hasOwnProperty.call(c.root[key].obj, name)) {
throw ("Found field which should be deleted: " + name)
}
} else if ('modify' === ops[name]) {
if (! ({}).hasOwnProperty.call(c.root[key].obj, name)) {
throw ("Failed to find field: " + name);
}
if (secret !== c.root[key].obj[name].modified) {
throw ("Found the wrong modified value in field: " + name);
}
} else if ('create' === ops[name]) {
if (! ({}).hasOwnProperty.call(c.root[key].obj, name)) {
throw ("Failed to find field: " + name);
}
if (secret !== c.root[key].obj[name].created) {
throw ("Found the wrong created value in field: " + name);
}
} else {
throw ("Found unknown op: " + ops[name]);
}
}
}
secret = Math.random();
ops = {secret: secret};
for (x = 0; x < 10; x += 1) {
name = Math.round(Math.random() * 100);
op = Math.random();
if (op > 0.9) {
delete c.root[key].obj[name];
ops[name] = 'delete';
} else if (op > 0.4 && undefined !== c.root[key].obj[name]) {
c.root[key].obj[name].modified = secret;
ops[name] = 'modify';
} else {
c.root[key].obj[name] = c.lift({created: secret,
modified: secret});
ops[name] = 'create';
}
}
c.root[key].obj.log = c.lift(ops);
}, function () {
ok(true, "Reached");
n += 1;
if (10 === n) {
semaphore.down();
} else {
fun(c, n);
}
});
};
// We use all but one client, and each of those gets 10
// txns concurrently
for (x = 1; x < clients.length; x += 1) {
clients[x].stm.prefix = "(" + x + "): ";
for (y = 0; y < clientConcurrency; y += 1) {
semaphore.up();
fun(clients[x], 0);
}
}
x = clients[0];
x.atomically(function () {
if (undefined === x.root[key]) {
x.retry();
}
x.root[key].obj = x.lift({});
});
});
});
}());
});
| Some cosmetic, some param tuning, and use a few more objects to ensure the test hits the previously existing bug (test against server revision 42768119819b to provoke bug)
--HG--
extra : signature : gnupg%3AiQEcBAABAgAGBQJPaLaGAAoJEO%2BewIrBgcV35AMIAIEjVhZl0XWfnQBLGfxqQjVPYlOy3g6vDtA5rmJHDua8IlLAeN60ht9V352q52xvl/JbL5XL2cxFzcUvHnU2fYZyY8N5dx9L39KsTeiZeSibcLvXTw1lnUMYDVoNdwfi1/nBiWCvIC%2B7zkC0Nsix11eD9Dimnv%2BbYLpHC3MBGNy8o86Lb06sghbblqYwvPk4wAQArkjCBDdv9MAl4c/qRVbtb/bPrPqkeGtkZ/pf93NmRT6U%2B01UEpOClyQcHkI%2BIRU/3SgT//3qzJ6ZgQd0VbtdxEQ%2B3LLnxN0kWeTje9s43o2V6Mx%2BrX6M2dl8uxpVBjRN496HNfxsaCzJysfeXy0%3D
| test/unittests.js | Some cosmetic, some param tuning, and use a few more objects to ensure the test hits the previously existing bug (test against server revision 42768119819b to provoke bug) | <ide><path>est/unittests.js
<ide> c.retry();
<ide> }
<ide> var keys = Object.keys(c.root[key].obj),
<del> max = 0,
<del> x, field, n, obj;
<add> max = 0,
<add> x, field, n, obj;
<ide> for (x = 0; x < keys.length; x += 1) {
<ide> field = parseInt(keys[x]);
<ide> max = field > max ? field : max;
<ide>
<ide> (function () {
<ide> var clientCount = 6,
<del> clientConcurrency = 5,
<add> clientConcurrency = 6,
<ide> txnCount = 10;
<ide>
<ide> asyncTest("Rampaging Transactions 2 (this takes a while)",
<ide> if (! ({}).hasOwnProperty.call(c.root[key].obj, name)) {
<ide> throw ("Failed to find field: " + name);
<ide> }
<del> if (secret !== c.root[key].obj[name].modified) {
<add> if (secret !== c.root[key].obj[name].modified.value) {
<ide> throw ("Found the wrong modified value in field: " + name);
<ide> }
<ide> } else if ('create' === ops[name]) {
<ide> if (! ({}).hasOwnProperty.call(c.root[key].obj, name)) {
<ide> throw ("Failed to find field: " + name);
<ide> }
<del> if (secret !== c.root[key].obj[name].created) {
<add> if (secret !== c.root[key].obj[name].created.value) {
<ide> throw ("Found the wrong created value in field: " + name);
<ide> }
<ide> } else {
<ide>
<ide> secret = Math.random();
<ide> ops = {secret: secret};
<del> for (x = 0; x < 10; x += 1) {
<del> name = Math.round(Math.random() * 100);
<add> for (x = 0; x < 20; x += 1) {
<add> name = Math.round(Math.random() * 50);
<ide> op = Math.random();
<ide> if (op > 0.9) {
<ide> delete c.root[key].obj[name];
<ide> ops[name] = 'delete';
<del> } else if (op > 0.4 && undefined !== c.root[key].obj[name]) {
<del> c.root[key].obj[name].modified = secret;
<add> } else if (op > 0.1 && ({}).hasOwnProperty.call(c.root[key].obj, name)) {
<add> c.root[key].obj[name].modified.value = secret;
<ide> ops[name] = 'modify';
<ide> } else {
<del> c.root[key].obj[name] = c.lift({created: secret,
<del> modified: secret});
<add> c.root[key].obj[name] = c.lift({});
<add> c.root[key].obj[name].created = c.lift({value: secret});
<add> c.root[key].obj[name].modified = c.lift({value: secret});
<ide> ops[name] = 'create';
<ide> }
<ide> } |
|
Java | apache-2.0 | aa3129a504d6a0bb08031eb29253117da4608bb5 | 0 | boalang/compiler,boalang/compiler,boalang/compiler,boalang/compiler,boalang/compiler | /*
* Copyright 2017, Hridesh Rajan, Ganesha Upadhyaya, Ramanathan Ramu
* and Iowa State University of Science and Technology
*
* 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 boa.functions;
import java.util.*;
import boa.graphs.cfg.CFG;
import boa.types.Ast.Expression;
import boa.types.Ast.Expression.ExpressionKind;
import boa.types.Ast.Method;
import boa.types.Ast.Variable;
import boa.types.Control.CFGNode;
/**
* Boa functions for working with control flow graphs.
*
* @author ganeshau
* @author rramu
*/
public class BoaGraphIntrinsics {
@FunctionSpec(name = "getcfg", returnType = "CFG", formalParameters = { "Method" })
public static CFG getcfg(final Method method) {
final CFG cfg = new CFG(method);
cfg.astToCFG();
return cfg;
}
@FunctionSpec(name = "get_nodes_with_definition", returnType = "set of string", formalParameters = { "CFGNode" })
public static HashSet<String> getNodesWithDefinition(final CFGNode node) {
final HashSet<String> vardef = new HashSet<String>();
if (node.getExpression() != null) {
if (node.getExpression().getKind() == ExpressionKind.VARDECL || node.getExpression().getKind() == ExpressionKind.ASSIGN) {
vardef.add(String.valueOf(node.getId()));
}
}
return vardef;
}
@FunctionSpec(name = "get_variable_killed", returnType = "set of string", formalParameters = {"CFG", "CFGNode" })
public static HashSet<String> getVariableKilled(final boa.types.Control.CFG cfg, final CFGNode node) {
final HashSet<String> varkilled = new HashSet<String>();
String vardef = "";
if (node.getExpression() != null) {
if (node.getExpression().getKind() == ExpressionKind.VARDECL) {
vardef = node.getExpression().getVariableDeclsList().get(0).getName();
}
else if (node.getExpression().getKind() == ExpressionKind.ASSIGN) {
vardef = node.getExpression().getExpressionsList().get(0).getVariable();
}
else {
return varkilled;
}
for (final CFGNode tnode : cfg.getNodesList()) {
if (tnode.getExpression() != null && tnode.getId() != node.getId()) {
if (tnode.getExpression().getKind() == ExpressionKind.VARDECL) {
if (tnode.getExpression().getVariableDeclsList().get(0).getName().equals(vardef)) {
varkilled.add(String.valueOf(tnode.getId()));
}
}
else if (tnode.getExpression().getKind() == ExpressionKind.ASSIGN) {
if (tnode.getExpression().getExpressionsList().get(0).getVariable().equals(vardef)) {
varkilled.add(String.valueOf(tnode.getId()));
}
}
}
}
}
return varkilled;
}
@FunctionSpec(name = "get_variable_def", returnType = "set of string", formalParameters = { "CFGNode" })
public static HashSet<String> getVariableDef(final CFGNode node) {
final HashSet<String> vardef = new HashSet<String>();
if (node.getExpression() != null) {
if (node.getExpression().getKind() == ExpressionKind.VARDECL) {
vardef.add(node.getExpression().getVariableDeclsList().get(0).getName());
}
else if (node.getExpression().getKind() == ExpressionKind.ASSIGN) {
vardef.add(node.getExpression().getExpressionsList().get(0).getVariable());
}
}
return vardef;
}
@FunctionSpec(name = "get_variable_used", returnType = "set of string", formalParameters = { "CFGNode" })
public static HashSet<String> getVariableUsed(final CFGNode node) {
final HashSet<String> varused = new HashSet<String>();
if (node.getExpression() != null) {
traverseExpr(varused,node.getExpression());
}
return varused;
}
public static void traverseExpr(final HashSet<String> varused, final Expression expr) {
if (expr.getVariable() != null) {
varused.add(expr.getVariable());
}
for (final Expression exprs : expr.getExpressionsList()) {
traverseExpr(varused, exprs);
}
for (final Variable vardecls : expr.getVariableDeclsList()) {
traverseVarDecls(varused, vardecls);
}
for (final Expression methodexpr : expr.getMethodArgsList()) {
traverseExpr(varused, methodexpr);
}
}
public static void traverseVarDecls(final HashSet<String> varused, final Variable vardecls) {
if (vardecls.getInitializer() != null) {
traverseExpr(varused, vardecls.getInitializer());
}
}
private static String dotEscape(final String s) {
final String escaped = s.replaceAll("\\\\", "\\\\\\\\").replaceAll("\"", "\\\\\"").replaceAll("\n", "\\\\l").replaceAll("\r", "\\\\l");
if (escaped.indexOf("\\l") != -1 && !escaped.endsWith("\\l"))
return escaped + "\\l";
return escaped;
}
@FunctionSpec(name = "dot", returnType = "string", formalParameters = { "CFG" })
public static String cfgToDot(final CFG cfg) {
final StringBuilder str = new StringBuilder();
str.append("digraph G {\n");
for (final boa.graphs.cfg.CFGNode n : cfg.getNodes()) {
final String shape;
switch (n.getKind()) {
case CONTROL:
shape = "shape=diamond";
break;
case METHOD:
shape = "shape=parallelogram";
break;
case OTHER:
shape = "shape=box";
break;
case ENTRY:
default:
shape = "shape=ellipse";
break;
}
if (n.hasStmt())
str.append("\t" + n.getId() + "[" + shape + ",label=\"" + dotEscape(boa.functions.BoaAstIntrinsics.prettyprint(n.getStmt())) + "\"]\n");
else if (n.hasExpr())
str.append("\t" + n.getId() + "[" + shape + ",label=\"" + dotEscape(boa.functions.BoaAstIntrinsics.prettyprint(n.getExpr())) + "\"]\n");
else if (n.getKind() == boa.types.Control.CFGNode.CFGNodeType.ENTRY)
str.append("\t" + n.getId() + "[" + shape + ",label=\"" + n.getName() + "\"]\n");
else
str.append("\t" + n.getId() + "[" + shape + "]\n");
}
final boa.runtime.BoaAbstractTraversal printGraph = new boa.runtime.BoaAbstractTraversal<Object>(false, false) {
protected Object preTraverse(final boa.graphs.cfg.CFGNode node) throws Exception {
final java.util.Set<boa.graphs.cfg.CFGEdge> edges = node.getOutEdges();
for (final boa.graphs.cfg.CFGEdge e : node.getOutEdges()) {
str.append("\t" + node.getId() + " -> " + e.getDest().getId());
if (!(e.label() == null || e.label().equals(".") || e.label().equals("")))
str.append(" [label=\"" + dotEscape(e.label()) + "\"]");
str.append("\n");
}
return null;
}
@Override
public void traverse(final boa.graphs.cfg.CFGNode node, boolean flag) throws Exception {
if (flag) {
currentResult = preTraverse(node);
outputMapObj.put(node.getId(), currentResult);
} else {
outputMapObj.put(node.getId(), preTraverse(node));
}
}
};
try {
printGraph.traverse(cfg, boa.types.Graph.Traversal.TraversalDirection.FORWARD, boa.types.Graph.Traversal.TraversalKind.DFS);
} catch (final Exception e) {
// do nothing
}
str.append("}");
return str.toString();
}
}
| src/java/boa/functions/BoaGraphIntrinsics.java | /*
* Copyright 2017, Hridesh Rajan, Ganesha Upadhyaya, Ramanathan Ramu
* and Iowa State University of Science and Technology
*
* 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 boa.functions;
import java.util.*;
import boa.graphs.cfg.CFG;
import boa.types.Ast.Expression;
import boa.types.Ast.Expression.ExpressionKind;
import boa.types.Ast.Method;
import boa.types.Ast.Variable;
import boa.types.Control.CFGNode;
/**
* Boa functions for working with control flow graphs.
*
* @author ganeshau
* @author rramu
*/
public class BoaGraphIntrinsics {
@FunctionSpec(name = "getcfg", returnType = "CFG", formalParameters = { "Method" })
public static CFG getcfg(final Method method) {
final CFG cfg = new CFG(method);
cfg.astToCFG();
return cfg;
}
@FunctionSpec(name = "get_nodes_with_definition", returnType = "set of string", formalParameters = { "CFGNode" })
public static HashSet<String> getNodesWithDefinition(final CFGNode node) {
final HashSet<String> vardef = new HashSet<String>();
if (node.getExpression() != null) {
if (node.getExpression().getKind() == ExpressionKind.VARDECL || node.getExpression().getKind() == ExpressionKind.ASSIGN) {
vardef.add(String.valueOf(node.getId()));
}
}
return vardef;
}
@FunctionSpec(name = "get_variable_killed", returnType = "set of string", formalParameters = {"CFG", "CFGNode" })
public static HashSet<String> getVariableKilled(final boa.types.Control.CFG cfg, final CFGNode node) {
final HashSet<String> varkilled = new HashSet<String>();
String vardef = "";
if (node.getExpression() != null) {
if (node.getExpression().getKind() == ExpressionKind.VARDECL) {
vardef = node.getExpression().getVariableDeclsList().get(0).getName();
}
else if (node.getExpression().getKind() == ExpressionKind.ASSIGN) {
vardef = node.getExpression().getExpressionsList().get(0).getVariable();
}
else {
return varkilled;
}
for (final CFGNode tnode : cfg.getNodesList()) {
if (tnode.getExpression() != null && tnode.getId() != node.getId()) {
if (tnode.getExpression().getKind() == ExpressionKind.VARDECL) {
if (tnode.getExpression().getVariableDeclsList().get(0).getName().equals(vardef)) {
varkilled.add(String.valueOf(tnode.getId()));
}
}
else if (tnode.getExpression().getKind() == ExpressionKind.ASSIGN) {
if (tnode.getExpression().getExpressionsList().get(0).getVariable().equals(vardef)) {
varkilled.add(String.valueOf(tnode.getId()));
}
}
}
}
}
return varkilled;
}
@FunctionSpec(name = "get_variable_def", returnType = "set of string", formalParameters = { "CFGNode" })
public static HashSet<String> getVariableDef(final CFGNode node) {
final HashSet<String> vardef = new HashSet<String>();
if (node.getExpression() != null) {
if (node.getExpression().getKind() == ExpressionKind.VARDECL) {
vardef.add(node.getExpression().getVariableDeclsList().get(0).getName());
}
else if (node.getExpression().getKind() == ExpressionKind.ASSIGN) {
vardef.add(node.getExpression().getExpressionsList().get(0).getVariable());
}
}
return vardef;
}
@FunctionSpec(name = "get_variable_used", returnType = "set of string", formalParameters = { "CFGNode" })
public static HashSet<String> getVariableUsed(final CFGNode node) {
final HashSet<String> varused = new HashSet<String>();
if (node.getExpression() != null) {
traverseExpr(varused,node.getExpression());
}
return varused;
}
public static void traverseExpr(final HashSet<String> varused, final Expression expr) {
if (expr.getVariable() != null) {
varused.add(expr.getVariable());
}
for (final Expression exprs : expr.getExpressionsList()) {
traverseExpr(varused, exprs);
}
for (final Variable vardecls : expr.getVariableDeclsList()) {
traverseVarDecls(varused, vardecls);
}
for (final Expression methodexpr : expr.getMethodArgsList()) {
traverseExpr(varused, methodexpr);
}
}
public static void traverseVarDecls(final HashSet<String> varused, final Variable vardecls) {
if (vardecls.getInitializer() != null) {
traverseExpr(varused, vardecls.getInitializer());
}
}
public static String cfgToDot(final CFG cfg) {
final StringBuilder str = new StringBuilder();
str.append("digraph G {\n");
final boa.runtime.BoaAbstractTraversal printGraph = new boa.runtime.BoaAbstractTraversal<Object>(false, false) {
protected Object preTraverse(final boa.graphs.cfg.CFGNode node) throws Exception {
final java.util.List<boa.graphs.cfg.CFGNode> succs = node .getSuccessorsList();
for (long i = 0; i < succs .size(); i++) {
if ((succs.get((int)(i)) != null)) {
str.append("\t" + node.getId() + " -> " + succs.get((int)(i)).getId() + "\n");
}
}
return null;
}
@Override
public void traverse(final boa.graphs.cfg.CFGNode node, boolean flag) throws Exception {
if (flag) {
currentResult = preTraverse(node);
outputMapObj.put(node.getId(), currentResult);
} else {
outputMapObj.put(node.getId(), preTraverse(node));
}
}
};
try {
printGraph.traverse(cfg, boa.types.Graph.Traversal.TraversalDirection.FORWARD, boa.types.Graph.Traversal.TraversalKind.DFS);
} catch (final Exception e) {
// do nothing
}
str.append("}");
return str.toString();
}
}
| add node/edge labels to dot() output
| src/java/boa/functions/BoaGraphIntrinsics.java | add node/edge labels to dot() output | <ide><path>rc/java/boa/functions/BoaGraphIntrinsics.java
<ide> }
<ide> }
<ide>
<add> private static String dotEscape(final String s) {
<add> final String escaped = s.replaceAll("\\\\", "\\\\\\\\").replaceAll("\"", "\\\\\"").replaceAll("\n", "\\\\l").replaceAll("\r", "\\\\l");
<add> if (escaped.indexOf("\\l") != -1 && !escaped.endsWith("\\l"))
<add> return escaped + "\\l";
<add> return escaped;
<add> }
<add>
<add> @FunctionSpec(name = "dot", returnType = "string", formalParameters = { "CFG" })
<ide> public static String cfgToDot(final CFG cfg) {
<ide> final StringBuilder str = new StringBuilder();
<ide> str.append("digraph G {\n");
<ide>
<add> for (final boa.graphs.cfg.CFGNode n : cfg.getNodes()) {
<add> final String shape;
<add> switch (n.getKind()) {
<add> case CONTROL:
<add> shape = "shape=diamond";
<add> break;
<add> case METHOD:
<add> shape = "shape=parallelogram";
<add> break;
<add> case OTHER:
<add> shape = "shape=box";
<add> break;
<add> case ENTRY:
<add> default:
<add> shape = "shape=ellipse";
<add> break;
<add> }
<add>
<add> if (n.hasStmt())
<add> str.append("\t" + n.getId() + "[" + shape + ",label=\"" + dotEscape(boa.functions.BoaAstIntrinsics.prettyprint(n.getStmt())) + "\"]\n");
<add> else if (n.hasExpr())
<add> str.append("\t" + n.getId() + "[" + shape + ",label=\"" + dotEscape(boa.functions.BoaAstIntrinsics.prettyprint(n.getExpr())) + "\"]\n");
<add> else if (n.getKind() == boa.types.Control.CFGNode.CFGNodeType.ENTRY)
<add> str.append("\t" + n.getId() + "[" + shape + ",label=\"" + n.getName() + "\"]\n");
<add> else
<add> str.append("\t" + n.getId() + "[" + shape + "]\n");
<add> }
<add>
<ide> final boa.runtime.BoaAbstractTraversal printGraph = new boa.runtime.BoaAbstractTraversal<Object>(false, false) {
<ide> protected Object preTraverse(final boa.graphs.cfg.CFGNode node) throws Exception {
<del> final java.util.List<boa.graphs.cfg.CFGNode> succs = node .getSuccessorsList();
<del> for (long i = 0; i < succs .size(); i++) {
<del> if ((succs.get((int)(i)) != null)) {
<del> str.append("\t" + node.getId() + " -> " + succs.get((int)(i)).getId() + "\n");
<del> }
<add> final java.util.Set<boa.graphs.cfg.CFGEdge> edges = node.getOutEdges();
<add> for (final boa.graphs.cfg.CFGEdge e : node.getOutEdges()) {
<add> str.append("\t" + node.getId() + " -> " + e.getDest().getId());
<add> if (!(e.label() == null || e.label().equals(".") || e.label().equals("")))
<add> str.append(" [label=\"" + dotEscape(e.label()) + "\"]");
<add> str.append("\n");
<ide> }
<ide> return null;
<ide> } |
|
Java | mit | 2197fae2c1de5846c324f90aeb04f7548442bfb8 | 0 | iBotPeaches/SimpleServer,iBotPeaches/SimpleServer,SimpleServer/SimpleServer,SimpleServer/SimpleServer | /*
* Copyright (c) 2010 SimpleServer authors (see CONTRIBUTORS)
*
* 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 simpleserver.stream;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.IllegalFormatException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import simpleserver.Coordinate;
import simpleserver.Group;
import simpleserver.Player;
import simpleserver.Server;
import simpleserver.command.LocalSayCommand;
import simpleserver.command.PlayerListCommand;
import simpleserver.config.ChestList.Chest;
public class StreamTunnel {
private static final boolean EXPENSIVE_DEBUG_LOGGING = Boolean.getBoolean("EXPENSIVE_DEBUG_LOGGING");
private static final int IDLE_TIME = 30000;
private static final int BUFFER_SIZE = 1024;
private static final byte BLOCK_DESTROYED_STATUS = 2;
private static final Pattern MESSAGE_PATTERN = Pattern.compile("^<([^>]+)> (.*)$");
private static final Pattern COLOR_PATTERN = Pattern.compile("\u00a7[0-9a-f]");
private final boolean isServerTunnel;
private final String streamType;
private final Player player;
private final Server server;
private final byte[] buffer;
private final Tunneler tunneler;
private DataInput in;
private DataOutput out;
private StreamDumper inputDumper;
private StreamDumper outputDumper;
private int motionCounter = 0;
private boolean inGame = false;
private volatile long lastRead;
private volatile boolean run = true;
public StreamTunnel(InputStream in, OutputStream out, boolean isServerTunnel,
Player player) {
this.isServerTunnel = isServerTunnel;
if (isServerTunnel) {
streamType = "ServerStream";
}
else {
streamType = "PlayerStream";
}
this.player = player;
server = player.getServer();
DataInputStream dIn = new DataInputStream(new BufferedInputStream(in));
DataOutputStream dOut = new DataOutputStream(new BufferedOutputStream(out));
if (EXPENSIVE_DEBUG_LOGGING) {
try {
OutputStream dump = new FileOutputStream(streamType + "Input.debug");
InputStreamDumper dumper = new InputStreamDumper(dIn, dump);
inputDumper = dumper;
this.in = dumper;
}
catch (FileNotFoundException e) {
System.out.println("Unable to open input debug dump!");
throw new RuntimeException(e);
}
try {
OutputStream dump = new FileOutputStream(streamType + "Output.debug");
OutputStreamDumper dumper = new OutputStreamDumper(dOut, dump);
outputDumper = dumper;
this.out = dumper;
}
catch (FileNotFoundException e) {
System.out.println("Unable to open output debug dump!");
throw new RuntimeException(e);
}
}
else {
this.in = dIn;
this.out = dOut;
}
buffer = new byte[BUFFER_SIZE];
tunneler = new Tunneler();
tunneler.start();
lastRead = System.currentTimeMillis();
}
public void stop() {
run = false;
}
public boolean isAlive() {
return tunneler.isAlive();
}
public boolean isActive() {
return System.currentTimeMillis() - lastRead < IDLE_TIME
|| player.isRobot();
}
private void handlePacket() throws IOException {
Byte packetId = in.readByte();
int x;
byte y;
int z;
switch (packetId) {
case 0x00: // Keep Alive
write(packetId);
break;
case 0x01: // Login Request/Response
write(packetId);
if (isServerTunnel) {
player.setEntityId(in.readInt());
write(player.getEntityId());
}
else {
write(in.readInt());
}
write(readUTF16());
write(in.readLong());
write(in.readByte());
break;
case 0x02: // Handshake
String name = readUTF16();
if (isServerTunnel || player.setName(name)) {
tunneler.setName(streamType + "-" + player.getName());
write(packetId);
write(name);
}
break;
case 0x03: // Chat Message
String message = readUTF16();
System.out.println(message);
if (isServerTunnel && server.options.getBoolean("useMsgFormats")) {
Matcher colorMatcher = COLOR_PATTERN.matcher(message);
String cleanMessage = colorMatcher.replaceAll("");
Matcher messageMatcher = MESSAGE_PATTERN.matcher(cleanMessage);
if (messageMatcher.find()) {
Player friend = server.findPlayerExact(messageMatcher.group(1));
if (friend != null) {
String color = "f";
String title = "";
String format = server.options.get("msgFormat");
Group group = friend.getGroup();
if (group != null) {
color = group.getColor();
if (group.showTitle()) {
title = group.getName();
format = server.options.get("msgTitleFormat");
}
}
try {
message = String.format(format, friend.getName(), title, color)
+ messageMatcher.group(2);
}
catch (IllegalFormatException e) {
System.out.println("[SimpleServer] There is an error in your msgFormat/msgTitleFormat settings!");
}
}
}
}
if (!isServerTunnel) {
if (player.isMuted() && !message.startsWith("/")
&& !message.startsWith("!")) {
player.addMessage("\u00a7cYou are muted! You may not send messages to all players.");
break;
}
if (player.parseCommand(message)) {
break;
}
if(player.localChat() && !message.startsWith("/") && !message.startsWith("!")) {
player.execute(LocalSayCommand.class, message);
break;
}
}
write(packetId);
write(message);
break;
case 0x04: // Time Update
write(packetId);
copyNBytes(8);
break;
case 0x05: // Player Inventory
write(packetId);
write(in.readInt());
write(in.readShort());
write(in.readShort());
write(in.readShort());
break;
case 0x06: // Spawn Position
write(packetId);
copyNBytes(12);
break;
case 0x07: // Use Entity?
int user = in.readInt();
int target = in.readInt();
Player targetPlayer = server.playerList.findPlayer(target);
if (targetPlayer != null) {
if (targetPlayer.godModeEnabled()) {
in.readBoolean();
break;
}
}
write(packetId);
write(user);
write(target);
write(in.readBoolean());
break;
case 0x08: // Update Health
write(packetId);
copyNBytes(2);
break;
case 0x09: // Respawn
write(packetId);
break;
case 0x0a: // Player
write(packetId);
copyNBytes(1);
if (!inGame && !isServerTunnel) {
player.sendMOTD();
if(server.options.getBoolean("showListOnConnect")){
//display player list if enabled in config
player.execute(PlayerListCommand.class);
}
inGame = true;
}
break;
case 0x0b: // Player Position
write(packetId);
copyPlayerLocation();
break;
case 0x0c: // Player Look
write(packetId);
copyNBytes(9);
break;
case 0x0d: // Player Position & Look
write(packetId);
copyPlayerLocation();
copyNBytes(8);
break;
case 0x0e: // Player Digging
if (!isServerTunnel) {
if (player.getGroupId() < 0) {
skipNBytes(11);
}
else {
byte status = in.readByte();
x = in.readInt();
y = in.readByte();
z = in.readInt();
byte face = in.readByte();
if (!server.chests.isLocked(x, y, z) || player.isAdmin()) {
if (server.chests.isLocked(x, y, z)
&& status == BLOCK_DESTROYED_STATUS) {
server.chests.releaseLock(x, y, z);
}
write(packetId);
write(status);
write(x);
write(y);
write(z);
write(face);
if (player.instantDestroyEnabled()) {
packetFinished();
write(packetId);
write(BLOCK_DESTROYED_STATUS);
write(x);
write(y);
write(z);
write(face);
}
if(status == BLOCK_DESTROYED_STATUS) {
player.destroyedBlock();
}
}
}
}
else {
write(packetId);
copyNBytes(11);
}
break;
case 0x0f: // Player Block Placement
x = in.readInt();
y = in.readByte();
z = in.readInt();
final byte direction = in.readByte();
final short dropItem = in.readShort();
byte itemCount = 0;
short uses = 0;
if (dropItem != -1) {
itemCount = in.readByte();
uses = in.readShort();
}
boolean writePacket = true;
boolean drop = false;
if (isServerTunnel || server.chests.isChest(x, y, z)) {
// continue
} else if ((player.getGroupId() < 0) || !server.blockFirewall.playerAllowed(player, dropItem)) {
String badBlock = String.format(server.l.get("BAD_BLOCK"), player.getName(), Short.toString(dropItem));
server.runCommand("say", badBlock);
writePacket = false;
drop = true;
} else if (dropItem == 54) {
int xPosition = x;
byte yPosition = y;
int zPosition = z;
switch (direction) {
case 0:
--yPosition;
break;
case 1:
++yPosition;
break;
case 2:
--zPosition;
break;
case 3:
++zPosition;
break;
case 4:
--xPosition;
break;
case 5:
++xPosition;
break;
}
Chest adjacentChest = server.chests.adjacentChest(xPosition, yPosition, zPosition);
if (adjacentChest != null && !adjacentChest.isOpen() && !adjacentChest.ownedBy(player)) {
player.addMessage("\u00a7cThe adjacent chest is locked!");
writePacket = false;
drop = true;
} else {
player.placingChest(new Coordinate(xPosition, yPosition, zPosition));
}
}
if (writePacket) {
write(packetId);
write(x);
write(y);
write(z);
write(direction);
write(dropItem);
if (dropItem != -1) {
write(itemCount);
write(uses);
if(dropItem <= 94 && direction >= 0) {
player.placedBlock();
}
}
player.openingChest(x,y,z);
}
else if(drop) {
// Drop the item in hand. This keeps the client state in-sync with the
// server. This generally prevents empty-hand clicks by the client
// from placing blocks the server thinks the client has in hand.
write((byte) 0x0e);
write((byte) 0x04);
write(x);
write(y);
write(z);
write(direction);
}
break;
case 0x10: // Holding Change
write(packetId);
copyNBytes(2);
break;
case 0x11: // Use Bed
write(packetId);
copyNBytes(14);
break;
case 0x12: // Animation
write(packetId);
copyNBytes(5);
break;
case 0x13: // ???
write(packetId);
write(in.readInt());
write(in.readByte());
break;
case 0x14: // Named Entity Spawn
write(packetId);
write(in.readInt());
write(readUTF16());
copyNBytes(16);
break;
case 0x15: // Pickup spawn
if (player.getGroupId() < 0) {
skipNBytes(24);
break;
}
write(packetId);
copyNBytes(24);
break;
case 0x16: // Collect Item
write(packetId);
copyNBytes(8);
break;
case 0x17: // Add Object/Vehicle
write(packetId);
copyNBytes(17);
break;
case 0x18: // Mob Spawn
write(packetId);
write(in.readInt());
write(in.readByte());
write(in.readInt());
write(in.readInt());
write(in.readInt());
write(in.readByte());
write(in.readByte());
copyUnknownBlob();
break;
case 0x19: // Painting
write(packetId);
write(in.readInt());
write(readUTF16());
write(in.readInt());
write(in.readInt());
write(in.readInt());
write(in.readInt());
break;
case 0x1b: // ???
write(packetId);
copyNBytes(18);
break;
case 0x1c: // Entity Velocity?
write(packetId);
copyNBytes(10);
break;
case 0x1d: // Destroy Entity
write(packetId);
copyNBytes(4);
break;
case 0x1e: // Entity
write(packetId);
copyNBytes(4);
break;
case 0x1f: // Entity Relative Move
write(packetId);
copyNBytes(7);
break;
case 0x20: // Entity Look
write(packetId);
copyNBytes(6);
break;
case 0x21: // Entity Look and Relative Move
write(packetId);
copyNBytes(9);
break;
case 0x22: // Entity Teleport
write(packetId);
copyNBytes(18);
break;
case 0x26: // Entity status?
write(packetId);
copyNBytes(5);
break;
case 0x27: // Attach Entity?
write(packetId);
copyNBytes(8);
break;
case 0x28: // Entity Metadata
write(packetId);
write(in.readInt());
copyUnknownBlob();
break;
case 0x32: // Pre-Chunk
write(packetId);
copyNBytes(9);
break;
case 0x33: // Map Chunk
write(packetId);
copyNBytes(13);
int chunkSize = in.readInt();
write(chunkSize);
copyNBytes(chunkSize);
break;
case 0x34: // Multi Block Change
write(packetId);
copyNBytes(8);
short arraySize = in.readShort();
write(arraySize);
copyNBytes(arraySize * 4);
break;
case 0x35: // Block Change
write(packetId);
x = in.readInt();
y = in.readByte();
z = in.readInt();
byte blockType = in.readByte();
byte metadata = in.readByte();
if(blockType == 54 && player.placedChest(x,y,z)) {
lockChest(x,y,z);
player.placingChest(null);
}
write(x);
write(y);
write(z);
write(blockType);
write(metadata);
break;
case 0x36: // ???
write(packetId);
copyNBytes(12);
break;
case 0x3c: // Explosion
write(packetId);
copyNBytes(28);
int recordCount = in.readInt();
write(recordCount);
copyNBytes(recordCount * 3);
break;
case 0x46: // Invalid Bed
write(packetId);
copyNBytes(1);
break;
case 0x47: // Weather
write(packetId);
copyNBytes(17);
break;
case 0x64:
byte id = in.readByte();
byte invtype = in.readByte();
String typeString = in.readUTF();
if(invtype == 0) {
if(server.chests.canOpen(player, player.openedChest()) || player.isAdmin()) {
if(server.chests.isLocked(player.openedChest())) {
if(player.isAttemptingUnlock()) {
server.chests.unlock(player.openedChest());
player.setAttemptedAction(null);
player.addMessage("\u00a77This chest is no longer locked!");
typeString = "Open Chest";
} else {
typeString = server.chests.chestName(player.openedChest());
}
} else {
typeString = "Open Chest";
if(player.isAttemptLock()) {
lockChest(player.openedChest());
typeString = player.nextChestName();
}
}
} else {
player.addMessage("\u00a7cThis chest is locked!");
in.readByte();
break;
}
}
write(packetId);
write(id);
write(invtype);
write8(typeString);
write(in.readByte());
break;
case 0x65:
write(packetId);
write(in.readByte());
break;
case 0x66: // Inventory Item Move
byte typeFrom = in.readByte();
short slotFrom = in.readShort();
byte typeTo = in.readByte();
short slotTo = in.readShort();
if ((typeFrom < 0 && typeTo < 0) || player.getGroupId() >= 0) {
write(packetId);
write(typeFrom);
write(slotFrom);
write(typeTo);
write(slotTo);
write(in.readBoolean());
short moveItem = in.readShort();
write(moveItem);
if (moveItem != -1) {
write(in.readByte());
write(in.readShort());
}
}
else {
short moveItem = in.readShort();
if (moveItem != -1) {
in.readByte();
in.readShort();
}
}
break;
case 0x67: // Inventory Item Update
byte type67 = in.readByte();
if (type67 < 0 || player.getGroupId() >= 0) {
write(packetId);
short slot = in.readShort();
write(type67);
write(slot);
short setItem = in.readShort();
write(setItem);
if (setItem != -1) {
write(in.readByte());
write(in.readShort());
}
}
else {
in.readShort();
short setItem = in.readShort();
if (setItem != -1) {
in.readByte();
in.readShort();
}
}
break;
case 0x68: // Inventory
byte type = in.readByte();
if (type < 0 || player.getGroupId() >= 0) {
write(packetId);
write(type);
short count = in.readShort();
write(count);
for (int c = 0; c < count; ++c) {
short item = in.readShort();
write(item);
if (item != -1) {
write(in.readByte());
write(in.readShort());
}
}
}
else {
short count = in.readShort();
for (int c = 0; c < count; ++c) {
short item = in.readShort();
if (item != -1) {
in.readByte();
in.readShort();
}
}
}
break;
case 0x69:
write(packetId);
write(in.readByte());
write(in.readShort());
write(in.readShort());
break;
case 0x6a:
write(packetId);
write(in.readByte());
write(in.readShort());
write(in.readByte());
break;
case (byte) 0x82: // Update Sign
write(packetId);
write(in.readInt());
write(in.readShort());
write(in.readInt());
write(readUTF16());
write(readUTF16());
write(readUTF16());
write(readUTF16());
break;
case (byte)0xc6:
write(packetId);
copyNBytes(5);
break;
case (byte) 0xff: // Disconnect/Kick
write(packetId);
String reason = readUTF16();
write(reason);
if (reason.startsWith("Took too long")) {
server.addRobot(player);
}
player.close();
break;
default:
if (EXPENSIVE_DEBUG_LOGGING) {
while (true) {
skipNBytes(1);
flushAll();
}
}
else {
throw new IOException("Unable to parse unknown " + streamType
+ " packet 0x" + Integer.toHexString(packetId) + " for player "
+ player.getName());
}
}
packetFinished();
}
private String readUTF16() throws IOException {
short length = in.readShort();
byte[] bytes = new byte[2+length*2];
bytes[0] = (byte)((length>>8)&0xFF);
bytes[1] = (byte)(length&0xFF);
for(short i = 0; i < length*2; i++) {
bytes[i+2] = in.readByte();
}
try {
String result = new String(bytes, "UTF-16");
return result;
} catch(Exception e) {
return "FUUUUU";
}
}
private void print(byte[] bytes) {
for(int i=0; i<bytes.length; i++) {
System.out.print(Integer.toHexString(bytes[i]) + " ");
}
System.out.println();
}
private void lockChest(Coordinate coords) {
lockChest(coords.x, coords.y, coords.z);
}
private void lockChest(int x, byte y, int z) {
Chest adjacentChest = server.chests.adjacentChest(x, y, z);
if(player.isAttemptLock() || adjacentChest != null && !adjacentChest.isOpen()) {
if(adjacentChest != null && !adjacentChest.isOpen()) {
server.chests.giveLock(adjacentChest.owner(), x, y, z, false, adjacentChest.name());
} else {
if(adjacentChest != null) {
adjacentChest.lock(player);
adjacentChest.rename(player.nextChestName());
}
server.chests.giveLock(player, x, y, z, false, player.nextChestName());
}
player.setAttemptedAction(null);
player.addMessage("\u00a77This chest is now locked.");
} else if(!server.chests.isChest(x, y, z)){
server.chests.addOpenChest(x, y, z);
}
}
private void copyPlayerLocation() throws IOException {
if (!isServerTunnel) {
motionCounter++;
}
if (!isServerTunnel && motionCounter % 8 == 0) {
double x = in.readDouble();
double y = in.readDouble();
double stance = in.readDouble();
double z = in.readDouble();
player.updateLocation(x, y, z, stance);
write(x);
write(y);
write(stance);
write(z);
copyNBytes(1);
}
else {
copyNBytes(33);
}
}
private void copyUnknownBlob() throws IOException {
byte unknown = in.readByte();
write(unknown);
while (unknown != 0x7f) {
int type = (unknown & 0xE0) >> 5;
switch (type) {
case 0:
write(in.readByte());
break;
case 1:
write(in.readShort());
break;
case 2:
write(in.readInt());
break;
case 3:
write(in.readFloat());
break;
case 4:
write(readUTF16());
break;
case 5:
write(in.readShort());
write(in.readByte());
write(in.readShort());
}
unknown = in.readByte();
write(unknown);
}
}
private void write(byte b) throws IOException {
out.writeByte(b);
}
private void write(short s) throws IOException {
out.writeShort(s);
}
private void write(int i) throws IOException {
out.writeInt(i);
}
private void write(long l) throws IOException {
out.writeLong(l);
}
private void write(float f) throws IOException {
out.writeFloat(f);
}
private void write(double d) throws IOException {
out.writeDouble(d);
}
private void write(String s) throws IOException {
byte[] bytes = s.getBytes("UTF-16");
for(int i = 2; i < bytes.length; i++) {
write(bytes[i]);
}
}
private void write8(String s) throws IOException {
out.writeUTF(s);
}
private void write(boolean b) throws IOException {
out.writeBoolean(b);
}
private void skipNBytes(int bytes) throws IOException {
int overflow = bytes / buffer.length;
for (int c = 0; c < overflow; ++c) {
in.readFully(buffer, 0, buffer.length);
}
in.readFully(buffer, 0, bytes % buffer.length);
}
private void copyNBytes(int bytes) throws IOException {
int overflow = bytes / buffer.length;
for (int c = 0; c < overflow; ++c) {
in.readFully(buffer, 0, buffer.length);
out.write(buffer, 0, buffer.length);
}
in.readFully(buffer, 0, bytes % buffer.length);
out.write(buffer, 0, bytes % buffer.length);
}
private void kick(String reason) throws IOException {
write((byte) 0xff);
write(reason);
packetFinished();
}
private void sendMessage(String message) throws IOException {
//write(0x03);
//write(message);
//packetFinished();
}
private void packetFinished() throws IOException {
if (EXPENSIVE_DEBUG_LOGGING) {
inputDumper.packetFinished();
outputDumper.packetFinished();
}
}
private void flushAll() throws IOException {
try {
((OutputStream) out).flush();
}
finally {
if (EXPENSIVE_DEBUG_LOGGING) {
inputDumper.flush();
}
}
}
private final class Tunneler extends Thread {
@Override
public void run() {
try {
while (run) {
lastRead = System.currentTimeMillis();
try {
handlePacket();
if (isServerTunnel) {
while (player.hasMessages()) {
sendMessage(player.getMessage());
}
}
flushAll();
}
catch (IOException e) {
if (run && !player.isRobot()) {
System.out.println("[SimpleServer] " + e);
System.out.println("[SimpleServer] " + streamType
+ " error handling traffic for " + player.getIPAddress());
e.printStackTrace();
}
break;
}
}
try {
if (player.isKicked()) {
kick(player.getKickMsg());
}
flushAll();
}
catch (IOException e) {
}
}
finally {
if (EXPENSIVE_DEBUG_LOGGING) {
inputDumper.cleanup();
outputDumper.cleanup();
}
}
}
}
}
| src/simpleserver/stream/StreamTunnel.java | /*
* Copyright (c) 2010 SimpleServer authors (see CONTRIBUTORS)
*
* 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 simpleserver.stream;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.IllegalFormatException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import simpleserver.Coordinate;
import simpleserver.Group;
import simpleserver.Player;
import simpleserver.Server;
import simpleserver.command.LocalSayCommand;
import simpleserver.command.PlayerListCommand;
import simpleserver.config.ChestList.Chest;
public class StreamTunnel {
private static final boolean EXPENSIVE_DEBUG_LOGGING = Boolean.getBoolean("EXPENSIVE_DEBUG_LOGGING");
private static final int IDLE_TIME = 30000;
private static final int BUFFER_SIZE = 1024;
private static final byte BLOCK_DESTROYED_STATUS = 2;
private static final Pattern MESSAGE_PATTERN = Pattern.compile("^<([^>]+)> (.*)$");
private static final Pattern COLOR_PATTERN = Pattern.compile("\u00a7[0-9a-f]");
private final boolean isServerTunnel;
private final String streamType;
private final Player player;
private final Server server;
private final byte[] buffer;
private final Tunneler tunneler;
private DataInput in;
private DataOutput out;
private StreamDumper inputDumper;
private StreamDumper outputDumper;
private int motionCounter = 0;
private boolean inGame = false;
private volatile long lastRead;
private volatile boolean run = true;
public StreamTunnel(InputStream in, OutputStream out, boolean isServerTunnel,
Player player) {
this.isServerTunnel = isServerTunnel;
if (isServerTunnel) {
streamType = "ServerStream";
}
else {
streamType = "PlayerStream";
}
this.player = player;
server = player.getServer();
DataInputStream dIn = new DataInputStream(new BufferedInputStream(in));
DataOutputStream dOut = new DataOutputStream(new BufferedOutputStream(out));
if (EXPENSIVE_DEBUG_LOGGING) {
try {
OutputStream dump = new FileOutputStream(streamType + "Input.debug");
InputStreamDumper dumper = new InputStreamDumper(dIn, dump);
inputDumper = dumper;
this.in = dumper;
}
catch (FileNotFoundException e) {
System.out.println("Unable to open input debug dump!");
throw new RuntimeException(e);
}
try {
OutputStream dump = new FileOutputStream(streamType + "Output.debug");
OutputStreamDumper dumper = new OutputStreamDumper(dOut, dump);
outputDumper = dumper;
this.out = dumper;
}
catch (FileNotFoundException e) {
System.out.println("Unable to open output debug dump!");
throw new RuntimeException(e);
}
}
else {
this.in = dIn;
this.out = dOut;
}
buffer = new byte[BUFFER_SIZE];
tunneler = new Tunneler();
tunneler.start();
lastRead = System.currentTimeMillis();
}
public void stop() {
run = false;
}
public boolean isAlive() {
return tunneler.isAlive();
}
public boolean isActive() {
return System.currentTimeMillis() - lastRead < IDLE_TIME
|| player.isRobot();
}
private void handlePacket() throws IOException {
Byte packetId = in.readByte();
int x;
byte y;
int z;
switch (packetId) {
case 0x00: // Keep Alive
write(packetId);
break;
case 0x01: // Login Request/Response
write(packetId);
if (isServerTunnel) {
player.setEntityId(in.readInt());
write(player.getEntityId());
}
else {
write(in.readInt());
}
write(in.readUTF());
write(in.readUTF());
write(in.readLong());
write(in.readByte());
break;
case 0x02: // Handshake
String name = in.readUTF();
if (isServerTunnel || player.setName(name)) {
tunneler.setName(streamType + "-" + player.getName());
write(packetId);
write(name);
}
break;
case 0x03: // Chat Message
String message = in.readUTF();
if (isServerTunnel && server.options.getBoolean("useMsgFormats")) {
Matcher colorMatcher = COLOR_PATTERN.matcher(message);
String cleanMessage = colorMatcher.replaceAll("");
Matcher messageMatcher = MESSAGE_PATTERN.matcher(cleanMessage);
if (messageMatcher.find()) {
Player friend = server.findPlayerExact(messageMatcher.group(1));
if (friend != null) {
String color = "f";
String title = "";
String format = server.options.get("msgFormat");
Group group = friend.getGroup();
if (group != null) {
color = group.getColor();
if (group.showTitle()) {
title = group.getName();
format = server.options.get("msgTitleFormat");
}
}
try {
message = String.format(format, friend.getName(), title, color)
+ messageMatcher.group(2);
}
catch (IllegalFormatException e) {
System.out.println("[SimpleServer] There is an error in your msgFormat/msgTitleFormat settings!");
}
}
}
}
if (!isServerTunnel) {
if (player.isMuted() && !message.startsWith("/")
&& !message.startsWith("!")) {
player.addMessage("\u00a7cYou are muted! You may not send messages to all players.");
break;
}
if (player.parseCommand(message)) {
break;
}
if(player.localChat() && !message.startsWith("/") && !message.startsWith("!")) {
player.execute(LocalSayCommand.class, message);
break;
}
}
write(packetId);
write(message);
break;
case 0x04: // Time Update
write(packetId);
copyNBytes(8);
break;
case 0x05: // Player Inventory
write(packetId);
write(in.readInt());
write(in.readShort());
write(in.readShort());
write(in.readShort());
break;
case 0x06: // Spawn Position
write(packetId);
copyNBytes(12);
break;
case 0x07: // Use Entity?
int user = in.readInt();
int target = in.readInt();
Player targetPlayer = server.playerList.findPlayer(target);
if (targetPlayer != null) {
if (targetPlayer.godModeEnabled()) {
in.readBoolean();
break;
}
}
write(packetId);
write(user);
write(target);
write(in.readBoolean());
break;
case 0x08: // Update Health
write(packetId);
copyNBytes(2);
break;
case 0x09: // Respawn
write(packetId);
break;
case 0x0a: // Player
write(packetId);
copyNBytes(1);
if (!inGame && !isServerTunnel) {
player.sendMOTD();
if(server.options.getBoolean("showListOnConnect")){
//display player list if enabled in config
player.execute(PlayerListCommand.class);
}
inGame = true;
}
break;
case 0x0b: // Player Position
write(packetId);
copyPlayerLocation();
break;
case 0x0c: // Player Look
write(packetId);
copyNBytes(9);
break;
case 0x0d: // Player Position & Look
write(packetId);
copyPlayerLocation();
copyNBytes(8);
break;
case 0x0e: // Player Digging
if (!isServerTunnel) {
if (player.getGroupId() < 0) {
skipNBytes(11);
}
else {
byte status = in.readByte();
x = in.readInt();
y = in.readByte();
z = in.readInt();
byte face = in.readByte();
if (!server.chests.isLocked(x, y, z) || player.isAdmin()) {
if (server.chests.isLocked(x, y, z)
&& status == BLOCK_DESTROYED_STATUS) {
server.chests.releaseLock(x, y, z);
}
write(packetId);
write(status);
write(x);
write(y);
write(z);
write(face);
if (player.instantDestroyEnabled()) {
packetFinished();
write(packetId);
write(BLOCK_DESTROYED_STATUS);
write(x);
write(y);
write(z);
write(face);
}
if(status == BLOCK_DESTROYED_STATUS) {
player.destroyedBlock();
}
}
}
}
else {
write(packetId);
copyNBytes(11);
}
break;
case 0x0f: // Player Block Placement
x = in.readInt();
y = in.readByte();
z = in.readInt();
final byte direction = in.readByte();
final short dropItem = in.readShort();
byte itemCount = 0;
short uses = 0;
if (dropItem != -1) {
itemCount = in.readByte();
uses = in.readShort();
}
boolean writePacket = true;
boolean drop = false;
if (isServerTunnel || server.chests.isChest(x, y, z)) {
// continue
} else if ((player.getGroupId() < 0) || !server.blockFirewall.playerAllowed(player, dropItem)) {
String badBlock = String.format(server.l.get("BAD_BLOCK"), player.getName(), Short.toString(dropItem));
server.runCommand("say", badBlock);
writePacket = false;
drop = true;
} else if (dropItem == 54) {
int xPosition = x;
byte yPosition = y;
int zPosition = z;
switch (direction) {
case 0:
--yPosition;
break;
case 1:
++yPosition;
break;
case 2:
--zPosition;
break;
case 3:
++zPosition;
break;
case 4:
--xPosition;
break;
case 5:
++xPosition;
break;
}
Chest adjacentChest = server.chests.adjacentChest(xPosition, yPosition, zPosition);
if (adjacentChest != null && !adjacentChest.isOpen() && !adjacentChest.ownedBy(player)) {
player.addMessage("\u00a7cThe adjacent chest is locked!");
writePacket = false;
drop = true;
} else {
player.placingChest(new Coordinate(xPosition, yPosition, zPosition));
}
}
if (writePacket) {
write(packetId);
write(x);
write(y);
write(z);
write(direction);
write(dropItem);
if (dropItem != -1) {
write(itemCount);
write(uses);
if(dropItem <= 94 && direction >= 0) {
player.placedBlock();
}
}
player.openingChest(x,y,z);
}
else if(drop) {
// Drop the item in hand. This keeps the client state in-sync with the
// server. This generally prevents empty-hand clicks by the client
// from placing blocks the server thinks the client has in hand.
write((byte) 0x0e);
write((byte) 0x04);
write(x);
write(y);
write(z);
write(direction);
}
break;
case 0x10: // Holding Change
write(packetId);
copyNBytes(2);
break;
case 0x11: // Use Bed
write(packetId);
copyNBytes(14);
break;
case 0x12: // Animation
write(packetId);
copyNBytes(5);
break;
case 0x13: // ???
write(packetId);
write(in.readInt());
write(in.readByte());
break;
case 0x14: // Named Entity Spawn
write(packetId);
write(in.readInt());
write(in.readUTF());
copyNBytes(16);
break;
case 0x15: // Pickup spawn
if (player.getGroupId() < 0) {
skipNBytes(24);
break;
}
write(packetId);
copyNBytes(24);
break;
case 0x16: // Collect Item
write(packetId);
copyNBytes(8);
break;
case 0x17: // Add Object/Vehicle
write(packetId);
copyNBytes(17);
break;
case 0x18: // Mob Spawn
write(packetId);
write(in.readInt());
write(in.readByte());
write(in.readInt());
write(in.readInt());
write(in.readInt());
write(in.readByte());
write(in.readByte());
copyUnknownBlob();
break;
case 0x19: // Painting
write(packetId);
write(in.readInt());
write(in.readUTF());
write(in.readInt());
write(in.readInt());
write(in.readInt());
write(in.readInt());
break;
case 0x1b: // ???
write(packetId);
copyNBytes(18);
break;
case 0x1c: // Entity Velocity?
write(packetId);
copyNBytes(10);
break;
case 0x1d: // Destroy Entity
write(packetId);
copyNBytes(4);
break;
case 0x1e: // Entity
write(packetId);
copyNBytes(4);
break;
case 0x1f: // Entity Relative Move
write(packetId);
copyNBytes(7);
break;
case 0x20: // Entity Look
write(packetId);
copyNBytes(6);
break;
case 0x21: // Entity Look and Relative Move
write(packetId);
copyNBytes(9);
break;
case 0x22: // Entity Teleport
write(packetId);
copyNBytes(18);
break;
case 0x26: // Entity status?
write(packetId);
copyNBytes(5);
break;
case 0x27: // Attach Entity?
write(packetId);
copyNBytes(8);
break;
case 0x28: // Entity Metadata
write(packetId);
write(in.readInt());
copyUnknownBlob();
break;
case 0x32: // Pre-Chunk
write(packetId);
copyNBytes(9);
break;
case 0x33: // Map Chunk
write(packetId);
copyNBytes(13);
int chunkSize = in.readInt();
write(chunkSize);
copyNBytes(chunkSize);
break;
case 0x34: // Multi Block Change
write(packetId);
copyNBytes(8);
short arraySize = in.readShort();
write(arraySize);
copyNBytes(arraySize * 4);
break;
case 0x35: // Block Change
write(packetId);
x = in.readInt();
y = in.readByte();
z = in.readInt();
byte blockType = in.readByte();
byte metadata = in.readByte();
if(blockType == 54 && player.placedChest(x,y,z)) {
lockChest(x,y,z);
player.placingChest(null);
}
write(x);
write(y);
write(z);
write(blockType);
write(metadata);
break;
case 0x36: // ???
write(packetId);
copyNBytes(12);
break;
case 0x3c: // Explosion
write(packetId);
copyNBytes(28);
int recordCount = in.readInt();
write(recordCount);
copyNBytes(recordCount * 3);
break;
case 0x46: // Invalid Bed
write(packetId);
copyNBytes(1);
break;
case 0x64:
byte id = in.readByte();
byte invtype = in.readByte();
String typeString = in.readUTF();
if(invtype == 0) {
if(server.chests.canOpen(player, player.openedChest()) || player.isAdmin()) {
if(server.chests.isLocked(player.openedChest())) {
if(player.isAttemptingUnlock()) {
server.chests.unlock(player.openedChest());
player.setAttemptedAction(null);
player.addMessage("\u00a77This chest is no longer locked!");
typeString = "Open Chest";
} else {
typeString = server.chests.chestName(player.openedChest());
}
} else {
typeString = "Open Chest";
if(player.isAttemptLock()) {
lockChest(player.openedChest());
typeString = player.nextChestName();
}
}
} else {
player.addMessage("\u00a7cThis chest is locked!");
in.readByte();
break;
}
}
write(packetId);
write(id);
write(invtype);
write(typeString);
write(in.readByte());
break;
case 0x65:
write(packetId);
write(in.readByte());
break;
case 0x66: // Inventory Item Move
byte typeFrom = in.readByte();
short slotFrom = in.readShort();
byte typeTo = in.readByte();
short slotTo = in.readShort();
if ((typeFrom < 0 && typeTo < 0) || player.getGroupId() >= 0) {
write(packetId);
write(typeFrom);
write(slotFrom);
write(typeTo);
write(slotTo);
short moveItem = in.readShort();
write(moveItem);
if (moveItem != -1) {
write(in.readByte());
write(in.readShort());
}
}
else {
short moveItem = in.readShort();
if (moveItem != -1) {
in.readByte();
in.readShort();
}
}
break;
case 0x67: // Inventory Item Update
byte type67 = in.readByte();
if (type67 < 0 || player.getGroupId() >= 0) {
write(packetId);
short slot = in.readShort();
write(type67);
write(slot);
short setItem = in.readShort();
write(setItem);
if (setItem != -1) {
write(in.readByte());
write(in.readShort());
}
}
else {
in.readShort();
short setItem = in.readShort();
if (setItem != -1) {
in.readByte();
in.readShort();
}
}
break;
case 0x68: // Inventory
byte type = in.readByte();
if (type < 0 || player.getGroupId() >= 0) {
write(packetId);
write(type);
short count = in.readShort();
write(count);
for (int c = 0; c < count; ++c) {
short item = in.readShort();
write(item);
if (item != -1) {
write(in.readByte());
write(in.readShort());
}
}
}
else {
short count = in.readShort();
for (int c = 0; c < count; ++c) {
short item = in.readShort();
if (item != -1) {
in.readByte();
in.readShort();
}
}
}
break;
case 0x69:
write(packetId);
write(in.readByte());
write(in.readShort());
write(in.readShort());
break;
case 0x6a:
write(packetId);
write(in.readByte());
write(in.readShort());
write(in.readByte());
break;
case (byte) 0x82: // Update Sign
write(packetId);
write(in.readInt());
write(in.readShort());
write(in.readInt());
write(in.readUTF());
write(in.readUTF());
write(in.readUTF());
write(in.readUTF());
break;
case (byte) 0xff: // Disconnect/Kick
write(packetId);
String reason = in.readUTF();
write(reason);
if (reason.startsWith("Took too long")) {
server.addRobot(player);
}
player.close();
break;
default:
if (EXPENSIVE_DEBUG_LOGGING) {
while (true) {
skipNBytes(1);
flushAll();
}
}
else {
throw new IOException("Unable to parse unknown " + streamType
+ " packet 0x" + Integer.toHexString(packetId) + " for player "
+ player.getName());
}
}
packetFinished();
}
private void lockChest(Coordinate coords) {
lockChest(coords.x, coords.y, coords.z);
}
private void lockChest(int x, byte y, int z) {
Chest adjacentChest = server.chests.adjacentChest(x, y, z);
if(player.isAttemptLock() || adjacentChest != null && !adjacentChest.isOpen()) {
if(adjacentChest != null && !adjacentChest.isOpen()) {
server.chests.giveLock(adjacentChest.owner(), x, y, z, false, adjacentChest.name());
} else {
if(adjacentChest != null) {
adjacentChest.lock(player);
adjacentChest.rename(player.nextChestName());
}
server.chests.giveLock(player, x, y, z, false, player.nextChestName());
}
player.setAttemptedAction(null);
player.addMessage("\u00a77This chest is now locked.");
} else if(!server.chests.isChest(x, y, z)){
server.chests.addOpenChest(x, y, z);
}
}
private void copyPlayerLocation() throws IOException {
if (!isServerTunnel) {
motionCounter++;
}
if (!isServerTunnel && motionCounter % 8 == 0) {
double x = in.readDouble();
double y = in.readDouble();
double stance = in.readDouble();
double z = in.readDouble();
player.updateLocation(x, y, z, stance);
write(x);
write(y);
write(stance);
write(z);
copyNBytes(1);
}
else {
copyNBytes(33);
}
}
private void copyUnknownBlob() throws IOException {
byte unknown = in.readByte();
write(unknown);
while (unknown != 0x7f) {
int type = (unknown & 0xE0) >> 5;
switch (type) {
case 0:
write(in.readByte());
break;
case 1:
write(in.readShort());
break;
case 2:
write(in.readInt());
break;
case 3:
write(in.readFloat());
break;
case 4:
write(in.readUTF());
break;
case 5:
write(in.readShort());
write(in.readByte());
write(in.readShort());
}
unknown = in.readByte();
write(unknown);
}
}
private void write(byte b) throws IOException {
out.writeByte(b);
}
private void write(short s) throws IOException {
out.writeShort(s);
}
private void write(int i) throws IOException {
out.writeInt(i);
}
private void write(long l) throws IOException {
out.writeLong(l);
}
private void write(float f) throws IOException {
out.writeFloat(f);
}
private void write(double d) throws IOException {
out.writeDouble(d);
}
private void write(String s) throws IOException {
out.writeUTF(s);
}
private void write(boolean b) throws IOException {
out.writeBoolean(b);
}
private void skipNBytes(int bytes) throws IOException {
int overflow = bytes / buffer.length;
for (int c = 0; c < overflow; ++c) {
in.readFully(buffer, 0, buffer.length);
}
in.readFully(buffer, 0, bytes % buffer.length);
}
private void copyNBytes(int bytes) throws IOException {
int overflow = bytes / buffer.length;
for (int c = 0; c < overflow; ++c) {
in.readFully(buffer, 0, buffer.length);
out.write(buffer, 0, buffer.length);
}
in.readFully(buffer, 0, bytes % buffer.length);
out.write(buffer, 0, bytes % buffer.length);
}
private void kick(String reason) throws IOException {
write((byte) 0xff);
write(reason);
packetFinished();
}
private void sendMessage(String message) throws IOException {
write(0x03);
write(message);
packetFinished();
}
private void packetFinished() throws IOException {
if (EXPENSIVE_DEBUG_LOGGING) {
inputDumper.packetFinished();
outputDumper.packetFinished();
}
}
private void flushAll() throws IOException {
try {
((OutputStream) out).flush();
}
finally {
if (EXPENSIVE_DEBUG_LOGGING) {
inputDumper.flush();
}
}
}
private final class Tunneler extends Thread {
@Override
public void run() {
try {
while (run) {
lastRead = System.currentTimeMillis();
try {
handlePacket();
if (isServerTunnel) {
while (player.hasMessages()) {
sendMessage(player.getMessage());
}
}
flushAll();
}
catch (IOException e) {
if (run && !player.isRobot()) {
System.out.println("[SimpleServer] " + e);
System.out.println("[SimpleServer] " + streamType
+ " error handling traffic for " + player.getIPAddress());
}
break;
}
}
try {
if (player.isKicked()) {
kick(player.getKickMsg());
}
flushAll();
}
catch (IOException e) {
}
}
finally {
if (EXPENSIVE_DEBUG_LOGGING) {
inputDumper.cleanup();
outputDumper.cleanup();
}
}
}
}
}
| fixed some 1.5 issues; still not working
| src/simpleserver/stream/StreamTunnel.java | fixed some 1.5 issues; still not working | <ide><path>rc/simpleserver/stream/StreamTunnel.java
<ide> else {
<ide> write(in.readInt());
<ide> }
<del> write(in.readUTF());
<del> write(in.readUTF());
<add> write(readUTF16());
<ide> write(in.readLong());
<ide> write(in.readByte());
<ide> break;
<ide> case 0x02: // Handshake
<del> String name = in.readUTF();
<add> String name = readUTF16();
<ide> if (isServerTunnel || player.setName(name)) {
<ide> tunneler.setName(streamType + "-" + player.getName());
<ide> write(packetId);
<ide> }
<ide> break;
<ide> case 0x03: // Chat Message
<del> String message = in.readUTF();
<add> String message = readUTF16();
<add> System.out.println(message);
<ide> if (isServerTunnel && server.options.getBoolean("useMsgFormats")) {
<ide>
<ide> Matcher colorMatcher = COLOR_PATTERN.matcher(message);
<ide> case 0x14: // Named Entity Spawn
<ide> write(packetId);
<ide> write(in.readInt());
<del> write(in.readUTF());
<add> write(readUTF16());
<ide> copyNBytes(16);
<ide> break;
<ide> case 0x15: // Pickup spawn
<ide> case 0x19: // Painting
<ide> write(packetId);
<ide> write(in.readInt());
<del> write(in.readUTF());
<add> write(readUTF16());
<ide> write(in.readInt());
<ide> write(in.readInt());
<ide> write(in.readInt());
<ide> case 0x46: // Invalid Bed
<ide> write(packetId);
<ide> copyNBytes(1);
<add> break;
<add> case 0x47: // Weather
<add> write(packetId);
<add> copyNBytes(17);
<ide> break;
<ide> case 0x64:
<ide> byte id = in.readByte();
<ide> write(packetId);
<ide> write(id);
<ide> write(invtype);
<del> write(typeString);
<add> write8(typeString);
<ide> write(in.readByte());
<ide> break;
<ide> case 0x65:
<ide> write(slotFrom);
<ide> write(typeTo);
<ide> write(slotTo);
<add> write(in.readBoolean());
<ide> short moveItem = in.readShort();
<ide> write(moveItem);
<ide> if (moveItem != -1) {
<ide> write(in.readInt());
<ide> write(in.readShort());
<ide> write(in.readInt());
<del> write(in.readUTF());
<del> write(in.readUTF());
<del> write(in.readUTF());
<del> write(in.readUTF());
<add> write(readUTF16());
<add> write(readUTF16());
<add> write(readUTF16());
<add> write(readUTF16());
<add> break;
<add> case (byte)0xc6:
<add> write(packetId);
<add> copyNBytes(5);
<ide> break;
<ide> case (byte) 0xff: // Disconnect/Kick
<ide> write(packetId);
<del> String reason = in.readUTF();
<add> String reason = readUTF16();
<ide> write(reason);
<ide> if (reason.startsWith("Took too long")) {
<ide> server.addRobot(player);
<ide> }
<ide> }
<ide> packetFinished();
<add> }
<add>
<add> private String readUTF16() throws IOException {
<add> short length = in.readShort();
<add> byte[] bytes = new byte[2+length*2];
<add> bytes[0] = (byte)((length>>8)&0xFF);
<add> bytes[1] = (byte)(length&0xFF);
<add> for(short i = 0; i < length*2; i++) {
<add> bytes[i+2] = in.readByte();
<add> }
<add> try {
<add> String result = new String(bytes, "UTF-16");
<add> return result;
<add> } catch(Exception e) {
<add> return "FUUUUU";
<add> }
<add> }
<add>
<add>
<add> private void print(byte[] bytes) {
<add> for(int i=0; i<bytes.length; i++) {
<add> System.out.print(Integer.toHexString(bytes[i]) + " ");
<add> }
<add> System.out.println();
<ide> }
<ide>
<ide> private void lockChest(Coordinate coords) {
<ide> write(in.readFloat());
<ide> break;
<ide> case 4:
<del> write(in.readUTF());
<add> write(readUTF16());
<ide> break;
<ide> case 5:
<ide> write(in.readShort());
<ide> }
<ide>
<ide> private void write(String s) throws IOException {
<add> byte[] bytes = s.getBytes("UTF-16");
<add> for(int i = 2; i < bytes.length; i++) {
<add> write(bytes[i]);
<add> }
<add> }
<add>
<add> private void write8(String s) throws IOException {
<ide> out.writeUTF(s);
<ide> }
<ide>
<ide> }
<ide>
<ide> private void sendMessage(String message) throws IOException {
<del> write(0x03);
<del> write(message);
<del> packetFinished();
<add> //write(0x03);
<add> //write(message);
<add> //packetFinished();
<ide> }
<ide>
<ide> private void packetFinished() throws IOException {
<ide> System.out.println("[SimpleServer] " + e);
<ide> System.out.println("[SimpleServer] " + streamType
<ide> + " error handling traffic for " + player.getIPAddress());
<add> e.printStackTrace();
<ide> }
<ide> break;
<ide> } |
|
Java | apache-2.0 | f223ec712d84a5eb4664a1fc76bb39ef895801eb | 0 | osmdroid/osmdroid,osmdroid/osmdroid,osmdroid/osmdroid,osmdroid/osmdroid | // Created by plusminus on 21:37:08 - 27.09.2008
package org.osmdroid.views;
import android.animation.Animator;
import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.annotation.TargetApi;
import android.graphics.Point;
import android.os.Build;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.ScaleAnimation;
import org.osmdroid.api.IGeoPoint;
import org.osmdroid.api.IMapController;
import org.osmdroid.config.Configuration;
import org.osmdroid.events.MapListener;
import org.osmdroid.events.ScrollEvent;
import org.osmdroid.events.ZoomEvent;
import org.osmdroid.util.BoundingBox;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.util.TileSystem;
import org.osmdroid.views.MapView.OnFirstLayoutListener;
import org.osmdroid.views.util.MyMath;
import java.util.LinkedList;
/**
* @author Nicolas Gramlich
* @author Marc Kurtz
*/
public class MapController implements IMapController, OnFirstLayoutListener {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
protected final MapView mMapView;
// Zoom animations
private ScaleAnimation mZoomInAnimationOld;
private ScaleAnimation mZoomOutAnimationOld;
private double mTargetZoomLevel=0;
private Animator mCurrentAnimator;
// Keep track of calls before initial layout
private ReplayController mReplayController;
// ===========================================================
// Constructors
// ===========================================================
public MapController(MapView mapView) {
mMapView = mapView;
// Keep track of initial layout
mReplayController = new ReplayController();
if (!mMapView.isLayoutOccurred()) {
mMapView.addOnFirstLayoutListener(this);
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
ZoomAnimationListener zoomAnimationListener = new ZoomAnimationListener(this);
mZoomInAnimationOld = new ScaleAnimation(1, 2, 1, 2, Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF, 0.5f);
mZoomOutAnimationOld = new ScaleAnimation(1, 0.5f, 1, 0.5f, Animation.RELATIVE_TO_SELF,
0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
mZoomInAnimationOld.setDuration(Configuration.getInstance().getAnimationSpeedShort());
mZoomOutAnimationOld.setDuration(Configuration.getInstance().getAnimationSpeedShort());
mZoomInAnimationOld.setAnimationListener(zoomAnimationListener);
mZoomOutAnimationOld.setAnimationListener(zoomAnimationListener);
}
}
@Override
public void onFirstLayout(View v, int left, int top, int right, int bottom) {
mReplayController.replayCalls();
}
@Override
public void zoomToSpan(double latSpan, double lonSpan) {
if (latSpan <= 0 || lonSpan <= 0) {
return;
}
// If no layout, delay this call
if (!mMapView.isLayoutOccurred()) {
mReplayController.zoomToSpan(latSpan, lonSpan);
return;
}
final BoundingBox bb = this.mMapView.getProjection().getBoundingBox();
final double curZoomLevel = this.mMapView.getProjection().getZoomLevel();
final double curLatSpan = bb.getLatitudeSpan();
final double curLonSpan = bb.getLongitudeSpan();
final double diffNeededLat = (double) latSpan / curLatSpan; // i.e. 600/500 = 1,2
final double diffNeededLon = (double) lonSpan / curLonSpan; // i.e. 300/400 = 0,75
final double diffNeeded = Math.max(diffNeededLat, diffNeededLon); // i.e. 1,2
if (diffNeeded > 1) { // Zoom Out
this.mMapView.setZoomLevel(curZoomLevel - MyMath.getNextSquareNumberAbove((float) diffNeeded));
} else if (diffNeeded < 0.5) { // Can Zoom in
this.mMapView.setZoomLevel(curZoomLevel
+ MyMath.getNextSquareNumberAbove(1 / (float) diffNeeded) - 1);
}
}
// TODO rework zoomToSpan
@Override
public void zoomToSpan(int latSpanE6, int lonSpanE6) {
zoomToSpan(latSpanE6 * 1E-6, lonSpanE6 * 1E-6);
}
/**
* Start animating the map towards the given point.
*/
@Override
public void animateTo(final IGeoPoint point) {
animateTo(point, null, null);
}
/**
* @since 6.0.2
*/
public void animateTo(final IGeoPoint point, final Double pZoom, final Long pSpeed) {
// If no layout, delay this call
if (!mMapView.isLayoutOccurred()) {
mReplayController.animateTo(point, pZoom, pSpeed);
return;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
final IGeoPoint currentCenter = new GeoPoint(mMapView.getProjection().getCurrentCenter());
final MapAnimatorListener mapAnimatorListener =
new MapAnimatorListener(this, mMapView.getZoomLevelDouble(), pZoom, currentCenter, point);
final ValueAnimator mapAnimator = ValueAnimator.ofFloat(0, 1);
mapAnimator.addListener(mapAnimatorListener);
mapAnimator.addUpdateListener(mapAnimatorListener);
if (pSpeed == null) {
mapAnimator.setDuration(Configuration.getInstance().getAnimationSpeedDefault());
} else {
mapAnimator.setDuration(pSpeed);
}
mCurrentAnimator = mapAnimator;
mapAnimator.start();
return;
}
// TODO handle the zoom part for the .3% of the population below HONEYCOMB (Feb. 2018)
Point p = mMapView.getProjection().toPixels(point, null);
animateTo(p.x, p.y);
}
/**
* Start animating the map towards the given point.
*/
@Override
public void animateTo(int x, int y) {
// If no layout, delay this call
if (!mMapView.isLayoutOccurred()) {
mReplayController.animateTo(x, y);
return;
}
if (!mMapView.isAnimating()) {
mMapView.mIsFlinging = false;
final int xStart = (int)mMapView.getMapScrollX();
final int yStart = (int)mMapView.getMapScrollY();
final int dx = x - mMapView.getWidth() / 2;
final int dy = y - mMapView.getHeight() / 2;
if (dx != xStart || dy != yStart) {
mMapView.getScroller().startScroll(xStart, yStart, dx, dy, Configuration.getInstance().getAnimationSpeedDefault());
mMapView.postInvalidate();
}
}
}
@Override
public void scrollBy(int x, int y) {
this.mMapView.scrollBy(x, y);
}
/**
* Set the map view to the given center. There will be no animation.
*/
@Override
public void setCenter(final IGeoPoint point) {
// If no layout, delay this call
for (MapListener mapListener: mMapView.mListners) {
mapListener.onScroll(new ScrollEvent(mMapView, 0, 0));
}
if (!mMapView.isLayoutOccurred()) {
mReplayController.setCenter(point);
return;
}
mMapView.setExpectedCenter(point);
}
@Override
public void stopPanning() {
mMapView.mIsFlinging = false;
mMapView.getScroller().forceFinished(true);
}
/**
* Stops a running animation.
*
* @param jumpToTarget
*/
@Override
public void stopAnimation(final boolean jumpToTarget) {
if (!mMapView.getScroller().isFinished()) {
if (jumpToTarget) {
mMapView.mIsFlinging = false;
mMapView.getScroller().abortAnimation();
} else
stopPanning();
}
// We ignore the jumpToTarget for zoom levels since it doesn't make sense to stop
// the animation in the middle. Maybe we could have it cancel the zoom operation and jump
// back to original zoom level?
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
final Animator currentAnimator = this.mCurrentAnimator;
if (mMapView.mIsAnimating.get()) {
currentAnimator.end();
}
} else {
if (mMapView.mIsAnimating.get()) {
mMapView.clearAnimation();
}
}
}
@Override
public int setZoom(final int zoomlevel) {
return (int) setZoom((double) zoomlevel);
}
/**
* @since 6.0
*/
@Override
public double setZoom(final double pZoomlevel) {
return mMapView.setZoomLevel(pZoomlevel);
}
/**
* Zoom in by one zoom level.
*/
@Override
public boolean zoomIn() {
return zoomIn(null);
}
@Override
public boolean zoomIn(Long animationSpeed) {
return zoomTo(mMapView.getZoomLevelDouble() + 1, animationSpeed);
}
/**
* @param xPixel
* @param yPixel
* @param zoomAnimation if null, the default is used
* @return
*/
@Override
public boolean zoomInFixing(final int xPixel, final int yPixel, Long zoomAnimation) {
return zoomToFixing(mMapView.getZoomLevelDouble() + 1, xPixel, yPixel, zoomAnimation);
}
@Override
public boolean zoomInFixing(final int xPixel, final int yPixel) {
return zoomInFixing(xPixel, yPixel, null);
}
@Override
public boolean zoomOut(Long animationSpeed) {
return zoomTo(mMapView.getZoomLevelDouble() - 1, animationSpeed);
}
/**
* Zoom out by one zoom level.
*/
@Override
public boolean zoomOut() {
return zoomOut(null);
}
@Deprecated
@Override
public boolean zoomOutFixing(final int xPixel, final int yPixel) {
return zoomToFixing(mMapView.getZoomLevelDouble() - 1, xPixel, yPixel, null);
}
@Override
public boolean zoomTo(int zoomLevel) {
return zoomTo(zoomLevel, null);
}
/**
* @since 6.0
*/
@Override
public boolean zoomTo(int zoomLevel, Long animationSpeed) {
return zoomTo((double)zoomLevel, animationSpeed);
}
/**
* @param zoomLevel
* @param xPixel
* @param yPixel
* @param zoomAnimationSpeed time in milliseconds, if null, the default settings will be used
* @return
* @since 6.0.0
*/
@Override
public boolean zoomToFixing(int zoomLevel, int xPixel, int yPixel, Long zoomAnimationSpeed) {
return zoomToFixing((double) zoomLevel, xPixel, yPixel, zoomAnimationSpeed);
}
@Override
public boolean zoomTo(double pZoomLevel, Long animationSpeed) {
return zoomToFixing(pZoomLevel, mMapView.getWidth() / 2, mMapView.getHeight() / 2, animationSpeed);
}
@Override
public boolean zoomTo(double pZoomLevel) {
return zoomTo(pZoomLevel, null);
}
@Override
public boolean zoomToFixing(double zoomLevel, int xPixel, int yPixel, Long zoomAnimationSpeed) {
zoomLevel = zoomLevel > mMapView.getMaxZoomLevel() ? mMapView.getMaxZoomLevel() : zoomLevel;
zoomLevel = zoomLevel < mMapView.getMinZoomLevel() ? mMapView.getMinZoomLevel() : zoomLevel;
double currentZoomLevel = mMapView.getZoomLevelDouble();
boolean canZoom = zoomLevel < currentZoomLevel && mMapView.canZoomOut() ||
zoomLevel > currentZoomLevel && mMapView.canZoomIn();
if (!canZoom) {
return false;
}
if (mMapView.mIsAnimating.getAndSet(true)) {
// TODO extend zoom (and return true)
return false;
}
for (MapListener mapListener: mMapView.mListners) {
mapListener.onZoom(new ZoomEvent(mMapView, zoomLevel));
}
mMapView.setMultiTouchScaleInitPoint(xPixel, yPixel);
mMapView.startAnimation();
float end = (float) Math.pow(2.0, zoomLevel - currentZoomLevel);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
final MapAnimatorListener zoomAnimatorListener = new MapAnimatorListener(this, currentZoomLevel, zoomLevel, null, null);
final ValueAnimator zoomToAnimator = ValueAnimator.ofFloat(0, 1);
zoomToAnimator.addListener(zoomAnimatorListener);
zoomToAnimator.addUpdateListener(zoomAnimatorListener);
if (zoomAnimationSpeed == null) {
zoomToAnimator.setDuration(Configuration.getInstance().getAnimationSpeedShort());
} else {
zoomToAnimator.setDuration(zoomAnimationSpeed);
}
mCurrentAnimator = zoomToAnimator;
zoomToAnimator.start();
return true;
}
mTargetZoomLevel = zoomLevel;
if (zoomLevel > currentZoomLevel)
mMapView.startAnimation(mZoomInAnimationOld);
else
mMapView.startAnimation(mZoomOutAnimationOld);
ScaleAnimation scaleAnimation;
scaleAnimation = new ScaleAnimation(
1f, end, //X
1f, end, //Y
Animation.RELATIVE_TO_SELF, 0.5f, //Pivot X
Animation.RELATIVE_TO_SELF, 0.5f); //Pivot Y
if (zoomAnimationSpeed == null) {
scaleAnimation.setDuration(Configuration.getInstance().getAnimationSpeedShort());
} else {
scaleAnimation.setDuration(zoomAnimationSpeed);
}
scaleAnimation.setAnimationListener(new ZoomAnimationListener(this));
return true;
}
/**
* @since 6.0
*/
@Override
public boolean zoomToFixing(double zoomLevel, int xPixel, int yPixel) {
return zoomToFixing(zoomLevel, xPixel, yPixel, null);
}
@Override
public boolean zoomToFixing(int zoomLevel, int xPixel, int yPixel) {
return zoomToFixing(zoomLevel, xPixel, yPixel, null);
}
protected void onAnimationStart() {
mMapView.mIsAnimating.set(true);
}
protected void onAnimationEnd() {
mMapView.mIsAnimating.set(false);
mMapView.resetMultiTouchScale();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
mCurrentAnimator = null;
} else { // Fix for issue 477
mMapView.clearAnimation();
mZoomInAnimationOld.reset();
mZoomOutAnimationOld.reset();
setZoom(mTargetZoomLevel);
}
mMapView.invalidate();
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private static class MapAnimatorListener
implements Animator.AnimatorListener, AnimatorUpdateListener {
private final GeoPoint mCenter = new GeoPoint(0., 0);
private final MapController mMapController;
private final Double mZoomStart;
private final Double mZoomEnd;
private final IGeoPoint mCenterStart;
private final IGeoPoint mCenterEnd;
public MapAnimatorListener(final MapController pMapController,
final Double pZoomStart, final Double pZoomEnd,
final IGeoPoint pCenterStart, final IGeoPoint pCenterEnd) {
mMapController = pMapController;
mZoomStart = pZoomStart;
mZoomEnd = pZoomEnd;
mCenterStart = pCenterStart;
mCenterEnd = pCenterEnd;
}
@Override
public void onAnimationStart(Animator animator) {
mMapController.onAnimationStart();
}
@Override
public void onAnimationEnd(Animator animator) {
mMapController.onAnimationEnd();
}
@Override
public void onAnimationCancel(Animator animator) {
//noOp
}
@Override
public void onAnimationRepeat(Animator animator) {
//noOp
}
@Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
final float value = (Float) valueAnimator.getAnimatedValue();
if (mZoomEnd != null) {
final double zoom = mZoomStart + (mZoomEnd - mZoomStart) * value;
mMapController.mMapView.setZoomLevel(zoom);
}
if (mCenterEnd != null) {
final double longitudeStart = cleanLongitude(mCenterStart.getLongitude());
final double longitudeEnd = cleanLongitude(mCenterEnd.getLongitude());
final double longitude = cleanLongitude(longitudeStart + (longitudeEnd - longitudeStart) * value);
final double latitudeStart = mCenterStart.getLatitude();
final double latitudeEnd = mCenterEnd.getLatitude();
final double latitude = cleanLongitude(latitudeStart + (latitudeEnd - latitudeStart) * value);
mCenter.setCoords(latitude, longitude);
mMapController.mMapView.setExpectedCenter(mCenter);
}
mMapController.mMapView.invalidate();
}
private double cleanLongitude(double pLongitude) {
while (pLongitude < TileSystem.MinLongitude) {
pLongitude += (TileSystem.MaxLongitude - TileSystem.MinLongitude);
}
while (pLongitude > TileSystem.MaxLongitude) {
pLongitude -= (TileSystem.MaxLongitude - TileSystem.MinLongitude);
}
return pLongitude;
}
}
protected static class ZoomAnimationListener implements AnimationListener {
private MapController mMapController;
public ZoomAnimationListener(MapController mapController) {
mMapController = mapController;
}
@Override
public void onAnimationStart(Animation animation) {
mMapController.onAnimationStart();
}
@Override
public void onAnimationEnd(Animation animation) {
mMapController.onAnimationEnd();
}
@Override
public void onAnimationRepeat(Animation animation) {
//noOp
}
}
private enum ReplayType {
ZoomToSpanPoint, AnimateToPoint, AnimateToGeoPoint, SetCenterPoint
}
;
private class ReplayController {
private LinkedList<ReplayClass> mReplayList = new LinkedList<ReplayClass>();
public void animateTo(IGeoPoint geoPoint, Double pZoom, Long pSpeed) {
mReplayList.add(new ReplayClass(ReplayType.AnimateToGeoPoint, null, geoPoint, pZoom, pSpeed));
}
public void animateTo(int x, int y) {
mReplayList.add(new ReplayClass(ReplayType.AnimateToPoint, new Point(x, y), null));
}
public void setCenter(IGeoPoint geoPoint) {
mReplayList.add(new ReplayClass(ReplayType.SetCenterPoint, null, geoPoint));
}
public void zoomToSpan(int x, int y) {
mReplayList.add(new ReplayClass(ReplayType.ZoomToSpanPoint, new Point(x, y), null));
}
public void zoomToSpan(double x, double y) {
mReplayList.add(new ReplayClass(ReplayType.ZoomToSpanPoint, new Point((int) (x * 1E6), (int) (y * 1E6)), null));
}
public void replayCalls() {
for (ReplayClass replay : mReplayList) {
switch (replay.mReplayType) {
case AnimateToGeoPoint:
if (replay.mGeoPoint != null)
MapController.this.animateTo(replay.mGeoPoint, replay.mZoom, replay.mSpeed);
break;
case AnimateToPoint:
if (replay.mPoint != null)
MapController.this.animateTo(replay.mPoint.x, replay.mPoint.y);
break;
case SetCenterPoint:
if (replay.mGeoPoint != null)
MapController.this.setCenter(replay.mGeoPoint);
break;
case ZoomToSpanPoint:
if (replay.mPoint != null)
MapController.this.zoomToSpan(replay.mPoint.x, replay.mPoint.y);
break;
}
}
mReplayList.clear();
}
private class ReplayClass {
private ReplayType mReplayType;
private Point mPoint;
private IGeoPoint mGeoPoint;
private final Long mSpeed;
private final Double mZoom;
public ReplayClass(ReplayType mReplayType, Point mPoint, IGeoPoint mGeoPoint) {
this(mReplayType, mPoint, mGeoPoint, null, null);
}
/**
* @since 6.0.2
*/
public ReplayClass(ReplayType pReplayType, Point pPoint, IGeoPoint pGeoPoint, Double pZoom, Long pSpeed) {
mReplayType = pReplayType;
mPoint = pPoint;
mGeoPoint = pGeoPoint;
mSpeed = pSpeed;
mZoom = pZoom;
}
}
}
}
| osmdroid-android/src/main/java/org/osmdroid/views/MapController.java | // Created by plusminus on 21:37:08 - 27.09.2008
package org.osmdroid.views;
import android.animation.Animator;
import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.annotation.TargetApi;
import android.graphics.Point;
import android.os.Build;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.ScaleAnimation;
import org.osmdroid.api.IGeoPoint;
import org.osmdroid.api.IMapController;
import org.osmdroid.config.Configuration;
import org.osmdroid.events.MapListener;
import org.osmdroid.events.ScrollEvent;
import org.osmdroid.events.ZoomEvent;
import org.osmdroid.util.BoundingBox;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.util.TileSystem;
import org.osmdroid.views.MapView.OnFirstLayoutListener;
import org.osmdroid.views.util.MyMath;
import java.util.LinkedList;
/**
* @author Nicolas Gramlich
* @author Marc Kurtz
*/
public class MapController implements IMapController, OnFirstLayoutListener {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
protected final MapView mMapView;
// Zoom animations
private ScaleAnimation mZoomInAnimationOld;
private ScaleAnimation mZoomOutAnimationOld;
private double mTargetZoomLevel=0;
private Animator mCurrentAnimator;
// Keep track of calls before initial layout
private ReplayController mReplayController;
// ===========================================================
// Constructors
// ===========================================================
public MapController(MapView mapView) {
mMapView = mapView;
// Keep track of initial layout
mReplayController = new ReplayController();
if (!mMapView.isLayoutOccurred()) {
mMapView.addOnFirstLayoutListener(this);
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
ZoomAnimationListener zoomAnimationListener = new ZoomAnimationListener(this);
mZoomInAnimationOld = new ScaleAnimation(1, 2, 1, 2, Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF, 0.5f);
mZoomOutAnimationOld = new ScaleAnimation(1, 0.5f, 1, 0.5f, Animation.RELATIVE_TO_SELF,
0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
mZoomInAnimationOld.setDuration(Configuration.getInstance().getAnimationSpeedShort());
mZoomOutAnimationOld.setDuration(Configuration.getInstance().getAnimationSpeedShort());
mZoomInAnimationOld.setAnimationListener(zoomAnimationListener);
mZoomOutAnimationOld.setAnimationListener(zoomAnimationListener);
}
}
@Override
public void onFirstLayout(View v, int left, int top, int right, int bottom) {
mReplayController.replayCalls();
}
@Override
public void zoomToSpan(double latSpan, double lonSpan) {
if (latSpan <= 0 || lonSpan <= 0) {
return;
}
// If no layout, delay this call
if (!mMapView.isLayoutOccurred()) {
mReplayController.zoomToSpan(latSpan, lonSpan);
return;
}
final BoundingBox bb = this.mMapView.getProjection().getBoundingBox();
final double curZoomLevel = this.mMapView.getProjection().getZoomLevel();
final double curLatSpan = bb.getLatitudeSpan();
final double curLonSpan = bb.getLongitudeSpan();
final double diffNeededLat = (double) latSpan / curLatSpan; // i.e. 600/500 = 1,2
final double diffNeededLon = (double) lonSpan / curLonSpan; // i.e. 300/400 = 0,75
final double diffNeeded = Math.max(diffNeededLat, diffNeededLon); // i.e. 1,2
if (diffNeeded > 1) { // Zoom Out
this.mMapView.setZoomLevel(curZoomLevel - MyMath.getNextSquareNumberAbove((float) diffNeeded));
} else if (diffNeeded < 0.5) { // Can Zoom in
this.mMapView.setZoomLevel(curZoomLevel
+ MyMath.getNextSquareNumberAbove(1 / (float) diffNeeded) - 1);
}
}
// TODO rework zoomToSpan
@Override
public void zoomToSpan(int latSpanE6, int lonSpanE6) {
zoomToSpan(latSpanE6 * 1E-6, lonSpanE6 * 1E-6);
}
/**
* Start animating the map towards the given point.
*/
@Override
public void animateTo(final IGeoPoint point) {
animateTo(point, null, null);
}
/**
* @since 6.0.2
*/
public void animateTo(final IGeoPoint point, final Double pZoom, final Long pSpeed) {
// If no layout, delay this call
if (!mMapView.isLayoutOccurred()) {
mReplayController.animateTo(point, pZoom, pSpeed);
return;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
final IGeoPoint currentCenter = new GeoPoint(mMapView.getProjection().getCurrentCenter());
final MapAnimatorListener mapAnimatorListener =
new MapAnimatorListener(this, mMapView.getZoomLevelDouble(), pZoom, currentCenter, point);
final ValueAnimator mapAnimator = ValueAnimator.ofFloat(0, 1);
mapAnimator.addListener(mapAnimatorListener);
mapAnimator.addUpdateListener(mapAnimatorListener);
if (pSpeed == null) {
mapAnimator.setDuration(Configuration.getInstance().getAnimationSpeedDefault());
} else {
mapAnimator.setDuration(pSpeed);
}
mCurrentAnimator = mapAnimator;
mapAnimator.start();
return;
}
// TODO handle the zoom part for the .3% of the population below HONEYCOMB (Feb. 2018)
Point p = mMapView.getProjection().toPixels(point, null);
animateTo(p.x, p.y);
}
/**
* Start animating the map towards the given point.
*/
@Override
public void animateTo(int x, int y) {
// If no layout, delay this call
if (!mMapView.isLayoutOccurred()) {
mReplayController.animateTo(x, y);
return;
}
if (!mMapView.isAnimating()) {
mMapView.mIsFlinging = false;
final int xStart = (int)mMapView.getMapScrollX();
final int yStart = (int)mMapView.getMapScrollY();
final int dx = x - mMapView.getWidth() / 2;
final int dy = y - mMapView.getHeight() / 2;
if (dx != xStart || dy != yStart) {
mMapView.getScroller().startScroll(xStart, yStart, dx, dy, Configuration.getInstance().getAnimationSpeedDefault());
mMapView.postInvalidate();
}
}
}
@Override
public void scrollBy(int x, int y) {
this.mMapView.scrollBy(x, y);
}
/**
* Set the map view to the given center. There will be no animation.
*/
@Override
public void setCenter(final IGeoPoint point) {
// If no layout, delay this call
for (MapListener mapListener: mMapView.mListners) {
mapListener.onScroll(new ScrollEvent(mMapView, 0, 0));
}
if (!mMapView.isLayoutOccurred()) {
mReplayController.setCenter(point);
return;
}
mMapView.setExpectedCenter(point);
}
@Override
public void stopPanning() {
mMapView.mIsFlinging = false;
mMapView.getScroller().forceFinished(true);
}
/**
* Stops a running animation.
*
* @param jumpToTarget
*/
@Override
public void stopAnimation(final boolean jumpToTarget) {
if (!mMapView.getScroller().isFinished()) {
if (jumpToTarget) {
mMapView.mIsFlinging = false;
mMapView.getScroller().abortAnimation();
} else
stopPanning();
}
// We ignore the jumpToTarget for zoom levels since it doesn't make sense to stop
// the animation in the middle. Maybe we could have it cancel the zoom operation and jump
// back to original zoom level?
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
final Animator currentAnimator = this.mCurrentAnimator;
if (mMapView.mIsAnimating.get()) {
currentAnimator.end();
}
} else {
if (mMapView.mIsAnimating.get()) {
mMapView.clearAnimation();
}
}
}
@Override
public int setZoom(final int zoomlevel) {
return (int) setZoom((double) zoomlevel);
}
/**
* @since 6.0
*/
@Override
public double setZoom(final double pZoomlevel) {
return mMapView.setZoomLevel(pZoomlevel);
}
/**
* Zoom in by one zoom level.
*/
@Override
public boolean zoomIn() {
return zoomIn(null);
}
@Override
public boolean zoomIn(Long animationSpeed) {
return zoomTo(mMapView.getZoomLevelDouble() + 1, animationSpeed);
}
/**
* @param xPixel
* @param yPixel
* @param zoomAnimation if null, the default is used
* @return
*/
@Override
public boolean zoomInFixing(final int xPixel, final int yPixel, Long zoomAnimation) {
return zoomToFixing(mMapView.getZoomLevelDouble() + 1, xPixel, yPixel, zoomAnimation);
}
@Override
public boolean zoomInFixing(final int xPixel, final int yPixel) {
return zoomInFixing(xPixel, yPixel, null);
}
@Override
public boolean zoomOut(Long animationSpeed) {
return zoomTo(mMapView.getZoomLevelDouble() - 1, animationSpeed);
}
/**
* Zoom out by one zoom level.
*/
@Override
public boolean zoomOut() {
return zoomOut(null);
}
@Deprecated
@Override
public boolean zoomOutFixing(final int xPixel, final int yPixel) {
return zoomToFixing(mMapView.getZoomLevelDouble() - 1, xPixel, yPixel, null);
}
@Override
public boolean zoomTo(int zoomLevel) {
return zoomTo(zoomLevel, null);
}
/**
* @since 6.0
*/
@Override
public boolean zoomTo(int zoomLevel, Long animationSpeed) {
return zoomTo((double)zoomLevel, animationSpeed);
}
/**
* @param zoomLevel
* @param xPixel
* @param yPixel
* @param zoomAnimationSpeed time in milliseconds, if null, the default settings will be used
* @return
* @since 6.0.0
*/
@Override
public boolean zoomToFixing(int zoomLevel, int xPixel, int yPixel, Long zoomAnimationSpeed) {
return zoomToFixing((double) zoomLevel, xPixel, yPixel, zoomAnimationSpeed);
}
@Override
public boolean zoomTo(double pZoomLevel, Long animationSpeed) {
return zoomToFixing(pZoomLevel, mMapView.getWidth() / 2, mMapView.getHeight() / 2, animationSpeed);
}
@Override
public boolean zoomTo(double pZoomLevel) {
return zoomTo(pZoomLevel, null);
}
@Override
public boolean zoomToFixing(double zoomLevel, int xPixel, int yPixel, Long zoomAnimationSpeed) {
zoomLevel = zoomLevel > mMapView.getMaxZoomLevel() ? mMapView.getMaxZoomLevel() : zoomLevel;
zoomLevel = zoomLevel < mMapView.getMinZoomLevel() ? mMapView.getMinZoomLevel() : zoomLevel;
double currentZoomLevel = mMapView.getZoomLevelDouble();
boolean canZoom = zoomLevel < currentZoomLevel && mMapView.canZoomOut() ||
zoomLevel > currentZoomLevel && mMapView.canZoomIn();
if (!canZoom) {
return false;
}
if (mMapView.mIsAnimating.getAndSet(true)) {
// TODO extend zoom (and return true)
return false;
}
for (MapListener mapListener: mMapView.mListners) {
mapListener.onZoom(new ZoomEvent(mMapView, zoomLevel));
}
mMapView.setMultiTouchScaleInitPoint(xPixel, yPixel);
mMapView.startAnimation();
float end = (float) Math.pow(2.0, zoomLevel - currentZoomLevel);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
final MapAnimatorListener zoomAnimatorListener = new MapAnimatorListener(this, currentZoomLevel, zoomLevel, null, null);
final ValueAnimator zoomToAnimator = ValueAnimator.ofFloat(0, 1);
zoomToAnimator.addListener(zoomAnimatorListener);
zoomToAnimator.addUpdateListener(zoomAnimatorListener);
if (zoomAnimationSpeed == null) {
zoomToAnimator.setDuration(Configuration.getInstance().getAnimationSpeedShort());
} else {
zoomToAnimator.setDuration(zoomAnimationSpeed);
}
mCurrentAnimator = zoomToAnimator;
zoomToAnimator.start();
return true;
}
mTargetZoomLevel = zoomLevel;
if (zoomLevel > currentZoomLevel)
mMapView.startAnimation(mZoomInAnimationOld);
else
mMapView.startAnimation(mZoomOutAnimationOld);
ScaleAnimation scaleAnimation;
scaleAnimation = new ScaleAnimation(
1f, end, //X
1f, end, //Y
Animation.RELATIVE_TO_SELF, 0.5f, //Pivot X
Animation.RELATIVE_TO_SELF, 0.5f); //Pivot Y
if (zoomAnimationSpeed == null) {
scaleAnimation.setDuration(Configuration.getInstance().getAnimationSpeedShort());
} else {
scaleAnimation.setDuration(zoomAnimationSpeed);
}
scaleAnimation.setAnimationListener(new ZoomAnimationListener(this));
return true;
}
/**
* @since 6.0
*/
@Override
public boolean zoomToFixing(double zoomLevel, int xPixel, int yPixel) {
return zoomToFixing(zoomLevel, xPixel, yPixel, null);
}
@Override
public boolean zoomToFixing(int zoomLevel, int xPixel, int yPixel) {
return zoomToFixing(zoomLevel, xPixel, yPixel, null);
}
protected void onAnimationStart() {
mMapView.mIsAnimating.set(true);
}
protected void onAnimationEnd() {
mMapView.mIsAnimating.set(false);
mMapView.resetMultiTouchScale();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
mCurrentAnimator = null;
} else { // Fix for issue 477
mMapView.clearAnimation();
mZoomInAnimationOld.reset();
mZoomOutAnimationOld.reset();
setZoom(mTargetZoomLevel);
}
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private static class MapAnimatorListener
implements Animator.AnimatorListener, AnimatorUpdateListener {
private final GeoPoint mCenter = new GeoPoint(0., 0);
private final MapController mMapController;
private final Double mZoomStart;
private final Double mZoomEnd;
private final IGeoPoint mCenterStart;
private final IGeoPoint mCenterEnd;
public MapAnimatorListener(final MapController pMapController,
final Double pZoomStart, final Double pZoomEnd,
final IGeoPoint pCenterStart, final IGeoPoint pCenterEnd) {
mMapController = pMapController;
mZoomStart = pZoomStart;
mZoomEnd = pZoomEnd;
mCenterStart = pCenterStart;
mCenterEnd = pCenterEnd;
}
@Override
public void onAnimationStart(Animator animator) {
mMapController.onAnimationStart();
}
@Override
public void onAnimationEnd(Animator animator) {
mMapController.onAnimationEnd();
}
@Override
public void onAnimationCancel(Animator animator) {
//noOp
}
@Override
public void onAnimationRepeat(Animator animator) {
//noOp
}
@Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
final float value = (Float) valueAnimator.getAnimatedValue();
if (mZoomEnd != null) {
final double zoom = mZoomStart + (mZoomEnd - mZoomStart) * value;
mMapController.mMapView.setZoomLevel(zoom);
}
if (mCenterEnd != null) {
final double longitudeStart = cleanLongitude(mCenterStart.getLongitude());
final double longitudeEnd = cleanLongitude(mCenterEnd.getLongitude());
final double longitude = cleanLongitude(longitudeStart + (longitudeEnd - longitudeStart) * value);
final double latitudeStart = mCenterStart.getLatitude();
final double latitudeEnd = mCenterEnd.getLatitude();
final double latitude = cleanLongitude(latitudeStart + (latitudeEnd - latitudeStart) * value);
mCenter.setCoords(latitude, longitude);
mMapController.mMapView.setExpectedCenter(mCenter);
}
mMapController.mMapView.invalidate();
}
private double cleanLongitude(double pLongitude) {
while (pLongitude < TileSystem.MinLongitude) {
pLongitude += (TileSystem.MaxLongitude - TileSystem.MinLongitude);
}
while (pLongitude > TileSystem.MaxLongitude) {
pLongitude -= (TileSystem.MaxLongitude - TileSystem.MinLongitude);
}
return pLongitude;
}
}
protected static class ZoomAnimationListener implements AnimationListener {
private MapController mMapController;
public ZoomAnimationListener(MapController mapController) {
mMapController = mapController;
}
@Override
public void onAnimationStart(Animation animation) {
mMapController.onAnimationStart();
}
@Override
public void onAnimationEnd(Animation animation) {
mMapController.onAnimationEnd();
}
@Override
public void onAnimationRepeat(Animation animation) {
//noOp
}
}
private enum ReplayType {
ZoomToSpanPoint, AnimateToPoint, AnimateToGeoPoint, SetCenterPoint
}
;
private class ReplayController {
private LinkedList<ReplayClass> mReplayList = new LinkedList<ReplayClass>();
public void animateTo(IGeoPoint geoPoint, Double pZoom, Long pSpeed) {
mReplayList.add(new ReplayClass(ReplayType.AnimateToGeoPoint, null, geoPoint, pZoom, pSpeed));
}
public void animateTo(int x, int y) {
mReplayList.add(new ReplayClass(ReplayType.AnimateToPoint, new Point(x, y), null));
}
public void setCenter(IGeoPoint geoPoint) {
mReplayList.add(new ReplayClass(ReplayType.SetCenterPoint, null, geoPoint));
}
public void zoomToSpan(int x, int y) {
mReplayList.add(new ReplayClass(ReplayType.ZoomToSpanPoint, new Point(x, y), null));
}
public void zoomToSpan(double x, double y) {
mReplayList.add(new ReplayClass(ReplayType.ZoomToSpanPoint, new Point((int) (x * 1E6), (int) (y * 1E6)), null));
}
public void replayCalls() {
for (ReplayClass replay : mReplayList) {
switch (replay.mReplayType) {
case AnimateToGeoPoint:
if (replay.mGeoPoint != null)
MapController.this.animateTo(replay.mGeoPoint, replay.mZoom, replay.mSpeed);
break;
case AnimateToPoint:
if (replay.mPoint != null)
MapController.this.animateTo(replay.mPoint.x, replay.mPoint.y);
break;
case SetCenterPoint:
if (replay.mGeoPoint != null)
MapController.this.setCenter(replay.mGeoPoint);
break;
case ZoomToSpanPoint:
if (replay.mPoint != null)
MapController.this.zoomToSpan(replay.mPoint.x, replay.mPoint.y);
break;
}
}
mReplayList.clear();
}
private class ReplayClass {
private ReplayType mReplayType;
private Point mPoint;
private IGeoPoint mGeoPoint;
private final Long mSpeed;
private final Double mZoom;
public ReplayClass(ReplayType mReplayType, Point mPoint, IGeoPoint mGeoPoint) {
this(mReplayType, mPoint, mGeoPoint, null, null);
}
/**
* @since 6.0.2
*/
public ReplayClass(ReplayType pReplayType, Point pPoint, IGeoPoint pGeoPoint, Double pZoom, Long pSpeed) {
mReplayType = pReplayType;
mPoint = pPoint;
mGeoPoint = pGeoPoint;
mSpeed = pSpeed;
mZoom = pZoom;
}
}
}
}
| bug/#1040 - explicit call to invalidate after animation
Thank you @InI4 for this bug fix suggestion.
Impacted classes:
* `MapController`: added an explicit call to `invalidate` after animation, in method `onAnimationEnd`
| osmdroid-android/src/main/java/org/osmdroid/views/MapController.java | bug/#1040 - explicit call to invalidate after animation | <ide><path>smdroid-android/src/main/java/org/osmdroid/views/MapController.java
<ide> mZoomOutAnimationOld.reset();
<ide> setZoom(mTargetZoomLevel);
<ide> }
<add> mMapView.invalidate();
<ide> }
<ide>
<ide> @TargetApi(Build.VERSION_CODES.HONEYCOMB) |
|
Java | agpl-3.0 | b2b9bcc4ad07c2f88e810747ee5405cfae12d3ec | 0 | splicemachine/spliceengine,CompilerWorks/spliceengine,CompilerWorks/spliceengine,CompilerWorks/spliceengine,splicemachine/spliceengine,splicemachine/spliceengine,splicemachine/spliceengine,splicemachine/spliceengine,CompilerWorks/spliceengine,CompilerWorks/spliceengine,CompilerWorks/spliceengine,splicemachine/spliceengine,splicemachine/spliceengine | /*
Derby - Class com.splicemachine.db.iapi.sql.execute.ResultSetFactory
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to you under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.splicemachine.db.iapi.sql.execute;
import java.util.List;
import com.splicemachine.db.iapi.error.StandardException;
import com.splicemachine.db.iapi.services.loader.GeneratedMethod;
import com.splicemachine.db.iapi.sql.Activation;
import com.splicemachine.db.iapi.sql.ResultSet;
import com.splicemachine.db.iapi.types.DataValueDescriptor;
/**
* ResultSetFactory provides a wrapper around all of
* the result sets needed in an execution implementation.
* <p>
* For the activations to avoid searching for this module
* in their execute methods, the base activation supertype
* should implement a method that does the lookup and salts
* away this factory for the activation to use as it needs it.
*
*/
public interface ResultSetFactory {
/**
Module name for the monitor's module locating system.
*/
String MODULE = "com.splicemachine.db.iapi.sql.execute.ResultSetFactory";
//
// DDL operations
//
/**
Generic DDL result set creation.
@param activation the activation for this result set
@return ResultSet A wrapper result set to run the Execution-time
logic.
@exception StandardException thrown when unable to create the
result set
*/
ResultSet getDDLResultSet(Activation activation)
throws StandardException;
//
// MISC operations
//
/**
Generic Misc result set creation.
@param activation the activation for this result set
@return ResultSet A wrapper result set to run the Execution-time
logic.
@exception StandardException thrown when unable to create the
result set
*/
ResultSet getMiscResultSet(Activation activation)
throws StandardException;
//
// Transaction operations
//
/**
@param activation the activation for this result set
@return ResultSet A wrapper result set to run the Execution-time
logic.
@exception StandardException thrown when unable to create the
result set
*/
ResultSet getSetTransactionResultSet(Activation activation)
throws StandardException;
//
// DML statement operations
//
/**
An insert result set simply reports that it completed, and
the number of rows inserted. It does not return rows.
The insert has been completed once the
insert result set is available.
@param source the result set from which to take rows to
be inserted into the target table.
@param generationClauses The code to compute column generation clauses if any
@param checkGM The code to enforce the check constraints, if any
@return the insert operation as a result set.
@exception StandardException thrown when unable to perform the insert
*/
ResultSet getInsertResultSet(NoPutResultSet source,
GeneratedMethod generationClauses,
GeneratedMethod checkGM,
String insertMode,
String statusDirectory,
int failBadRecordCount,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost,
String tableVersion,
String explainPlan)
throws StandardException;
/**
An insert VTI result set simply reports that it completed, and
the number of rows inserted. It does not return rows.
The insert has been completed once the
insert result set is available.
@param source the result set from which to take rows to
be inserted into the target table.
@param vtiRS The code to instantiate the VTI, if necessary
@return the insert VTI operation as a result set.
@exception StandardException thrown when unable to perform the insert
*/
ResultSet getInsertVTIResultSet(NoPutResultSet source,
NoPutResultSet vtiRS,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost)
throws StandardException;
/**
A delete VTI result set simply reports that it completed, and
the number of rows deleted. It does not return rows.
The delete has been completed once the
delete result set is available.
@param source the result set from which to take rows to
be inserted into the target table.
@return the delete VTI operation as a result set.
@exception StandardException thrown when unable to perform the insert
*/
ResultSet getDeleteVTIResultSet(NoPutResultSet source,double optimizerEstimatedRowCount,
double optimizerEstimatedCost)
throws StandardException;
/**
A delete result set simply reports that it completed, and
the number of rows deleted. It does not return rows.
The delete has been completed once the
delete result set is available.
@param source the result set from which to take rows to
be deleted from the target table. This result set must
contain one column which provides RowLocations that are
valid in the target table.
@return the delete operation as a result set.
@exception StandardException thrown when unable to perform the delete
*/
ResultSet getDeleteResultSet(NoPutResultSet source,double optimizerEstimatedRowCount,
double optimizerEstimatedCost, String tableVersion,
String explainPlan)
throws StandardException;
/**
A delete Cascade result set simply reports that it completed, and
the number of rows deleted. It does not return rows.
The delete has been completed once the
delete result set is available.
@param source the result set from which to take rows to
be deleted from the target table.
@param constantActionItem a constant action saved object reference
@param dependentResultSets an array of DeleteCascade Resultsets
for the current table referential action
dependents tables.
@param resultSetId an Id which is used to store the refence
to the temporary result set created of
the materilized rows.Dependent table resultsets
uses the same id to access their parent temporary result sets.
@return the delete operation as a delete cascade result set.
@exception StandardException thrown when unable to perform the delete
*/
ResultSet getDeleteCascadeResultSet(NoPutResultSet source,
int constantActionItem,
ResultSet[] dependentResultSets,
String resultSetId)
throws StandardException;
/**
An update result set simply reports that it completed, and
the number of rows updated. It does not return rows.
The update has been completed once the
update result set is available.
@param source the result set from which to take rows to be
updated in the target table. This result set must contain
a column which provides RowLocations that are valid in the
target table, and new values to be placed in those rows.
@param generationClauses The code to compute column generation clauses if any
@param checkGM The code to enforce the check constraints, if any
@return the update operation as a result set.
@exception StandardException thrown when unable to perform the update
*/
ResultSet getUpdateResultSet(NoPutResultSet source, GeneratedMethod generationClauses,
GeneratedMethod checkGM,double optimizerEstimatedRowCount,
double optimizerEstimatedCost, String tableVersion,
String explainPlan)
throws StandardException;
/**
* @param source the result set from which to take rows to be
* updated in the target table.
* @return the update operation as a result set.
* @exception StandardException thrown on error
*/
public ResultSet getUpdateVTIResultSet(NoPutResultSet source,double optimizerEstimatedRowCount,
double optimizerEstimatedCost)
throws StandardException;
/**
An update result set simply reports that it completed, and
the number of rows updated. It does not return rows.
The update has been completed once the
update result set is available.
@param source the result set from which to take rows to be
updated in the target table. This result set must contain
a column which provides RowLocations that are valid in the
target table, and new values to be placed in those rows.
@param generationClauses The code to compute generated columns, if any
@param checkGM The code to enforce the check constraints, if any
@param constantActionItem a constant action saved object reference
@param rsdItem result Description, saved object id.
@return the update operation as a result set.
@exception StandardException thrown when unable to perform the update
*/
ResultSet getDeleteCascadeUpdateResultSet(NoPutResultSet source,
GeneratedMethod generationClauses,
GeneratedMethod checkGM,
int constantActionItem,
int rsdItem)
throws StandardException;
/**
A call statement result set simply reports that it completed.
It does not return rows.
@param methodCall a reference to a method in the activation
for the method call
@param activation the activation for this result set
@return the call statement operation as a result set.
@exception StandardException thrown when unable to perform the call statement
*/
ResultSet getCallStatementResultSet(GeneratedMethod methodCall,
Activation activation)
throws StandardException;
ResultSet getCallStatementResultSet(GeneratedMethod methodCall,
Activation activation,
String origClassName,
String origMethodName)
throws StandardException;
//
// Query expression operations
//
/**
A project restrict result set iterates over its source,
evaluating a restriction and when it is satisfied,
constructing a row to return in its result set based on
its projection.
The rows can be constructed as they are requested from the
result set.
@param source the result set from which to take rows to be
filtered by this operation.
@param restriction a reference to a method in the activation
that is applied to the activation's "current row" field
to determine whether the restriction is satisfied or not.
The signature of this method is
<verbatim>
Boolean restriction() throws StandardException;
</verbatim>
@param projection a reference to a method in the activation
that is applied to the activation's "current row" field
to project out the expected result row.
The signature of this method is
<verbatim>
ExecRow projection() throws StandardException;
</verbatim>
@param resultSetNumber The resultSetNumber for the ResultSet
@param constantRestriction a reference to a method in the activation
that represents a constant expression (eg where 1 = 2).
The signature of this method is
<verbatim>
Boolean restriction() throws StandardException;
</verbatim>
@param mapArrayItem Item # for mapping of source to target columns
@param cloneMapItem Item # for columns that need cloning
@param reuseResult Whether or not to reuse the result row.
@param doesProjection Whether or not this PRN does a projection
@param optimizerEstimatedRowCount Estimated total # of rows by
optimizer
@param optimizerEstimatedCost Estimated total cost by optimizer
@return the project restrict operation as a result set.
@exception StandardException thrown when unable to create the
result set
*/
NoPutResultSet getProjectRestrictResultSet(NoPutResultSet source,
GeneratedMethod restriction,
GeneratedMethod projection, int resultSetNumber,
GeneratedMethod constantRestriction,
int mapArrayItem,
int cloneMapItem,
boolean reuseResult,
boolean doesProjection,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost,
String explainPlan) throws StandardException;
/**
A hash table result set builds a hash table on its source,
applying a list of predicates, if any, to the source,
when building the hash table. It then does a look up into
the hash table on a probe.
The rows can be constructed as they are requested from the
result set.
@param source the result set from which to take rows to be
filtered by this operation.
@param singleTableRestriction restriction, if any, applied to
input of hash table.
@param equijoinQualifiers Qualifier[] for look up into hash table
@param projection a reference to a method in the activation
that is applied to the activation's "current row" field
to project out the expected result row.
The signature of this method is
<verbatim>
ExecRow projection() throws StandardException;
</verbatim>
@param resultSetNumber The resultSetNumber for the ResultSet
@param mapRefItem Item # for mapping of source to target columns
@param reuseResult Whether or not to reuse the result row.
@param keyColItem Item for hash key column array
@param removeDuplicates Whether or not to remove duplicates when building the hash table
@param maxInMemoryRowCount Max size of in-memory hash table
@param initialCapacity initialCapacity for java.util.HashTable
@param loadFactor loadFactor for java.util.HashTable
@param optimizerEstimatedRowCount Estimated total # of rows by
optimizer
@param optimizerEstimatedCost Estimated total cost by optimizer
@return the project restrict operation as a result set.
@exception StandardException thrown when unable to create the
result set
*/
public NoPutResultSet getHashTableResultSet(NoPutResultSet source,
GeneratedMethod singleTableRestriction,
String equijoinQualifiersField,
GeneratedMethod projection, int resultSetNumber,
int mapRefItem,
boolean reuseResult,
int keyColItem,
boolean removeDuplicates,
long maxInMemoryRowCount,
int initialCapacity,
float loadFactor,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost)
throws StandardException;
/**
A sort result set sorts its source and if requested removes
duplicates. It will generate the entire result when open, and
then return it a row at a time.
<p>
If passed aggregates it will do scalar or vector aggregate
processing. A list of aggregator information is passed
off of the PreparedStatement's savedObjects. Aggregation
and SELECT DISTINCT cannot be processed in the same sort.
@param source the result set from which to take rows to be
filtered by this operation.
@param distinct true if distinct SELECT list
@param isInSortedOrder true if the source result set is in sorted order
@param orderItem entry in preparedStatement's savedObjects for order
@param rowAllocator a reference to a method in the activation
that generates rows of the right size and shape for the source
@param rowSize the size of the row that is allocated by rowAllocator.
size should be the maximum size of the sum of all the datatypes.
user type are necessarily approximated
@param resultSetNumber The resultSetNumber for the ResultSet
@param optimizerEstimatedRowCount Estimated total # of rows by
optimizer
@param optimizerEstimatedCost Estimated total cost by optimizer
@return the distinct operation as a result set.
@exception StandardException thrown when unable to create the
result set
*/
NoPutResultSet getSortResultSet(NoPutResultSet source,
boolean distinct,
boolean isInSortedOrder,
int orderItem,
GeneratedMethod rowAllocator,
int rowSize,
int resultSetNumber,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost,
String explainPlan)
throws StandardException;
/**
A ScalarAggregateResultSet computes non-distinct scalar aggregates.
It will compute the aggregates when open.
@param source the result set from which to take rows to be
filtered by this operation.
@param isInSortedOrder true if the source result set is in sorted order
@param aggregateItem entry in preparedStatement's savedObjects for aggregates
@param orderingItem Ignored to allow same signature as getDistinctScalarAggregateResultSet
@param rowAllocator a reference to a method in the activation
that generates rows of the right size and shape for the source
@param rowSize Ignored to allow same signature as getDistinctScalarAggregateResultSet
@param resultSetNumber The resultSetNumber for the ResultSet
@param singleInputRow Whether we know we have a single input row or not
@param optimizerEstimatedRowCount Estimated total # of rows by
optimizer
@param optimizerEstimatedCost Estimated total cost by optimizer
@return the scalar aggregation operation as a result set.
@exception StandardException thrown when unable to create the
result set
*/
NoPutResultSet getScalarAggregateResultSet(NoPutResultSet source,
boolean isInSortedOrder,
int aggregateItem,
int orderingItem,
GeneratedMethod rowAllocator,
int rowSize,
int resultSetNumber,
boolean singleInputRow,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost,
String explainPlan)
throws StandardException;
/**
A DistinctScalarAggregateResultSet computes scalar aggregates when
at least one of them is a distinct aggregate.
It will compute the aggregates when open.
@param source the result set from which to take rows to be
filtered by this operation.
@param isInSortedOrder true if the source result set is in sorted order
@param aggregateItem entry in preparedStatement's savedObjects for aggregates
@param orderingItem entry in preparedStatement's savedObjects for order
@param rowAllocator a reference to a method in the activation
that generates rows of the right size and shape for the source
@param rowSize the size of the row that is allocated by rowAllocator.
size should be the maximum size of the sum of all the datatypes.
user type are necessarily approximated
@param resultSetNumber The resultSetNumber for the ResultSet
@param singleInputRow Whether we know we have a single input row or not
@param optimizerEstimatedRowCount Estimated total # of rows by
optimizer
@param optimizerEstimatedCost Estimated total cost by optimizer
@return the scalar aggregation operation as a result set.
@exception StandardException thrown when unable to create the
result set
*/
NoPutResultSet getDistinctScalarAggregateResultSet(NoPutResultSet source,
boolean isInSortedOrder,
int aggregateItem,
int orderingItem,
GeneratedMethod rowAllocator,
int rowSize,
int resultSetNumber,
boolean singleInputRow,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost,
String explainPlan)
throws StandardException;
/**
A GroupedAggregateResultSet computes non-distinct grouped aggregates.
It will compute the aggregates when open.
@param source the result set from which to take rows to be
filtered by this operation.
@param isInSortedOrder true if the source result set is in sorted order
@param aggregateItem entry in preparedStatement's savedObjects for aggregates
@param orderingItem Ignored to allow same signature as getDistinctScalarAggregateResultSet
@param rowAllocator a reference to a method in the activation
that generates rows of the right size and shape for the source
@param rowSize Ignored to allow same signature as getDistinctScalarAggregateResultSet
@param resultSetNumber The resultSetNumber for the ResultSet
@param optimizerEstimatedRowCount Estimated total # of rows by
optimizer
@param optimizerEstimatedCost Estimated total cost by optimizer
@param isRollup true if this is a GROUP BY ROLLUP()
@return the scalar aggregation operation as a result set.
@exception StandardException thrown when unable to create the
result set
*/
NoPutResultSet getGroupedAggregateResultSet(NoPutResultSet source,
boolean isInSortedOrder,
int aggregateItem,
int orderingItem,
GeneratedMethod rowAllocator,
int rowSize,
int resultSetNumber,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost,
boolean isRollup,
String explainPlan)
throws StandardException;
/**
A DistinctGroupedAggregateResultSet computes scalar aggregates when
at least one of them is a distinct aggregate.
It will compute the aggregates when open.
@param source the result set from which to take rows to be
filtered by this operation.
@param isInSortedOrder true if the source result set is in sorted order
@param aggregateItem entry in preparedStatement's savedObjects for aggregates
@param orderingItem entry in preparedStatement's savedObjects for order
@param rowAllocator a reference to a method in the activation
that generates rows of the right size and shape for the source
@param rowSize the size of the row that is allocated by rowAllocator.
size should be the maximum size of the sum of all the datatypes.
user type are necessarily approximated
@param resultSetNumber The resultSetNumber for the ResultSet
@param optimizerEstimatedRowCount Estimated total # of rows by
optimizer
@param optimizerEstimatedCost Estimated total cost by optimizer
@param isRollup true if this is a GROUP BY ROLLUP()
@return the scalar aggregation operation as a result set.
@exception StandardException thrown when unable to create the
result set
*/
NoPutResultSet getDistinctGroupedAggregateResultSet(NoPutResultSet source,
boolean isInSortedOrder,
int aggregateItem,
int orderingItem,
GeneratedMethod rowAllocator,
int rowSize,
int resultSetNumber,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost,
boolean isRollup,
String explainPlan)
throws StandardException;
/**
An any result set iterates over its source,
returning a row with all columns set to nulls
if the source returns no rows.
@param source the result set from which to take rows to be
filtered by this operation.
@param emptyRowFun a reference to a method in the activation
that is called if the source returns no rows
@param resultSetNumber The resultSetNumber for the ResultSet
@param subqueryNumber The subquery number for this subquery.
@param pointOfAttachment The point of attachment for this subquery.
@param optimizerEstimatedRowCount Estimated total # of rows by
optimizer
@param optimizerEstimatedCost Estimated total cost by optimizer
@return the any operation as a result set.
@exception StandardException thrown when unable to create the
result set
*/
NoPutResultSet getAnyResultSet(NoPutResultSet source,
GeneratedMethod emptyRowFun, int resultSetNumber,
int subqueryNumber, int pointOfAttachment,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost)
throws StandardException;
/**
A once result set iterates over its source,
raising an error if the source returns > 1 row and
returning a row with all columns set to nulls
if the source returns no rows.
@param source the result set from which to take rows to be
filtered by this operation.
@param emptyRowFun a reference to a method in the activation
that is called if the source returns no rows
@param cardinalityCheck The type of cardinality check, if any that
is required
@param resultSetNumber The resultSetNumber for the ResultSet
@param subqueryNumber The subquery number for this subquery.
@param pointOfAttachment The point of attachment for this subquery.
@param optimizerEstimatedRowCount Estimated total # of rows by
optimizer
@param optimizerEstimatedCost Estimated total cost by optimizer
@return the once operation as a result set.
@exception StandardException thrown when unable to create the
result set
*/
NoPutResultSet getOnceResultSet(NoPutResultSet source,
GeneratedMethod emptyRowFun,
int cardinalityCheck, int resultSetNumber,
int subqueryNumber, int pointOfAttachment,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost)
throws StandardException;
/**
A row result set forms a result set on a single, known row value.
It is used to turn constant rows into result sets for use in
the result set paradigm.
The row can be constructed when it is requested from the
result set.
@param activation the activation for this result set,
against which the row operation is performed to
create the result set.
@param row a reference to a method in the activation
that creates the expected row.
<verbatim>
ExecRow row() throws StandardException;
</verbatim>
@param canCacheRow True if execution can cache the input row
after it has gotten it. If the input row is constructed soley
of constants or parameters, it is ok to cache this row rather
than recreating it each time it is requested.
@param resultSetNumber The resultSetNumber for the ResultSet
@param optimizerEstimatedRowCount Estimated total # of rows by
optimizer
@param optimizerEstimatedCost Estimated total cost by optimizer
@return the row as a result set.
@exception StandardException thrown when unable to create the
result set
*/
NoPutResultSet getRowResultSet(Activation activation, GeneratedMethod row,
boolean canCacheRow,
int resultSetNumber,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost)
throws StandardException;
NoPutResultSet getRowResultSet(Activation activation, ExecRow row,
boolean canCacheRow,
int resultSetNumber,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost)
throws StandardException;
/**
Splice Addition
A resultset that forms a result set on a collection of known rows.
It is used to cache rows from a result set that's been materialized.
@param activation The activation for this result set
@param rows The collection of known ExecRows
@param resultSetNumber The resultSetNumber for the result set being materialized
*/
NoPutResultSet getCachedResultSet(Activation activation, List rows, int resultSetNumber)
throws StandardException;
/**
A VTI result set wraps a user supplied result set.
@param activation the activation for this result set,
against which the row operation is performed to
create the result set.
@param row a reference to a method in the activation
that creates the expected row.
<verbatim>
ExecRow row() throws StandardException;
</verbatim>
@param resultSetNumber The resultSetNumber for the ResultSet
@param constructor The GeneratedMethod for the user's constructor
@param javaClassName The java class name for the VTI
@param erdNumber int for referenced column BitSet (so it can be turned back into an object)
@param version2 Whether or not VTI is a version 2 VTI.
@param isTarget Whether or not VTI is a target VTI.
@param optimizerEstimatedRowCount Estimated total # of rows by optimizer
@param optimizerEstimatedCost Estimated total cost by optimizer
@param isDerbyStyleTableFunction True if this is a Derby-style table function
@param returnTypeNumber Which saved object contains the return type (a multi-set) serialized as a byte array
@param vtiProjectionNumber Which saved object contains the projection for a RestrictedVTI
@param vtiRestrictionNumber Which saved object contains the restriction for a RestrictedVTI
@return the row as a result set.
@exception StandardException thrown when unable to create the
result set
*/
public NoPutResultSet getVTIResultSet(Activation activation, GeneratedMethod row,
int resultSetNumber,
GeneratedMethod constructor,
String javaClassName,
String pushedQualifiersField,
int erdNumber,
int ctcNumber,
boolean isTarget,
int scanIsolationLevel,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost,
boolean isDerbyStyleTableFunction,
int returnTypeNumber,
int vtiProjectionNumber,
int vtiRestrictionNumber,
String explainPlan)
throws StandardException;
/*
* This method was purely added to get some stored prepared statements to pass the validation stage of their compilation.
* The existing method used a String for pushedQualifiersField. However, nothing was done with the initial value that
* was passed into the constructor. So this method does the same thing and ignores the pushedQualifiersField which is
* an com.splicemachine.db.iapi.store.access.Qualifier[][].
*/
public NoPutResultSet getVTIResultSet(
Activation activation,
GeneratedMethod row,
int resultSetNumber,
GeneratedMethod constructor,
String javaClassName,
com.splicemachine.db.iapi.store.access.Qualifier[][] pushedQualifiersField,
int erdNumber,
int ctcNumber,
boolean isTarget,
int scanIsolationLevel,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost,
boolean isDerbyStyleTableFunction,
int returnTypeNumber,
int vtiProjectionNumber,
int vtiRestrictionNumber,
String explainPlan
)
throws StandardException;
/**
A hash result set forms a result set on a hash table built on a scan
of a table.
The rows are put into the hash table on the 1st open.
<p>
@param activation the activation for this result set,
which provides the context for the row allocation operation.
@param conglomId the conglomerate of the table to be scanned.
@param scociItem The saved item for the static conglomerate info.
@param resultRowAllocator a reference to a method in the activation
that creates a holder for the rows from the scan.
<verbatim>
ExecRow rowAllocator() throws StandardException;
</verbatim>
@param resultSetNumber The resultSetNumber for the ResultSet
@param startKeyGetter a reference to a method in the activation
that gets the start key indexable row for the scan. Null
means there is no start key.
<verbatim>
ExecIndexRow startKeyGetter() throws StandardException;
</verbatim>
@param startSearchOperator The start search operator for opening
the scan
@param stopKeyGetter a reference to a method in the activation
that gets the stop key indexable row for the scan. Null means
there is no stop key.
<verbatim>
ExecIndexRow stopKeyGetter() throws StandardException;
</verbatim>
@param stopSearchOperator The stop search operator for opening
the scan
@param sameStartStopPosition Re-use the startKeyGetter for the stopKeyGetter
(Exact match search.)
@param scanQualifiers the array of Qualifiers for the scan.
Null or an array length of zero means there are no qualifiers.
@param nextQualifiers the array of Qualifiers for the look up into the hash table.
@param initialCapacity The initialCapacity for the HashTable.
@param loadFactor The loadFactor for the HashTable.
@param maxCapacity The maximum size for the HashTable.
@param hashKeyColumn The 0-based column # for the hash key.
@param tableName The full name of the table
@param userSuppliedOptimizerOverrides Overrides specified by the user on the sql
@param indexName The name of the index, if one used to access table.
@param isConstraint If index, if used, is a backing index for a constraint.
@param forUpdate True means open for update
@param colRefItem An saved item for a bitSet of columns that
are referenced in the underlying table. -1 if
no item.
@param lockMode The lock granularity to use (see
TransactionController in access)
@param tableLocked Whether or not the table is marked as using table locking
(in sys.systables)
@param isolationLevel Isolation level (specified or not) to use on scans
@param optimizerEstimatedRowCount Estimated total # of rows by
optimizer
@param optimizerEstimatedCost Estimated total cost by optimizer
@return the table scan operation as a result set.
@exception StandardException thrown when unable to create the
result set
*/
NoPutResultSet getHashScanResultSet(
Activation activation,
long conglomId,
int scociItem,
GeneratedMethod resultRowAllocator,
int resultSetNumber,
GeneratedMethod startKeyGetter,
int startSearchOperator,
GeneratedMethod stopKeyGetter,
int stopSearchOperator,
boolean sameStartStopPosition,
boolean rowIdKey,
String scanQualifiersField,
String nextQualifierField,
int initialCapacity,
float loadFactor,
int maxCapacity,
int hashKeyColumn,
String tableName,
String userSuppliedOptimizerOverrides,
String indexName,
boolean isConstraint,
boolean forUpdate,
int colRefItem,
int indexColItem,
int lockMode,
boolean tableLocked,
int isolationLevel,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost)
throws StandardException;
/**
A distinct scan result set pushes duplicate elimination into
the scan.
<p>
@param activation the activation for this result set,
which provides the context for the row allocation operation.
@param conglomId the conglomerate of the table to be scanned.
@param scociItem The saved item for the static conglomerate info.
@param resultRowAllocator a reference to a method in the activation
that creates a holder for the rows from the scan.
<verbatim>
ExecRow rowAllocator() throws StandardException;
</verbatim>
@param resultSetNumber The resultSetNumber for the ResultSet
@param hashKeyColumn The 0-based column # for the hash key.
@param tableName The full name of the table
@param userSuppliedOptimizerOverrides Overrides specified by the user on the sql
@param indexName The name of the index, if one used to access table.
@param isConstraint If index, if used, is a backing index for a constraint.
@param colRefItem An saved item for a bitSet of columns that
are referenced in the underlying table. -1 if
no item.
@param lockMode The lock granularity to use (see
TransactionController in access)
@param tableLocked Whether or not the table is marked as using table locking
(in sys.systables)
@param isolationLevel Isolation level (specified or not) to use on scans
@param optimizerEstimatedRowCount Estimated total # of rows by
optimizer
@param optimizerEstimatedCost Estimated total cost by optimizer
@return the table scan operation as a result set.
@exception StandardException thrown when unable to create the
result set
*/
NoPutResultSet getDistinctScanResultSet(
Activation activation,
long conglomId,
int scociItem,
GeneratedMethod resultRowAllocator,
int resultSetNumber,
int hashKeyColumn,
String tableName,
String userSuppliedOptimizerOverrides,
String indexName,
boolean isConstraint,
int colRefItem,
int lockMode,
boolean tableLocked,
int isolationLevel,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost,
String tableVersion,
String explainPlan)
throws StandardException;
/**
A table scan result set forms a result set on a scan
of a table.
The rows can be constructed as they are requested from the
result set.
<p>
This form of the table scan operation is simple, and is
to be used when there are no predicates to be passed down
to the scan to limit its scope on the target table.
@param conglomId the conglomerate of the table to be scanned.
@param scociItem The saved item for the static conglomerate info.
@param activation the activation for this result set,
which provides the context for the row allocation operation.
@param resultRowAllocator a reference to a method in the activation
that creates a holder for the result row of the scan. May
be a partial row.
<verbatim>
ExecRow rowAllocator() throws StandardException;
</verbatim>
@param resultSetNumber The resultSetNumber for the ResultSet
@param startKeyGetter a reference to a method in the activation
that gets the start key indexable row for the scan. Null
means there is no start key.
<verbatim>
ExecIndexRow startKeyGetter() throws StandardException;
</verbatim>
@param startSearchOperator The start search operator for opening
the scan
@param stopKeyGetter a reference to a method in the activation
that gets the stop key indexable row for the scan. Null means
there is no stop key.
<verbatim>
ExecIndexRow stopKeyGetter() throws StandardException;
</verbatim>
@param stopSearchOperator The stop search operator for opening
the scan
@param sameStartStopPosition Re-use the startKeyGetter for the stopKeyGetter
(Exact match search.)
@param qualifiers the array of Qualifiers for the scan.
Null or an array length of zero means there are no qualifiers.
@param tableName The full name of the table
@param userSuppliedOptimizerOverrides Overrides specified by the user on the sql
@param indexName The name of the index, if one used to access table.
@param isConstraint If index, if used, is a backing index for a constraint.
@param forUpdate True means open for update
@param colRefItem An saved item for a bitSet of columns that
are referenced in the underlying table. -1 if
no item.
@param lockMode The lock granularity to use (see
TransactionController in access)
@param tableLocked Whether or not the table is marked as using table locking
(in sys.systables)
@param isolationLevel Isolation level (specified or not) to use on scans
@param oneRowScan Whether or not this is a 1 row scan.
@param optimizerEstimatedRowCount Estimated total # of rows by
optimizer
@param optimizerEstimatedCost Estimated total cost by optimizer
@return the table scan operation as a result set.
@exception StandardException thrown when unable to create the
result set
*/
NoPutResultSet getTableScanResultSet(
Activation activation,
long conglomId,
int scociItem,
GeneratedMethod resultRowAllocator,
int resultSetNumber,
GeneratedMethod startKeyGetter,
int startSearchOperator,
GeneratedMethod stopKeyGetter,
int stopSearchOperator,
boolean sameStartStopPosition,
boolean rowIdKey,
String qualifiersField,
String tableName,
String userSuppliedOptimizerOverrides,
String indexName,
boolean isConstraint,
boolean forUpdate,
int colRefItem,
int indexColItem,
int lockMode,
boolean tableLocked,
int isolationLevel,
boolean oneRowScan,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost,
String tableVersion,
String explainPlan)
throws StandardException;
/**
A table scan result set forms a result set on a scan
of a table.
The rows can be constructed as they are requested from the
result set.
<p>
This form of the table scan operation is simple, and is
to be used when there are no predicates to be passed down
to the scan to limit its scope on the target table.
@param conglomId the conglomerate of the table to be scanned.
@param scociItem The saved item for the static conglomerate info.
@param activation the activation for this result set,
which provides the context for the row allocation operation.
@param resultRowAllocator a reference to a method in the activation
that creates a holder for the result row of the scan. May
be a partial row.
<verbatim>
ExecRow rowAllocator() throws StandardException;
</verbatim>
@param resultSetNumber The resultSetNumber for the ResultSet
@param startKeyGetter a reference to a method in the activation
that gets the start key indexable row for the scan. Null
means there is no start key.
<verbatim>
ExecIndexRow startKeyGetter() throws StandardException;
</verbatim>
@param startSearchOperator The start search operator for opening
the scan
@param stopKeyGetter a reference to a method in the activation
that gets the stop key indexable row for the scan. Null means
there is no stop key.
<verbatim>
ExecIndexRow stopKeyGetter() throws StandardException;
</verbatim>
@param stopSearchOperator The stop search operator for opening
the scan
@param sameStartStopPosition Re-use the startKeyGetter for the stopKeyGetter
(Exact match search.)
@param qualifiers the array of Qualifiers for the scan.
Null or an array length of zero means there are no qualifiers.
@param tableName The full name of the table
@param userSuppliedOptimizerOverrides Overrides specified by the user on the sql
@param indexName The name of the index, if one used to access table.
@param isConstraint If index, if used, is a backing index for a constraint.
@param forUpdate True means open for update
@param colRefItem An saved item for a bitSet of columns that
are referenced in the underlying table. -1 if
no item.
@param lockMode The lock granularity to use (see
TransactionController in access)
@param tableLocked Whether or not the table is marked as using table locking
(in sys.systables)
@param isolationLevel Isolation level (specified or not) to use on scans
@param rowsPerRead The number of rows to read per fetch.
@param disableForHoldable Whether or not bulk fetch should be disabled
at runtime if the cursor is holdable.
@param oneRowScan Whether or not this is a 1 row scan.
@param optimizerEstimatedRowCount Estimated total # of rows by
optimizer
@param optimizerEstimatedCost Estimated total cost by optimizer
@return the table scan operation as a result set.
@exception StandardException thrown when unable to create the
result set
*/
NoPutResultSet getBulkTableScanResultSet(
Activation activation,
long conglomId,
int scociItem,
GeneratedMethod resultRowAllocator,
int resultSetNumber,
GeneratedMethod startKeyGetter,
int startSearchOperator,
GeneratedMethod stopKeyGetter,
int stopSearchOperator,
boolean sameStartStopPosition,
boolean rowIdKey,
String qualifiersField,
String tableName,
String userSuppliedOptimizerOverrides,
String indexName,
boolean isConstraint,
boolean forUpdate,
int colRefItem,
int indexColItem,
int lockMode,
boolean tableLocked,
int isolationLevel,
int rowsPerRead,
boolean disableForHoldable,
boolean oneRowScan,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost,
String tableVersion,
String explainPlan)
throws StandardException;
/**
A multi-probe result set, used for probing an index with one or more
target values (probeValues) and returning the matching rows. This
type of result set is useful for IN lists as it allows us to avoid
scannning an entire, potentially very large, index for a mere handful
of rows (DERBY-47).
All arguments are the same as for TableScanResultSet, plus the
following:
@param probeVals List of values with which to probe the underlying
table. Should not be null.
@param sortRequired Which type of sort we need for the values
(ascending, descending, or none).
*/
NoPutResultSet getMultiProbeTableScanResultSet(
Activation activation,
long conglomId,
int scociItem,
GeneratedMethod resultRowAllocator,
int resultSetNumber,
GeneratedMethod startKeyGetter,
int startSearchOperator,
GeneratedMethod stopKeyGetter,
int stopSearchOperator,
boolean sameStartStopPosition,
boolean rowIdKey,
String qualifiersField,
DataValueDescriptor [] probeVals,
int sortRequired,
String tableName,
String userSuppliedOptimizerOverrides,
String indexName,
boolean isConstraint,
boolean forUpdate,
int colRefItem,
int indexColItem,
int lockMode,
boolean tableLocked,
int isolationLevel,
boolean oneRowScan,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost,
String tableVersion,
String explainPlan)
throws StandardException;
/**
An index row to base row result set gets an index row from its source
and uses the RowLocation in its last column to get the row from the
base conglomerate.
<p>
@param conglomId Conglomerate # for the heap.
@param scoci The saved item for the static conglomerate info.
@param source the source result set, which is expected to provide
rows from an index conglomerate
@param resultRowAllocator a reference to a method in the activation
that creates a holder for the rows from the scan.
<verbatim>
ExecRow rowAllocator() throws StandardException;
</verbatim>
@param resultSetNumber The resultSetNumber for the ResultSet
@param indexName The name of the index.
@param heapColRefItem A saved item for a bitImpl of columns that
are referenced in the underlying heap. -1 if
no item.
@param allColRefItem A saved item for a bitImpl of columns
that are referenced in the underlying
index and heap. -1 if no item.
@param heapOnlyColRefItem A saved item for a bitImpl of
columns that are referenced in the
underlying heap only. -1 if no item.
@param indexColMapItem A saved item for a ReferencedColumnsDescriptorImpl
which tell which columms are coming from the index.
@param restriction The restriction, if any, to be applied to the base row
@param forUpdate True means to open for update
@param optimizerEstimatedRowCount Estimated total # of rows by
optimizer
@param optimizerEstimatedCost Estimated total cost by optimizer
@return the index row to base row operation as a result set.
@exception StandardException thrown when unable to create the
result set
*/
public NoPutResultSet getIndexRowToBaseRowResultSet(
long conglomId,
int scoci,
NoPutResultSet source,
GeneratedMethod resultRowAllocator,
int resultSetNumber,
String indexName,
int heapColRefItem,
int allColRefItem,
int heapOnlyColRefItem,
int indexColMapItem,
GeneratedMethod restriction,
boolean forUpdate,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost,
String tableVersion,
String explainPlan)
throws StandardException;
/**
A OLAP window on top of a regular result set. It is used to realize
window functions.
@param source the result set from which to take rows to be
filtered by this operation.
@param isInSortedOrder true if the source result set is in sorted order
@param aggregateItem entry in preparedStatement's savedObjects for aggregates
@param rowAllocator a reference to a method in the activation
that generates rows of the right size and shape for the source
@param rowSize the size of the row that is allocated by rowAllocator.
size should be the maximum size of the sum of all the datatypes.
user type are necessarily approximated
@param resultSetNumber The resultSetNumber for the ResultSet
@param optimizerEstimatedRowCount Estimated total # of rows by
optimizer
@param optimizerEstimatedCost Estimated total cost by optimizer
@return the scalar aggregation operation as a result set.
@exception StandardException thrown when unable to create the
result set
*/
NoPutResultSet getWindowResultSet(NoPutResultSet source,
boolean isInSortedOrder,
int aggregateItem,
GeneratedMethod rowAllocator,
int rowSize,
int resultSetNumber,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost,
String explainPlan)
throws StandardException;
/**
A nested loop left outer join result set forms a result set on top of
2 other result sets.
The rows can be constructed as they are requested from the
result set.
<p>
This form of the nested loop join operation is simple, and is
to be used when there are no join predicates to be passed down
to the join to limit its scope on the right ResultSet.
@param leftResultSet Outer ResultSet for join.
@param leftNumCols Number of columns in the leftResultSet
@param rightResultSet Inner ResultSet for join.
@param rightNumCols Number of columns in the rightResultSet
@param joinClause a reference to a method in the activation
that is applied to the activation's "current row" field
to determine whether the joinClause is satisfied or not.
The signature of this method is
<verbatim>
Boolean joinClause() throws StandardException;
</verbatim>
@param resultSetNumber The resultSetNumber for the ResultSet
@param oneRowRightSide boolean, whether or not the right side returns
a single row. (No need to do 2nd next() if it does.)
@param notExistsRightSide boolean, whether or not the right side resides a
NOT EXISTS base table
@param optimizerEstimatedRowCount Estimated total # of rows by
optimizer
@param optimizerEstimatedCost Estimated total cost by optimizer
@param userSuppliedOptimizerOverrides Overrides specified by the user on the sql
@return the nested loop join operation as a result set.
@exception StandardException thrown when unable to create the
result set
*/
public NoPutResultSet getNestedLoopJoinResultSet(NoPutResultSet leftResultSet,
int leftNumCols,
NoPutResultSet rightResultSet,
int rightNumCols,
GeneratedMethod joinClause,
int resultSetNumber,
boolean oneRowRightSide,
boolean notExistsRightSide,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost,
String userSuppliedOptimizerOverrides,
String explainPlan)
throws StandardException;
public NoPutResultSet getMergeSortJoinResultSet(NoPutResultSet leftResultSet,
int leftNumCols,
NoPutResultSet rightResultSet,
int rightNumCols,
int leftHashKeyItem,
int rightHashKeyItem,
GeneratedMethod joinClause,
int resultSetNumber,
boolean oneRowRightSide,
boolean notExistsRightSide,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost,
String userSuppliedOptimizerOverrides,
String explainPlan)
throws StandardException;
public NoPutResultSet getMergeJoinResultSet(NoPutResultSet leftResultSet,
int leftNumCols,
NoPutResultSet rightResultSet,
int rightNumCols,
int leftHashKeyItem,
int rightHashKeyItem,
GeneratedMethod joinClause,
int resultSetNumber,
boolean oneRowRightSide,
boolean notExistsRightSide,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost,
String userSuppliedOptimizerOverrides,
String explainPlan)
throws StandardException;
public NoPutResultSet getBroadcastJoinResultSet(NoPutResultSet leftResultSet,
int leftNumCols,
NoPutResultSet rightResultSet,
int rightNumCols,
int leftHashKeyItem,
int rightHashKeyItem,
GeneratedMethod joinClause,
int resultSetNumber,
boolean oneRowRightSide,
boolean notExistsRightSide,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost,
String userSuppliedOptimizerOverrides,
String explainPlan)
throws StandardException;
/**
A hash join.
@param leftResultSet Outer ResultSet for join.
@param leftNumCols Number of columns in the leftResultSet
@param rightResultSet Inner ResultSet for join.
@param rightNumCols Number of columns in the rightResultSet
@param joinClause a reference to a method in the activation
that is applied to the activation's "current row" field
to determine whether the joinClause is satisfied or not.
The signature of this method is
<verbatim>
Boolean joinClause() throws StandardException;
</verbatim>
@param resultSetNumber The resultSetNumber for the ResultSet
@param oneRowRightSide boolean, whether or not the right side returns
a single row. (No need to do 2nd next() if it does.)
@param notExistsRightSide boolean, whether or not the right side resides a
NOT EXISTS base table
@param optimizerEstimatedRowCount Estimated total # of rows by
optimizer
@param optimizerEstimatedCost Estimated total cost by optimizer
@param userSuppliedOptimizerOverrides Overrides specified by the user on the sql
@return the nested loop join operation as a result set.
@exception StandardException thrown when unable to create the
result set
*/
public NoPutResultSet getHashJoinResultSet(NoPutResultSet leftResultSet,
int leftNumCols,
NoPutResultSet rightResultSet,
int rightNumCols,
int leftHashKeyitem,
int rightHashKeyItem,
GeneratedMethod joinClause,
int resultSetNumber,
boolean oneRowRightSide,
boolean notExistsRightSide,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost,
String userSuppliedOptimizerOverrides,
String explainPlan)
throws StandardException;
/**
A nested loop join result set forms a result set on top of
2 other result sets.
The rows can be constructed as they are requested from the
result set.
<p>
This form of the nested loop join operation is simple, and is
to be used when there are no join predicates to be passed down
to the join to limit its scope on the right ResultSet.
@param leftResultSet Outer ResultSet for join.
@param leftNumCols Number of columns in the leftResultSet
@param rightResultSet Inner ResultSet for join.
@param rightNumCols Number of columns in the rightResultSet
@param joinClause a reference to a method in the activation
that is applied to the activation's "current row" field
to determine whether the joinClause is satisfied or not.
The signature of this method is
<verbatim>
Boolean joinClause() throws StandardException;
</verbatim>
@param resultSetNumber The resultSetNumber for the ResultSet
@param emptyRowFun a reference to a method in the activation
that is called if the right child returns no rows
@param wasRightOuterJoin Whether or not this was originally a right outer join
@param oneRowRightSide boolean, whether or not the right side returns
a single row. (No need to do 2nd next() if it does.)
@param notExistsRightSide boolean, whether or not the right side resides a
NOT EXISTS base table
@param optimizerEstimatedRowCount Estimated total # of rows by
optimizer
@param optimizerEstimatedCost Estimated total cost by optimizer
@param userSuppliedOptimizerOverrides Overrides specified by the user on the sql
@return the nested loop join operation as a result set.
@exception StandardException thrown when unable to create the
result set
*/
public NoPutResultSet getNestedLoopLeftOuterJoinResultSet(NoPutResultSet leftResultSet,
int leftNumCols,
NoPutResultSet rightResultSet,
int rightNumCols,
GeneratedMethod joinClause,
int resultSetNumber,
GeneratedMethod emptyRowFun,
boolean wasRightOuterJoin,
boolean oneRowRightSide,
boolean notExistsRightSide,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost,
String userSuppliedOptimizerOverrides,
String explainPlan)
throws StandardException;
/**
A left outer join using a hash join.
@param leftResultSet Outer ResultSet for join.
@param leftNumCols Number of columns in the leftResultSet
@param rightResultSet Inner ResultSet for join.
@param rightNumCols Number of columns in the rightResultSet
@param joinClause a reference to a method in the activation
that is applied to the activation's "current row" field
to determine whether the joinClause is satisfied or not.
The signature of this method is
<verbatim>
Boolean joinClause() throws StandardException;
</verbatim>
@param resultSetNumber The resultSetNumber for the ResultSet
@param emptyRowFun a reference to a method in the activation
that is called if the right child returns no rows
@param wasRightOuterJoin Whether or not this was originally a right outer join
@param oneRowRightSide boolean, whether or not the right side returns
a single row. (No need to do 2nd next() if it does.)
@param notExistsRightSide boolean, whether or not the right side resides a
NOT EXISTS base table
@param optimizerEstimatedRowCount Estimated total # of rows by
optimizer
@param optimizerEstimatedCost Estimated total cost by optimizer
@param userSuppliedOptimizerOverrides Overrides specified by the user on the sql
@return the nested loop join operation as a result set.
@exception StandardException thrown when unable to create the
result set
*/
public NoPutResultSet getHashLeftOuterJoinResultSet(NoPutResultSet leftResultSet,
int leftNumCols,
NoPutResultSet rightResultSet,
int rightNumCols,
int leftHashKeyItem,
int rightHashKeyItem,
GeneratedMethod joinClause,
int resultSetNumber,
GeneratedMethod emptyRowFun,
boolean wasRightOuterJoin,
boolean oneRowRightSide,
boolean notExistsRightSide,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost,
String userSuppliedOptimizerOverrides,
String explainPlan)
throws StandardException;
/**
A ResultSet which materializes the underlying ResultSet tree into a
temp table on the 1st open. All subsequent "scans" of this ResultSet
will return results from the temp table.
@param source the result set input to this result set.
@param resultSetNumber The resultSetNumber for the ResultSet
@param optimizerEstimatedRowCount Estimated total # of rows by
optimizer
@param optimizerEstimatedCost Estimated total cost by optimizer
@return the materialization operation as a result set.
@exception StandardException Thrown on failure
*/
NoPutResultSet getMaterializedResultSet(NoPutResultSet source,
int resultSetNumber,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost)
throws StandardException;
/**
A ResultSet which provides the insensitive scrolling functionality
for the underlying result set by materializing the underlying ResultSet
tree into a hash table while scrolling forward.
@param source the result set input to this result set.
@param activation the activation for this result set,
which provides the context for normalization.
@param resultSetNumber The resultSetNumber for the ResultSet
@param sourceRowWidth The # of columns in the source row.
@param optimizerEstimatedRowCount Estimated total # of rows by
optimizer
@param optimizerEstimatedCost Estimated total cost by optimizer
@return the materialization operation as a result set.
@exception StandardException Thrown on failure
*/
NoPutResultSet getScrollInsensitiveResultSet(NoPutResultSet source,
Activation activation,
int resultSetNumber,
int sourceRowWidth,
boolean scrollable,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost,
String explainPlan)
throws StandardException;
/**
A left outer join using a sort merge join.
@param leftResultSet Outer ResultSet for join.
@param leftNumCols Number of columns in the leftResultSet
@param rightResultSet Inner ResultSet for join.
@param rightNumCols Number of columns in the rightResultSet
@param joinClause a reference to a method in the activation
that is applied to the activation's "current row" field
to determine whether the joinClause is staisfied or not.
The signature of this method is
<verbatim>
Boolean joinClause() throws StandardException;
</verbatim>
@param resultSetNumber The resultSetNumber for the ResultSet
@param emptyRowFun a reference to a method in the activation
that is called if the right child returns no rows
@param wasRightOuterJoin Whether or not this was originally a right outer join
@param oneRowRightSide boolean, whether or not the right side returns
a single row. (No need to do 2nd next() if it does.)
@param notExistsRightSide boolean, whether or not the right side resides a
NOT EXISTS base table
@param optimizerEstimatedRowCount Estimated total # of rows by
optimizer
@param optimizerEstimatedCost Estimated total cost by optimizer
@param userSuppliedOptimizerOverrides Overrides specified by the user on the sql
@return the nested loop join operation as a result set.
@exception StandardException thrown when unable to create the
result set
*/
public NoPutResultSet getMergeSortLeftOuterJoinResultSet(NoPutResultSet leftResultSet,
int leftNumCols,
NoPutResultSet rightResultSet,
int rightNumCols,
int leftHashKeyItem,
int rightHashKeyItem,
GeneratedMethod joinClause,
int resultSetNUmber,
GeneratedMethod emptyRowFun,
boolean wasRightOuterJoin,
boolean oneRowRightSide,
boolean noExistsRightSide,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost,
String userSuppliedOptimizerOverrides,
String explainPlan)
throws StandardException;
public NoPutResultSet getMergeLeftOuterJoinResultSet(NoPutResultSet leftResultSet,
int leftNumCols,
NoPutResultSet rightResultSet,
int rightNumCols,
int leftHashKeyItem,
int rightHashKeyItem,
GeneratedMethod joinClause,
int resultSetNUmber,
GeneratedMethod emptyRowFun,
boolean wasRightOuterJoin,
boolean oneRowRightSide,
boolean noExistsRightSide,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost,
String userSuppliedOptimizerOverrides,
String explainPlan)
throws StandardException;
public NoPutResultSet getBroadcastLeftOuterJoinResultSet(NoPutResultSet leftResultSet,
int leftNumCols,
NoPutResultSet rightResultSet,
int rightNumCols,
int leftHashKeyItem,
int rightHashKeyItem,
GeneratedMethod joinClause,
int resultSetNUmber,
GeneratedMethod emptyRowFun,
boolean wasRightOuterJoin,
boolean oneRowRightSide,
boolean noExistsRightSide,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost,
String userSuppliedOptimizerOverrides,
String explainPlan)
throws StandardException;
/**
REMIND: needs more description...
@param source the result set input to this result set.
@param resultSetNumber The resultSetNumber for the ResultSet
@param erdNumber int for ResultDescription
(so it can be turned back into an object)
@param optimizerEstimatedRowCount Estimated total # of rows by
optimizer
@param optimizerEstimatedCost Estimated total cost by optimizer
@return the normalization operation as a result set.
@exception StandardException Thrown on failure
*/
NoPutResultSet getNormalizeResultSet(NoPutResultSet source,
int resultSetNumber,
int erdNumber,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost,
boolean forUpdate,
String explainPlan)
throws StandardException;
/**
A current of result set forms a result set on the
current row of an open cursor.
It is used to perform positioned operations such as
positioned update and delete, using the result set paradigm.
@param cursorName the name of the cursor providing the row.
@param resultSetNumber The resultSetNumber for the ResultSet
*/
NoPutResultSet getCurrentOfResultSet(String cursorName, Activation activation,
int resultSetNumber);
/**
* The Union interface is used to evaluate the union (all) of two ResultSets.
* (Any duplicate elimination is performed above this ResultSet.)
*
* Forms a ResultSet returning the union of the rows in two source
* ResultSets. The column types in source1 and source2 are assumed to be
* the same.
*
* @param source1 The first ResultSet whose rows go into the union
* @param source2 The second ResultSet whose rows go into the
* union
* @param resultSetNumber The resultSetNumber for the ResultSet
* @param optimizerEstimatedRowCount Estimated total # of rows by
* optimizer
* @param optimizerEstimatedCost Estimated total cost by optimizer
*
* @return A ResultSet from which the caller can get the union
* of the two source ResultSets.
*
* @exception StandardException Thrown on failure
*/
NoPutResultSet getUnionResultSet(NoPutResultSet source1,
NoPutResultSet source2,
int resultSetNumber,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost,
String explainPlan)
throws StandardException;
/**
* The SetOpResultSet is used to implement an INTERSECT or EXCEPT operation.
* It selects rows from two ordered input result sets.
*
* @param leftSource The result set that implements the left input
* @param rightSource The result set that implements the right input
* @param activation the activation for this result set
* @param resultSetNumber
* @param optimizerEstimatedRowCount
* @param optimizerEstimatedCost
* @param opType IntersectOrExceptNode.INTERSECT_OP or EXCEPT_OP
* @param all true if the operation is an INTERSECT ALL or an EXCEPT ALL,
* false if the operation is an INTERSECT DISCTINCT or an EXCEPT DISCTINCT
* @param intermediateOrderByColumnsSavedObject The saved object index for the array of order by columns for the
* ordering of the left and right sources. That is, both the left and right sources have an order by
* clause of the form ORDER BY intermediateOrderByColumns[0],intermediateOrderByColumns[1],...
* @param intermediateOrderByDirectionSavedObject The saved object index for the array of source
* order by directions. That is, the ordering of the i'th order by column in the input is ascending
* if intermediateOrderByDirection[i] is 1, descending if intermediateOrderByDirection[i] is -1.
*
* @return A ResultSet from which the caller can get the INTERSECT or EXCEPT
*
* @exception StandardException Thrown on failure
*/
NoPutResultSet getSetOpResultSet( NoPutResultSet leftSource,
NoPutResultSet rightSource,
Activation activation,
int resultSetNumber,
long optimizerEstimatedRowCount,
double optimizerEstimatedCost,
int opType,
boolean all,
int intermediateOrderByColumnsSavedObject,
int intermediateOrderByDirectionSavedObject,
int intermediateOrderByNullsLowSavedObject)
throws StandardException;
//
// Misc operations
//
/**
* A last index key result set returns the last row from
* the index in question. It is used as an ajunct to max().
*
* @param activation the activation for this result set,
* which provides the context for the row allocation operation.
* @param resultSetNumber The resultSetNumber for the ResultSet
* @param resultRowAllocator a reference to a method in the activation
* that creates a holder for the result row of the scan. May
* be a partial row. <verbatim>
* ExecRow rowAllocator() throws StandardException; </verbatim>
* @param conglomId the conglomerate of the table to be scanned.
* @param tableName The full name of the table
* @param userSuppliedOptimizerOverrides Overrides specified by the user on the sql
* @param indexName The name of the index, if one used to access table.
* @param colRefItem An saved item for a bitSet of columns that
* are referenced in the underlying table. -1 if
* no item.
* @param lockMode The lock granularity to use (see
* TransactionController in access)
* @param tableLocked Whether or not the table is marked as using table locking
* (in sys.systables)
* @param isolationLevel Isolation level (specified or not) to use on scans
* @param optimizerEstimatedRowCount Estimated total # of rows by
* optimizer
* @param optimizerEstimatedCost Estimated total cost by optimizer
*
* @return the scan operation as a result set.
*
* @exception StandardException thrown when unable to create the
* result set
*/
NoPutResultSet getLastIndexKeyResultSet
(
Activation activation,
int resultSetNumber,
GeneratedMethod resultRowAllocator,
long conglomId,
String tableName,
String userSuppliedOptimizerOverrides,
String indexName,
int colRefItem,
int lockMode,
boolean tableLocked,
int isolationLevel,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost,
String tableVersion,
String explainPlan
) throws StandardException;
/**
A Dependent table scan result set forms a result set on a scan
of a dependent table for the rows that got materilized
on the scan of its parent table and if the row being deleted
on parent table has a reference in the dependent table.
@param activation the activation for this result set,
which provides the context for the row allocation operation.
@param conglomId the conglomerate of the table to be scanned.
@param scociItem The saved item for the static conglomerate info.
@param resultRowAllocator a reference to a method in the activation
that creates a holder for the result row of the scan. May
be a partial row.
<verbatim>
ExecRow rowAllocator() throws StandardException;
</verbatim>
@param resultSetNumber The resultSetNumber for the ResultSet
@param startKeyGetter a reference to a method in the activation
that gets the start key indexable row for the scan. Null
means there is no start key.
<verbatim>
ExecIndexRow startKeyGetter() throws StandardException;
</verbatim>
@param startSearchOperator The start search operator for opening
the scan
@param stopKeyGetter a reference to a method in the activation
that gets the stop key indexable row for the scan. Null means
there is no stop key.
<verbatim>
ExecIndexRow stopKeyGetter() throws StandardException;
</verbatim>
@param stopSearchOperator The stop search operator for opening
the scan
@param sameStartStopPosition Re-use the startKeyGetter for the stopKeyGetter
(Exact match search.)
@param qualifiers the array of Qualifiers for the scan.
Null or an array length of zero means there are no qualifiers.
@param tableName The full name of the table
@param userSuppliedOptimizerOverrides Overrides specified by the user on the sql
@param indexName The name of the index, if one used to access table.
@param isConstraint If index, if used, is a backing index for a constraint.
@param forUpdate True means open for update
@param colRefItem An saved item for a bitSet of columns that
are referenced in the underlying table. -1 if
no item.
@param lockMode The lock granularity to use (see
TransactionController in access)
@param tableLocked Whether or not the table is marked as using table locking
(in sys.systables)
@param isolationLevel Isolation level (specified or not) to use on scans
@param oneRowScan Whether or not this is a 1 row scan.
@param optimizerEstimatedRowCount Estimated total # of rows by
optimizer
@param optimizerEstimatedCost Estimated total cost by optimizer
@param parentResultSetId Id to access the materlized temporary result
set from the refence stored in the activation.
@param fkIndexConglomId foreign key index conglomerate id.
@param fkColArrayItem saved column array object that matches the foreign key index
columns and the resultset from the parent table.
@param rltItem row location template
@return the table scan operation as a result set.
@exception StandardException thrown when unable to create the
result set
*/
public NoPutResultSet getRaDependentTableScanResultSet(
Activation activation,
long conglomId,
int scociItem,
GeneratedMethod resultRowAllocator,
int resultSetNumber,
GeneratedMethod startKeyGetter,
int startSearchOperator,
GeneratedMethod stopKeyGetter,
int stopSearchOperator,
boolean sameStartStopPosition,
boolean rowIdKey,
String qualifiersField,
String tableName,
String userSuppliedOptimizerOverrides,
String indexName,
boolean isConstraint,
boolean forUpdate,
int colRefItem,
int indexColItem,
int lockMode,
boolean tableLocked,
int isolationLevel,
boolean oneRowScan,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost,
String parentResultSetId,
long fkIndexConglomId,
int fkColArrayItem,
int rltItem)
throws StandardException;
/**
* This result sets implements the filtering needed by <result offset
* clause> and <fetch first clause>. It is only ever generated if at least
* one of the two clauses is present.
*
* @param source The source result set being filtered
* @param activation The activation for this result set,
* which provides the context for the row
* allocation operation
* @param resultSetNumber The resultSetNumber for the ResultSet
* @param offsetMethod The OFFSET parameter was specified
* @param fetchFirstMethod The FETCH FIRST/NEXT parameter was specified
* @param hasJDBClimitClause True if the offset/fetchFirst clauses were added by JDBC LIMExeIT escape syntax
* @param optimizerEstimatedRowCount
* Estimated total # of rows by optimizer
* @param optimizerEstimatedCost
* Estimated total cost by optimizer
* @exception StandardException Standard error policy
*/
public NoPutResultSet getRowCountResultSet(
NoPutResultSet source,
Activation activation,
int resultSetNumber,
GeneratedMethod offsetMethod,
GeneratedMethod fetchFirstMethod,
boolean hasJDBClimitClause,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost,
String explainPlan) throws StandardException;
public NoPutResultSet getExplainResultSet(ResultSet source, Activation activation, int resultSetNumber) throws StandardException;
public NoPutResultSet getExplainResultSet(NoPutResultSet source, Activation activation, int resultSetNumber) throws StandardException;
/**
* Export
*/
public NoPutResultSet getExportResultSet(NoPutResultSet source,
Activation activation,
int resultSetNumber,
String exportPath,
boolean compression,
int replicationCount,
String encoding,
String fieldSeparator,
String quoteChar,
int srcResultDescriptionSavedObjectNum) throws StandardException;
/**
* Batch Once
*/
public NoPutResultSet getBatchOnceResultSet(NoPutResultSet source,
Activation activation,
int resultSetNumber,
NoPutResultSet subqueryResultSet,
String updateResultSetFieldName,
int sourceRowLocationColumnPosition,
int sourceCorrelatedColumnPosition,
int subqueryCorrelatedColumnPosition) throws StandardException;
}
| db-engine/src/main/java/com/splicemachine/db/iapi/sql/execute/ResultSetFactory.java | /*
Derby - Class com.splicemachine.db.iapi.sql.execute.ResultSetFactory
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to you under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.splicemachine.db.iapi.sql.execute;
import java.util.List;
import com.splicemachine.db.iapi.error.StandardException;
import com.splicemachine.db.iapi.services.loader.GeneratedMethod;
import com.splicemachine.db.iapi.sql.Activation;
import com.splicemachine.db.iapi.sql.ResultSet;
import com.splicemachine.db.iapi.types.DataValueDescriptor;
/**
* ResultSetFactory provides a wrapper around all of
* the result sets needed in an execution implementation.
* <p>
* For the activations to avoid searching for this module
* in their execute methods, the base activation supertype
* should implement a method that does the lookup and salts
* away this factory for the activation to use as it needs it.
*
*/
public interface ResultSetFactory {
/**
Module name for the monitor's module locating system.
*/
String MODULE = "com.splicemachine.db.iapi.sql.execute.ResultSetFactory";
//
// DDL operations
//
/**
Generic DDL result set creation.
@param activation the activation for this result set
@return ResultSet A wrapper result set to run the Execution-time
logic.
@exception StandardException thrown when unable to create the
result set
*/
ResultSet getDDLResultSet(Activation activation)
throws StandardException;
//
// MISC operations
//
/**
Generic Misc result set creation.
@param activation the activation for this result set
@return ResultSet A wrapper result set to run the Execution-time
logic.
@exception StandardException thrown when unable to create the
result set
*/
ResultSet getMiscResultSet(Activation activation)
throws StandardException;
//
// Transaction operations
//
/**
@param activation the activation for this result set
@return ResultSet A wrapper result set to run the Execution-time
logic.
@exception StandardException thrown when unable to create the
result set
*/
ResultSet getSetTransactionResultSet(Activation activation)
throws StandardException;
//
// DML statement operations
//
/**
An insert result set simply reports that it completed, and
the number of rows inserted. It does not return rows.
The insert has been completed once the
insert result set is available.
@param source the result set from which to take rows to
be inserted into the target table.
@param generationClauses The code to compute column generation clauses if any
@param checkGM The code to enforce the check constraints, if any
@return the insert operation as a result set.
@exception StandardException thrown when unable to perform the insert
*/
ResultSet getInsertResultSet(NoPutResultSet source,
GeneratedMethod generationClauses,
GeneratedMethod checkGM,
String insertMode,
String statusDirectory,
int failBadRecordCount,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost,
String tableVersion,
String explainPlan)
throws StandardException;
/**
An insert VTI result set simply reports that it completed, and
the number of rows inserted. It does not return rows.
The insert has been completed once the
insert result set is available.
@param source the result set from which to take rows to
be inserted into the target table.
@param vtiRS The code to instantiate the VTI, if necessary
@return the insert VTI operation as a result set.
@exception StandardException thrown when unable to perform the insert
*/
ResultSet getInsertVTIResultSet(NoPutResultSet source,
NoPutResultSet vtiRS,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost)
throws StandardException;
/**
A delete VTI result set simply reports that it completed, and
the number of rows deleted. It does not return rows.
The delete has been completed once the
delete result set is available.
@param source the result set from which to take rows to
be inserted into the target table.
@return the delete VTI operation as a result set.
@exception StandardException thrown when unable to perform the insert
*/
ResultSet getDeleteVTIResultSet(NoPutResultSet source,double optimizerEstimatedRowCount,
double optimizerEstimatedCost)
throws StandardException;
/**
A delete result set simply reports that it completed, and
the number of rows deleted. It does not return rows.
The delete has been completed once the
delete result set is available.
@param source the result set from which to take rows to
be deleted from the target table. This result set must
contain one column which provides RowLocations that are
valid in the target table.
@return the delete operation as a result set.
@exception StandardException thrown when unable to perform the delete
*/
ResultSet getDeleteResultSet(NoPutResultSet source,double optimizerEstimatedRowCount,
double optimizerEstimatedCost, String tableVersion,
String explainPlan)
throws StandardException;
/**
A delete Cascade result set simply reports that it completed, and
the number of rows deleted. It does not return rows.
The delete has been completed once the
delete result set is available.
@param source the result set from which to take rows to
be deleted from the target table.
@param constantActionItem a constant action saved object reference
@param dependentResultSets an array of DeleteCascade Resultsets
for the current table referential action
dependents tables.
@param resultSetId an Id which is used to store the refence
to the temporary result set created of
the materilized rows.Dependent table resultsets
uses the same id to access their parent temporary result sets.
@return the delete operation as a delete cascade result set.
@exception StandardException thrown when unable to perform the delete
*/
ResultSet getDeleteCascadeResultSet(NoPutResultSet source,
int constantActionItem,
ResultSet[] dependentResultSets,
String resultSetId)
throws StandardException;
/**
An update result set simply reports that it completed, and
the number of rows updated. It does not return rows.
The update has been completed once the
update result set is available.
@param source the result set from which to take rows to be
updated in the target table. This result set must contain
a column which provides RowLocations that are valid in the
target table, and new values to be placed in those rows.
@param generationClauses The code to compute column generation clauses if any
@param checkGM The code to enforce the check constraints, if any
@return the update operation as a result set.
@exception StandardException thrown when unable to perform the update
*/
ResultSet getUpdateResultSet(NoPutResultSet source, GeneratedMethod generationClauses,
GeneratedMethod checkGM,double optimizerEstimatedRowCount,
double optimizerEstimatedCost, String tableVersion,
String explainPlan)
throws StandardException;
/**
* @param source the result set from which to take rows to be
* updated in the target table.
* @return the update operation as a result set.
* @exception StandardException thrown on error
*/
public ResultSet getUpdateVTIResultSet(NoPutResultSet source,double optimizerEstimatedRowCount,
double optimizerEstimatedCost)
throws StandardException;
/**
An update result set simply reports that it completed, and
the number of rows updated. It does not return rows.
The update has been completed once the
update result set is available.
@param source the result set from which to take rows to be
updated in the target table. This result set must contain
a column which provides RowLocations that are valid in the
target table, and new values to be placed in those rows.
@param generationClauses The code to compute generated columns, if any
@param checkGM The code to enforce the check constraints, if any
@param constantActionItem a constant action saved object reference
@param rsdItem result Description, saved object id.
@return the update operation as a result set.
@exception StandardException thrown when unable to perform the update
*/
ResultSet getDeleteCascadeUpdateResultSet(NoPutResultSet source,
GeneratedMethod generationClauses,
GeneratedMethod checkGM,
int constantActionItem,
int rsdItem)
throws StandardException;
/**
A call statement result set simply reports that it completed.
It does not return rows.
@param methodCall a reference to a method in the activation
for the method call
@param activation the activation for this result set
@return the call statement operation as a result set.
@exception StandardException thrown when unable to perform the call statement
*/
ResultSet getCallStatementResultSet(GeneratedMethod methodCall,
Activation activation)
throws StandardException;
ResultSet getCallStatementResultSet(GeneratedMethod methodCall,
Activation activation,
String origClassName,
String origMethodName)
throws StandardException;
//
// Query expression operations
//
/**
A project restrict result set iterates over its source,
evaluating a restriction and when it is satisfied,
constructing a row to return in its result set based on
its projection.
The rows can be constructed as they are requested from the
result set.
@param source the result set from which to take rows to be
filtered by this operation.
@param restriction a reference to a method in the activation
that is applied to the activation's "current row" field
to determine whether the restriction is satisfied or not.
The signature of this method is
<verbatim>
Boolean restriction() throws StandardException;
</verbatim>
@param projection a reference to a method in the activation
that is applied to the activation's "current row" field
to project out the expected result row.
The signature of this method is
<verbatim>
ExecRow projection() throws StandardException;
</verbatim>
@param resultSetNumber The resultSetNumber for the ResultSet
@param constantRestriction a reference to a method in the activation
that represents a constant expression (eg where 1 = 2).
The signature of this method is
<verbatim>
Boolean restriction() throws StandardException;
</verbatim>
@param mapArrayItem Item # for mapping of source to target columns
@param cloneMapItem Item # for columns that need cloning
@param reuseResult Whether or not to reuse the result row.
@param doesProjection Whether or not this PRN does a projection
@param optimizerEstimatedRowCount Estimated total # of rows by
optimizer
@param optimizerEstimatedCost Estimated total cost by optimizer
@return the project restrict operation as a result set.
@exception StandardException thrown when unable to create the
result set
*/
NoPutResultSet getProjectRestrictResultSet(NoPutResultSet source,
GeneratedMethod restriction,
GeneratedMethod projection, int resultSetNumber,
GeneratedMethod constantRestriction,
int mapArrayItem,
int cloneMapItem,
boolean reuseResult,
boolean doesProjection,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost,
String explainPlan) throws StandardException;
/**
A hash table result set builds a hash table on its source,
applying a list of predicates, if any, to the source,
when building the hash table. It then does a look up into
the hash table on a probe.
The rows can be constructed as they are requested from the
result set.
@param source the result set from which to take rows to be
filtered by this operation.
@param singleTableRestriction restriction, if any, applied to
input of hash table.
@param equijoinQualifiers Qualifier[] for look up into hash table
@param projection a reference to a method in the activation
that is applied to the activation's "current row" field
to project out the expected result row.
The signature of this method is
<verbatim>
ExecRow projection() throws StandardException;
</verbatim>
@param resultSetNumber The resultSetNumber for the ResultSet
@param mapRefItem Item # for mapping of source to target columns
@param reuseResult Whether or not to reuse the result row.
@param keyColItem Item for hash key column array
@param removeDuplicates Whether or not to remove duplicates when building the hash table
@param maxInMemoryRowCount Max size of in-memory hash table
@param initialCapacity initialCapacity for java.util.HashTable
@param loadFactor loadFactor for java.util.HashTable
@param optimizerEstimatedRowCount Estimated total # of rows by
optimizer
@param optimizerEstimatedCost Estimated total cost by optimizer
@return the project restrict operation as a result set.
@exception StandardException thrown when unable to create the
result set
*/
public NoPutResultSet getHashTableResultSet(NoPutResultSet source,
GeneratedMethod singleTableRestriction,
String equijoinQualifiersField,
GeneratedMethod projection, int resultSetNumber,
int mapRefItem,
boolean reuseResult,
int keyColItem,
boolean removeDuplicates,
long maxInMemoryRowCount,
int initialCapacity,
float loadFactor,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost)
throws StandardException;
/**
A sort result set sorts its source and if requested removes
duplicates. It will generate the entire result when open, and
then return it a row at a time.
<p>
If passed aggregates it will do scalar or vector aggregate
processing. A list of aggregator information is passed
off of the PreparedStatement's savedObjects. Aggregation
and SELECT DISTINCT cannot be processed in the same sort.
@param source the result set from which to take rows to be
filtered by this operation.
@param distinct true if distinct SELECT list
@param isInSortedOrder true if the source result set is in sorted order
@param orderItem entry in preparedStatement's savedObjects for order
@param rowAllocator a reference to a method in the activation
that generates rows of the right size and shape for the source
@param rowSize the size of the row that is allocated by rowAllocator.
size should be the maximum size of the sum of all the datatypes.
user type are necessarily approximated
@param resultSetNumber The resultSetNumber for the ResultSet
@param optimizerEstimatedRowCount Estimated total # of rows by
optimizer
@param optimizerEstimatedCost Estimated total cost by optimizer
@return the distinct operation as a result set.
@exception StandardException thrown when unable to create the
result set
*/
NoPutResultSet getSortResultSet(NoPutResultSet source,
boolean distinct,
boolean isInSortedOrder,
int orderItem,
GeneratedMethod rowAllocator,
int rowSize,
int resultSetNumber,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost,
String explainPlan)
throws StandardException;
/**
A ScalarAggregateResultSet computes non-distinct scalar aggregates.
It will compute the aggregates when open.
@param source the result set from which to take rows to be
filtered by this operation.
@param isInSortedOrder true if the source result set is in sorted order
@param aggregateItem entry in preparedStatement's savedObjects for aggregates
@param orderingItem Ignored to allow same signature as getDistinctScalarAggregateResultSet
@param rowAllocator a reference to a method in the activation
that generates rows of the right size and shape for the source
@param rowSize Ignored to allow same signature as getDistinctScalarAggregateResultSet
@param resultSetNumber The resultSetNumber for the ResultSet
@param singleInputRow Whether we know we have a single input row or not
@param optimizerEstimatedRowCount Estimated total # of rows by
optimizer
@param optimizerEstimatedCost Estimated total cost by optimizer
@return the scalar aggregation operation as a result set.
@exception StandardException thrown when unable to create the
result set
*/
NoPutResultSet getScalarAggregateResultSet(NoPutResultSet source,
boolean isInSortedOrder,
int aggregateItem,
int orderingItem,
GeneratedMethod rowAllocator,
int rowSize,
int resultSetNumber,
boolean singleInputRow,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost,
String explainPlan)
throws StandardException;
/**
A DistinctScalarAggregateResultSet computes scalar aggregates when
at least one of them is a distinct aggregate.
It will compute the aggregates when open.
@param source the result set from which to take rows to be
filtered by this operation.
@param isInSortedOrder true if the source result set is in sorted order
@param aggregateItem entry in preparedStatement's savedObjects for aggregates
@param orderingItem entry in preparedStatement's savedObjects for order
@param rowAllocator a reference to a method in the activation
that generates rows of the right size and shape for the source
@param rowSize the size of the row that is allocated by rowAllocator.
size should be the maximum size of the sum of all the datatypes.
user type are necessarily approximated
@param resultSetNumber The resultSetNumber for the ResultSet
@param singleInputRow Whether we know we have a single input row or not
@param optimizerEstimatedRowCount Estimated total # of rows by
optimizer
@param optimizerEstimatedCost Estimated total cost by optimizer
@return the scalar aggregation operation as a result set.
@exception StandardException thrown when unable to create the
result set
*/
NoPutResultSet getDistinctScalarAggregateResultSet(NoPutResultSet source,
boolean isInSortedOrder,
int aggregateItem,
int orderingItem,
GeneratedMethod rowAllocator,
int rowSize,
int resultSetNumber,
boolean singleInputRow,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost,
String explainPlan)
throws StandardException;
/**
A GroupedAggregateResultSet computes non-distinct grouped aggregates.
It will compute the aggregates when open.
@param source the result set from which to take rows to be
filtered by this operation.
@param isInSortedOrder true if the source result set is in sorted order
@param aggregateItem entry in preparedStatement's savedObjects for aggregates
@param orderingItem Ignored to allow same signature as getDistinctScalarAggregateResultSet
@param rowAllocator a reference to a method in the activation
that generates rows of the right size and shape for the source
@param rowSize Ignored to allow same signature as getDistinctScalarAggregateResultSet
@param resultSetNumber The resultSetNumber for the ResultSet
@param optimizerEstimatedRowCount Estimated total # of rows by
optimizer
@param optimizerEstimatedCost Estimated total cost by optimizer
@param isRollup true if this is a GROUP BY ROLLUP()
@return the scalar aggregation operation as a result set.
@exception StandardException thrown when unable to create the
result set
*/
NoPutResultSet getGroupedAggregateResultSet(NoPutResultSet source,
boolean isInSortedOrder,
int aggregateItem,
int orderingItem,
GeneratedMethod rowAllocator,
int rowSize,
int resultSetNumber,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost,
boolean isRollup,
String explainPlan)
throws StandardException;
/**
A DistinctGroupedAggregateResultSet computes scalar aggregates when
at least one of them is a distinct aggregate.
It will compute the aggregates when open.
@param source the result set from which to take rows to be
filtered by this operation.
@param isInSortedOrder true if the source result set is in sorted order
@param aggregateItem entry in preparedStatement's savedObjects for aggregates
@param orderingItem entry in preparedStatement's savedObjects for order
@param rowAllocator a reference to a method in the activation
that generates rows of the right size and shape for the source
@param rowSize the size of the row that is allocated by rowAllocator.
size should be the maximum size of the sum of all the datatypes.
user type are necessarily approximated
@param resultSetNumber The resultSetNumber for the ResultSet
@param optimizerEstimatedRowCount Estimated total # of rows by
optimizer
@param optimizerEstimatedCost Estimated total cost by optimizer
@param isRollup true if this is a GROUP BY ROLLUP()
@return the scalar aggregation operation as a result set.
@exception StandardException thrown when unable to create the
result set
*/
NoPutResultSet getDistinctGroupedAggregateResultSet(NoPutResultSet source,
boolean isInSortedOrder,
int aggregateItem,
int orderingItem,
GeneratedMethod rowAllocator,
int rowSize,
int resultSetNumber,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost,
boolean isRollup,
String explainPlan)
throws StandardException;
/**
An any result set iterates over its source,
returning a row with all columns set to nulls
if the source returns no rows.
@param source the result set from which to take rows to be
filtered by this operation.
@param emptyRowFun a reference to a method in the activation
that is called if the source returns no rows
@param resultSetNumber The resultSetNumber for the ResultSet
@param subqueryNumber The subquery number for this subquery.
@param pointOfAttachment The point of attachment for this subquery.
@param optimizerEstimatedRowCount Estimated total # of rows by
optimizer
@param optimizerEstimatedCost Estimated total cost by optimizer
@return the any operation as a result set.
@exception StandardException thrown when unable to create the
result set
*/
NoPutResultSet getAnyResultSet(NoPutResultSet source,
GeneratedMethod emptyRowFun, int resultSetNumber,
int subqueryNumber, int pointOfAttachment,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost)
throws StandardException;
/**
A once result set iterates over its source,
raising an error if the source returns > 1 row and
returning a row with all columns set to nulls
if the source returns no rows.
@param source the result set from which to take rows to be
filtered by this operation.
@param emptyRowFun a reference to a method in the activation
that is called if the source returns no rows
@param cardinalityCheck The type of cardinality check, if any that
is required
@param resultSetNumber The resultSetNumber for the ResultSet
@param subqueryNumber The subquery number for this subquery.
@param pointOfAttachment The point of attachment for this subquery.
@param optimizerEstimatedRowCount Estimated total # of rows by
optimizer
@param optimizerEstimatedCost Estimated total cost by optimizer
@return the once operation as a result set.
@exception StandardException thrown when unable to create the
result set
*/
NoPutResultSet getOnceResultSet(NoPutResultSet source,
GeneratedMethod emptyRowFun,
int cardinalityCheck, int resultSetNumber,
int subqueryNumber, int pointOfAttachment,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost)
throws StandardException;
/**
A row result set forms a result set on a single, known row value.
It is used to turn constant rows into result sets for use in
the result set paradigm.
The row can be constructed when it is requested from the
result set.
@param activation the activation for this result set,
against which the row operation is performed to
create the result set.
@param row a reference to a method in the activation
that creates the expected row.
<verbatim>
ExecRow row() throws StandardException;
</verbatim>
@param canCacheRow True if execution can cache the input row
after it has gotten it. If the input row is constructed soley
of constants or parameters, it is ok to cache this row rather
than recreating it each time it is requested.
@param resultSetNumber The resultSetNumber for the ResultSet
@param optimizerEstimatedRowCount Estimated total # of rows by
optimizer
@param optimizerEstimatedCost Estimated total cost by optimizer
@return the row as a result set.
@exception StandardException thrown when unable to create the
result set
*/
NoPutResultSet getRowResultSet(Activation activation, GeneratedMethod row,
boolean canCacheRow,
int resultSetNumber,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost)
throws StandardException;
NoPutResultSet getRowResultSet(Activation activation, ExecRow row,
boolean canCacheRow,
int resultSetNumber,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost)
throws StandardException;
/**
Splice Addition
A resultset that forms a result set on a collection of known rows.
It is used to cache rows from a result set that's been materialized.
@param activation The activation for this result set
@param rows The collection of known ExecRows
@param resultSetNumber The resultSetNumber for the result set being materialized
*/
NoPutResultSet getCachedResultSet(Activation activation, List rows, int resultSetNumber)
throws StandardException;
/**
A VTI result set wraps a user supplied result set.
@param activation the activation for this result set,
against which the row operation is performed to
create the result set.
@param row a reference to a method in the activation
that creates the expected row.
<verbatim>
ExecRow row() throws StandardException;
</verbatim>
@param resultSetNumber The resultSetNumber for the ResultSet
@param constructor The GeneratedMethod for the user's constructor
@param javaClassName The java class name for the VTI
@param erdNumber int for referenced column BitSet (so it can be turned back into an object)
@param version2 Whether or not VTI is a version 2 VTI.
@param isTarget Whether or not VTI is a target VTI.
@param optimizerEstimatedRowCount Estimated total # of rows by optimizer
@param optimizerEstimatedCost Estimated total cost by optimizer
@param isDerbyStyleTableFunction True if this is a Derby-style table function
@param returnTypeNumber Which saved object contains the return type (a multi-set) serialized as a byte array
@param vtiProjectionNumber Which saved object contains the projection for a RestrictedVTI
@param vtiRestrictionNumber Which saved object contains the restriction for a RestrictedVTI
@return the row as a result set.
@exception StandardException thrown when unable to create the
result set
*/
public NoPutResultSet getVTIResultSet(Activation activation, GeneratedMethod row,
int resultSetNumber,
GeneratedMethod constructor,
String javaClassName,
String pushedQualifiersField,
int erdNumber,
int ctcNumber,
boolean isTarget,
int scanIsolationLevel,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost,
boolean isDerbyStyleTableFunction,
int returnTypeNumber,
int vtiProjectionNumber,
int vtiRestrictionNumber,
String explainPlan)
throws StandardException;
/*
* This method was purely added to get some stored prepared statements to pass the validation stage of their compilation.
* The existing method used a String for pushedQualifiersField. However, nothing was done with the initial value that
* was passed into the constructor. So this method does the same thing and ignores the pushedQualifiersField which is
* an com.splicemachine.db.iapi.store.access.Qualifier[][].
*/
public NoPutResultSet getVTIResultSet(
Activation activation,
GeneratedMethod row,
int resultSetNumber,
GeneratedMethod constructor,
String javaClassName,
com.splicemachine.db.iapi.store.access.Qualifier[][] pushedQualifiersField,
int erdNumber,
int ctcNumber,
boolean isTarget,
int scanIsolationLevel,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost,
boolean isDerbyStyleTableFunction,
int returnTypeNumber,
int vtiProjectionNumber,
int vtiRestrictionNumber,
String explainPlan
)
throws StandardException;
/**
A hash result set forms a result set on a hash table built on a scan
of a table.
The rows are put into the hash table on the 1st open.
<p>
@param activation the activation for this result set,
which provides the context for the row allocation operation.
@param conglomId the conglomerate of the table to be scanned.
@param scociItem The saved item for the static conglomerate info.
@param resultRowAllocator a reference to a method in the activation
that creates a holder for the rows from the scan.
<verbatim>
ExecRow rowAllocator() throws StandardException;
</verbatim>
@param resultSetNumber The resultSetNumber for the ResultSet
@param startKeyGetter a reference to a method in the activation
that gets the start key indexable row for the scan. Null
means there is no start key.
<verbatim>
ExecIndexRow startKeyGetter() throws StandardException;
</verbatim>
@param startSearchOperator The start search operator for opening
the scan
@param stopKeyGetter a reference to a method in the activation
that gets the stop key indexable row for the scan. Null means
there is no stop key.
<verbatim>
ExecIndexRow stopKeyGetter() throws StandardException;
</verbatim>
@param stopSearchOperator The stop search operator for opening
the scan
@param sameStartStopPosition Re-use the startKeyGetter for the stopKeyGetter
(Exact match search.)
@param scanQualifiers the array of Qualifiers for the scan.
Null or an array length of zero means there are no qualifiers.
@param nextQualifiers the array of Qualifiers for the look up into the hash table.
@param initialCapacity The initialCapacity for the HashTable.
@param loadFactor The loadFactor for the HashTable.
@param maxCapacity The maximum size for the HashTable.
@param hashKeyColumn The 0-based column # for the hash key.
@param tableName The full name of the table
@param userSuppliedOptimizerOverrides Overrides specified by the user on the sql
@param indexName The name of the index, if one used to access table.
@param isConstraint If index, if used, is a backing index for a constraint.
@param forUpdate True means open for update
@param colRefItem An saved item for a bitSet of columns that
are referenced in the underlying table. -1 if
no item.
@param lockMode The lock granularity to use (see
TransactionController in access)
@param tableLocked Whether or not the table is marked as using table locking
(in sys.systables)
@param isolationLevel Isolation level (specified or not) to use on scans
@param optimizerEstimatedRowCount Estimated total # of rows by
optimizer
@param optimizerEstimatedCost Estimated total cost by optimizer
@return the table scan operation as a result set.
@exception StandardException thrown when unable to create the
result set
*/
NoPutResultSet getHashScanResultSet(
Activation activation,
long conglomId,
int scociItem,
GeneratedMethod resultRowAllocator,
int resultSetNumber,
GeneratedMethod startKeyGetter,
int startSearchOperator,
GeneratedMethod stopKeyGetter,
int stopSearchOperator,
boolean sameStartStopPosition,
boolean rowIdKey,
String scanQualifiersField,
String nextQualifierField,
int initialCapacity,
float loadFactor,
int maxCapacity,
int hashKeyColumn,
String tableName,
String userSuppliedOptimizerOverrides,
String indexName,
boolean isConstraint,
boolean forUpdate,
int colRefItem,
int indexColItem,
int lockMode,
boolean tableLocked,
int isolationLevel,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost)
throws StandardException;
/**
A distinct scan result set pushes duplicate elimination into
the scan.
<p>
@param activation the activation for this result set,
which provides the context for the row allocation operation.
@param conglomId the conglomerate of the table to be scanned.
@param scociItem The saved item for the static conglomerate info.
@param resultRowAllocator a reference to a method in the activation
that creates a holder for the rows from the scan.
<verbatim>
ExecRow rowAllocator() throws StandardException;
</verbatim>
@param resultSetNumber The resultSetNumber for the ResultSet
@param hashKeyColumn The 0-based column # for the hash key.
@param tableName The full name of the table
@param userSuppliedOptimizerOverrides Overrides specified by the user on the sql
@param indexName The name of the index, if one used to access table.
@param isConstraint If index, if used, is a backing index for a constraint.
@param colRefItem An saved item for a bitSet of columns that
are referenced in the underlying table. -1 if
no item.
@param lockMode The lock granularity to use (see
TransactionController in access)
@param tableLocked Whether or not the table is marked as using table locking
(in sys.systables)
@param isolationLevel Isolation level (specified or not) to use on scans
@param optimizerEstimatedRowCount Estimated total # of rows by
optimizer
@param optimizerEstimatedCost Estimated total cost by optimizer
@return the table scan operation as a result set.
@exception StandardException thrown when unable to create the
result set
*/
NoPutResultSet getDistinctScanResultSet(
Activation activation,
long conglomId,
int scociItem,
GeneratedMethod resultRowAllocator,
int resultSetNumber,
int hashKeyColumn,
String tableName,
String userSuppliedOptimizerOverrides,
String indexName,
boolean isConstraint,
int colRefItem,
int lockMode,
boolean tableLocked,
int isolationLevel,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost,
String tableVersion)
throws StandardException;
/**
A table scan result set forms a result set on a scan
of a table.
The rows can be constructed as they are requested from the
result set.
<p>
This form of the table scan operation is simple, and is
to be used when there are no predicates to be passed down
to the scan to limit its scope on the target table.
@param conglomId the conglomerate of the table to be scanned.
@param scociItem The saved item for the static conglomerate info.
@param activation the activation for this result set,
which provides the context for the row allocation operation.
@param resultRowAllocator a reference to a method in the activation
that creates a holder for the result row of the scan. May
be a partial row.
<verbatim>
ExecRow rowAllocator() throws StandardException;
</verbatim>
@param resultSetNumber The resultSetNumber for the ResultSet
@param startKeyGetter a reference to a method in the activation
that gets the start key indexable row for the scan. Null
means there is no start key.
<verbatim>
ExecIndexRow startKeyGetter() throws StandardException;
</verbatim>
@param startSearchOperator The start search operator for opening
the scan
@param stopKeyGetter a reference to a method in the activation
that gets the stop key indexable row for the scan. Null means
there is no stop key.
<verbatim>
ExecIndexRow stopKeyGetter() throws StandardException;
</verbatim>
@param stopSearchOperator The stop search operator for opening
the scan
@param sameStartStopPosition Re-use the startKeyGetter for the stopKeyGetter
(Exact match search.)
@param qualifiers the array of Qualifiers for the scan.
Null or an array length of zero means there are no qualifiers.
@param tableName The full name of the table
@param userSuppliedOptimizerOverrides Overrides specified by the user on the sql
@param indexName The name of the index, if one used to access table.
@param isConstraint If index, if used, is a backing index for a constraint.
@param forUpdate True means open for update
@param colRefItem An saved item for a bitSet of columns that
are referenced in the underlying table. -1 if
no item.
@param lockMode The lock granularity to use (see
TransactionController in access)
@param tableLocked Whether or not the table is marked as using table locking
(in sys.systables)
@param isolationLevel Isolation level (specified or not) to use on scans
@param oneRowScan Whether or not this is a 1 row scan.
@param optimizerEstimatedRowCount Estimated total # of rows by
optimizer
@param optimizerEstimatedCost Estimated total cost by optimizer
@return the table scan operation as a result set.
@exception StandardException thrown when unable to create the
result set
*/
NoPutResultSet getTableScanResultSet(
Activation activation,
long conglomId,
int scociItem,
GeneratedMethod resultRowAllocator,
int resultSetNumber,
GeneratedMethod startKeyGetter,
int startSearchOperator,
GeneratedMethod stopKeyGetter,
int stopSearchOperator,
boolean sameStartStopPosition,
boolean rowIdKey,
String qualifiersField,
String tableName,
String userSuppliedOptimizerOverrides,
String indexName,
boolean isConstraint,
boolean forUpdate,
int colRefItem,
int indexColItem,
int lockMode,
boolean tableLocked,
int isolationLevel,
boolean oneRowScan,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost,
String tableVersion,
String explainPlan)
throws StandardException;
/**
A table scan result set forms a result set on a scan
of a table.
The rows can be constructed as they are requested from the
result set.
<p>
This form of the table scan operation is simple, and is
to be used when there are no predicates to be passed down
to the scan to limit its scope on the target table.
@param conglomId the conglomerate of the table to be scanned.
@param scociItem The saved item for the static conglomerate info.
@param activation the activation for this result set,
which provides the context for the row allocation operation.
@param resultRowAllocator a reference to a method in the activation
that creates a holder for the result row of the scan. May
be a partial row.
<verbatim>
ExecRow rowAllocator() throws StandardException;
</verbatim>
@param resultSetNumber The resultSetNumber for the ResultSet
@param startKeyGetter a reference to a method in the activation
that gets the start key indexable row for the scan. Null
means there is no start key.
<verbatim>
ExecIndexRow startKeyGetter() throws StandardException;
</verbatim>
@param startSearchOperator The start search operator for opening
the scan
@param stopKeyGetter a reference to a method in the activation
that gets the stop key indexable row for the scan. Null means
there is no stop key.
<verbatim>
ExecIndexRow stopKeyGetter() throws StandardException;
</verbatim>
@param stopSearchOperator The stop search operator for opening
the scan
@param sameStartStopPosition Re-use the startKeyGetter for the stopKeyGetter
(Exact match search.)
@param qualifiers the array of Qualifiers for the scan.
Null or an array length of zero means there are no qualifiers.
@param tableName The full name of the table
@param userSuppliedOptimizerOverrides Overrides specified by the user on the sql
@param indexName The name of the index, if one used to access table.
@param isConstraint If index, if used, is a backing index for a constraint.
@param forUpdate True means open for update
@param colRefItem An saved item for a bitSet of columns that
are referenced in the underlying table. -1 if
no item.
@param lockMode The lock granularity to use (see
TransactionController in access)
@param tableLocked Whether or not the table is marked as using table locking
(in sys.systables)
@param isolationLevel Isolation level (specified or not) to use on scans
@param rowsPerRead The number of rows to read per fetch.
@param disableForHoldable Whether or not bulk fetch should be disabled
at runtime if the cursor is holdable.
@param oneRowScan Whether or not this is a 1 row scan.
@param optimizerEstimatedRowCount Estimated total # of rows by
optimizer
@param optimizerEstimatedCost Estimated total cost by optimizer
@return the table scan operation as a result set.
@exception StandardException thrown when unable to create the
result set
*/
NoPutResultSet getBulkTableScanResultSet(
Activation activation,
long conglomId,
int scociItem,
GeneratedMethod resultRowAllocator,
int resultSetNumber,
GeneratedMethod startKeyGetter,
int startSearchOperator,
GeneratedMethod stopKeyGetter,
int stopSearchOperator,
boolean sameStartStopPosition,
boolean rowIdKey,
String qualifiersField,
String tableName,
String userSuppliedOptimizerOverrides,
String indexName,
boolean isConstraint,
boolean forUpdate,
int colRefItem,
int indexColItem,
int lockMode,
boolean tableLocked,
int isolationLevel,
int rowsPerRead,
boolean disableForHoldable,
boolean oneRowScan,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost,
String tableVersion,
String explainPlan)
throws StandardException;
/**
A multi-probe result set, used for probing an index with one or more
target values (probeValues) and returning the matching rows. This
type of result set is useful for IN lists as it allows us to avoid
scannning an entire, potentially very large, index for a mere handful
of rows (DERBY-47).
All arguments are the same as for TableScanResultSet, plus the
following:
@param probeVals List of values with which to probe the underlying
table. Should not be null.
@param sortRequired Which type of sort we need for the values
(ascending, descending, or none).
*/
NoPutResultSet getMultiProbeTableScanResultSet(
Activation activation,
long conglomId,
int scociItem,
GeneratedMethod resultRowAllocator,
int resultSetNumber,
GeneratedMethod startKeyGetter,
int startSearchOperator,
GeneratedMethod stopKeyGetter,
int stopSearchOperator,
boolean sameStartStopPosition,
boolean rowIdKey,
String qualifiersField,
DataValueDescriptor [] probeVals,
int sortRequired,
String tableName,
String userSuppliedOptimizerOverrides,
String indexName,
boolean isConstraint,
boolean forUpdate,
int colRefItem,
int indexColItem,
int lockMode,
boolean tableLocked,
int isolationLevel,
boolean oneRowScan,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost,
String tableVersion,
String explainPlan)
throws StandardException;
/**
An index row to base row result set gets an index row from its source
and uses the RowLocation in its last column to get the row from the
base conglomerate.
<p>
@param conglomId Conglomerate # for the heap.
@param scoci The saved item for the static conglomerate info.
@param source the source result set, which is expected to provide
rows from an index conglomerate
@param resultRowAllocator a reference to a method in the activation
that creates a holder for the rows from the scan.
<verbatim>
ExecRow rowAllocator() throws StandardException;
</verbatim>
@param resultSetNumber The resultSetNumber for the ResultSet
@param indexName The name of the index.
@param heapColRefItem A saved item for a bitImpl of columns that
are referenced in the underlying heap. -1 if
no item.
@param allColRefItem A saved item for a bitImpl of columns
that are referenced in the underlying
index and heap. -1 if no item.
@param heapOnlyColRefItem A saved item for a bitImpl of
columns that are referenced in the
underlying heap only. -1 if no item.
@param indexColMapItem A saved item for a ReferencedColumnsDescriptorImpl
which tell which columms are coming from the index.
@param restriction The restriction, if any, to be applied to the base row
@param forUpdate True means to open for update
@param optimizerEstimatedRowCount Estimated total # of rows by
optimizer
@param optimizerEstimatedCost Estimated total cost by optimizer
@return the index row to base row operation as a result set.
@exception StandardException thrown when unable to create the
result set
*/
public NoPutResultSet getIndexRowToBaseRowResultSet(
long conglomId,
int scoci,
NoPutResultSet source,
GeneratedMethod resultRowAllocator,
int resultSetNumber,
String indexName,
int heapColRefItem,
int allColRefItem,
int heapOnlyColRefItem,
int indexColMapItem,
GeneratedMethod restriction,
boolean forUpdate,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost,
String tableVersion,
String explainPlan)
throws StandardException;
/**
A OLAP window on top of a regular result set. It is used to realize
window functions.
@param source the result set from which to take rows to be
filtered by this operation.
@param isInSortedOrder true if the source result set is in sorted order
@param aggregateItem entry in preparedStatement's savedObjects for aggregates
@param rowAllocator a reference to a method in the activation
that generates rows of the right size and shape for the source
@param rowSize the size of the row that is allocated by rowAllocator.
size should be the maximum size of the sum of all the datatypes.
user type are necessarily approximated
@param resultSetNumber The resultSetNumber for the ResultSet
@param optimizerEstimatedRowCount Estimated total # of rows by
optimizer
@param optimizerEstimatedCost Estimated total cost by optimizer
@return the scalar aggregation operation as a result set.
@exception StandardException thrown when unable to create the
result set
*/
NoPutResultSet getWindowResultSet(NoPutResultSet source,
boolean isInSortedOrder,
int aggregateItem,
GeneratedMethod rowAllocator,
int rowSize,
int resultSetNumber,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost,
String explainPlan)
throws StandardException;
/**
A nested loop left outer join result set forms a result set on top of
2 other result sets.
The rows can be constructed as they are requested from the
result set.
<p>
This form of the nested loop join operation is simple, and is
to be used when there are no join predicates to be passed down
to the join to limit its scope on the right ResultSet.
@param leftResultSet Outer ResultSet for join.
@param leftNumCols Number of columns in the leftResultSet
@param rightResultSet Inner ResultSet for join.
@param rightNumCols Number of columns in the rightResultSet
@param joinClause a reference to a method in the activation
that is applied to the activation's "current row" field
to determine whether the joinClause is satisfied or not.
The signature of this method is
<verbatim>
Boolean joinClause() throws StandardException;
</verbatim>
@param resultSetNumber The resultSetNumber for the ResultSet
@param oneRowRightSide boolean, whether or not the right side returns
a single row. (No need to do 2nd next() if it does.)
@param notExistsRightSide boolean, whether or not the right side resides a
NOT EXISTS base table
@param optimizerEstimatedRowCount Estimated total # of rows by
optimizer
@param optimizerEstimatedCost Estimated total cost by optimizer
@param userSuppliedOptimizerOverrides Overrides specified by the user on the sql
@return the nested loop join operation as a result set.
@exception StandardException thrown when unable to create the
result set
*/
public NoPutResultSet getNestedLoopJoinResultSet(NoPutResultSet leftResultSet,
int leftNumCols,
NoPutResultSet rightResultSet,
int rightNumCols,
GeneratedMethod joinClause,
int resultSetNumber,
boolean oneRowRightSide,
boolean notExistsRightSide,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost,
String userSuppliedOptimizerOverrides,
String explainPlan)
throws StandardException;
public NoPutResultSet getMergeSortJoinResultSet(NoPutResultSet leftResultSet,
int leftNumCols,
NoPutResultSet rightResultSet,
int rightNumCols,
int leftHashKeyItem,
int rightHashKeyItem,
GeneratedMethod joinClause,
int resultSetNumber,
boolean oneRowRightSide,
boolean notExistsRightSide,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost,
String userSuppliedOptimizerOverrides,
String explainPlan)
throws StandardException;
public NoPutResultSet getMergeJoinResultSet(NoPutResultSet leftResultSet,
int leftNumCols,
NoPutResultSet rightResultSet,
int rightNumCols,
int leftHashKeyItem,
int rightHashKeyItem,
GeneratedMethod joinClause,
int resultSetNumber,
boolean oneRowRightSide,
boolean notExistsRightSide,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost,
String userSuppliedOptimizerOverrides,
String explainPlan)
throws StandardException;
public NoPutResultSet getBroadcastJoinResultSet(NoPutResultSet leftResultSet,
int leftNumCols,
NoPutResultSet rightResultSet,
int rightNumCols,
int leftHashKeyItem,
int rightHashKeyItem,
GeneratedMethod joinClause,
int resultSetNumber,
boolean oneRowRightSide,
boolean notExistsRightSide,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost,
String userSuppliedOptimizerOverrides,
String explainPlan)
throws StandardException;
/**
A hash join.
@param leftResultSet Outer ResultSet for join.
@param leftNumCols Number of columns in the leftResultSet
@param rightResultSet Inner ResultSet for join.
@param rightNumCols Number of columns in the rightResultSet
@param joinClause a reference to a method in the activation
that is applied to the activation's "current row" field
to determine whether the joinClause is satisfied or not.
The signature of this method is
<verbatim>
Boolean joinClause() throws StandardException;
</verbatim>
@param resultSetNumber The resultSetNumber for the ResultSet
@param oneRowRightSide boolean, whether or not the right side returns
a single row. (No need to do 2nd next() if it does.)
@param notExistsRightSide boolean, whether or not the right side resides a
NOT EXISTS base table
@param optimizerEstimatedRowCount Estimated total # of rows by
optimizer
@param optimizerEstimatedCost Estimated total cost by optimizer
@param userSuppliedOptimizerOverrides Overrides specified by the user on the sql
@return the nested loop join operation as a result set.
@exception StandardException thrown when unable to create the
result set
*/
public NoPutResultSet getHashJoinResultSet(NoPutResultSet leftResultSet,
int leftNumCols,
NoPutResultSet rightResultSet,
int rightNumCols,
int leftHashKeyitem,
int rightHashKeyItem,
GeneratedMethod joinClause,
int resultSetNumber,
boolean oneRowRightSide,
boolean notExistsRightSide,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost,
String userSuppliedOptimizerOverrides,
String explainPlan)
throws StandardException;
/**
A nested loop join result set forms a result set on top of
2 other result sets.
The rows can be constructed as they are requested from the
result set.
<p>
This form of the nested loop join operation is simple, and is
to be used when there are no join predicates to be passed down
to the join to limit its scope on the right ResultSet.
@param leftResultSet Outer ResultSet for join.
@param leftNumCols Number of columns in the leftResultSet
@param rightResultSet Inner ResultSet for join.
@param rightNumCols Number of columns in the rightResultSet
@param joinClause a reference to a method in the activation
that is applied to the activation's "current row" field
to determine whether the joinClause is satisfied or not.
The signature of this method is
<verbatim>
Boolean joinClause() throws StandardException;
</verbatim>
@param resultSetNumber The resultSetNumber for the ResultSet
@param emptyRowFun a reference to a method in the activation
that is called if the right child returns no rows
@param wasRightOuterJoin Whether or not this was originally a right outer join
@param oneRowRightSide boolean, whether or not the right side returns
a single row. (No need to do 2nd next() if it does.)
@param notExistsRightSide boolean, whether or not the right side resides a
NOT EXISTS base table
@param optimizerEstimatedRowCount Estimated total # of rows by
optimizer
@param optimizerEstimatedCost Estimated total cost by optimizer
@param userSuppliedOptimizerOverrides Overrides specified by the user on the sql
@return the nested loop join operation as a result set.
@exception StandardException thrown when unable to create the
result set
*/
public NoPutResultSet getNestedLoopLeftOuterJoinResultSet(NoPutResultSet leftResultSet,
int leftNumCols,
NoPutResultSet rightResultSet,
int rightNumCols,
GeneratedMethod joinClause,
int resultSetNumber,
GeneratedMethod emptyRowFun,
boolean wasRightOuterJoin,
boolean oneRowRightSide,
boolean notExistsRightSide,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost,
String userSuppliedOptimizerOverrides,
String explainPlan)
throws StandardException;
/**
A left outer join using a hash join.
@param leftResultSet Outer ResultSet for join.
@param leftNumCols Number of columns in the leftResultSet
@param rightResultSet Inner ResultSet for join.
@param rightNumCols Number of columns in the rightResultSet
@param joinClause a reference to a method in the activation
that is applied to the activation's "current row" field
to determine whether the joinClause is satisfied or not.
The signature of this method is
<verbatim>
Boolean joinClause() throws StandardException;
</verbatim>
@param resultSetNumber The resultSetNumber for the ResultSet
@param emptyRowFun a reference to a method in the activation
that is called if the right child returns no rows
@param wasRightOuterJoin Whether or not this was originally a right outer join
@param oneRowRightSide boolean, whether or not the right side returns
a single row. (No need to do 2nd next() if it does.)
@param notExistsRightSide boolean, whether or not the right side resides a
NOT EXISTS base table
@param optimizerEstimatedRowCount Estimated total # of rows by
optimizer
@param optimizerEstimatedCost Estimated total cost by optimizer
@param userSuppliedOptimizerOverrides Overrides specified by the user on the sql
@return the nested loop join operation as a result set.
@exception StandardException thrown when unable to create the
result set
*/
public NoPutResultSet getHashLeftOuterJoinResultSet(NoPutResultSet leftResultSet,
int leftNumCols,
NoPutResultSet rightResultSet,
int rightNumCols,
int leftHashKeyItem,
int rightHashKeyItem,
GeneratedMethod joinClause,
int resultSetNumber,
GeneratedMethod emptyRowFun,
boolean wasRightOuterJoin,
boolean oneRowRightSide,
boolean notExistsRightSide,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost,
String userSuppliedOptimizerOverrides,
String explainPlan)
throws StandardException;
/**
A ResultSet which materializes the underlying ResultSet tree into a
temp table on the 1st open. All subsequent "scans" of this ResultSet
will return results from the temp table.
@param source the result set input to this result set.
@param resultSetNumber The resultSetNumber for the ResultSet
@param optimizerEstimatedRowCount Estimated total # of rows by
optimizer
@param optimizerEstimatedCost Estimated total cost by optimizer
@return the materialization operation as a result set.
@exception StandardException Thrown on failure
*/
NoPutResultSet getMaterializedResultSet(NoPutResultSet source,
int resultSetNumber,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost)
throws StandardException;
/**
A ResultSet which provides the insensitive scrolling functionality
for the underlying result set by materializing the underlying ResultSet
tree into a hash table while scrolling forward.
@param source the result set input to this result set.
@param activation the activation for this result set,
which provides the context for normalization.
@param resultSetNumber The resultSetNumber for the ResultSet
@param sourceRowWidth The # of columns in the source row.
@param optimizerEstimatedRowCount Estimated total # of rows by
optimizer
@param optimizerEstimatedCost Estimated total cost by optimizer
@return the materialization operation as a result set.
@exception StandardException Thrown on failure
*/
NoPutResultSet getScrollInsensitiveResultSet(NoPutResultSet source,
Activation activation,
int resultSetNumber,
int sourceRowWidth,
boolean scrollable,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost,
String explainPlan)
throws StandardException;
/**
A left outer join using a sort merge join.
@param leftResultSet Outer ResultSet for join.
@param leftNumCols Number of columns in the leftResultSet
@param rightResultSet Inner ResultSet for join.
@param rightNumCols Number of columns in the rightResultSet
@param joinClause a reference to a method in the activation
that is applied to the activation's "current row" field
to determine whether the joinClause is staisfied or not.
The signature of this method is
<verbatim>
Boolean joinClause() throws StandardException;
</verbatim>
@param resultSetNumber The resultSetNumber for the ResultSet
@param emptyRowFun a reference to a method in the activation
that is called if the right child returns no rows
@param wasRightOuterJoin Whether or not this was originally a right outer join
@param oneRowRightSide boolean, whether or not the right side returns
a single row. (No need to do 2nd next() if it does.)
@param notExistsRightSide boolean, whether or not the right side resides a
NOT EXISTS base table
@param optimizerEstimatedRowCount Estimated total # of rows by
optimizer
@param optimizerEstimatedCost Estimated total cost by optimizer
@param userSuppliedOptimizerOverrides Overrides specified by the user on the sql
@return the nested loop join operation as a result set.
@exception StandardException thrown when unable to create the
result set
*/
public NoPutResultSet getMergeSortLeftOuterJoinResultSet(NoPutResultSet leftResultSet,
int leftNumCols,
NoPutResultSet rightResultSet,
int rightNumCols,
int leftHashKeyItem,
int rightHashKeyItem,
GeneratedMethod joinClause,
int resultSetNUmber,
GeneratedMethod emptyRowFun,
boolean wasRightOuterJoin,
boolean oneRowRightSide,
boolean noExistsRightSide,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost,
String userSuppliedOptimizerOverrides,
String explainPlan)
throws StandardException;
public NoPutResultSet getMergeLeftOuterJoinResultSet(NoPutResultSet leftResultSet,
int leftNumCols,
NoPutResultSet rightResultSet,
int rightNumCols,
int leftHashKeyItem,
int rightHashKeyItem,
GeneratedMethod joinClause,
int resultSetNUmber,
GeneratedMethod emptyRowFun,
boolean wasRightOuterJoin,
boolean oneRowRightSide,
boolean noExistsRightSide,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost,
String userSuppliedOptimizerOverrides,
String explainPlan)
throws StandardException;
public NoPutResultSet getBroadcastLeftOuterJoinResultSet(NoPutResultSet leftResultSet,
int leftNumCols,
NoPutResultSet rightResultSet,
int rightNumCols,
int leftHashKeyItem,
int rightHashKeyItem,
GeneratedMethod joinClause,
int resultSetNUmber,
GeneratedMethod emptyRowFun,
boolean wasRightOuterJoin,
boolean oneRowRightSide,
boolean noExistsRightSide,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost,
String userSuppliedOptimizerOverrides,
String explainPlan)
throws StandardException;
/**
REMIND: needs more description...
@param source the result set input to this result set.
@param resultSetNumber The resultSetNumber for the ResultSet
@param erdNumber int for ResultDescription
(so it can be turned back into an object)
@param optimizerEstimatedRowCount Estimated total # of rows by
optimizer
@param optimizerEstimatedCost Estimated total cost by optimizer
@return the normalization operation as a result set.
@exception StandardException Thrown on failure
*/
NoPutResultSet getNormalizeResultSet(NoPutResultSet source,
int resultSetNumber,
int erdNumber,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost,
boolean forUpdate,
String explainPlan)
throws StandardException;
/**
A current of result set forms a result set on the
current row of an open cursor.
It is used to perform positioned operations such as
positioned update and delete, using the result set paradigm.
@param cursorName the name of the cursor providing the row.
@param resultSetNumber The resultSetNumber for the ResultSet
*/
NoPutResultSet getCurrentOfResultSet(String cursorName, Activation activation,
int resultSetNumber);
/**
* The Union interface is used to evaluate the union (all) of two ResultSets.
* (Any duplicate elimination is performed above this ResultSet.)
*
* Forms a ResultSet returning the union of the rows in two source
* ResultSets. The column types in source1 and source2 are assumed to be
* the same.
*
* @param source1 The first ResultSet whose rows go into the union
* @param source2 The second ResultSet whose rows go into the
* union
* @param resultSetNumber The resultSetNumber for the ResultSet
* @param optimizerEstimatedRowCount Estimated total # of rows by
* optimizer
* @param optimizerEstimatedCost Estimated total cost by optimizer
*
* @return A ResultSet from which the caller can get the union
* of the two source ResultSets.
*
* @exception StandardException Thrown on failure
*/
NoPutResultSet getUnionResultSet(NoPutResultSet source1,
NoPutResultSet source2,
int resultSetNumber,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost,
String explainPlan)
throws StandardException;
/**
* The SetOpResultSet is used to implement an INTERSECT or EXCEPT operation.
* It selects rows from two ordered input result sets.
*
* @param leftSource The result set that implements the left input
* @param rightSource The result set that implements the right input
* @param activation the activation for this result set
* @param resultSetNumber
* @param optimizerEstimatedRowCount
* @param optimizerEstimatedCost
* @param opType IntersectOrExceptNode.INTERSECT_OP or EXCEPT_OP
* @param all true if the operation is an INTERSECT ALL or an EXCEPT ALL,
* false if the operation is an INTERSECT DISCTINCT or an EXCEPT DISCTINCT
* @param intermediateOrderByColumnsSavedObject The saved object index for the array of order by columns for the
* ordering of the left and right sources. That is, both the left and right sources have an order by
* clause of the form ORDER BY intermediateOrderByColumns[0],intermediateOrderByColumns[1],...
* @param intermediateOrderByDirectionSavedObject The saved object index for the array of source
* order by directions. That is, the ordering of the i'th order by column in the input is ascending
* if intermediateOrderByDirection[i] is 1, descending if intermediateOrderByDirection[i] is -1.
*
* @return A ResultSet from which the caller can get the INTERSECT or EXCEPT
*
* @exception StandardException Thrown on failure
*/
NoPutResultSet getSetOpResultSet( NoPutResultSet leftSource,
NoPutResultSet rightSource,
Activation activation,
int resultSetNumber,
long optimizerEstimatedRowCount,
double optimizerEstimatedCost,
int opType,
boolean all,
int intermediateOrderByColumnsSavedObject,
int intermediateOrderByDirectionSavedObject,
int intermediateOrderByNullsLowSavedObject)
throws StandardException;
//
// Misc operations
//
/**
* A last index key result set returns the last row from
* the index in question. It is used as an ajunct to max().
*
* @param activation the activation for this result set,
* which provides the context for the row allocation operation.
* @param resultSetNumber The resultSetNumber for the ResultSet
* @param resultRowAllocator a reference to a method in the activation
* that creates a holder for the result row of the scan. May
* be a partial row. <verbatim>
* ExecRow rowAllocator() throws StandardException; </verbatim>
* @param conglomId the conglomerate of the table to be scanned.
* @param tableName The full name of the table
* @param userSuppliedOptimizerOverrides Overrides specified by the user on the sql
* @param indexName The name of the index, if one used to access table.
* @param colRefItem An saved item for a bitSet of columns that
* are referenced in the underlying table. -1 if
* no item.
* @param lockMode The lock granularity to use (see
* TransactionController in access)
* @param tableLocked Whether or not the table is marked as using table locking
* (in sys.systables)
* @param isolationLevel Isolation level (specified or not) to use on scans
* @param optimizerEstimatedRowCount Estimated total # of rows by
* optimizer
* @param optimizerEstimatedCost Estimated total cost by optimizer
*
* @return the scan operation as a result set.
*
* @exception StandardException thrown when unable to create the
* result set
*/
NoPutResultSet getLastIndexKeyResultSet
(
Activation activation,
int resultSetNumber,
GeneratedMethod resultRowAllocator,
long conglomId,
String tableName,
String userSuppliedOptimizerOverrides,
String indexName,
int colRefItem,
int lockMode,
boolean tableLocked,
int isolationLevel,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost,
String tableVersion
) throws StandardException;
/**
A Dependent table scan result set forms a result set on a scan
of a dependent table for the rows that got materilized
on the scan of its parent table and if the row being deleted
on parent table has a reference in the dependent table.
@param activation the activation for this result set,
which provides the context for the row allocation operation.
@param conglomId the conglomerate of the table to be scanned.
@param scociItem The saved item for the static conglomerate info.
@param resultRowAllocator a reference to a method in the activation
that creates a holder for the result row of the scan. May
be a partial row.
<verbatim>
ExecRow rowAllocator() throws StandardException;
</verbatim>
@param resultSetNumber The resultSetNumber for the ResultSet
@param startKeyGetter a reference to a method in the activation
that gets the start key indexable row for the scan. Null
means there is no start key.
<verbatim>
ExecIndexRow startKeyGetter() throws StandardException;
</verbatim>
@param startSearchOperator The start search operator for opening
the scan
@param stopKeyGetter a reference to a method in the activation
that gets the stop key indexable row for the scan. Null means
there is no stop key.
<verbatim>
ExecIndexRow stopKeyGetter() throws StandardException;
</verbatim>
@param stopSearchOperator The stop search operator for opening
the scan
@param sameStartStopPosition Re-use the startKeyGetter for the stopKeyGetter
(Exact match search.)
@param qualifiers the array of Qualifiers for the scan.
Null or an array length of zero means there are no qualifiers.
@param tableName The full name of the table
@param userSuppliedOptimizerOverrides Overrides specified by the user on the sql
@param indexName The name of the index, if one used to access table.
@param isConstraint If index, if used, is a backing index for a constraint.
@param forUpdate True means open for update
@param colRefItem An saved item for a bitSet of columns that
are referenced in the underlying table. -1 if
no item.
@param lockMode The lock granularity to use (see
TransactionController in access)
@param tableLocked Whether or not the table is marked as using table locking
(in sys.systables)
@param isolationLevel Isolation level (specified or not) to use on scans
@param oneRowScan Whether or not this is a 1 row scan.
@param optimizerEstimatedRowCount Estimated total # of rows by
optimizer
@param optimizerEstimatedCost Estimated total cost by optimizer
@param parentResultSetId Id to access the materlized temporary result
set from the refence stored in the activation.
@param fkIndexConglomId foreign key index conglomerate id.
@param fkColArrayItem saved column array object that matches the foreign key index
columns and the resultset from the parent table.
@param rltItem row location template
@return the table scan operation as a result set.
@exception StandardException thrown when unable to create the
result set
*/
public NoPutResultSet getRaDependentTableScanResultSet(
Activation activation,
long conglomId,
int scociItem,
GeneratedMethod resultRowAllocator,
int resultSetNumber,
GeneratedMethod startKeyGetter,
int startSearchOperator,
GeneratedMethod stopKeyGetter,
int stopSearchOperator,
boolean sameStartStopPosition,
boolean rowIdKey,
String qualifiersField,
String tableName,
String userSuppliedOptimizerOverrides,
String indexName,
boolean isConstraint,
boolean forUpdate,
int colRefItem,
int indexColItem,
int lockMode,
boolean tableLocked,
int isolationLevel,
boolean oneRowScan,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost,
String parentResultSetId,
long fkIndexConglomId,
int fkColArrayItem,
int rltItem)
throws StandardException;
/**
* This result sets implements the filtering needed by <result offset
* clause> and <fetch first clause>. It is only ever generated if at least
* one of the two clauses is present.
*
* @param source The source result set being filtered
* @param activation The activation for this result set,
* which provides the context for the row
* allocation operation
* @param resultSetNumber The resultSetNumber for the ResultSet
* @param offsetMethod The OFFSET parameter was specified
* @param fetchFirstMethod The FETCH FIRST/NEXT parameter was specified
* @param hasJDBClimitClause True if the offset/fetchFirst clauses were added by JDBC LIMExeIT escape syntax
* @param optimizerEstimatedRowCount
* Estimated total # of rows by optimizer
* @param optimizerEstimatedCost
* Estimated total cost by optimizer
* @exception StandardException Standard error policy
*/
public NoPutResultSet getRowCountResultSet(
NoPutResultSet source,
Activation activation,
int resultSetNumber,
GeneratedMethod offsetMethod,
GeneratedMethod fetchFirstMethod,
boolean hasJDBClimitClause,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost,
String explainPlan) throws StandardException;
public NoPutResultSet getExplainResultSet(ResultSet source, Activation activation, int resultSetNumber) throws StandardException;
public NoPutResultSet getExplainResultSet(NoPutResultSet source, Activation activation, int resultSetNumber) throws StandardException;
/**
* Export
*/
public NoPutResultSet getExportResultSet(NoPutResultSet source,
Activation activation,
int resultSetNumber,
String exportPath,
boolean compression,
int replicationCount,
String encoding,
String fieldSeparator,
String quoteChar,
int srcResultDescriptionSavedObjectNum) throws StandardException;
/**
* Batch Once
*/
public NoPutResultSet getBatchOnceResultSet(NoPutResultSet source,
Activation activation,
int resultSetNumber,
NoPutResultSet subqueryResultSet,
String updateResultSetFieldName,
int sourceRowLocationColumnPosition,
int sourceCorrelatedColumnPosition,
int subqueryCorrelatedColumnPosition) throws StandardException;
}
| Fixed distinct scan explain text for ui.
| db-engine/src/main/java/com/splicemachine/db/iapi/sql/execute/ResultSetFactory.java | Fixed distinct scan explain text for ui. | <ide><path>b-engine/src/main/java/com/splicemachine/db/iapi/sql/execute/ResultSetFactory.java
<ide> int isolationLevel,
<ide> double optimizerEstimatedRowCount,
<ide> double optimizerEstimatedCost,
<del> String tableVersion)
<add> String tableVersion,
<add> String explainPlan)
<ide> throws StandardException;
<ide>
<ide> /**
<ide> int isolationLevel,
<ide> double optimizerEstimatedRowCount,
<ide> double optimizerEstimatedCost,
<del> String tableVersion
<add> String tableVersion,
<add> String explainPlan
<ide> ) throws StandardException;
<ide>
<ide> |
|
Java | apache-2.0 | d4f7dfc95bfb8a73a0892a065c05cde654e791b2 | 0 | jitsi/libjitsi,jitsi/libjitsi,jitsi/libjitsi,jitsi/libjitsi | /*
* Copyright @ 2015 Atlassian Pty Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jitsi.impl.neomedia.rtcp;
import net.sf.fmj.media.rtp.*;
import org.jitsi.service.neomedia.*;
import org.jitsi.util.*;
import java.io.*;
import java.util.*;
/**
* A class which represents an RTCP packet carrying transport-wide congestion
* control (transport-cc) feedback information. The format is defined here:
* https://tools.ietf.org/html/draft-holmer-rmcat-transport-wide-cc-extensions-01
*
* <pre>{@code
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* |V=2|P| FMT=15 | PT=205 | length |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | SSRC of packet sender |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | SSRC of media source |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | base sequence number | packet status count |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | reference time | fb pkt. count |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | packet chunk | packet chunk |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* . .
* . .
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | packet chunk | recv delta | recv delta |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* . .
* . .
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | recv delta | recv delta | zero padding |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* }</pre>
*
* @author Boris Grozev
*/
public class RTCPTCCPacket
extends RTCPFBPacket
{
/**
* Gets a boolean indicating whether or not the RTCP packet specified in the
* {@link ByteArrayBuffer} that is passed as an argument is a NACK packet or
* not.
*
* @param baf the {@link ByteArrayBuffer}
* @return true if the byte array buffer holds a NACK packet, otherwise
* false.
*/
public static boolean isTCCPacket(ByteArrayBuffer baf)
{
int rc = RTCPHeaderUtils.getReportCount(baf);
return rc == FMT && isRTPFBPacket(baf);
}
/**
* @return the packets represented in an RTCP transport-cc feedback packet.
*
* Note that the timestamps are represented in the 250µs format used by the
* on-the-wire format, and don't represent local time.
*
* @param baf the buffer which contains the RTCP packet.
*/
public static PacketMap getPackets(ByteArrayBuffer baf)
{
return getPacketsFci(getFCI(baf));
}
/**
* @return the packets represented in the FCI portion of an RTCP
* transport-cc feedback packet.
*
* Note that the timestamps are represented in the 250µs format used by the
* on-the-wire format, and don't represent local time.
*
* @param fciBuffer the buffer which contains the FCI portion of the RTCP
* feedback packet.
*/
public static PacketMap getPacketsFci(ByteArrayBuffer fciBuffer)
{
if (fciBuffer == null)
{
return null;
}
byte[] buf = fciBuffer.getBuffer();
int off = fciBuffer.getOffset();
int len = fciBuffer.getLength();
if (len < MIN_FCI_LENGTH)
{
logger.warn(PARSE_ERROR + "length too small: " + len);
return null;
}
// The fixed fields
int baseSeq = RTPUtils.readUint16AsInt(buf, off);
int packetStatusCount = RTPUtils.readUint16AsInt(buf, off + 2);
// reference time. The 24 bit field uses increments of 2^6ms, and we
// shift by 8 to change the resolution to 250µs.
long referenceTime = RTPUtils.readUint24AsInt(buf, off + 4) << 8;
// The offset at which the packet status chunk list starts.
int pscOff = off + 8;
// First find where the delta list begins.
int packetsRemaining = packetStatusCount;
while (packetsRemaining > 0)
{
if (pscOff + 2 > off + len)
{
logger.warn(PARSE_ERROR + "reached the end while reading chunks");
return null;
}
int packetsInChunk = getPacketCount(buf, pscOff);
packetsRemaining -= packetsInChunk;
pscOff += 2; // all chunks are 16bit
}
// At this point we have the the beginning of the delta list. Start
// reading from the chunk and delta lists together.
int deltaStart = pscOff;
int deltaOff = pscOff;
// Reset to the start of the chunks list.
pscOff = off + 8;
packetsRemaining = packetStatusCount;
PacketMap packets = new PacketMap();
while (packetsRemaining > 0 && pscOff < deltaStart)
{
// packetsRemaining is based on the "packet status count" field,
// which helps us find the correct number of packets described in
// the last chunk. E.g. if the last chunk is a vector chunk, we
// don't really know by the chunk alone how many packets are
// described.
int packetsInChunk
= Math.min(getPacketCount(buf, pscOff), packetsRemaining);
// Read deltas for all packets in the chunk.
for (int i = 0; i < packetsInChunk; i++)
{
int symbol = readSymbol(buf, pscOff, i);
// -1 or delta in 250µs increments
int delta = -1;
switch (symbol)
{
case SYMBOL_SMALL_DELTA:
// The delta is an 8-bit unsigned integer.
deltaOff++;
if (deltaOff > off + len)
{
logger.warn(PARSE_ERROR
+ "reached the end while reading delta.");
return null;
}
delta = buf[deltaOff] & 0xff;
break;
case SYMBOL_LARGE_DELTA:
// The delta is a 6-bit signed integer.
deltaOff += 2;
if (deltaOff > off + len)
{
logger.warn(PARSE_ERROR
+ "reached the end while reading long delta.");
return null;
}
delta = RTPUtils.readInt16AsInt(buf, deltaOff);
break;
case SYMBOL_NOT_RECEIVED:
default:
delta = -1;
break;
}
if (delta == -1)
{
// Packet not received. We don't update the reference time,
// but we push the packet in the map to indicate that it was
// marked as not received.
packets.put(baseSeq, NEGATIVE_ONE);
}
else
{
// The spec is not clear about what the reference time for
// each packet is. We assume that every packet for which
// there is a delta updates the reference (even if the
// delta is negative).
// TODO: check what webrtc.org does
referenceTime += delta;
packets.put(baseSeq, referenceTime);
}
baseSeq = (baseSeq + 1) & 0xffff;
}
// next packet status chunk
pscOff += 2;
packetsRemaining -= packetsInChunk;
}
return packets;
}
/**
* Reads the {@code i}-th (zero-based) symbol from the Packet Status Chunk
* contained in {@code buf} at offset {@code off}. Returns -1 if the index
* is found to be invalid (although the validity check is not performed
* for RLE chunks).
*
* @param buf the buffer which contains the Packet Status Chunk.
* @param off the offset in {@code buf} at which the Packet Status Chunk
* begins.
* @param i the zero-based index of the symbol to return.
* @return the {@code i}-th symbol from the given Packet Status Chunk.
*/
private static int readSymbol(byte[] buf, int off, int i)
{
int chunkType = buf[off] & 0x80 >> 7;
if (chunkType == CHUNK_TYPE_VECTOR)
{
int symbolType = buf[off] & 0x40 >> 6;
switch (symbolType)
{
case SYMBOL_TYPE_LONG:
// 0 1
// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// |T|S| s0| s1| s2| s3| s4| s5| s6|
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
if (0 <= i && i <= 2)
{
return (buf[off] >> (4-2*i)) & 0x03;
}
else if (3 <= i && i <= 6)
{
return (buf[off + 1] >> (6-2*(i-3))) & 0x03;
}
return -1;
case SYMBOL_TYPE_SHORT:
// The format is similar to above, except with 14 one-bit
// symbols.
int shortSymbol;
if (0 <= i && i <= 5)
{
shortSymbol = (buf[off] >> (5-i)) & 0x01;
}
else if (6 <= i && i <= 13)
{
shortSymbol = (buf[off + 1] >> (13-i)) & 0x01;
}
else
{
return -1;
}
return shortToLong(shortSymbol);
default:
return -1;
}
}
else if (chunkType == CHUNK_TYPE_RLE)
{
// A RLE chunk looks like this:
// 0 1
// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// |T| S | Run Length |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// We assume the caller knows what they are doing and they have
// given us a valid i, so we just return the symbol (S). Otherwise
// we'd have to read the Run Length field every time.
return buf[off] >> 5 & 0x03;
}
return -1;
}
/**
* Converts a short symbol to a long symbol.
* @param shortSymbol the short symbol.
* @return the long (two-bit) symbol corresponding to {@code shortSymbol}.
*/
private static int shortToLong(int shortSymbol)
{
switch (shortSymbol)
{
case SHORT_SYMBOL_NOT_RECEIVED:
return SYMBOL_NOT_RECEIVED;
case SHORT_SYMBOL_RECEIVED:
return SYMBOL_SMALL_DELTA;
default:
return -1;
}
}
/**
* Returns the number of packets described in the Packet Status Chunk
* contained in the buffer {@code buf} at offset {@code off}.
* Note that this may not necessarily match with the number of packets
* that we want to read from the chunk. E.g. if a feedback packet describes
* 3 packets (indicated by the value "3" in the "packet status count" field),
* and it contains a Vector Status Chunk which can describe 7 packets (long
* symbols), then we want to read only 3 packets (but this method will
* return 7).
*
* @param buf the buffer which contains the Packet Status Chunk
* @param off the offset at which the Packet Status Chunk starts.
*
* @return the number of packets described by the Packet Status Chunk.
*/
private static int getPacketCount(byte[] buf, int off)
{
int chunkType = buf[off] & 0x80 >> 7;
if (chunkType == CHUNK_TYPE_VECTOR)
{
// A vector chunk looks like this:
// 0 1
// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// |1|S| symbol list |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// The 14-bit long symbol list consists of either 14 single-bit
// symbols, or 7 two-bit symbols, according to the S bit.
int symbolType = buf[off] & 0x40 >> 6;
return symbolType == SYMBOL_TYPE_SHORT ? 14 : 7;
}
else if (chunkType == CHUNK_TYPE_RLE)
{
// A RLE chunk looks like this:
// 0 1
// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// |T| S | Run Length |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
return
((buf[off] & 0x1f) << 8)
| (buf[off + 1] & 0xff);
}
return -1;
}
/**
* The {@link Logger} used by the {@link RTCPTCCPacket} class and its
* instances for logging output.
*/
private static final Logger logger
= Logger.getLogger(RTCPTCCPacket.class);
/**
* The value of the "fmt" field for a transport-cc RTCP feedback packet.
*/
public static final int FMT = 15;
/**
* The symbol which indicates that a packet was not received.
*/
private static final int SYMBOL_NOT_RECEIVED = 0;
/**
* The symbol which indicates that a packet was received with a small delta
* (represented in a 1-byte field).
*/
private static final int SYMBOL_SMALL_DELTA = 1;
/**
* The symbol which indicates that a packet was received with a large or
* negative delta (represented in a 2-byte field).
*/
private static final int SYMBOL_LARGE_DELTA = 2;
/**
* The short (1-bit) symbol which indicates that a packet was received
* (with a small delta).
*/
private static final int SHORT_SYMBOL_RECEIVED = 0;
/**
* The short (1-bit) symbol which indicates that a packet was not received.
*/
private static final int SHORT_SYMBOL_NOT_RECEIVED = 1;
/**
* The value of the {@code T} bit of a Packet Status Chunk, which
* identifies it as a Vector chunk.
*/
private static final int CHUNK_TYPE_VECTOR = 0;
/**
* The value of the {@code T} bit of a Packet Status Chunk, which
* identifies it as a Run Length Encoding chunk.
*/
private static final int CHUNK_TYPE_RLE = 1;
/**
* The value of the {@code S} bit og a Status Vector Chunk, which
* indicates 1-bit (short) symbols.
*/
private static final int SYMBOL_TYPE_SHORT = 0;
/**
* The value of the {@code S} bit of a Status Vector Chunk, which
* indicates 2-bit (long) symbols.
*/
private static final int SYMBOL_TYPE_LONG = 1;
/**
* A static object defined here in the hope that it will reduce boxing.
*/
private static final Long NEGATIVE_ONE = -1L;
/**
* The minimum length of the FCI field of a valid transport-cc RTCP
* feedback message. 8 bytes for the fixed fields + 2 bytes for one
* packet status chunk.
*/
private static final int MIN_FCI_LENGTH = 10;
/**
* An error message to use when parsing failed.
*/
private static final String PARSE_ERROR
= "Failed to parse an RTCP transport-cc feedback packet: ";
/**
* The map which contains the sequence numbers (mapped to the reception
* timestamp) of the packets described by this RTCP packet.
*/
private PacketMap packets = null;
/**
* Initializes a new <tt>NACKPacket</tt> instance.
* @param base
*/
public RTCPTCCPacket(RTCPCompoundPacket base)
{
super(base);
}
/**
* Initializes a new {@link RTCPTCCPacket} instance with a specific "packet
* sender SSRC" and "media source SSRC" values, and which describes a
* specific set of sequence numbers.
* @param senderSSRC the value to use for the "packet sender SSRC" field.
* @param sourceSSRC the value to use for the "media source SSRC" field.
* @param packets the set of RTP sequence numbers and their reception
* timestamps which this packet is to describe.
* @param fbPacketCount the index of this feedback packet, to be used in the
* "fb pkt count" field.
*
* Note that this implementation is not optimized and might not always use
* the minimal possible number of bytes to describe a given set of packets.
* Specifically, it does take into account that sequence numbers wrap
* at 2^16 and fails to pack numbers close to 2^16 with those close to 0.
*/
public RTCPTCCPacket(long senderSSRC, long sourceSSRC,
PacketMap packets,
byte fbPacketCount)
{
super(FMT, RTPFB, senderSSRC, sourceSSRC);
Map.Entry<Integer, Long> first = packets.firstEntry();
int firstSeq = first.getKey();
Map.Entry<Integer, Long> last = packets.lastEntry();
int packetCount
= 1 + RTPUtils.sequenceNumberDiff(last.getKey(), firstSeq);
// Temporary buffer to store the fixed fields (8 bytes) and the list of
// packet status chunks (see the format above). The buffer may be longer
// than needed. We pack 7 packets in a chunk, and a chunk is 2 bytes.
byte[] buf = new byte[(packetCount / 7 + 1) * 2 + 8];
// Temporary buffer to store the list of deltas (see the format above).
// We allocated for the worst case (2 bytes per packet), which may
// be longer than needed.
byte[] deltas = new byte[packetCount * 2];
int deltaOff = 0;
int off = 0;
long referenceTime = first.getValue();
referenceTime -= referenceTime % 64;
// Set the 'base sequence number' field
off += RTPUtils.writeShort(buf, off, (short) (int) first.getKey());
// Set the 'packet status count' field
off += RTPUtils.writeShort(buf, off, (short) packetCount);
// Set the 'reference time' field
off +=
RTPUtils.writeUint24(buf, off,
(int) ((referenceTime >> 6) & 0xffffff));
// Set the 'fb pkt count' field. TODO increment
buf[off++] = fbPacketCount;
// Add the packet status chunks. In this first impl we'll just use
// status vector chunks (T=1) with two-bit symbols (S=1) as this is
// most straightforward to implement.
// TODO: optimize for size
long nextReferenceTime = referenceTime;
off--; // we'll take care of this inside the loop.
for (int seqDelta = 0; seqDelta < packetCount; seqDelta++)
{
// A status vector chunk with two-bit symbols contains 7 packet
// symbols
if (seqDelta % 7 == 0)
{
off++;
buf[off] = (byte) 0xc0; //T=1, S=1
}
else if (seqDelta % 7 == 3)
{
off++;
buf[off] = 0;
}
int symbol;
int seq = (firstSeq + seqDelta) & 0xffff;
Long ts = packets.get(seq);
if (ts == null)
{
symbol = SYMBOL_NOT_RECEIVED;
}
else
{
long tsDelta = ts - nextReferenceTime;
if (tsDelta >= 0 && tsDelta < 63)
{
symbol = SYMBOL_SMALL_DELTA;
// The small delta is an 8-bit unsigned with a resolution of
// 250µs. Our deltas are all in milliseconds (hence << 2).
deltas[deltaOff++] = (byte ) ((tsDelta << 2) & 0xff);
}
else if (tsDelta < 8191 && tsDelta > -8192)
{
symbol = SYMBOL_LARGE_DELTA;
// The large or negative delta is a 16-bit signed integer
// with a resolution of 250µs (hence << 2).
short d = (short) (tsDelta << 2);
deltas[deltaOff++] = (byte) ((d >> 8) & 0xff);
deltas[deltaOff++] = (byte) ((d) & 0xff);
}
else
{
// The RTCP packet format does not support deltas bigger
// than what we handle above. As per the draft, if we want
// send feedback with such deltas, we should split it up
// into multiple RTCP packets. We can't do that here in the
// constructor.
throw new IllegalArgumentException("Delta too big, needs new reference.");
}
// If the packet was received, the next delta will be relative
// to its time. Otherwise, we'll just the previous reference.
nextReferenceTime = ts;
}
// Depending on the index of our packet, we have to offset its
// symbol (we've already set 'off' to point to the correct byte).
// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
// S T <0> <1> <2> <3> <4> <5> <6>
int symbolOffset;
switch (seqDelta % 7)
{
case 0:
case 4:
symbolOffset = 4;
break;
case 1:
case 5:
symbolOffset = 2;
break;
case 2:
case 6:
symbolOffset = 0;
break;
case 3:
default:
symbolOffset = 6;
}
symbol <<= symbolOffset;
buf[off] |= symbol;
}
off++;
if (packetCount % 7 <= 3)
{
// the last chunk was not complete
buf[off++] = 0;
}
fci = new byte[off + deltaOff];
System.arraycopy(buf, 0, fci, 0, off);
System.arraycopy(deltas, 0, fci, off, deltaOff);
this.packets = packets;
}
/**
* @return the map of packets represented by this {@link RTCPTCCPacket}.
*/
synchronized public Map<Integer, Long> getPackets()
{
if (packets == null)
{
packets = getPacketsFci(new ByteArrayBufferImpl(fci, 0, fci.length));
}
return packets;
}
@Override
public void assemble(DataOutputStream dataoutputstream)
throws IOException
{
dataoutputstream.writeByte((byte) (0x80 /* version */ | FMT));
dataoutputstream.writeByte((byte) RTPFB);
dataoutputstream.writeShort(2 + (fci.length / 4));
dataoutputstream.writeInt((int) senderSSRC);
dataoutputstream.writeInt((int) sourceSSRC);
dataoutputstream.write(fci);
}
@Override
public String toString()
{
return "RTCP transport-cc feedback";
}
/**
* An ordered collection which maps sequence numbers to timestamps, the
* order is by the sequence number.
*/
public static class PacketMap extends TreeMap<Integer, Long>
{
public PacketMap()
{
super(RTPUtils.sequenceNumberComparator);
}
}
}
| src/org/jitsi/impl/neomedia/rtcp/RTCPTCCPacket.java | /*
* Copyright @ 2015 Atlassian Pty Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jitsi.impl.neomedia.rtcp;
import net.sf.fmj.media.rtp.*;
import org.jitsi.service.neomedia.*;
import org.jitsi.util.*;
import java.io.*;
import java.util.*;
/**
* A class which represents an RTCP packet carrying transport-wide congestion
* control (transport-cc) feedback information. The format is defined here:
* https://tools.ietf.org/html/draft-holmer-rmcat-transport-wide-cc-extensions-01
*
* <pre>{@code
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* |V=2|P| FMT=15 | PT=205 | length |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | SSRC of packet sender |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | SSRC of media source |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | base sequence number | packet status count |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | reference time | fb pkt. count |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | packet chunk | packet chunk |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* . .
* . .
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | packet chunk | recv delta | recv delta |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* . .
* . .
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | recv delta | recv delta | zero padding |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* }</pre>
*
* @author Boris Grozev
*/
public class RTCPTCCPacket
extends RTCPFBPacket
{
/**
* Gets a boolean indicating whether or not the RTCP packet specified in the
* {@link ByteArrayBuffer} that is passed as an argument is a NACK packet or
* not.
*
* @param baf the {@link ByteArrayBuffer}
* @return true if the byte array buffer holds a NACK packet, otherwise
* false.
*/
public static boolean isTCCPacket(ByteArrayBuffer baf)
{
int rc = RTCPHeaderUtils.getReportCount(baf);
return rc == FMT && isRTPFBPacket(baf);
}
/**
* @return the packets represented in an RTCP transport-cc feedback packet.
*
* Note that the timestamps are represented in the 250µs format used by the
* on-the-wire format, and don't represent local time.
*
* @param baf the buffer which contains the RTCP packet.
*/
public static PacketMap getPackets(ByteArrayBuffer baf)
{
return getPacketsFci(getFCI(baf));
}
/**
* @return the packets represented in the FCI portion of an RTCP
* transport-cc feedback packet.
*
* Note that the timestamps are represented in the 250µs format used by the
* on-the-wire format, and don't represent local time.
*
* @param fciBuffer the buffer which contains the FCI portion of the RTCP
* feedback packet.
*/
public static PacketMap getPacketsFci(ByteArrayBuffer fciBuffer)
{
if (fciBuffer == null)
{
return null;
}
byte[] buf = fciBuffer.getBuffer();
int off = fciBuffer.getOffset();
int len = fciBuffer.getLength();
if (len < MIN_FCI_LENGTH)
{
logger.warn(PARSE_ERROR + "length too small: " + len);
return null;
}
// The fixed fields
int baseSeq = RTPUtils.readUint16AsInt(buf, off);
int packetStatusCount = RTPUtils.readUint16AsInt(buf, off + 2);
// reference time. The 24 bit field uses increments of 2^6ms, and we
// shift by 8 to change the resolution to 250µs.
long referenceTime = RTPUtils.readUint24AsInt(buf, off + 4) << 8;
// The offset at which the packet status chunk list starts.
int pscOff = off + 8;
// First find where the delta list begins.
int packetsRemaining = packetStatusCount;
while (packetsRemaining > 0)
{
if (pscOff + 2 > off + len)
{
logger.warn(PARSE_ERROR + "reached the end while reading chunks");
return null;
}
int packetsInChunk = getPacketCount(buf, pscOff);
packetsRemaining -= packetsInChunk;
pscOff += 2; // all chunks are 16bit
}
// At this point we have the the beginning of the delta list. Start
// reading from the chunk and delta lists together.
int deltaStart = pscOff;
int deltaOff = pscOff;
// Reset to the start of the chunks list.
pscOff = off + 8;
packetsRemaining = packetStatusCount;
PacketMap packets = new PacketMap();
while (packetsRemaining > 0 && pscOff < deltaStart)
{
// packetsRemaining is based on the "packet status count" field,
// which helps us find the correct number of packets described in
// the last chunk. E.g. if the last chunk is a vector chunk, we
// don't really know by the chunk alone how many packets are
// described.
int packetsInChunk
= Math.min(getPacketCount(buf, pscOff), packetsRemaining);
// Read deltas for all packets in the chunk.
for (int i = 0; i < packetsInChunk; i++)
{
int symbol = readSymbol(buf, pscOff, i);
// -1 or delta in 250µs increments
int delta = -1;
switch (symbol)
{
case SYMBOL_SMALL_DELTA:
// The delta is an 8-bit unsigned integer.
deltaOff++;
if (deltaOff > off + len)
{
logger.warn(PARSE_ERROR
+ "reached the end while reading delta.");
return null;
}
delta = buf[deltaOff] & 0xff;
break;
case SYMBOL_LARGE_DELTA:
// The delta is a 6-bit signed integer.
deltaOff += 2;
if (deltaOff > off + len)
{
logger.warn(PARSE_ERROR
+ "reached the end while reading long delta.");
return null;
}
delta = RTPUtils.readInt16AsInt(buf, deltaOff);
break;
case SYMBOL_NOT_RECEIVED:
default:
delta = -1;
break;
}
if (delta == -1)
{
// Packet not received. We don't update the reference time,
// but we push the packet in the map to indicate that it was
// marked as not received.
packets.put(baseSeq, NEGATIVE_ONE);
}
else
{
// The spec is not clear about what the reference time for
// each packet is. We assume that every packet for which
// there is a delta updates the reference (even if the
// delta is negative).
// TODO: check what webrtc.org does
referenceTime += delta;
packets.put(baseSeq, referenceTime);
}
baseSeq = (baseSeq + 1) & 0xffff;
}
// next packet status chunk
pscOff += 2;
packetsRemaining -= packetsInChunk;
}
return packets;
}
/**
* Reads the {@code i}-th (zero-based) symbol from the Packet Status Chunk
* contained in {@code buf} at offset {@code off}. Returns -1 if the index
* is found to be invalid (although the validity check is not performed
* for RLE chunks).
*
* @param buf the buffer which contains the Packet Status Chunk.
* @param off the offset in {@code buf} at which the Packet Status Chunk
* begins.
* @param i the zero-based index of the symbol to return.
* @return the {@code i}-th symbol from the given Packet Status Chunk.
*/
private static int readSymbol(byte[] buf, int off, int i)
{
int chunkType = buf[off] & 0x80 >> 7;
if (chunkType == CHUNK_TYPE_VECTOR)
{
int symbolType = buf[off] & 0x40 >> 6;
switch (symbolType)
{
case SYMBOL_TYPE_LONG:
// 0 1
// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// |T|S| s0| s1| s2| s3| s4| s5| s6|
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
if (0 <= i && i <= 2)
{
return (buf[off] >> (4-2*i)) & 0x03;
}
else if (3 <= i && i <= 6)
{
return (buf[off + 1] >> (6-2*(i-3))) & 0x03;
}
return -1;
case SYMBOL_TYPE_SHORT:
// The format is similar to above, except with 14 one-bit
// symbols.
int shortSymbol;
if (0 <= i && i <= 5)
{
shortSymbol = (buf[off] >> (5-i)) & 0x01;
}
else if (6 <= i && i <= 13)
{
shortSymbol = (buf[off + 1] >> (13-i)) & 0x01;
}
else
{
return -1;
}
return shortToLong(shortSymbol);
default:
return -1;
}
}
else if (chunkType == CHUNK_TYPE_RLE)
{
// A RLE chunk looks like this:
// 0 1
// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// |T| S | Run Length |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// We assume the caller knows what they are doing and they have
// given us a valid i, so we just return the symbol (S). Otherwise
// we'd have to read the Run Length field every time.
return buf[off] >> 5 & 0x03;
}
return -1;
}
/**
* Converts a short symbol to a long symbol.
* @param shortSymbol the short symbol.
* @return the long (two-bit) symbol corresponding to {@code shortSymbol}.
*/
private static int shortToLong(int shortSymbol)
{
switch (shortSymbol)
{
case SHORT_SYMBOL_NOT_RECEIVED:
return SYMBOL_NOT_RECEIVED;
case SHORT_SYMBOL_RECEIVED:
return SYMBOL_SMALL_DELTA;
default:
return -1;
}
}
/**
* Returns the number of packets described in the Packet Status Chunk
* contained in the buffer {@code buf} at offset {@code off}.
* Note that this may not necessarily match with the number of packets
* that we want to read from the chunk. E.g. if a feedback packet describes
* 3 packets (indicated by the value "3" in the "packet status count" field),
* and it contains a Vector Status Chunk which can describe 7 packets (long
* symbols), then we want to read only 3 packets (but this method will
* return 7).
*
* @param buf the buffer which contains the Packet Status Chunk
* @param off the offset at which the Packet Status Chunk starts.
*
* @return the number of packets described by the Packet Status Chunk.
*/
private static int getPacketCount(byte[] buf, int off)
{
int chunkType = buf[off] & 0x80 >> 7;
if (chunkType == CHUNK_TYPE_VECTOR)
{
// A vector chunk looks like this:
// 0 1
// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// |1|S| symbol list |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// The 14-bit long symbol list consists of either 14 single-bit
// symbols, or 7 two-bit symbols, according to the S bit.
int symbolType = buf[off] & 0x40 >> 6;
return symbolType == SYMBOL_TYPE_SHORT ? 14 : 7;
}
else if (chunkType == CHUNK_TYPE_RLE)
{
// A RLE chunk looks like this:
// 0 1
// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// |T| S | Run Length |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
return
((buf[off] & 0x1f) << 8)
| (buf[off + 1] & 0xff);
}
return -1;
}
/**
* The {@link Logger} used by the {@link RTCPTCCPacket} class and its
* instances for logging output.
*/
private static final Logger logger
= Logger.getLogger(RTCPTCCPacket.class);
/**
* The value of the "fmt" field for a transport-cc RTCP feedback packet.
*/
public static final int FMT = 15;
/**
* The symbol which indicates that a packet was not received.
*/
private static final int SYMBOL_NOT_RECEIVED = 0;
/**
* The symbol which indicates that a packet was received with a small delta
* (represented in a 1-byte field).
*/
private static final int SYMBOL_SMALL_DELTA = 1;
/**
* The symbol which indicates that a packet was received with a large or
* negative delta (represented in a 2-byte field).
*/
private static final int SYMBOL_LARGE_DELTA = 2;
/**
* The short (1-bit) symbol which indicates that a packet was received
* (with a small delta).
*/
private static final int SHORT_SYMBOL_RECEIVED = 0;
/**
* The short (1-bit) symbol which indicates that a packet was not received.
*/
private static final int SHORT_SYMBOL_NOT_RECEIVED = 1;
/**
* The value of the {@code T} bit of a Packet Status Chunk, which
* identifies it as a Vector chunk.
*/
private static final int CHUNK_TYPE_VECTOR = 0;
/**
* The value of the {@code T} bit of a Packet Status Chunk, which
* identifies it as a Run Length Encoding chunk.
*/
private static final int CHUNK_TYPE_RLE = 1;
/**
* The value of the {@code S} bit og a Status Vector Chunk, which
* indicates 1-bit (short) symbols.
*/
private static final int SYMBOL_TYPE_SHORT = 0;
/**
* The value of the {@code S} bit of a Status Vector Chunk, which
* indicates 2-bit (long) symbols.
*/
private static final int SYMBOL_TYPE_LONG = 1;
/**
* A static object defined here in the hope that it will reduce boxing.
*/
private static final Long NEGATIVE_ONE = -1L;
/**
* The minimum length of the FCI field of a valid transport-cc RTCP
* feedback message. 8 bytes for the fixed fields + 2 bytes for one
* packet status chunk.
*/
private static final int MIN_FCI_LENGTH = 10;
/**
* An error message to use when parsing failed.
*/
private static final String PARSE_ERROR
= "Failed to parse an RTCP transport-cc feedback packet: ";
/**
* The map which contains the sequence numbers (mapped to the reception
* timestamp) of the packets described by this RTCP packet.
*/
private PacketMap packets = null;
/**
* Initializes a new <tt>NACKPacket</tt> instance.
* @param base
*/
public RTCPTCCPacket(RTCPCompoundPacket base)
{
super(base);
}
/**
* Initializes a new {@link RTCPTCCPacket} instance with a specific "packet
* sender SSRC" and "media source SSRC" values, and which describes a
* specific set of sequence numbers.
* @param senderSSRC the value to use for the "packet sender SSRC" field.
* @param sourceSSRC the value to use for the "media source SSRC" field.
* @param packets the set of RTP sequence numbers and their reception
* timestamps which this packet is to describe.
* @param fbPacketCount the index of this feedback packet, to be used in the
* "fb pkt count" field.
*
* Note that this implementation is not optimized and might not always use
* the minimal possible number of bytes to describe a given set of packets.
* Specifically, it does take into account that sequence numbers wrap
* at 2^16 and fails to pack numbers close to 2^16 with those close to 0.
*/
public RTCPTCCPacket(long senderSSRC, long sourceSSRC,
PacketMap packets,
byte fbPacketCount)
{
super(FMT, RTPFB, senderSSRC, sourceSSRC);
TreeSet<Map.Entry<Integer, Long>> sequenceNumbers
= (TreeSet) packets.entrySet();
Map.Entry<Integer, Long> first = sequenceNumbers.first();
int firstSeq = first.getKey();
Map.Entry<Integer, Long> last = sequenceNumbers.last();
int packetCount
= 1 + RTPUtils.sequenceNumberDiff(last.getKey(), firstSeq);
// Temporary buffer to store the fixed fields (8 bytes) and the list of
// packet status chunks (see the format above). The buffer may be longer
// than needed. We pack 7 packets in a chunk, and a chunk is 2 bytes.
byte[] buf = new byte[(packetCount / 7 + 1) * 2 + 8];
// Temporary buffer to store the list of deltas (see the format above).
// We allocated for the worst case (2 bytes per packet), which may
// be longer than needed.
byte[] deltas = new byte[packetCount * 2];
int deltaOff = 0;
int off = 0;
long referenceTime = first.getValue();
referenceTime -= referenceTime % 64;
// Set the 'base sequence number' field
off += RTPUtils.writeShort(buf, off, (short) (int) first.getKey());
// Set the 'packet status count' field
off += RTPUtils.writeShort(buf, off, (short) packetCount);
// Set the 'reference time' field
off +=
RTPUtils.writeUint24(buf, off,
(int) ((referenceTime >> 6) & 0xffffff));
// Set the 'fb pkt count' field. TODO increment
buf[off++] = fbPacketCount;
// Add the packet status chunks. In this first impl we'll just use
// status vector chunks (T=1) with two-bit symbols (S=1) as this is
// most straightforward to implement.
// TODO: optimize for size
long nextReferenceTime = referenceTime;
off--; // we'll take care of this inside the loop.
for (int seqDelta = 0; seqDelta < packetCount; seqDelta++)
{
// A status vector chunk with two-bit symbols contains 7 packet
// symbols
if (seqDelta % 7 == 0)
{
off++;
buf[off] = (byte) 0xc0; //T=1, S=1
}
else if (seqDelta % 7 == 3)
{
off++;
buf[off] = 0;
}
int symbol;
int seq = (firstSeq + seqDelta) & 0xffff;
Long ts = packets.get(seq);
if (ts == null)
{
symbol = SYMBOL_NOT_RECEIVED;
}
else
{
long tsDelta = ts - nextReferenceTime;
if (tsDelta >= 0 && tsDelta < 63)
{
symbol = SYMBOL_SMALL_DELTA;
// The small delta is an 8-bit unsigned with a resolution of
// 250µs. Our deltas are all in milliseconds (hence << 2).
deltas[deltaOff++] = (byte ) ((tsDelta << 2) & 0xff);
}
else if (tsDelta < 8191 && tsDelta > -8192)
{
symbol = SYMBOL_LARGE_DELTA;
// The large or negative delta is a 16-bit signed integer
// with a resolution of 250µs (hence << 2).
short d = (short) (tsDelta << 2);
deltas[deltaOff++] = (byte) ((d >> 8) & 0xff);
deltas[deltaOff++] = (byte) ((d) & 0xff);
}
else
{
// The RTCP packet format does not support deltas bigger
// than what we handle above. As per the draft, if we want
// send feedback with such deltas, we should split it up
// into multiple RTCP packets. We can't do that here in the
// constructor.
throw new IllegalArgumentException("Delta too big, needs new reference.");
}
// If the packet was received, the next delta will be relative
// to its time. Otherwise, we'll just the previous reference.
nextReferenceTime = ts;
}
// Depending on the index of our packet, we have to offset its
// symbol (we've already set 'off' to point to the correct byte).
// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
// S T <0> <1> <2> <3> <4> <5> <6>
int symbolOffset;
switch (seqDelta % 7)
{
case 0:
case 4:
symbolOffset = 4;
break;
case 1:
case 5:
symbolOffset = 2;
break;
case 2:
case 6:
symbolOffset = 0;
break;
case 3:
default:
symbolOffset = 6;
}
symbol <<= symbolOffset;
buf[off] |= symbol;
}
off++;
if (packetCount % 7 <= 3)
{
// the last chunk was not complete
buf[off++] = 0;
}
fci = new byte[off + deltaOff];
System.arraycopy(buf, 0, fci, 0, off);
System.arraycopy(deltas, 0, fci, off, deltaOff);
this.packets = packets;
}
/**
* @return the map of packets represented by this {@link RTCPTCCPacket}.
*/
synchronized public Map<Integer, Long> getPackets()
{
if (packets == null)
{
packets = getPacketsFci(new ByteArrayBufferImpl(fci, 0, fci.length));
}
return packets;
}
@Override
public void assemble(DataOutputStream dataoutputstream)
throws IOException
{
dataoutputstream.writeByte((byte) (0x80 /* version */ | FMT));
dataoutputstream.writeByte((byte) RTPFB);
dataoutputstream.writeShort(2 + (fci.length / 4));
dataoutputstream.writeInt((int) senderSSRC);
dataoutputstream.writeInt((int) sourceSSRC);
dataoutputstream.write(fci);
}
@Override
public String toString()
{
return "RTCP transport-cc feedback";
}
/**
* An ordered collection which maps sequence numbers to timestamps, the
* order is by the sequence number.
*/
public static class PacketMap extends TreeMap<Integer, Long>
{
public PacketMap()
{
super(RTPUtils.sequenceNumberComparator);
}
}
}
| fix: Fixes an exception.
| src/org/jitsi/impl/neomedia/rtcp/RTCPTCCPacket.java | fix: Fixes an exception. | <ide><path>rc/org/jitsi/impl/neomedia/rtcp/RTCPTCCPacket.java
<ide> {
<ide> super(FMT, RTPFB, senderSSRC, sourceSSRC);
<ide>
<del> TreeSet<Map.Entry<Integer, Long>> sequenceNumbers
<del> = (TreeSet) packets.entrySet();
<del>
<del> Map.Entry<Integer, Long> first = sequenceNumbers.first();
<add> Map.Entry<Integer, Long> first = packets.firstEntry();
<ide> int firstSeq = first.getKey();
<del> Map.Entry<Integer, Long> last = sequenceNumbers.last();
<add> Map.Entry<Integer, Long> last = packets.lastEntry();
<ide> int packetCount
<ide> = 1 + RTPUtils.sequenceNumberDiff(last.getKey(), firstSeq);
<ide> |
|
JavaScript | mit | d2937e1eca4b2f9081dcc07dc6f11aa5a12b5398 | 0 | bholloway/gulp-slash | var slash = require('slash');
var through = require('through2');
/**
* Convert given text using node slash, or where no text is given, return a stream
* that similarly converts gulp (vinyl) file paths in place.
* @param {string} [text] Text to convert (per node slash)
* @returns {string|Transform} Converted text where given, else a transform stream for gulp
*/
module.exports = function(text) {
'use strict';
if (arguments.length > 0) {
return !!(text) ? slash(text) : text;
} else {
return through.obj(function(file, encoding, done) {
[ 'path', 'cwd', 'base' ].forEach(function(field) {
var isValid = (field in file) && (typeof file[field] === typeof '');
if (isValid) {
file[field] = slash(file[field]);
}
});
this.push(file);
done();
});
}
} | index.js | var slash = require('slash');
var through = require('through2');
/**
* Convert given text using node slash, or where no text is given, return a stream
* that similarly converts gulp (vinyl) file paths in place.
* @param {string} [text] Text to convert (per node slash)
* @returns {string|Transform} Converted text where given, else a transform stream for gulp
*/
module.exports = function(text) {
'use strict';
if (arguments.length > 0) {
return slash(text);
} else {
return through.obj(function(file, encoding, done) {
[ 'path', 'cwd', 'base' ].forEach(function(field) {
var isValid = (field in file) && (typeof file[field] === typeof '');
if (isValid) {
file[field] = slash(file[field]);
}
});
this.push(file);
done();
});
}
} | added check for degenerate string before passing to slash
| index.js | added check for degenerate string before passing to slash | <ide><path>ndex.js
<ide> module.exports = function(text) {
<ide> 'use strict';
<ide> if (arguments.length > 0) {
<del> return slash(text);
<add> return !!(text) ? slash(text) : text;
<ide> } else {
<ide> return through.obj(function(file, encoding, done) {
<ide> [ 'path', 'cwd', 'base' ].forEach(function(field) { |
|
JavaScript | mit | 60b5fd47dad069d062510c782a5db01fed6122c8 | 0 | dalekjs/dalek-browser-chrome | /*!
*
* Copyright (c) 2013 Sebastian Golasch
*
* 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.
*
*/
'use strict';
// ext. libs
var Q = require('q');
var fs = require('fs');
var cp = require('child_process');
var portscanner = require('portscanner');
// int. libs
var chromedriver = require('./lib/chromedriver');
/**
* This module is a browser plugin for [DalekJS](//github.com/dalekjs/dalek).
* It provides all a WebDriverServer & browser launcher for Google Chrome.
*
* The browser plugin can be installed with the following command:
*
* ```bash
* $ npm install dalek-browser-chrome --save-dev
* ```
*
* You can use the browser plugin by adding a config option to the your [Dalekfile](/pages/config.html)
*
* ```javascript
* "browser": ["chrome"]
* ```
*
* Or you can tell Dalek that it should test in this browser via the command line:
*
* ```bash
* $ dalek mytest.js -b chrome
* ```
*
* The Webdriver Server tries to open Port 9002 by default,
* if this port is blocked, it tries to use a port between 9003 & 9092
* You can specifiy a different port from within your [Dalekfile](/pages/config.html) like so:
*
* ```javascript
* "browsers": {
* "chrome": {
* "port": 5555
* }
* }
* ```
*
* It is also possible to specify a range of ports:
*
* ```javascript
* "browsers": {
* "chrome": {
* "portRange": [6100, 6120]
* }
* }
* ```
*
* If you would like to test Chrome Canary oder Chromium releases, you can simply apply a snd. argument,
* which defines the browser type:
*
* ```bash
* $ dalek mytest.js -b chrome:canary
* ```
*
* for canary, and if you would like to use chromium, just append `:chromium`:
*
* ```bash
* $ dalek mytest.js -b chrome:chromium
* ```
*
* This will only work if you installed your browser in the default locations,
* if the browsers binary is located in a non default location, you are able to specify
* its location in your [Dalekfile](/pages/config.html):
*
* ```javascript
* "browsers": {
* "chrome": {
* "binary": "/Applications/Custom Located Chrome.app/MacOS/Contents/Chrome"
* }
* }
* ```
*
* This also works for the canary & chromium builds
*
* ```javascript
* "browsers": {
* "chrome": {
* "binary": "/Applications/Custom Located Chrome.app/MacOS/Contents/Chrome"
* }
* }
* ```
*
* @module DalekJS
* @class ChromeDriver
* @namespace Browser
* @part Chrome
* @api
*/
var ChromeDriver = {
/**
* Verbose version of the browser name
*
* @property longName
* @type string
* @default Google Chrome
*/
longName: 'Google Chrome',
/**
* Default port of the ChromeWebDriverServer
* The port may change, cause the port conflict resolution
* tool might pick another one, if the default one is blocked
*
* @property port
* @type integer
* @default 9002
*/
port: 9002,
/**
* Default maximum port of the ChromeWebDriverServer
* The port is the highest port in the range that can be allocated
* by the ChromeWebDriverServer
*
* @property maxPort
* @type integer
* @default 9092
*/
maxPort: 9092,
/**
* Default host of the ChromeWebDriverServer
* The host may be overridden with
* a user configured value
*
* @property host
* @type string
* @default localhost
*/
host: 'localhost',
/**
* Default desired capabilities that should be
* transferred when the browser session gets requested
*
* @property desiredCapabilities
* @type object
*/
desiredCapabilities: {
browserName: 'chrome'
},
/**
* Driver defaults, what should the driver be able to access.
*
* @property driverDefaults
* @type object
*/
driverDefaults: {
viewport: true,
status: true,
sessionInfo: true
},
/**
* Root path of the ChromeWebDriverServer
*
* @property path
* @type string
* @default /wd/hub
*/
path: '/wd/hub',
/**
* Child process instance of the Chrome browser
*
* @property spawned
* @type null|Object
* @default null
*/
spawned: null,
/**
* Chrome processes that are running on startup,
* and therefor shouldn`t be closed
*
* @property openProcesses
* @type array
* @default []
*/
openProcesses: [],
/**
* Name of the process (platform dependent)
* that represents the browser itself
*
* @property processName
* @type string
* @default chrome.exe / Chrome
*/
processName: (process.platform === 'win32' ? 'chrome.exe' : 'Chrome'),
/**
* Different browser types (Canary / Chromium) that can be controlled
* via the Chromedriver
*
* @property browserTypes
* @type object
*/
browserTypes: {
/**
* Chrome Canary
*
* @property canary
* @type object
*/
canary: {
name: 'Chrome Canary',
linux: 'google-chrome-canary',
darwin: '/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary',
win32: process.env.LOCALAPPDATA + '\\Google\\Chrome SxS\\Application\\chrome.exe'
},
/**
* Chromium
*
* @property chromium
* @type object
*/
chromium: {
name: 'Chromium',
process: (process.platform === 'win32' ? 'chromium.exe' : 'Chromium'),
linux: 'chromium-browser',
darwin: '/Applications/Chromium.app/Contents/MacOS/Chromium',
win32: process.env.LOCALAPPDATA + '\\Google\\Chrome SxS\\Application\\chrome.exe'
}
},
/**
* Resolves the driver port
*
* @method getPort
* @return {integer} port WebDriver server port
*/
getPort: function () {
return this.port;
},
/**
* Resolves the maximum range for the driver port
*
* @method getMaxPort
* @return {integer} port Max WebDriver server port range
*/
getMaxPort: function () {
return this.maxPort;
},
/**
* Returns the driver host
*
* @method getHost
* @return {string} host WebDriver server hostname
*/
getHost: function () {
return this.host;
},
/**
* Launches the ChromeWebDriverServer
* (which implicitly launches Chrome itself)
* and checks for an available port
*
* @method launch
* @param {object} configuration Browser configuration
* @param {EventEmitter2} events EventEmitter (Reporter Emitter instance)
* @param {Dalek.Internal.Config} config Dalek configuration class
* @return {object} promise Browser promise
*/
launch: function (configuration, events, config) {
var deferred = Q.defer();
// store injected configuration/log event handlers
this.reporterEvents = events;
this.configuration = configuration;
this.config = config;
// check for a user set port
var browsers = this.config.get('browsers');
if (browsers && Array.isArray(browsers)) {
browsers.forEach(this._checkUserDefinedPorts.bind(this));
}
// check for a user defined binary
if (configuration && configuration.binary) {
var binaryExists = this._checkUserDefinedBinary(configuration.binary);
if (binaryExists) {
// check for new verbose & process name
this.longName = this._modifyVerboseBrowserName(configuration);
this.processName = this._fetchProcessName(configuration);
}
}
// check if the current port is in use, if so, scan for free ports
portscanner.findAPortNotInUse(this.getPort(), this.getMaxPort(), this.getHost(), this._checkPorts.bind(this, deferred));
return deferred.promise;
},
/**
* Kills the ChromeWebDriverServer
* & Chrome browser processes
*
* @method kill
* @chainable
*/
kill: function () {
this._processes(process.platform, this._checkProcesses.bind(this));
return this;
},
/**
* Modifies the verbose browser name
*
* @method _modifyVerboseBrowserName
* @param {object} configuration User configuration
* @return {string} Verbose browser name
* @private
*/
_modifyVerboseBrowserName: function (configuration) {
if (configuration.type && this.browserTypes[configuration.type]) {
return this.browserTypes[configuration.type].name + ' (' + this.longName + ')';
}
return this.longName;
},
/**
* Change the process name for browser instances like Canary & Chromium
*
* @method _fetchProcessName
* @param {object} configuration User configuration
* @return {string} Verbose browser name
* @private
*/
_fetchProcessName: function (configuration) {
// check if the process name must be overridden (to shut down the browser)
if (this.browserTypes[configuration.type] && this.browserTypes[configuration.type].process) {
return this.browserTypes[configuration.type].process;
}
return this.processName;
},
/**
* Process user defined ports
*
* @method _checkUserDefinedPorts
* @param {object} browser Browser configuration
* @chainable
* @private
*/
_checkUserDefinedPorts: function (browser) {
// check for a single defined port
if (browser.chrome && browser.chrome.port) {
this.port = parseInt(browser.chrome.port, 10);
this.maxPort = this.port + 90;
this.reporterEvents.emit('report:log:system', 'dalek-browser-chrome: Switching to user defined port: ' + this.port);
}
// check for a port range
if (browser.chrome && browser.chrome.portRange && browser.chrome.portRange.length === 2) {
this.port = parseInt(browser.chrome.portRange[0], 10);
this.maxPort = parseInt(browser.chrome.portRange[1], 10);
this.reporterEvents.emit('report:log:system', 'dalek-browser-chrome: Switching to user defined port(s): ' + this.port + ' -> ' + this.maxPort);
}
return this;
},
/**
* Checks if the binary exists,
* when set manually by the user
*
* @method _checkUserDefinedBinary
* @param {string} binary Path to the browser binary
* @return {bool} Binary exists
* @private
*/
_checkUserDefinedBinary: function (binary) {
// check if we need to replace the users home directory
if (process.platform === 'darwin' && binary.trim()[0] === '~') {
binary = binary.replace('~', process.env.HOME);
}
// check if the binary exists
if (!fs.existsSync(binary)) {
this.reporterEvents.emit('error', 'dalek-driver-chrome: Binary not found: ' + binary);
process.exit(127);
return false;
}
// add the binary to the desired capabilities
this.desiredCapabilities.chromeOptions = {
binary: binary
};
return true;
},
/**
* Checks if the def. port is blocked & if we need to switch to another port
* Kicks off the process manager (for closing the opened browsers after the run has been finished)
* Also starts the chromedriver instance
*
* @method _checkPorts
* @param {object} deferred Promise
* @param {null|object} error Error object
* @param {integer} port Found open port
* @private
* @chainable
*/
_checkPorts: function(deferred, error, port) {
// check if the port was blocked & if we need to switch to another port
if (this.port !== port) {
this.reporterEvents.emit('report:log:system', 'dalek-browser-chrome: Switching to port: ' + port);
this.port = port;
}
// get the currently running processes & invoke the chromedriver afterwards
this._processes(process.platform, this._startChromedriver.bind(this, deferred));
return this;
},
/**
* Spawns an instance of Chromedriver
*
* @method _startChromedriver
* @param {object} deferred Promise
* @param {null|object} error Error object
* @param {string} result List of open chrome processes BEFORE the test browser has been launched
* @private
* @chainable
*/
_startChromedriver: function (deferred, err, result) {
var args = ['--port=' + this.getPort(), '--url-base=' + this.path];
this.spawned = cp.spawn(chromedriver.path, args);
this.openProcesses = result;
this.spawned.stdout.on('data', this._catchDriverLogs.bind(this, deferred));
return this;
},
/**
* Watches the chromedriver console output to capture the starting message
*
* @method _catchDriverLogs
* @param {object} deferred Promise
* @param {buffer} data Chromedriver console output
* @private
* @chainable
*/
_catchDriverLogs: function (deferred, data) {
var dataStr = data + '';
// timeout to catch if chromedriver couldnt be launched
if (dataStr.search('DVFreeThread') === -1) {
var timeout = setTimeout(function () {
deferred.reject();
this.reporterEvents.emit('error', 'dalek-driver-chrome: Could not launch Chromedriver');
process.exit(127);
}.bind(this), 2000);
}
// look for the success message
if (dataStr.search('Starting ChromeDriver') !== -1) {
this.reporterEvents.emit('report:log:system', 'dalek-browser-chrome: Started ChromeDriver');
clearTimeout(timeout);
deferred.resolve();
}
return this;
},
/**
* Remove the chromedriver log that is written to the current working directory
*
* @method _unlinkChromedriverLog
* @param {bool} retry Delete has been tried min 1 time before
* @private
* @chainable
*/
_unlinkChromedriverLog: function (retry) {
var logfile = process.cwd() + '/chromedriver.log';
try {
if (fs.existsSync(logfile)) {
fs.unlinkSync(logfile);
}
} catch (e) {
if (!retry) {
setTimeout(this._unlinkChromedriverLog.bind(this, true), 1000);
}
}
return this;
},
/**
* Tracks running browser processes for chrome on mac & linux
*
* @method _processes
* @param {string} platform Current OS
* @param {function} fn Callback
* @chainable
* @private
*/
_processes: function (platform, fn) {
if (platform === 'win32') {
this._processesWin(fn);
return this;
}
this._processesNix(fn);
return this;
},
/**
* Kills all associated processes
*
* @method _checkProcesses
* @param {object|null} err Error object or null
* @param {array} result List of running processes
* @chainable
* @private
*/
_checkProcesses: function (err, result) {
// log that the driver shutdown process has been initiated
this.reporterEvents.emit('report:log:system', 'dalek-browser-chrome: Shutting down ChromeDriver');
// kill leftover chrome browser processes
result.forEach(this[(process.platform === 'win32' ? '_killWindows' : '_killNix')].bind(this));
// kill chromedriver binary
this.spawned.kill('SIGTERM');
// clean up the file mess the chromedriver leaves us behind
this._unlinkChromedriverLog();
return this;
},
// UNIX ONLY
// ---------
/**
* Kills a process
*
* @method _killNix
* @param {integer} processID Process ID
* @chainable
* @private
*/
_killNix: function (processID) {
var kill = true;
this.openProcesses.forEach(function (pid) {
if (pid === processID) {
kill = false;
}
});
if (kill === true) {
var killer = cp.spawn;
killer('kill', [processID]);
}
return this;
},
/**
* Lists all chrome processes on *NIX systems
*
* @method _processesNix
* @param {function} fn Calback
* @chainable
* @private
*/
_processesNix: function (fn) {
var cmd = ['ps -ax', '|', 'grep ' + this.processName];
cp.exec(cmd.join(' '), this._processListNix.bind(this, fn));
return this;
},
/**
* Deserializes a process list on nix
*
* @method _processListNix
* @param {function} fn Calback
* @param {object|null} err Error object
* @param {string} stdout Output of the process list shell command
* @chainable
* @private
*/
_processListNix: function(fn, err, stdout) {
var result = [];
stdout.split('\n').forEach(this._splitProcessListNix.bind(this, result));
fn(err, result);
return this;
},
/**
* Reformats the process list output on *NIX systems
*
* @method _splitProcessListNix
* @param {array} result Reference to the process list
* @param {string} line Single process in text representation
* @chainable
* @private
*/
_splitProcessListNix: function(result, line) {
var data = line.split(' ');
data = data.filter(this._filterProcessItemsNix.bind(this));
if (data[1] !== '??') {
result.push(data[0]);
}
return this;
},
/**
* Filters empty process list entries on *NIX
*
* @method _filterProcessItemsNix
* @param {string} item Item to check
* @return {string|bool} Item or falsy
* @private
*/
_filterProcessItemsNix: function (item) {
if (item !== '') {
return item;
}
return false;
},
// WIN ONLY
// --------
/**
* Lists all running processes (win only)
*
* @method _processesWin
* @param {Function} callback Receives the process object as the only callback argument
* @chainable
* @private
*/
_processesWin: function (callback) {
cp.exec('tasklist /FO CSV', this._processListWin.bind(this, callback));
return this;
},
/**
* Deserializes the process list on win
*
* @method _processListWin
* @param {function} callback Callback to be executed after the list has been transformed
* @param {object|null} err Error if error, else null
* @param {string} stdout Output of the process list command
* @chainable
* @private
*/
_processListWin: function (callback, err, stdout) {
var p = [];
stdout.split('\r\n').forEach(this._splitProcessListWin.bind(this, p));
var proc = [];
var head = null;
while (p.length > 1) {
var rec = p.shift();
var tmp = {};
rec = rec.replace(/\"\,/gi,'";').replace(/\"|\'/gi,'').split(';');
for (var j=0;j<rec.length;j++){
tmp[head[j]] = rec[j].replace(/\"|\'/gi,'');
}
proc.push(tmp);
}
var result = [];
proc.forEach(this._filterProcessItemsWin.bind(this, result));
callback(null, result);
return this;
},
/**
* Processes (transforms) the list of processes
*
* @method _filterProcessItemsWin
* @param {array} result Reference to the result process list
* @param {object} process Single piece of process information
* @chainable
* @private
*/
_filterProcessItemsWin: function (result, process) {
Object.keys(process).forEach(function (key) {
if (process[key] === this.processName) {
result.push(process.PID);
}
});
return this;
},
/**
* Filters empty lines out of the process result
*
* @method _splitProcessListWin
* @param {array} p Reference to the process list
* @param {string} line Process item
* @chainable
* @private
*/
_splitProcessListWin: function (p, line) {
if (line.trim().length !== 0) {
p.push(line);
}
return this;
},
/**
* Kills a process (based on a PID)
* that was not opened BEFORE Dalek has
* been started
*
* @method _killWindows
* @param {integer} pid Process id
* @chainable
* @private
*/
_killWindows: function (pid) {
var kill = true;
// check if the process was running BEFORE we started dalek
this.openProcesses.forEach(function (opid) {
if (opid === pid) {
kill = false;
}
});
// kill the browser process
if (kill === true) {
cp.exec('taskkill /PID ' + pid + ' /f', function(){});
}
return this;
}
};
// expose the module
module.exports = ChromeDriver;
| index.js | /*!
*
* Copyright (c) 2013 Sebastian Golasch
*
* 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.
*
*/
'use strict';
// ext. libs
var Q = require('q');
var fs = require('fs');
var cp = require('child_process');
var portscanner = require('portscanner');
// int. libs
var chromedriver = require('./lib/chromedriver');
/**
* This module is a browser plugin for [DalekJS](//github.com/dalekjs/dalek).
* It provides all a WebDriverServer & browser launcher for Google Chrome.
*
* The browser plugin can be installed with the following command:
*
* ```bash
* $ npm install dalek-browser-chrome --save-dev
* ```
*
* You can use the browser plugin by adding a config option to the your [Dalekfile](/pages/config.html)
*
* ```javascript
* "browser": ["chrome"]
* ```
*
* Or you can tell Dalek that it should test in this browser via the command line:
*
* ```bash
* $ dalek mytest.js -b chrome
* ```
*
* The Webdriver Server tries to open Port 9002 by default,
* if this port is blocked, it tries to use a port between 9003 & 9092
* You can specifiy a different port from within your [Dalekfile](/pages/config.html) like so:
*
* ```javascript
* "browsers": {
* "chrome": {
* "port": 5555
* }
* }
* ```
*
* It is also possible to specify a range of ports:
*
* ```javascript
* "browsers": {
* "chrome": {
* "portRange": [6100, 6120]
* }
* }
* ```
*
* If you would like to test Chrome Canary oder Chromium releases, you can simply apply a snd. argument,
* which defines the browser type:
*
* ```bash
* $ dalek mytest.js -b chrome:canary
* ```
*
* for canary, and if you would like to use chromium, just append `:chromium`:
*
* ```bash
* $ dalek mytest.js -b chrome:chromium
* ```
*
* This will only work if you installed your browser in the default locations,
* if the browsers binary is located in a non default location, you are able to specify
* its location in your [Dalekfile](/pages/config.html):
*
* ```javascript
* "browsers": {
* "chrome": {
* "binary": "/Applications/Custom Located Chrome.app/MacOS/Contents/Chrome"
* }
* }
* ```
*
* This also works for the canary & chromium builds
*
* ```javascript
* "browsers": {
* "chrome": {
* "binary": "/Applications/Custom Located Chrome.app/MacOS/Contents/Chrome"
* }
* }
* ```
*
* @module DalekJS
* @class ChromeDriver
* @namespace Browser
* @part Chrome
* @api
*/
var ChromeDriver = {
/**
* Verbose version of the browser name
*
* @property longName
* @type string
* @default Google Chrome
*/
longName: 'Google Chrome',
/**
* Default port of the ChromeWebDriverServer
* The port may change, cause the port conflict resolution
* tool might pick another one, if the default one is blocked
*
* @property port
* @type integer
* @default 9002
*/
port: 9002,
/**
* Default maximum port of the ChromeWebDriverServer
* The port is the highest port in the range that can be allocated
* by the ChromeWebDriverServer
*
* @property maxPort
* @type integer
* @default 9092
*/
maxPort: 9092,
/**
* Default host of the ChromeWebDriverServer
* The host may be overridden with
* a user configured value
*
* @property host
* @type string
* @default localhost
*/
host: 'localhost',
/**
* Default desired capabilities that should be
* transferred when the browser session gets requested
*
* @property desiredCapabilities
* @type object
*/
desiredCapabilities: {
browserName: 'chrome'
},
/**
* Driver defaults, what should the driver be able to access.
*
* @property driverDefaults
* @type object
*/
driverDefaults: {
viewport: true,
status: true,
sessionInfo: true
},
/**
* Root path of the ChromeWebDriverServer
*
* @property path
* @type string
* @default /wd/hub
*/
path: '/wd/hub',
/**
* Child process instance of the Chrome browser
*
* @property spawned
* @type null|Object
* @default null
*/
spawned: null,
/**
* Chrome processes that are running on startup,
* and therefor shouldn`t be closed
*
* @property openProcesses
* @type array
* @default []
*/
openProcesses: [],
/**
* Name of the process (platform dependent)
* that represents the browser itself
*
* @property processName
* @type string
* @default chrome.exe / Chrome
*/
processName: (process.platform === 'win32' ? 'chrome.exe' : 'Chrome'),
/**
* Different browser types (Canary / Chromium) that can be controlled
* via the Chromedriver
*
*/
browserTypes: {
/**
* Chrome Canary
*
* @property canary
* @type object
*/
canary: {
name: 'Chrome Canary',
linux: 'google-chrome-canary',
darwin: '/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary',
win32: process.env.LOCALAPPDATA + '\\Google\\Chrome SxS\\Application\\chrome.exe'
},
/**
* Chromium
*
* @property chromium
* @type object
*/
chromium: {
name: 'Chromium',
process: (process.platform === 'win32' ? 'chromium.exe' : 'Chromium'),
linux: 'chromium-browser',
darwin: '/Applications/Chromium.app/Contents/MacOS/Chromium',
win32: process.env.LOCALAPPDATA + '\\Google\\Chrome SxS\\Application\\chrome.exe'
}
},
/**
* Resolves the driver port
*
* @method getPort
* @return {integer} port WebDriver server port
*/
getPort: function () {
return this.port;
},
/**
* Resolves the maximum range for the driver port
*
* @method getMaxPort
* @return {integer} port Max WebDriver server port range
*/
getMaxPort: function () {
return this.maxPort;
},
/**
* Returns the driver host
*
* @method getHost
* @return {string} host WebDriver server hostname
*/
getHost: function () {
return this.host;
},
/**
* Launches the ChromeWebDriverServer
* (which implicitly launches Chrome itself)
* and checks for an available port
*
* @method launch
* @param {object} configuration Browser configuration
* @param {EventEmitter2} events EventEmitter (Reporter Emitter instance)
* @param {Dalek.Internal.Config} config Dalek configuration class
* @return {object} promise Browser promise
*/
launch: function (configuration, events, config) {
var deferred = Q.defer();
// store injected configuration/log event handlers
this.reporterEvents = events;
this.configuration = configuration;
this.config = config;
// check for a user set port
var browsers = this.config.get('browsers');
if (browsers && Array.isArray(browsers)) {
browsers.forEach(this._checkUserDefinedPorts.bind(this));
}
// check for a user defined binary
if (configuration && configuration.binary) {
var binaryExists = this._checkUserDefinedBinary(configuration.binary);
if (binaryExists) {
// check for new verbose & process name
this.longName = this._modifyVerboseBrowserName(configuration);
this.processName = this._fetchProcessName(configuration);
}
}
// check if the current port is in use, if so, scan for free ports
portscanner.findAPortNotInUse(this.getPort(), this.getMaxPort(), this.getHost(), this._checkPorts.bind(this, deferred));
return deferred.promise;
},
/**
* Kills the ChromeWebDriverServer
* & Chrome browser processes
*
* @method kill
* @chainable
*/
kill: function () {
this._processes(process.platform, this._checkProcesses.bind(this));
return this;
},
/**
* Modifies the verbose browser name
*
* @method _modifyVerboseBrowserName
* @param {object} configuration User configuration
* @return {string} Verbose browser name
* @private
*/
_modifyVerboseBrowserName: function (configuration) {
if (configuration.type && this.browserTypes[configuration.type]) {
return this.browserTypes[configuration.type].name + ' (' + this.longName + ')';
}
return this.longName;
},
/**
* Change the process name for browser instances like Canary & Chromium
*
* @method _fetchProcessName
* @param {object} configuration User configuration
* @return {string} Verbose browser name
* @private
*/
_fetchProcessName: function (configuration) {
// check if the process name must be overridden (to shut down the browser)
if (this.browserTypes[configuration.type] && this.browserTypes[configuration.type].process) {
return this.browserTypes[configuration.type].process;
}
return this.processName;
},
/**
* Process user defined ports
*
* @method _checkUserDefinedPorts
* @param {object} browser Browser configuration
* @chainable
* @private
*/
_checkUserDefinedPorts: function (browser) {
// check for a single defined port
if (browser.chrome && browser.chrome.port) {
this.port = parseInt(browser.chrome.port, 10);
this.maxPort = this.port + 90;
this.reporterEvents.emit('report:log:system', 'dalek-browser-chrome: Switching to user defined port: ' + this.port);
}
// check for a port range
if (browser.chrome && browser.chrome.portRange && browser.chrome.portRange.length === 2) {
this.port = parseInt(browser.chrome.portRange[0], 10);
this.maxPort = parseInt(browser.chrome.portRange[1], 10);
this.reporterEvents.emit('report:log:system', 'dalek-browser-chrome: Switching to user defined port(s): ' + this.port + ' -> ' + this.maxPort);
}
return this;
},
/**
* Checks if the binary exists,
* when set manually by the user
*
* @method _checkUserDefinedBinary
* @param {string} binary Path to the browser binary
* @return {bool} Binary exists
* @private
*/
_checkUserDefinedBinary: function (binary) {
// check if the binary exists
if (!fs.existsSync(binary)) {
this.reporterEvents.emit('error', 'dalek-driver-chrome: Binary not found: ' + binary);
process.exit(127);
return false;
}
// add the binary to the desired capabilities
this.desiredCapabilities.chromeOptions = {
binary: binary
};
return true;
},
/**
* Checks if the def. port is blocked & if we need to switch to another port
* Kicks off the process manager (for closing the opened browsers after the run has been finished)
* Also starts the chromedriver instance
*
* @method _checkPorts
* @param {object} deferred Promise
* @param {null|object} error Error object
* @param {integer} port Found open port
* @private
* @chainable
*/
_checkPorts: function(deferred, error, port) {
// check if the port was blocked & if we need to switch to another port
if (this.port !== port) {
this.reporterEvents.emit('report:log:system', 'dalek-browser-chrome: Switching to port: ' + port);
this.port = port;
}
// get the currently running processes & invoke the chromedriver afterwards
this._processes(process.platform, this._startChromedriver.bind(this, deferred));
return this;
},
/**
* Spawns an instance of Chromedriver
*
* @method _startChromedriver
* @param {object} deferred Promise
* @param {null|object} error Error object
* @param {string} result List of open chrome processes BEFORE the test browser has been launched
* @private
* @chainable
*/
_startChromedriver: function (deferred, err, result) {
var args = ['--port=' + this.getPort(), '--url-base=' + this.path];
this.spawned = cp.spawn(chromedriver.path, args);
this.openProcesses = result;
this.spawned.stdout.on('data', this._catchDriverLogs.bind(this, deferred));
return this;
},
/**
* Watches the chromedriver console output to capture the starting message
*
* @method _catchDriverLogs
* @param {object} deferred Promise
* @param {buffer} data Chromedriver console output
* @private
* @chainable
*/
_catchDriverLogs: function (deferred, data) {
var dataStr = data + '';
// timeout to catch if chromedriver couldnt be launched
var timeout = setTimeout(function () {
deferred.reject();
this.reporterEvents.emit('error', 'dalek-driver-chrome: Could not launch Chromedriver');
process.exit(127);
}.bind(this), 2000);
// look for the success message
if (dataStr.search('Starting ChromeDriver') !== -1) {
this.reporterEvents.emit('report:log:system', 'dalek-browser-chrome: Started ChromeDriver');
clearTimeout(timeout);
deferred.resolve();
}
return this;
},
/**
* Remove the chromedriver log that is written to the current working directory
*
* @method _unlinkChromedriverLog
* @param {bool} retry Delete has been tried min 1 time before
* @private
* @chainable
*/
_unlinkChromedriverLog: function (retry) {
var logfile = process.cwd() + '/chromedriver.log';
try {
if (fs.existsSync(logfile)) {
fs.unlinkSync(logfile);
}
} catch (e) {
if (!retry) {
setTimeout(this._unlinkChromedriverLog.bind(this, true), 1000);
}
}
return this;
},
/**
* Tracks running browser processes for chrome on mac & linux
*
* @method _processes
* @param {string} platform Current OS
* @param {function} fn Callback
* @chainable
* @private
*/
_processes: function (platform, fn) {
if (platform === 'win32') {
this._processesWin(fn);
return this;
}
this._processesNix(fn);
return this;
},
/**
* Kills all associated processes
*
* @method _checkProcesses
* @param {object|null} err Error object or null
* @param {array} result List of running processes
* @chainable
* @private
*/
_checkProcesses: function (err, result) {
// log that the driver shutdown process has been initiated
this.reporterEvents.emit('report:log:system', 'dalek-browser-chrome: Shutting down ChromeDriver');
// kill leftover chrome browser processes
result.forEach(this[(process.platform === 'win32' ? '_killWindows' : '_killNix')].bind(this));
// kill chromedriver binary
this.spawned.kill('SIGTERM');
// clean up the file mess the chromedriver leaves us behind
this._unlinkChromedriverLog();
return this;
},
// UNIX ONLY
// ---------
/**
* Kills a process
*
* @method _killNix
* @param {integer} processID Process ID
* @chainable
* @private
*/
_killNix: function (processID) {
var kill = true;
this.openProcesses.forEach(function (pid) {
if (pid === processID) {
kill = false;
}
});
if (kill === true) {
var killer = cp.spawn;
killer('kill', [processID]);
}
return this;
},
/**
* Lists all chrome processes on *NIX systems
*
* @method _processesNix
* @param {function} fn Calback
* @chainable
* @private
*/
_processesNix: function (fn) {
var cmd = ['ps -ax', '|', 'grep ' + this.processName];
cp.exec(cmd.join(' '), this._processListNix.bind(this, fn));
return this;
},
/**
* Deserializes a process list on nix
*
* @method _processListNix
* @param {function} fn Calback
* @param {object|null} err Error object
* @param {string} stdout Output of the process list shell command
* @chainable
* @private
*/
_processListNix: function(fn, err, stdout) {
var result = [];
stdout.split('\n').forEach(this._splitProcessListNix.bind(this, result));
fn(err, result);
return this;
},
/**
* Reformats the process list output on *NIX systems
*
* @method _splitProcessListNix
* @param {array} result Reference to the process list
* @param {string} line Single process in text representation
* @chainable
* @private
*/
_splitProcessListNix: function(result, line) {
var data = line.split(' ');
data = data.filter(this._filterProcessItemsNix.bind(this));
if (data[1] !== '??') {
result.push(data[0]);
}
return this;
},
/**
* Filters empty process list entries on *NIX
*
* @method _filterProcessItemsNix
* @param {string} item Item to check
* @return {string|bool} Item or falsy
* @private
*/
_filterProcessItemsNix: function (item) {
if (item !== '') {
return item;
}
return false;
},
// WIN ONLY
// --------
/**
* Lists all running processes (win only)
*
* @method _processesWin
* @param {Function} callback Receives the process object as the only callback argument
* @chainable
* @private
*/
_processesWin: function (callback) {
cp.exec('tasklist /FO CSV', this._processListWin.bind(this, callback));
return this;
},
/**
* Deserializes the process list on win
*
* @method _processListWin
* @param {function} callback Callback to be executed after the list has been transformed
* @param {object|null} err Error if error, else null
* @param {string} stdout Output of the process list command
* @chainable
* @private
*/
_processListWin: function (callback, err, stdout) {
var p = [];
stdout.split('\r\n').forEach(this._splitProcessListWin.bind(this, p));
var proc = [];
var head = null;
while (p.length > 1) {
var rec = p.shift();
var tmp = {};
rec = rec.replace(/\"\,/gi,'";').replace(/\"|\'/gi,'').split(';');
for (var j=0;j<rec.length;j++){
tmp[head[j]] = rec[j].replace(/\"|\'/gi,'');
}
proc.push(tmp);
}
var result = [];
proc.forEach(this._filterProcessItemsWin.bind(this, result));
callback(null, result);
return this;
},
/**
* Processes (transforms) the list of processes
*
* @method _filterProcessItemsWin
* @param {array} result Reference to the result process list
* @param {object} process Single piece of process information
* @chainable
* @private
*/
_filterProcessItemsWin: function (result, process) {
Object.keys(process).forEach(function (key) {
if (process[key] === this.processName) {
result.push(process.PID);
}
});
return this;
},
/**
* Filters empty lines out of the process result
*
* @method _splitProcessListWin
* @param {array} p Reference to the process list
* @param {string} line Process item
* @chainable
* @private
*/
_splitProcessListWin: function (p, line) {
if (line.trim().length !== 0) {
p.push(line);
}
return this;
},
/**
* Kills a process (based on a PID)
* that was not opened BEFORE Dalek has
* been started
*
* @method _killWindows
* @param {integer} pid Process id
* @chainable
* @private
*/
_killWindows: function (pid) {
var kill = true;
// check if the process was running BEFORE we started dalek
this.openProcesses.forEach(function (opid) {
if (opid === pid) {
kill = false;
}
});
// kill the browser process
if (kill === true) {
cp.exec('taskkill /PID ' + pid + ' /f', function(){});
}
return this;
}
};
// expose the module
module.exports = ChromeDriver;
| Proper shutdown of chromedriver
| index.js | Proper shutdown of chromedriver | <ide><path>ndex.js
<ide> * Different browser types (Canary / Chromium) that can be controlled
<ide> * via the Chromedriver
<ide> *
<add> * @property browserTypes
<add> * @type object
<ide> */
<ide>
<ide> browserTypes: {
<ide> */
<ide>
<ide> _checkUserDefinedBinary: function (binary) {
<add> // check if we need to replace the users home directory
<add> if (process.platform === 'darwin' && binary.trim()[0] === '~') {
<add> binary = binary.replace('~', process.env.HOME);
<add> }
<add>
<ide> // check if the binary exists
<ide> if (!fs.existsSync(binary)) {
<ide> this.reporterEvents.emit('error', 'dalek-driver-chrome: Binary not found: ' + binary);
<ide> var dataStr = data + '';
<ide>
<ide> // timeout to catch if chromedriver couldnt be launched
<del> var timeout = setTimeout(function () {
<del> deferred.reject();
<del> this.reporterEvents.emit('error', 'dalek-driver-chrome: Could not launch Chromedriver');
<del> process.exit(127);
<del> }.bind(this), 2000);
<add> if (dataStr.search('DVFreeThread') === -1) {
<add> var timeout = setTimeout(function () {
<add> deferred.reject();
<add> this.reporterEvents.emit('error', 'dalek-driver-chrome: Could not launch Chromedriver');
<add> process.exit(127);
<add> }.bind(this), 2000);
<add> }
<ide>
<ide> // look for the success message
<ide> if (dataStr.search('Starting ChromeDriver') !== -1) { |
|
Java | apache-2.0 | 652516fbf919c7004fef0563c5a15e98deb47286 | 0 | facebook/litho,facebook/litho,facebook/litho,facebook/litho,facebook/litho,facebook/litho | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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.facebook.litho.widget;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.widget.FrameLayout;
import androidx.annotation.UiThread;
import com.facebook.litho.Component;
import com.facebook.litho.ComponentContext;
import com.facebook.litho.ComponentLayout;
import com.facebook.litho.ComponentTree;
import com.facebook.litho.LithoView;
import com.facebook.litho.Size;
import com.facebook.litho.SizeSpec;
import com.facebook.litho.StateValue;
import com.facebook.litho.ThreadUtils;
import com.facebook.litho.TreeProps;
import com.facebook.litho.annotations.MountSpec;
import com.facebook.litho.annotations.OnBind;
import com.facebook.litho.annotations.OnBoundsDefined;
import com.facebook.litho.annotations.OnCreateInitialState;
import com.facebook.litho.annotations.OnCreateMountContent;
import com.facebook.litho.annotations.OnDetached;
import com.facebook.litho.annotations.OnMeasure;
import com.facebook.litho.annotations.OnMount;
import com.facebook.litho.annotations.OnUnbind;
import com.facebook.litho.annotations.OnUnmount;
import com.facebook.litho.annotations.Prop;
import com.facebook.litho.annotations.State;
import java.util.concurrent.atomic.AtomicReference;
/**
* A {@link MountSpec} implementation to provide width and height information to the wrapped
* component.
*
* <p>Usage: Create a {@link SizeSpecMountWrapperComponentSpec} with a {@link Component} added to
* it, and it will provide the width and height information through a {@link Size} typed {@link
* com.facebook.litho.annotations.TreeProp}.
*/
@MountSpec(hasChildLithoViews = true)
public class SizeSpecMountWrapperComponentSpec {
private static final Handler sMainThreadHandler = new Handler(Looper.getMainLooper());
@OnCreateInitialState
static void onCreateInitialState(
ComponentContext c, StateValue<AtomicReference<ComponentTree>> componentTreeRef) {
componentTreeRef.set(new AtomicReference<ComponentTree>());
// This is the component tree to be added to the LithoView.
getOrCreateComponentTree(c, componentTreeRef.get());
}
@OnCreateMountContent
static FrameLayout onCreateMountContent(Context c) {
// This LithoView will contain the new tree that's created from this point onwards
// TODO: T59446191 Replace with proper solution. Remove the use of FrameLayout.
FrameLayout wrapperView = new FrameLayout(c);
wrapperView.addView(new LithoView(c));
return wrapperView;
}
@UiThread
@OnMount
static void onMount(
ComponentContext c,
FrameLayout wrapperView,
@State AtomicReference<ComponentTree> componentTreeRef) {
((LithoView) wrapperView.getChildAt(0)).setComponentTree(componentTreeRef.get());
}
@UiThread
@OnUnmount
static void onUnmount(ComponentContext c, FrameLayout wrapperView) {
((LithoView) wrapperView.getChildAt(0)).setComponentTree(null);
}
@OnMeasure
static void onMeasure(
ComponentContext c,
ComponentLayout layout,
int widthSpec,
int heightSpec,
Size size,
@Prop Component component,
@State AtomicReference<ComponentTree> componentTreeRef) {
final ComponentTree componentTree = getOrCreateComponentTree(c, componentTreeRef);
componentTree.setVersionedRootAndSizeSpec(
component,
widthSpec,
heightSpec,
size,
getTreePropWithSize(c, widthSpec, heightSpec),
c.getLayoutVersion());
if (size.width < 0 || size.height < 0) {
// if this happens it means that the componentTree was probably released in the UI Thread so
// this measurement is not needed.
size.width = size.height = 0;
}
}
@OnBoundsDefined
static void onBoundsDefined(
ComponentContext c,
ComponentLayout layout,
@Prop Component component,
@State AtomicReference<ComponentTree> componentTreeRef) {
// the updated width and height is passed down.
int widthSpec = SizeSpec.makeSizeSpec(layout.getWidth(), SizeSpec.EXACTLY);
int heightSpec = SizeSpec.makeSizeSpec(layout.getHeight(), SizeSpec.EXACTLY);
final ComponentTree componentTree = getOrCreateComponentTree(c, componentTreeRef);
// This check is also done in the setRootAndSizeSpec method, but we need to do this here since
// it will fail if a ErrorBoundariesConfiguration.rootWrapperComponentFactory was set.
// TODO: T60426216
if (!componentTree.hasCompatibleLayout(widthSpec, heightSpec)) {
componentTree.setVersionedRootAndSizeSpec(
component,
widthSpec,
heightSpec,
null,
getTreePropWithSize(c, widthSpec, heightSpec),
c.getLayoutVersion());
}
}
@OnDetached
static void onDetached(
ComponentContext c, @State AtomicReference<ComponentTree> componentTreeRef) {
// We need to release the component tree here to allow for a proper memory deallocation
final ComponentTree componentTree = componentTreeRef.get();
if (componentTree != null) {
componentTreeRef.set(null);
if (ThreadUtils.isMainThread()) {
componentTree.release();
} else {
sMainThreadHandler.post(
new Runnable() {
@Override
public void run() {
componentTree.release();
}
});
}
}
}
@UiThread
@OnBind
static void onBind(ComponentContext c, FrameLayout wrapperView) {
((LithoView) wrapperView.getChildAt(0)).rebind();
}
@UiThread
@OnUnbind
static void onUnbind(ComponentContext c, FrameLayout wrapperView) {
((LithoView) wrapperView.getChildAt(0)).unbind();
}
/**
* Creates a TreeProp with the size information. We need to do this every time we call
* setRootAndSizeSpec on the new tree.
*
* @param c
* @param widthSpec
* @param heightSpec
* @return
*/
private static TreeProps getTreePropWithSize(ComponentContext c, int widthSpec, int heightSpec) {
TreeProps tp = c.getTreePropsCopy();
if (tp == null) {
tp = new TreeProps();
}
tp.put(Size.class, new Size(widthSpec, heightSpec));
return tp;
}
/**
* We create get a componentTree, we have to create it in case it's been released.
*
* @param c
* @param componentTreeRef
* @return
*/
private static ComponentTree getOrCreateComponentTree(
ComponentContext c, AtomicReference<ComponentTree> componentTreeRef) {
ComponentTree componentTree = componentTreeRef.get();
if (componentTree == null || componentTree.isReleased()) {
componentTree = ComponentTree.create(c).build();
componentTreeRef.set(componentTree);
}
return componentTree;
}
}
| litho-widget/src/main/java/com/facebook/litho/widget/SizeSpecMountWrapperComponentSpec.java | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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.facebook.litho.widget;
import android.content.Context;
import android.widget.FrameLayout;
import androidx.annotation.UiThread;
import com.facebook.litho.Component;
import com.facebook.litho.ComponentContext;
import com.facebook.litho.ComponentLayout;
import com.facebook.litho.ComponentTree;
import com.facebook.litho.LithoView;
import com.facebook.litho.Size;
import com.facebook.litho.SizeSpec;
import com.facebook.litho.StateValue;
import com.facebook.litho.TreeProps;
import com.facebook.litho.annotations.MountSpec;
import com.facebook.litho.annotations.OnBind;
import com.facebook.litho.annotations.OnBoundsDefined;
import com.facebook.litho.annotations.OnCreateInitialState;
import com.facebook.litho.annotations.OnCreateMountContent;
import com.facebook.litho.annotations.OnDetached;
import com.facebook.litho.annotations.OnMeasure;
import com.facebook.litho.annotations.OnMount;
import com.facebook.litho.annotations.OnUnbind;
import com.facebook.litho.annotations.OnUnmount;
import com.facebook.litho.annotations.Prop;
import com.facebook.litho.annotations.State;
import java.util.concurrent.atomic.AtomicReference;
/**
* A {@link MountSpec} implementation to provide width and height information to the wrapped
* component.
*
* <p>Usage: Create a {@link SizeSpecMountWrapperComponentSpec} with a {@link Component} added to
* it, and it will provide the width and height information through a {@link Size} typed {@link
* com.facebook.litho.annotations.TreeProp}.
*/
@MountSpec(hasChildLithoViews = true)
public class SizeSpecMountWrapperComponentSpec {
@OnCreateInitialState
static void onCreateInitialState(
ComponentContext c, StateValue<AtomicReference<ComponentTree>> componentTreeRef) {
componentTreeRef.set(new AtomicReference<ComponentTree>());
// This is the component tree to be added to the LithoView.
getOrCreateComponentTree(c, componentTreeRef.get());
}
@OnCreateMountContent
static FrameLayout onCreateMountContent(Context c) {
// This LithoView will contain the new tree that's created from this point onwards
// TODO: T59446191 Replace with proper solution. Remove the use of FrameLayout.
FrameLayout wrapperView = new FrameLayout(c);
wrapperView.addView(new LithoView(c));
return wrapperView;
}
@UiThread
@OnMount
static void onMount(
ComponentContext c,
FrameLayout wrapperView,
@State AtomicReference<ComponentTree> componentTreeRef) {
((LithoView) wrapperView.getChildAt(0)).setComponentTree(componentTreeRef.get());
}
@UiThread
@OnUnmount
static void onUnmount(ComponentContext c, FrameLayout wrapperView) {
((LithoView) wrapperView.getChildAt(0)).setComponentTree(null);
}
@OnMeasure
static void onMeasure(
ComponentContext c,
ComponentLayout layout,
int widthSpec,
int heightSpec,
Size size,
@Prop Component component,
@State AtomicReference<ComponentTree> componentTreeRef) {
final ComponentTree componentTree = getOrCreateComponentTree(c, componentTreeRef);
componentTree.setVersionedRootAndSizeSpec(
component,
widthSpec,
heightSpec,
size,
getTreePropWithSize(c, widthSpec, heightSpec),
c.getLayoutVersion());
if (size.width < 0 || size.height < 0) {
// if this happens it means that the componentTree was probably released in the UI Thread so
// this measurement is not needed.
size.width = size.height = 0;
}
}
@OnBoundsDefined
static void onBoundsDefined(
ComponentContext c,
ComponentLayout layout,
@Prop Component component,
@State AtomicReference<ComponentTree> componentTreeRef) {
// the updated width and height is passed down.
int widthSpec = SizeSpec.makeSizeSpec(layout.getWidth(), SizeSpec.EXACTLY);
int heightSpec = SizeSpec.makeSizeSpec(layout.getHeight(), SizeSpec.EXACTLY);
final ComponentTree componentTree = getOrCreateComponentTree(c, componentTreeRef);
// This check is also done in the setRootAndSizeSpec method, but we need to do this here since
// it will fail if a ErrorBoundariesConfiguration.rootWrapperComponentFactory was set.
// TODO: T60426216
if (!componentTree.hasCompatibleLayout(widthSpec, heightSpec)) {
componentTree.setVersionedRootAndSizeSpec(
component,
widthSpec,
heightSpec,
null,
getTreePropWithSize(c, widthSpec, heightSpec),
c.getLayoutVersion());
}
}
@OnDetached
static void onDetached(
ComponentContext c, @State AtomicReference<ComponentTree> componentTreeRef) {
if (componentTreeRef.get() != null) {
// We need to release the component tree here to allow for a proper memory deallocation
componentTreeRef.get().release();
componentTreeRef.set(null);
}
}
@UiThread
@OnBind
static void onBind(ComponentContext c, FrameLayout wrapperView) {
((LithoView) wrapperView.getChildAt(0)).rebind();
}
@UiThread
@OnUnbind
static void onUnbind(ComponentContext c, FrameLayout wrapperView) {
((LithoView) wrapperView.getChildAt(0)).unbind();
}
/**
* Creates a TreeProp with the size information. We need to do this every time we call
* setRootAndSizeSpec on the new tree.
*
* @param c
* @param widthSpec
* @param heightSpec
* @return
*/
private static TreeProps getTreePropWithSize(ComponentContext c, int widthSpec, int heightSpec) {
TreeProps tp = c.getTreePropsCopy();
if (tp == null) {
tp = new TreeProps();
}
tp.put(Size.class, new Size(widthSpec, heightSpec));
return tp;
}
/**
* We create get a componentTree, we have to create it in case it's been released.
*
* @param c
* @param componentTreeRef
* @return
*/
private static ComponentTree getOrCreateComponentTree(
ComponentContext c, AtomicReference<ComponentTree> componentTreeRef) {
ComponentTree componentTree = componentTreeRef.get();
if (componentTree == null || componentTree.isReleased()) {
componentTree = ComponentTree.create(c).build();
componentTreeRef.set(componentTree);
}
return componentTree;
}
}
| Force ComponentTree release to the main thread.
Summary:
We need to make sure the ComponentTree is released in the main thread.
**Why?**
The ComponentTree release method call LithoView [setComponentTree](https://our.intern.facebook.com/intern/diffusion/FBS/browse/master/fbandroid/libraries/components/litho-core/src/main/java/com/facebook/litho/ComponentTree.java?commit=659646f0adffc9177ccf928905a383e2efbaf9b6&lines=2260), that [asserts](https://our.intern.facebook.com/intern/diffusion/FBS/browse/master/fbandroid/libraries/components/litho-core/src/main/java/com/facebook/litho/LithoView.java?commit=b4bc41337c4b8f8b223b6563ec3242f46f04bfff&lines=576%2C577) that we are in the main thread
Reviewed By: topwu
Differential Revision: D21130489
fbshipit-source-id: bf1016e3abf80e34e5d608afb2e08ee4ad5224cb
| litho-widget/src/main/java/com/facebook/litho/widget/SizeSpecMountWrapperComponentSpec.java | Force ComponentTree release to the main thread. | <ide><path>itho-widget/src/main/java/com/facebook/litho/widget/SizeSpecMountWrapperComponentSpec.java
<ide> package com.facebook.litho.widget;
<ide>
<ide> import android.content.Context;
<add>import android.os.Handler;
<add>import android.os.Looper;
<ide> import android.widget.FrameLayout;
<ide> import androidx.annotation.UiThread;
<ide> import com.facebook.litho.Component;
<ide> import com.facebook.litho.Size;
<ide> import com.facebook.litho.SizeSpec;
<ide> import com.facebook.litho.StateValue;
<add>import com.facebook.litho.ThreadUtils;
<ide> import com.facebook.litho.TreeProps;
<ide> import com.facebook.litho.annotations.MountSpec;
<ide> import com.facebook.litho.annotations.OnBind;
<ide> */
<ide> @MountSpec(hasChildLithoViews = true)
<ide> public class SizeSpecMountWrapperComponentSpec {
<add> private static final Handler sMainThreadHandler = new Handler(Looper.getMainLooper());
<ide>
<ide> @OnCreateInitialState
<ide> static void onCreateInitialState(
<ide> @OnDetached
<ide> static void onDetached(
<ide> ComponentContext c, @State AtomicReference<ComponentTree> componentTreeRef) {
<del> if (componentTreeRef.get() != null) {
<del> // We need to release the component tree here to allow for a proper memory deallocation
<del> componentTreeRef.get().release();
<add> // We need to release the component tree here to allow for a proper memory deallocation
<add> final ComponentTree componentTree = componentTreeRef.get();
<add> if (componentTree != null) {
<ide> componentTreeRef.set(null);
<add> if (ThreadUtils.isMainThread()) {
<add> componentTree.release();
<add> } else {
<add> sMainThreadHandler.post(
<add> new Runnable() {
<add> @Override
<add> public void run() {
<add> componentTree.release();
<add> }
<add> });
<add> }
<ide> }
<ide> }
<ide> |
|
JavaScript | mit | 7e7f5148d3504d893c136f361a3b9f291c5d616b | 0 | Discordius/Lesswrong2,Discordius/Lesswrong2,Discordius/Lesswrong2,Discordius/Telescope,Discordius/Lesswrong2,Discordius/Telescope,Discordius/Telescope,Discordius/Telescope | /* global Vulcan */
import { Collections, getCollection } from 'meteor/vulcan:core';
import { getFieldsWithAttribute } from './utils';
import { migrateDocuments } from '../migrations/migrationUtils'
export const recomputeAllDenormalizedValues = async () => {
for(let collection of Collections) {
await Vulcan.recomputeDenormalizedValues({
collectionName: collection.options.collectionName
})
}
}
Vulcan.recomputeAllDenormalizedValues = recomputeAllDenormalizedValues;
export const validateAllDenormalizedValues = async () => {
for(let collection of Collections) {
await Vulcan.recomputeDenormalizedValues({
collectionName: collection.options.collectionName,
validateOnly: true
})
}
}
Vulcan.validateAllDenormalizedValues = validateAllDenormalizedValues;
// Recompute the value of denormalized fields (that are tagged with canAutoDenormalize).
// If validateOnly is true, compare them with the existing values in the database and
// report how many differ; otherwise update them to the correct values. If fieldName
// is given, recompute a single field; otherwise recompute all fields on the collection.
export const recomputeDenormalizedValues = async ({collectionName, fieldName=null, validateOnly=false}) => {
// eslint-disable-next-line no-console
console.log(`Recomputing denormalize values for ${collectionName} ${fieldName ? `and ${fieldName}` : ""}`)
const collection = getCollection(collectionName)
if (!collection.simpleSchema) {
// eslint-disable-next-line no-console
console.log(`${collectionName} does not have a schema defined, not computing denormalized values`)
return
}
const schema = collection.simpleSchema()._schema
if (fieldName) {
if (!schema[fieldName]) {
// eslint-disable-next-line no-console
throw new Error(`${collectionName} does not have field ${fieldName}, not computing denormalized values`)
}
if (!schema[fieldName].denormalized) {
throw new Error(`${collectionName}.${fieldName} is not marked as a denormalized field`)
}
if (!schema[fieldName].canAutoDenormalize) {
throw new Error(`${collectionName}.${fieldName} is not marked as canAutoDenormalize`)
}
const getValue = schema[fieldName].getValue
if (!getValue) {
throw new Error(`${collectionName}.${fieldName} is missing its getValue function`)
}
await runDenormalizedFieldMigration({ collection, fieldName, getValue, validateOnly })
} else {
const denormalizedFields = getFieldsWithAttribute(schema, 'canAutoDenormalize')
if (denormalizedFields.length == 0) {
// eslint-disable-next-line no-console
console.log(`${collectionName} does not have any fields with "canAutoDenormalize", not computing denormalized values`)
return;
}
// eslint-disable-next-line no-console
console.log(`Recomputing denormalized values for ${collection.collectionName} in fields: ${denormalizedFields}`);
for (let j=0; j<denormalizedFields.length; j++) {
const fieldName = denormalizedFields[j];
const getValue = schema[fieldName].getValue
await runDenormalizedFieldMigration({ collection, fieldName, getValue, validateOnly })
}
}
// eslint-disable-next-line no-console
console.log(`Finished recomputing denormalized values for ${collectionName} ${fieldName ? `and ${fieldName}` : ""}`)
}
Vulcan.recomputeDenormalizedValues = recomputeDenormalizedValues;
async function runDenormalizedFieldMigration({ collection, fieldName, getValue, validateOnly }) {
let numDifferent = 0;
await migrateDocuments({
description: `Recomputing denormalized values for ${collection.collectionName} field ${fieldName}`,
collection,
batchSize: 100,
migrate: async (documents) => {
// eslint-disable-next-line no-console
const updates = await Promise.all(documents.map(async doc => {
const newValue = await getValue(doc)
// If the correct value is already present, don't make a database update
if ((isNullOrDefined(newValue) && isNullOrDefined(doc[fieldName])) || doc[fieldName] === newValue) return null
return {
updateOne: {
filter: {_id: doc._id},
update: {
$set: {
[fieldName]: newValue
}
},
}
}
}))
const nonEmptyUpdates = _.without(updates, null)
numDifferent += nonEmptyUpdates.length;
// eslint-disable-next-line no-console
console.log(`${nonEmptyUpdates.length} documents in batch with changing denormalized value`)
if (!validateOnly) {
// eslint-disable-next-line no-console
if (nonEmptyUpdates.length > 0) {
await collection.rawCollection().bulkWrite(
nonEmptyUpdates,
{ ordered: false }
);
}
} else {
// TODO: This is a hack, but better than leaving it. We're basically
// breaking the expected API from migrateDocuments by supporting a
// validateOnly option, so it does not offer us good hooks to do this.
throw new Error([
'Abort! validateOnly means the document will not change and the migration will never',
'complete. This error is expected behavior to cause the migration to end.'
].join(' '))
}
},
});
// eslint-disable-next-line no-console
console.log(`${numDifferent} total documents had wrong denormalized value`)
}
function isNullOrDefined(value) {
return value === null || value === undefined
}
| packages/lesswrong/server/scripts/recomputeDenormalized.js | /* global Vulcan */
import { Collections, getCollection } from 'meteor/vulcan:core';
import { getFieldsWithAttribute } from './utils';
import { migrateDocuments } from '../migrations/migrationUtils'
export const recomputeAllDenormalizedValues = async () => {
for(let collection of Collections) {
await Vulcan.recomputeDenormalizedValues({
collectionName: collection.options.collectionName
})
}
}
Vulcan.recomputeAllDenormalizedValues = recomputeAllDenormalizedValues;
export const validateAllDenormalizedValues = async () => {
for(let collection of Collections) {
await Vulcan.recomputeDenormalizedValues({
collectionName: collection.options.collectionName,
validateOnly: true
})
}
}
Vulcan.validateAllDenormalizedValues = validateAllDenormalizedValues;
// Recompute the value of denormalized fields (that are tagged with canAutoDenormalize).
// If validateOnly is true, compare them with the existing values in the database and
// report how many differ; otherwise update them to the correct values. If fieldName
// is given, recompute a single field; otherwise recompute all fields on the collection.
export const recomputeDenormalizedValues = async ({collectionName, fieldName=null, validateOnly=false}) => {
// eslint-disable-next-line no-console
console.log(`Recomputing denormalize values for ${collectionName} ${fieldName ? `and ${fieldName}` : ""}`)
const collection = getCollection(collectionName)
if (!collection.simpleSchema) {
// eslint-disable-next-line no-console
console.log(`${collectionName} does not have a schema defined, not computing denormalized values`)
return
}
const schema = collection.simpleSchema()._schema
if (fieldName) {
if (!schema[fieldName]) {
// eslint-disable-next-line no-console
throw new Error(`${collectionName} does not have field ${fieldName}, not computing denormalized values`)
}
if (!schema[fieldName].denormalized) {
throw new Error(`${collectionName}.${fieldName} is not marked as a denormalized field`)
}
if (!schema[fieldName].canAutoDenormalize) {
throw new Error(`${collectionName}.${fieldName} is not marked as canAutoDenormalize`)
}
const getValue = schema[fieldName].getValue
if (!getValue) {
throw new Error(`${collectionName}.${fieldName} is missing its getValue function`)
}
await runDenormalizedFieldMigration({ collection, fieldName, getValue, validateOnly })
} else {
const denormalizedFields = getFieldsWithAttribute(schema, 'canAutoDenormalize')
if (denormalizedFields.length == 0) {
// eslint-disable-next-line no-console
console.log(`${collectionName} does not have any fields with "canAutoDenormalize", not computing denormalized values`)
return;
}
// eslint-disable-next-line no-console
console.log(`Recomputing denormalized values for ${collection.collectionName} in fields: ${denormalizedFields}`);
for (let j=0; j<denormalizedFields.length; j++) {
const fieldName = denormalizedFields[j];
const getValue = schema[fieldName].getValue
await runDenormalizedFieldMigration({ collection, fieldName, getValue, validateOnly })
}
}
// eslint-disable-next-line no-console
console.log(`Finished recomputing denormalized values for ${collectionName} ${fieldName ? `and ${fieldName}` : ""}`)
}
Vulcan.recomputeDenormalizedValues = recomputeDenormalizedValues;
async function runDenormalizedFieldMigration({ collection, fieldName, getValue, validateOnly }) {
let numDifferent = 0;
await migrateDocuments({
description: `Recomputing denormalized values for ${collection.collectionName} field ${fieldName}`,
collection,
batchSize: 100,
migrate: async (documents) => {
// eslint-disable-next-line no-console
const updates = await Promise.all(documents.map(async doc => {
const newValue = await getValue(doc)
// If the correct value is already present, don't make a database update
if ((isNullOrDefined(newValue) && isNullOrDefined(doc[fieldName])) || doc[fieldName] === newValue) return null
return {
updateOne: {
filter: {_id: doc._id},
update: {
$set: {
[fieldName]: newValue
}
},
}
}
}))
const nonEmptyUpdates = _.without(updates, null)
numDifferent += nonEmptyUpdates.length;
// eslint-disable-next-line no-console
console.log(`${nonEmptyUpdates.length} documents in batch with changing denormalized value`)
if (!validateOnly) {
// eslint-disable-next-line no-console
if (nonEmptyUpdates.length > 0) {
await collection.rawCollection().bulkWrite(
nonEmptyUpdates,
{ ordered: false }
);
}
}
},
});
// eslint-disable-next-line no-console
console.log(`${numDifferent} total documents had wrong denormalized value`)
}
function isNullOrDefined(value) {
return value === null || value === undefined
} | hackily cause validate only recomputes to exit
| packages/lesswrong/server/scripts/recomputeDenormalized.js | hackily cause validate only recomputes to exit | <ide><path>ackages/lesswrong/server/scripts/recomputeDenormalized.js
<ide> if (!getValue) {
<ide> throw new Error(`${collectionName}.${fieldName} is missing its getValue function`)
<ide> }
<del>
<add>
<ide> await runDenormalizedFieldMigration({ collection, fieldName, getValue, validateOnly })
<ide> } else {
<ide> const denormalizedFields = getFieldsWithAttribute(schema, 'canAutoDenormalize')
<ide> console.log(`${collectionName} does not have any fields with "canAutoDenormalize", not computing denormalized values`)
<ide> return;
<ide> }
<del>
<add>
<ide> // eslint-disable-next-line no-console
<ide> console.log(`Recomputing denormalized values for ${collection.collectionName} in fields: ${denormalizedFields}`);
<del>
<add>
<ide> for (let j=0; j<denormalizedFields.length; j++) {
<ide> const fieldName = denormalizedFields[j];
<ide> const getValue = schema[fieldName].getValue
<ide>
<ide> async function runDenormalizedFieldMigration({ collection, fieldName, getValue, validateOnly }) {
<ide> let numDifferent = 0;
<del>
<add>
<ide> await migrateDocuments({
<ide> description: `Recomputing denormalized values for ${collection.collectionName} field ${fieldName}`,
<ide> collection,
<ide>
<ide> const nonEmptyUpdates = _.without(updates, null)
<ide> numDifferent += nonEmptyUpdates.length;
<del>
<add>
<ide> // eslint-disable-next-line no-console
<ide> console.log(`${nonEmptyUpdates.length} documents in batch with changing denormalized value`)
<ide> if (!validateOnly) {
<ide> { ordered: false }
<ide> );
<ide> }
<add> } else {
<add> // TODO: This is a hack, but better than leaving it. We're basically
<add> // breaking the expected API from migrateDocuments by supporting a
<add> // validateOnly option, so it does not offer us good hooks to do this.
<add> throw new Error([
<add> 'Abort! validateOnly means the document will not change and the migration will never',
<add> 'complete. This error is expected behavior to cause the migration to end.'
<add> ].join(' '))
<ide> }
<ide> },
<ide> });
<del>
<add>
<ide> // eslint-disable-next-line no-console
<ide> console.log(`${numDifferent} total documents had wrong denormalized value`)
<ide> } |
|
Java | apache-2.0 | b07c9ab24526c884273f107c2a55cc41f2d855d6 | 0 | HuangLS/neo4j,HuangLS/neo4j,HuangLS/neo4j,HuangLS/neo4j,HuangLS/neo4j | /*
* Copyright (c) 2002-2015 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* Neo4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.neo4j.kernel.api.cursor;
import org.neo4j.collection.primitive.PrimitiveIntIterator;
import org.neo4j.collection.primitive.PrimitiveIntStack;
import org.neo4j.cursor.Cursor;
import org.neo4j.graphdb.NotFoundException;
/**
* Represents a single node or relationship cursor item.
*/
public interface EntityItem
{
public abstract class EntityItemHelper
implements EntityItem
{
@Override
public boolean hasProperty( int propertyKeyId )
{
try ( Cursor<PropertyItem> cursor = property( propertyKeyId ) )
{
return cursor.next();
}
}
@Override
public Object getProperty( int propertyKeyId )
{
try ( Cursor<PropertyItem> cursor = property( propertyKeyId ) )
{
if ( cursor.next() )
{
return cursor.get().value();
}
}
catch ( NotFoundException e )
{
return null;
}
return null;
}
@Override
public PrimitiveIntIterator getPropertyKeys()
{
PrimitiveIntStack keys = new PrimitiveIntStack();
try ( Cursor<PropertyItem> properties = properties() )
{
while ( properties.next() )
{
keys.push( properties.get().propertyKeyId() );
}
}
return keys.iterator();
}
}
/**
* @return id of current entity
* @throws IllegalStateException if no current entity is selected
*/
long id();
/**
* @return cursor for properties of current entity
* @throws IllegalStateException if no current entity is selected
*/
Cursor<PropertyItem> properties();
/**
* @param propertyKeyId of property to find
* @return cursor for specific property of current entity
* @throws IllegalStateException if no current entity is selected
*/
Cursor<PropertyItem> property( int propertyKeyId );
boolean hasProperty( int propertyKeyId );
Object getProperty( int propertyKeyId );
PrimitiveIntIterator getPropertyKeys();
}
| community/kernel/src/main/java/org/neo4j/kernel/api/cursor/EntityItem.java | /*
* Copyright (c) 2002-2015 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* Neo4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.neo4j.kernel.api.cursor;
import org.neo4j.collection.primitive.PrimitiveIntIterator;
import org.neo4j.collection.primitive.PrimitiveIntStack;
import org.neo4j.cursor.Cursor;
/**
* Represents a single node or relationship cursor item.
*/
public interface EntityItem
{
public abstract class EntityItemHelper
implements EntityItem
{
@Override
public boolean hasProperty( int propertyKeyId )
{
try ( Cursor<PropertyItem> cursor = property( propertyKeyId ) )
{
return cursor.next();
}
}
@Override
public Object getProperty( int propertyKeyId )
{
try ( Cursor<PropertyItem> cursor = property( propertyKeyId ) )
{
if ( cursor.next() )
{
return cursor.get().value();
}
}
return null;
}
@Override
public PrimitiveIntIterator getPropertyKeys()
{
PrimitiveIntStack keys = new PrimitiveIntStack();
try ( Cursor<PropertyItem> properties = properties() )
{
while ( properties.next() )
{
keys.push( properties.get().propertyKeyId() );
}
}
return keys.iterator();
}
}
/**
* @return id of current entity
* @throws IllegalStateException if no current entity is selected
*/
long id();
/**
* @return cursor for properties of current entity
* @throws IllegalStateException if no current entity is selected
*/
Cursor<PropertyItem> properties();
/**
* @param propertyKeyId of property to find
* @return cursor for specific property of current entity
* @throws IllegalStateException if no current entity is selected
*/
Cursor<PropertyItem> property( int propertyKeyId );
boolean hasProperty( int propertyKeyId );
Object getProperty( int propertyKeyId );
PrimitiveIntIterator getPropertyKeys();
}
| Return null when property does not exist
Under concurrent modification we could run across property records that
are not in use. Instead of throwing an exception in this case, return
null to note that the property was not found.
| community/kernel/src/main/java/org/neo4j/kernel/api/cursor/EntityItem.java | Return null when property does not exist | <ide><path>ommunity/kernel/src/main/java/org/neo4j/kernel/api/cursor/EntityItem.java
<ide> import org.neo4j.collection.primitive.PrimitiveIntIterator;
<ide> import org.neo4j.collection.primitive.PrimitiveIntStack;
<ide> import org.neo4j.cursor.Cursor;
<add>import org.neo4j.graphdb.NotFoundException;
<ide>
<ide> /**
<ide> * Represents a single node or relationship cursor item.
<ide> {
<ide> return cursor.get().value();
<ide> }
<add> }
<add> catch ( NotFoundException e )
<add> {
<add> return null;
<ide> }
<ide>
<ide> return null; |
|
Java | apache-2.0 | 2214a242f218dfc571f98b64fcde61f1a9f6013a | 0 | zentol/flink,mbode/flink,clarkyzl/flink,zjureel/flink,twalthr/flink,zentol/flink,greghogan/flink,lincoln-lil/flink,rmetzger/flink,lincoln-lil/flink,StephanEwen/incubator-flink,lincoln-lil/flink,twalthr/flink,zjureel/flink,yew1eb/flink,aljoscha/flink,wwjiang007/flink,zhangminglei/flink,ueshin/apache-flink,apache/flink,aljoscha/flink,apache/flink,sunjincheng121/flink,gyfora/flink,aljoscha/flink,tzulitai/flink,aljoscha/flink,twalthr/flink,rmetzger/flink,tzulitai/flink,bowenli86/flink,twalthr/flink,kl0u/flink,tony810430/flink,godfreyhe/flink,lincoln-lil/flink,tzulitai/flink,greghogan/flink,GJL/flink,zentol/flink,lincoln-lil/flink,rmetzger/flink,zentol/flink,wwjiang007/flink,sunjincheng121/flink,kaibozhou/flink,kaibozhou/flink,wwjiang007/flink,godfreyhe/flink,greghogan/flink,hequn8128/flink,jinglining/flink,sunjincheng121/flink,darionyaphet/flink,clarkyzl/flink,apache/flink,tony810430/flink,jinglining/flink,kaibozhou/flink,ueshin/apache-flink,ueshin/apache-flink,xccui/flink,yew1eb/flink,fhueske/flink,hequn8128/flink,lincoln-lil/flink,bowenli86/flink,kl0u/flink,wwjiang007/flink,xccui/flink,kl0u/flink,apache/flink,gyfora/flink,greghogan/flink,tzulitai/flink,bowenli86/flink,zentol/flink,fhueske/flink,StephanEwen/incubator-flink,hequn8128/flink,godfreyhe/flink,shaoxuan-wang/flink,hequn8128/flink,godfreyhe/flink,darionyaphet/flink,darionyaphet/flink,GJL/flink,tillrohrmann/flink,jinglining/flink,rmetzger/flink,yew1eb/flink,ueshin/apache-flink,xccui/flink,xccui/flink,zhangminglei/flink,aljoscha/flink,darionyaphet/flink,gyfora/flink,hequn8128/flink,yew1eb/flink,greghogan/flink,gyfora/flink,mbode/flink,zhangminglei/flink,godfreyhe/flink,clarkyzl/flink,kl0u/flink,GJL/flink,mbode/flink,gyfora/flink,zentol/flink,kl0u/flink,shaoxuan-wang/flink,wwjiang007/flink,clarkyzl/flink,tillrohrmann/flink,kaibozhou/flink,mbode/flink,twalthr/flink,wwjiang007/flink,tillrohrmann/flink,jinglining/flink,kaibozhou/flink,bowenli86/flink,kaibozhou/flink,wwjiang007/flink,apache/flink,shaoxuan-wang/flink,tzulitai/flink,yew1eb/flink,apache/flink,kl0u/flink,tony810430/flink,mylog00/flink,greghogan/flink,twalthr/flink,clarkyzl/flink,mylog00/flink,bowenli86/flink,zjureel/flink,mylog00/flink,shaoxuan-wang/flink,StephanEwen/incubator-flink,mbode/flink,mylog00/flink,GJL/flink,tillrohrmann/flink,tillrohrmann/flink,GJL/flink,sunjincheng121/flink,shaoxuan-wang/flink,zentol/flink,jinglining/flink,apache/flink,shaoxuan-wang/flink,bowenli86/flink,sunjincheng121/flink,zjureel/flink,rmetzger/flink,sunjincheng121/flink,StephanEwen/incubator-flink,tony810430/flink,GJL/flink,fhueske/flink,fhueske/flink,aljoscha/flink,xccui/flink,lincoln-lil/flink,zhangminglei/flink,tillrohrmann/flink,ueshin/apache-flink,tillrohrmann/flink,twalthr/flink,xccui/flink,fhueske/flink,zhangminglei/flink,rmetzger/flink,tony810430/flink,xccui/flink,mylog00/flink,gyfora/flink,jinglining/flink,gyfora/flink,tony810430/flink,zjureel/flink,StephanEwen/incubator-flink,StephanEwen/incubator-flink,tony810430/flink,tzulitai/flink,darionyaphet/flink,godfreyhe/flink,rmetzger/flink,hequn8128/flink,zjureel/flink,zjureel/flink,fhueske/flink,godfreyhe/flink | /*
* 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.flink.runtime.io.network.partition;
import org.apache.flink.annotation.VisibleForTesting;
import org.apache.flink.runtime.io.network.api.EndOfPartitionEvent;
import org.apache.flink.runtime.io.network.api.serialization.EventSerializer;
import org.apache.flink.runtime.io.network.buffer.Buffer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import javax.annotation.concurrent.GuardedBy;
import java.io.IOException;
import java.util.ArrayDeque;
import static org.apache.flink.util.Preconditions.checkNotNull;
import static org.apache.flink.util.Preconditions.checkState;
/**
* A pipelined in-memory only subpartition, which can be consumed once.
*/
class PipelinedSubpartition extends ResultSubpartition {
private static final Logger LOG = LoggerFactory.getLogger(PipelinedSubpartition.class);
// ------------------------------------------------------------------------
/** All buffers of this subpartition. Access to the buffers is synchronized on this object. */
private final ArrayDeque<Buffer> buffers = new ArrayDeque<>();
/** The read view to consume this subpartition. */
private PipelinedSubpartitionView readView;
/** Flag indicating whether the subpartition has been finished. */
private boolean isFinished;
/** Flag indicating whether the subpartition has been released. */
private volatile boolean isReleased;
/** The number of non-event buffers currently in this subpartition. */
@GuardedBy("buffers")
private int buffersInBacklog;
// ------------------------------------------------------------------------
PipelinedSubpartition(int index, ResultPartition parent) {
super(index, parent);
}
@Override
public boolean add(Buffer buffer) throws IOException {
return add(buffer, false);
}
@Override
public void finish() throws IOException {
add(EventSerializer.toBuffer(EndOfPartitionEvent.INSTANCE), true);
LOG.debug("Finished {}.", this);
}
private boolean add(Buffer buffer, boolean finish) throws IOException {
checkNotNull(buffer);
// view reference accessible outside the lock, but assigned inside the locked scope
final PipelinedSubpartitionView reader;
synchronized (buffers) {
if (isFinished || isReleased) {
buffer.recycleBuffer();
return false;
}
// Add the buffer and update the stats
buffers.add(buffer);
reader = readView;
updateStatistics(buffer);
increaseBuffersInBacklog(buffer);
if (finish) {
isFinished = true;
}
}
// Notify the listener outside of the synchronized block
if (reader != null) {
reader.notifyBuffersAvailable(1);
}
return true;
}
@Override
public void release() {
// view reference accessible outside the lock, but assigned inside the locked scope
final PipelinedSubpartitionView view;
synchronized (buffers) {
if (isReleased) {
return;
}
// Release all available buffers
Buffer buffer;
while ((buffer = buffers.poll()) != null) {
buffer.recycleBuffer();
}
view = readView;
readView = null;
// Make sure that no further buffers are added to the subpartition
isReleased = true;
}
LOG.debug("Released {}.", this);
if (view != null) {
view.releaseAllResources();
}
}
@Nullable
BufferAndBacklog pollBuffer() {
synchronized (buffers) {
Buffer buffer = buffers.pollFirst();
decreaseBuffersInBacklog(buffer);
if (buffer != null) {
return new BufferAndBacklog(buffer, buffersInBacklog, _nextBufferIsEvent());
} else {
return null;
}
}
}
boolean nextBufferIsEvent() {
synchronized (buffers) {
return _nextBufferIsEvent();
}
}
private boolean _nextBufferIsEvent() {
assert Thread.holdsLock(buffers);
return !buffers.isEmpty() && !buffers.peekFirst().isBuffer();
}
@Override
public int releaseMemory() {
// The pipelined subpartition does not react to memory release requests.
// The buffers will be recycled by the consuming task.
return 0;
}
@Override
public boolean isReleased() {
return isReleased;
}
@Override
@VisibleForTesting
public int getBuffersInBacklog() {
return buffersInBacklog;
}
/**
* Decreases the number of non-event buffers by one after fetching a non-event
* buffer from this subpartition.
*/
private void decreaseBuffersInBacklog(Buffer buffer) {
assert Thread.holdsLock(buffers);
if (buffer != null && buffer.isBuffer()) {
buffersInBacklog--;
}
}
/**
* Increases the number of non-event buffers by one after adding a non-event
* buffer into this subpartition.
*/
private void increaseBuffersInBacklog(Buffer buffer) {
assert Thread.holdsLock(buffers);
if (buffer != null && buffer.isBuffer()) {
buffersInBacklog++;
}
}
@Override
public PipelinedSubpartitionView createReadView(BufferAvailabilityListener availabilityListener) throws IOException {
final int queueSize;
synchronized (buffers) {
checkState(!isReleased);
checkState(readView == null,
"Subpartition %s of is being (or already has been) consumed, " +
"but pipelined subpartitions can only be consumed once.", index, parent.getPartitionId());
LOG.debug("Creating read view for subpartition {} of partition {}.", index, parent.getPartitionId());
queueSize = buffers.size();
readView = new PipelinedSubpartitionView(this, availabilityListener);
}
readView.notifyBuffersAvailable(queueSize);
return readView;
}
// ------------------------------------------------------------------------
int getCurrentNumberOfBuffers() {
return buffers.size();
}
// ------------------------------------------------------------------------
@Override
public String toString() {
final long numBuffers;
final long numBytes;
final boolean finished;
final boolean hasReadView;
synchronized (buffers) {
numBuffers = getTotalNumberOfBuffers();
numBytes = getTotalNumberOfBytes();
finished = isFinished;
hasReadView = readView != null;
}
return String.format(
"PipelinedSubpartition [number of buffers: %d (%d bytes), number of buffers in backlog: %d, finished? %s, read view? %s]",
numBuffers, numBytes, buffersInBacklog, finished, hasReadView);
}
@Override
public int unsynchronizedGetNumberOfQueuedBuffers() {
// since we do not synchronize, the size may actually be lower than 0!
return Math.max(buffers.size(), 0);
}
}
| flink-runtime/src/main/java/org/apache/flink/runtime/io/network/partition/PipelinedSubpartition.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.flink.runtime.io.network.partition;
import org.apache.flink.annotation.VisibleForTesting;
import org.apache.flink.runtime.io.network.api.EndOfPartitionEvent;
import org.apache.flink.runtime.io.network.api.serialization.EventSerializer;
import org.apache.flink.runtime.io.network.buffer.Buffer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import javax.annotation.concurrent.GuardedBy;
import java.io.IOException;
import java.util.ArrayDeque;
import static org.apache.flink.util.Preconditions.checkNotNull;
import static org.apache.flink.util.Preconditions.checkState;
/**
* A pipelined in-memory only subpartition, which can be consumed once.
*/
class PipelinedSubpartition extends ResultSubpartition {
private static final Logger LOG = LoggerFactory.getLogger(PipelinedSubpartition.class);
// ------------------------------------------------------------------------
/** All buffers of this subpartition. Access to the buffers is synchronized on this object. */
private final ArrayDeque<Buffer> buffers = new ArrayDeque<>();
/** The read view to consume this subpartition. */
private PipelinedSubpartitionView readView;
/** Flag indicating whether the subpartition has been finished. */
private boolean isFinished;
/** Flag indicating whether the subpartition has been released. */
private volatile boolean isReleased;
/** The number of non-event buffers currently in this subpartition. */
@GuardedBy("buffers")
private int buffersInBacklog;
// ------------------------------------------------------------------------
PipelinedSubpartition(int index, ResultPartition parent) {
super(index, parent);
}
@Override
public boolean add(Buffer buffer) throws IOException {
checkNotNull(buffer);
// view reference accessible outside the lock, but assigned inside the locked scope
final PipelinedSubpartitionView reader;
synchronized (buffers) {
if (isFinished || isReleased) {
buffer.recycleBuffer();
return false;
}
// Add the buffer and update the stats
buffers.add(buffer);
reader = readView;
updateStatistics(buffer);
increaseBuffersInBacklog(buffer);
}
// Notify the listener outside of the synchronized block
if (reader != null) {
reader.notifyBuffersAvailable(1);
}
return true;
}
@Override
public void finish() throws IOException {
final Buffer buffer = EventSerializer.toBuffer(EndOfPartitionEvent.INSTANCE);
// view reference accessible outside the lock, but assigned inside the locked scope
final PipelinedSubpartitionView reader;
synchronized (buffers) {
if (isFinished || isReleased) {
return;
}
buffers.add(buffer);
reader = readView;
updateStatistics(buffer);
isFinished = true;
}
LOG.debug("Finished {}.", this);
// Notify the listener outside of the synchronized block
if (reader != null) {
reader.notifyBuffersAvailable(1);
}
}
@Override
public void release() {
// view reference accessible outside the lock, but assigned inside the locked scope
final PipelinedSubpartitionView view;
synchronized (buffers) {
if (isReleased) {
return;
}
// Release all available buffers
Buffer buffer;
while ((buffer = buffers.poll()) != null) {
buffer.recycleBuffer();
}
view = readView;
readView = null;
// Make sure that no further buffers are added to the subpartition
isReleased = true;
}
LOG.debug("Released {}.", this);
if (view != null) {
view.releaseAllResources();
}
}
@Nullable
BufferAndBacklog pollBuffer() {
synchronized (buffers) {
Buffer buffer = buffers.pollFirst();
decreaseBuffersInBacklog(buffer);
if (buffer != null) {
return new BufferAndBacklog(buffer, buffersInBacklog, _nextBufferIsEvent());
} else {
return null;
}
}
}
boolean nextBufferIsEvent() {
synchronized (buffers) {
return _nextBufferIsEvent();
}
}
private boolean _nextBufferIsEvent() {
assert Thread.holdsLock(buffers);
return !buffers.isEmpty() && !buffers.peekFirst().isBuffer();
}
@Override
public int releaseMemory() {
// The pipelined subpartition does not react to memory release requests.
// The buffers will be recycled by the consuming task.
return 0;
}
@Override
public boolean isReleased() {
return isReleased;
}
@Override
@VisibleForTesting
public int getBuffersInBacklog() {
return buffersInBacklog;
}
/**
* Decreases the number of non-event buffers by one after fetching a non-event
* buffer from this subpartition.
*/
private void decreaseBuffersInBacklog(Buffer buffer) {
assert Thread.holdsLock(buffers);
if (buffer != null && buffer.isBuffer()) {
buffersInBacklog--;
}
}
/**
* Increases the number of non-event buffers by one after adding a non-event
* buffer into this subpartition.
*/
private void increaseBuffersInBacklog(Buffer buffer) {
assert Thread.holdsLock(buffers);
if (buffer != null && buffer.isBuffer()) {
buffersInBacklog++;
}
}
@Override
public PipelinedSubpartitionView createReadView(BufferAvailabilityListener availabilityListener) throws IOException {
final int queueSize;
synchronized (buffers) {
checkState(!isReleased);
checkState(readView == null,
"Subpartition %s of is being (or already has been) consumed, " +
"but pipelined subpartitions can only be consumed once.", index, parent.getPartitionId());
LOG.debug("Creating read view for subpartition {} of partition {}.", index, parent.getPartitionId());
queueSize = buffers.size();
readView = new PipelinedSubpartitionView(this, availabilityListener);
}
readView.notifyBuffersAvailable(queueSize);
return readView;
}
// ------------------------------------------------------------------------
int getCurrentNumberOfBuffers() {
return buffers.size();
}
// ------------------------------------------------------------------------
@Override
public String toString() {
final long numBuffers;
final long numBytes;
final boolean finished;
final boolean hasReadView;
synchronized (buffers) {
numBuffers = getTotalNumberOfBuffers();
numBytes = getTotalNumberOfBytes();
finished = isFinished;
hasReadView = readView != null;
}
return String.format(
"PipelinedSubpartition [number of buffers: %d (%d bytes), number of buffers in backlog: %d, finished? %s, read view? %s]",
numBuffers, numBytes, buffersInBacklog, finished, hasReadView);
}
@Override
public int unsynchronizedGetNumberOfQueuedBuffers() {
// since we do not synchronize, the size may actually be lower than 0!
return Math.max(buffers.size(), 0);
}
}
| [hotfix][runtime] Deduplicate code in PipelinedSubpartition
| flink-runtime/src/main/java/org/apache/flink/runtime/io/network/partition/PipelinedSubpartition.java | [hotfix][runtime] Deduplicate code in PipelinedSubpartition | <ide><path>link-runtime/src/main/java/org/apache/flink/runtime/io/network/partition/PipelinedSubpartition.java
<ide>
<ide> @Override
<ide> public boolean add(Buffer buffer) throws IOException {
<add> return add(buffer, false);
<add> }
<add>
<add> @Override
<add> public void finish() throws IOException {
<add> add(EventSerializer.toBuffer(EndOfPartitionEvent.INSTANCE), true);
<add> LOG.debug("Finished {}.", this);
<add> }
<add>
<add> private boolean add(Buffer buffer, boolean finish) throws IOException {
<ide> checkNotNull(buffer);
<ide>
<ide> // view reference accessible outside the lock, but assigned inside the locked scope
<ide> reader = readView;
<ide> updateStatistics(buffer);
<ide> increaseBuffersInBacklog(buffer);
<add>
<add> if (finish) {
<add> isFinished = true;
<add> }
<ide> }
<ide>
<ide> // Notify the listener outside of the synchronized block
<ide> }
<ide>
<ide> return true;
<del> }
<del>
<del> @Override
<del> public void finish() throws IOException {
<del> final Buffer buffer = EventSerializer.toBuffer(EndOfPartitionEvent.INSTANCE);
<del>
<del> // view reference accessible outside the lock, but assigned inside the locked scope
<del> final PipelinedSubpartitionView reader;
<del>
<del> synchronized (buffers) {
<del> if (isFinished || isReleased) {
<del> return;
<del> }
<del>
<del> buffers.add(buffer);
<del> reader = readView;
<del> updateStatistics(buffer);
<del>
<del> isFinished = true;
<del> }
<del>
<del> LOG.debug("Finished {}.", this);
<del>
<del> // Notify the listener outside of the synchronized block
<del> if (reader != null) {
<del> reader.notifyBuffersAvailable(1);
<del> }
<ide> }
<ide>
<ide> @Override |
|
JavaScript | mit | 9c85102f489e9d83f86be747d72bda577fc469bd | 0 | hash-bang/Monoxide,hash-bang/Mongoloid | var _ = require('lodash')
.mixin(require('lodash-deep'));
var argy = require('argy');
var async = require('async-chainable');
var debug = require('debug')('monoxide');
var deepDiff = require('deep-diff');
var events = require('events');
var mongoose = require('mongoose');
var traverse = require('traverse');
var util = require('util');
/**
* @static monoxide
*/
function Monoxide() {
var o = this;
o.mongoose = mongoose;
o.models = {};
o.connection;
o.settings = {
removeAll: true, // Allow db.model.delete() calls with no arguments
versionIncErr: /^MongoError: Cannot apply \$inc to a value of non-numeric type. {.+} has the field '__v' of non-numeric type null$/i, // RegExp error detector used to detect $inc problems when trying to increment `__v` in update operations
};
// .connect {{{
/**
* Connect to a Mongo database
* @param {string} uri The URL of the database to connect to
* @param {function} [callback] Optional callback when connected, if omitted this function is syncronous
* @return {monoxide} The Monoxide chainable object
*/
o.connect = function(uri, callback) {
mongoose.set('useFindAndModify', false);
mongoose.set('useCreateIndex', true);
mongoose.connect(uri, {
promiseLibrary: global.Promise,
useNewUrlParser: true,
}, function(err) {
if (err) {
if (_.isFunction(callback)) callback(err);
} else {
o.connection = mongoose.connection;
if (_.isFunction(callback)) callback();
}
})
return o;
};
// }}}
// .disconnect {{{
/**
* Disconnect from an active connection
* @return {monoxide} The Monoxide chainable object
*/
o.disconnect = function(callback) {
mongoose.disconnect(callback);
return o;
};
// }}}
// .get(q, [id], callback) {{{
/**
* Retrieve a single record from a model via its ID
* This function will ONLY retrieve via the ID field, all other fields are ignored
* NOTE: Really this function just wraps the monoxide.query() function to provide functionality like populate
*
* @name monoxide.get
* @memberof monoxide
*
* @param {Object} q The object to process
* @param {string} q.$collection The collection / model to query
* @param {string} [q.$id] The ID to return
* @param {(string|string[]|object[])} [q.$populate] Population criteria to apply
*
* @param {string} [id] The ID to return (alternative syntax)
*
* @param {function} callback(err, result) the callback to call on completion or error
*
* @return {Object} This chainable object
*
* @example
* // Return a single widget by its ID (string syntax)
* monoxide.get('widgets', '56e2421f475c1ef4135a1d58', function(err, res) {
* console.log('Widget:', res);
* });
*
* @example
* // Return a single widget by its ID (object syntax)
* monoxide.get({$collection: 'widgets', $id: '56e2421f475c1ef4135a1d58'}, function(err, res) {
* console.log('Widget:', res);
* });
*/
o.get = argy('[object|string|number] [string|number|object] function', function(q, id, callback) {
argy(arguments)
.ifForm('object function', function(aQ, aCallback) {
q = aQ;
callback = aCallback;
})
.ifForm('string string|number function', function(aCollection, aId, aCallback) {
q = {
$collection: aCollection,
$id: aId,
};
})
.ifForm('string object function', function(aCollection, aId, aCallback) { // Probably being passed a Mongoose objectId as the ID
q = {
$collection: aCollection,
$id: aId.toString(),
};
});
if (!q.$id) return callback('No $id specified');
return o.internal.query(q, callback);
});
// }}}
// .query([q], callback) {{{
/**
* Query Mongo directly with the Monoxide query syntax
*
* @name monoxide.query
* @fires query
*
* @param {Object} q The object to process
* @param {string} q.$collection The collection / model to query
* @param {string} [q.$id] If specified return only one record by its master ID (implies $one=true). If present all other conditionals will be ignored and only the object is returned (see $one)
* @param {(string|string[]|object[])} [q.$select] Field selection criteria to apply (implies q.$applySchema=false as we will be dealing with a partial schema). Any fields prefixed with '-' are removed
* @param {(string|string[]|object[])} [q.$sort] Sorting criteria to apply
* @param {(string|string[]|object[])} [q.$populate] Population criteria to apply
* @param {boolean} [q.$one=false] Whether a single object should be returned (implies $limit=1). If enabled an object is returned not an array
* @param {number} [q.$limit] Limit the return to this many rows
* @param {number} [q.$skip] Offset return by this number of rows
* @param {boolean=false} [q.$count=false] Only count the results - do not return them. If enabled a number of returned with the result
* @param {object|function} [q.$data] Set the user-defined data object, if this is a function the callback result is used
* @param {boolean} [q.$decorate=true] Add all Monoxide methods, functions and meta properties
* @param {string} [q.$want='array'] How to return data contents. ENUM: 'array', 'cursor'
* @param {boolean} [q.$plain=false] Return a plain object or object array. This is the equivelent of calling .toObject() on any resultant object. Implies $decorate=true
* @param {boolean} [q.$cacheFKs=true] Cache the foreign keys (objectIDs) within an object so future retrievals dont have to recalculate the model structure
* @param {boolean} [q.$applySchema=true] Apply the schema for each document retrieval - this slows retrieval but means any alterations to the schema are applied to each retrieved record
* @param {boolean} [q.$dirty=false] Whether the entire document contents should be marked as dirty (modified). If true this also skips the computation of modified fields
* @param {boolean} [q.$errNotFound] Raise an error if a specifically requested document is not found (requires $id)
* @param {...*} [q.filter] Any other field (not beginning with '$') is treated as filtering criteria
*
* @param {function} callback(err, result) the callback to call on completion or error. If $one is truthy this returns a single monoxide.monoxideDocument, if not it returns an array of them
*
* @return {Object} This chainable object
*
* @example
* // Return all Widgets, sorted by name
* monoxide.query({$collection: 'widgets', $sort: 'name'}, function(err, res) {
* console.log('Widgets:', res);
* });
* @example
* // Filter Users to only return admins while also populating their country
* monoxide.query({$collection: 'users', $populate: 'country', role: 'admin'}, function(err, res) {
* console.log('Admin users:', res);
* });
*/
o.query = argy('[string|object] function', function MonoxideQuery(q, callback) {
if (argy.isType(q, 'string')) q = {$collection: q};
_.defaults(q || {}, {
$cacheFKs: true, // Cache model Foreign Keys (used for populates) or compute them every time
$want: 'array',
$applySchema: true, // Apply the schema on retrieval - this slows ths record retrieval but means any alterations to the schema are applied to each retrieved record
$errNotFound: true, // During $id / $one operations raise an error if the record is not found
});
if (!_.isEmpty(q.$select)) q.$applySchema = false; // Turn off schema application when using $select as we wont be grabbing the full object
async()
.set('metaFields', [
'$collection', // Collection to query
'$data', // Meta user-defined data object
'$dirty', // Whether the document is unclean
'$id', // If specified return only one record by its master ID (implies $one=true). If present all other conditionals will be ignored and only the object is returned (see $one)
'$select', // Field selection criteria to apply
'$sort', // Sorting criteria to apply
'$populate', // Population criteria to apply
'$one', // Whether a single object should be returned (implies $limit=1). If enabled an object is returned not an array
'$limit', // Limit the return to this many rows
'$skip', // Offset return by this number of rows
'$count', // Only count the results - do not return them
'$want', // What result we are looking for from the query
'$cacheFKs', // Cache model Foreign Keys (used for populates) or compute them every time
'$applySchema', // Apply the schema on retrieval - this slows ths record retrieval but means any alterations to the schema are applied to each retrieved record
'$decorate',
'$plain',
'$errNotFound', // During $id / $one operations raise an error if the record is not found
])
// Sanity checks {{{
.then(function(next) {
if (!q || _.isEmpty(q)) return next('No query given for get operation');
if (!q.$collection) return next('$collection must be specified for get operation');
if (!o.models[q.$collection]) return next('Model not initalized: "' + q.$collection + '"');
next();
})
// }}}
// .query - start the find query {{{
.set('filterPostPopulate', {}) // Filter by these fields post populate
.then('query', function(next) {
var me = this;
var fields;
if (q.$id) { // Search by one ID only - ignore other fields
fields = {_id: q.$id};
q.$one = true;
} else { // Search by query
fields = _(q)
.omit(this.metaFields) // Remove all meta fields
// FIXME: Ensure all fields are flat
.omitBy(function(val, key) { // Remove all fields that will need populating later
if (_.some(q.$collection.$oids, function(FK) {
return _.startsWith(key, FK);
})) {
me.filterPostPopulate[key] = val;
return true;
} else {
return false;
}
})
.value();
}
//console.log('FIELDS', fields);
//console.log('POSTPOPFIELDS', o.filterPostPopulate);
if (q.$count) {
next(null, o.models[q.$collection].$mongooseModel.countDocuments(fields));
} else if (q.$one) {
next(null, o.models[q.$collection].$mongooseModel.findOne(fields));
} else {
next(null, o.models[q.$collection].$mongooseModel.find(fields));
}
})
// }}}
// Apply various simple criteria {{{
.then(function(next) {
if (q.$count) return next(); // No point doing anything else if just counting
if (q.$limit) this.query.limit(q.$limit);
if (q.$skip) this.query.skip(q.$skip);
// q.$populate {{{
if (q.$populate) {
if (_.isArray(q.$populate)) {
this.query.populate(q.$populate);
} else if (_.isString(q.$populate) || _.isObject(q.$populate)) {
this.query.populate(q.$populate);
q.$populate = [q.$populate]; // Also rewrite into an array so we can destructure later
} else {
throw new Error('Invalid sort type: ' + (typeof q.$sort));
}
}
// }}}
// q.$select {{{
if (q.$select) {
if (_.isArray(q.$select)) {
var query = this.query;
q.$select.forEach(function(s) {
query.select(s);
});
} else if (_.isString(q.$select) || _.isObject(q.$select)) {
this.query.select(q.$select);
} else {
throw new Error('Invalid select type: ' + (typeof q.$select));
}
}
// }}}
// q.$sort {{{
if (q.$sort) {
if (_.isArray(q.$sort)) {
var query = this.query;
q.$sort.forEach(function(s) {
query.sort(s);
});
} else if (_.isString(q.$sort) || _.isObject(q.$sort)) {
this.query.sort(q.$sort);
} else {
throw new Error('Invalid sort type: ' + (typeof q.$sort));
}
}
// }}}
next();
})
// }}}
// Calculate $data if it is a function {{{
.then('data', function(next) {
if (!q.$data) return next();
if (_.isFunction(q.$data)) {
q.$data(function(err, data) {
if (err) return next(err);
q.$data = data;
});
}
next();
})
// }}}
// Fire hooks {{{
.then(function(next) {
o.models[q.$collection].fire('query', next, q);
})
// }}}
// Execute and capture return {{{
.then('result', function(next) {
switch (q.$want) {
case 'array':
this.query.exec(function(err, res) {
if (err) return next(err);
if (q.$one) {
if (_.isEmpty(res)) {
if (q.$errNotFound) {
next('Not found');
} else {
next(null, undefined);
}
} else {
next(null, res);
}
} else if (q.$count) {
next(null, res);
} else {
next(null, res);
}
});
break;
case 'cursor':
next(null, this.query.cursor());
break;
default:
next('Unknown $want type');
}
})
// }}}
// Convert Mongoose Documents into Monoxide Documents {{{
.then('result', function(next) {
// Not wanting an array of data? - pass though the result
if (q.$want != 'array') return next(null, this.result);
if (this.result === undefined) {
next(null, undefined);
} else if (q.$one) {
if (q.$decorate) return next(null, this.result.toObject());
next(null, new o.monoxideDocument({
$collection: q.$collection,
$applySchema: q.$applySchema,
$decorate: q.$decorate,
$dirty: q.$dirty,
}, this.result));
} else if (q.$count) {
next(null, this.result);
} else {
next(null, this.result.map(function(doc) {
if (q.$decorate) return doc.toObject();
return new o.monoxideDocument({
$collection: q.$collection,
$applySchema: q.$applySchema,
$decorate: q.$decorate,
$dirty: q.$dirty,
}, doc.toObject());
}));
}
})
// }}}
// Apply populates {{{
.then(function(next) {
// Not wanting an array of data? - pass though the result
if (q.$want != 'array') return next(null, this.result);
if (!q.$populate || !q.$populate.length || q.$count || q.$decorate === false || q.$plain === false || this.result === undefined) return next(); // Skip
async()
.forEach(_.castArray(this.result), (next, doc) => {
async()
.forEach(q.$populate, (next, pop) => {
var path = _.isString(pop) ? pop : pop.path;
if (!o.utilities.isObjectId(_.get(doc, path))) return next(); // Already populated
doc.populate(path, next);
})
.end(next);
})
.end(next);
})
// }}}
// End {{{
.end(function(err) {
if (err) {
debug('get() error', err);
return callback(err);
} else if (q.$count) {
callback(null, this.result);
} else {
callback(null, this.result);
}
});
// }}}
return o;
});
// }}}
// .count([q], callback) {{{
/**
* Similar to query() but only return the count of possible results rather than the results themselves
*
* @name monoxide.count
* @see monoxide.query
*
* @param {Object} q The object to process
* @param {string} q.$collection The collection / model to query
* @param {...*} [q.filter] Any other field (not beginning with '$') is treated as filtering criteria
*
* @param {function} callback(err,count) the callback to call on completion or error
*
* @return {Object} This chainable object
*
* @example
* // Count all Widgets
* monoxide.count({$collection: 'widgets'}, function(err, count) {
* console.log('Number of Widgets:', count);
* });
*
* @example
* // Count all admin Users
* monoxide.query({$collection: 'users', role: 'admin'}, function(err, count) {
* console.log('Number of Admin Users:', count);
* });
*/
o.count = argy('[string|object] function', function MonoxideCount(q, callback) {
if (argy.isType(q, 'string')) q = {$collection: q};
// Glue count functionality to query
q.$count = true;
return o.internal.query(q, callback);
});
// }}}
// .save(item, [callback]) {{{
/**
* Save an existing Mongo document by its ID
* If you wish to create a new document see the monoxide.create() function.
* If the existing document ID is not found this function will execute the callback with an error
*
* @name monoxide.save
* @fires save
* @fires postSave
*
* @param {Object} q The object to process
* @param {string} q.$collection The collection / model to query
* @param {string} q.$id The ID of the document to save
* @param {boolean} [q.$refetch=true] Whether to refetch the record after update, false returns `null` in the callback
* @param {boolean} [q.$errNoUpdate=false] Raise an error if no documents were actually updated
* @param {boolean} [q.$errBlankUpdate=false] Raise an error if no fields are updated
* @param {boolean} [q.$returnUpdated=true] If true returns the updated document, if false it returns the document that was replaced
* @param {boolean} [q.$version=true] Increment the `__v` property when updating
* @param {...*} [q.field] Any other field (not beginning with '$') is treated as data to save
*
* @param {function} [callback(err,result)] Optional callback to call on completion or error
*
* @return {Object} This chainable object
*
* @example
* // Save a Widget
* monoxide.save({
* $collection: 'widgets',
* $id: 1234,
* name: 'New name',
* }, function(err, widget) {
* console.log('Saved widget is now', widget);
* });
*/
o.save = argy('object [function]', function(q, callback) {
_.defaults(q || {}, {
$refetch: true, // Fetch and return the record when updated (false returns null)
$errNoUpdate: false,
$errBlankUpdate: false,
$returnUpdated: true,
$version: true,
});
async()
.set('metaFields', [
'$id', // Mandatory field to specify while record to update
'_id', // We also need to clip this from the output (as we cant write to it), but we need to pass it to hooks
'$collection', // Collection to query to find the original record
'$data', // Meta user-defined data
'$refetch',
'$errNoUpdate',
'$errBlankUpdate',
'$version',
'$returnUpdated',
])
// Sanity checks {{{
.then(function(next) {
if (!q || _.isEmpty(q)) return next('No query given for save operation');
if (!q.$collection) return next('$collection must be specified for save operation');
if (!q.$id) return next('ID not specified');
if (!o.models[q.$collection]) return next('Model not initalized');
q._id = q.$id;
next();
})
// }}}
// Calculate $data if it is a function {{{
.then(function(next) {
if (!q.$data) return next();
if (_.isFunction(q.$data)) {
q.$data(function(err, data) {
if (err) return next(err);
q.$data = data;
});
}
next();
})
// }}}
// Fire the 'save' hook on the model {{{
.then(function(next) {
o.models[q.$collection].fire('save', next, q);
})
// }}}
// Peform the update {{{
.then('newRec', function(next) {
var patch = _.omit(q, this.metaFields);
if (_.isEmpty(patch)) {
if (q.$errBlankUpdate) return next('Nothing to update');
if (q.$refetch) {
return o.internal.get({$collection: q.$collection, $id: q.$id}, next);
} else {
return next(null, {});
}
}
_.forEach(o.models[q.$collection].$oids, function(fkType, schemaPath) {
if (!_.has(patch, schemaPath)) return; // Not patching this field anyway
switch(fkType.type) {
case 'objectId': // Convert the field to an OID if it isn't already
if (_.has(q, schemaPath)) {
var newVal = _.get(q, schemaPath);
if (!o.utilities.isObjectID(newVal))
_.set(patch, schemaPath, o.utilities.objectID(newVal));
}
break;
case 'objectIdArray': // Convert each item to an OID if it isn't already
if (_.has(q, schemaPath)) {
var gotOIDs = _.get(q, schemaPath);
if (_.isArray(gotOIDs)) {
_.set(patch, schemaPath, gotOIDs.map(function(i, idx) {
return (!o.utilities.isObjectID(newVal))
? o.utilities.objectID(i)
: i;
}));
} else {
throw new Error('Expected ' + schemaPath + ' to contain an array of OIDs but got ' + (typeof gotOIDs));
}
}
break;
}
});
var updateQuery = { _id: o.utilities.objectID(q.$id) };
var updatePayload = {$set: patch};
var updateOptions = { returnOriginal: !q.$returnUpdated };
var updateCallback = function(err, res) {
if (q.$version && err && o.settings.versionIncErr.test(err.toString())) { // Error while setting `__v`
// Remove __v as an increment operator + retry the operation
// It would be good if $inc could assume `0` when null, but Mongo doesn't support that
updatePayload.$set.__v = 1;
delete updatePayload.$inc;
o.models[q.$collection].$mongoModel.findOneAndUpdate(updateQuery, updatePayload, updateOptions, updateCallback);
} else if (err) {
next(err);
} else {
// This would only really happen if the record has gone away since we started updating
if (q.$errNoUpdate && !res.ok) return next('No documents updated');
if (!q.$refetch) return next(null, null);
next(null, new o.monoxideDocument({$collection: q.$collection}, res.value));
}
};
if (q.$version) {
updatePayload.$inc = {'__v': 1};
delete updatePayload.$set.__v; // Remove user updates of __v
}
// Actually perform the action
o.models[q.$collection].$mongoModel.findOneAndUpdate(
updateQuery, // What we are writing to
updatePayload, // What we are saving
updateOptions, // Options passed to Mongo
updateCallback
);
})
// }}}
// Fire the 'postSave' hook {{{
.then(function(next) {
o.models[q.$collection].fire('postSave', next, q, this.newRec);
})
// }}}
// End {{{
.end(function(err) {
if (err) {
debug('save() error', err);
if (_.isFunction(callback)) callback(err);
} else {
if (_.isFunction(callback)) callback(null, this.newRec);
}
});
// }}}
return o;
});
// }}}
// .update(q, [with], [callback]) {{{
/**
* Update multiple documents
*
* @name monoxide.update
* @fires update
*
* @param {Object} q The object to query by
* @param {string} q.$collection The collection / model to query
* @param {boolean} [q.$refetch=true] Return the newly updated record
* @param {...*} [q.field] Any other field (not beginning with '$') is treated as filter data
*
* @param {Object} qUpdate The object to update into the found documents
* @param {...*} [qUpdate.field] Data to save into every record found by `q`
*
* @param {function} [callback(err,result)] Optional callback to call on completion or error
*
* @return {Object} This chainable object
*
* @example
* // Set all widgets to active
* monoxide.update({
* $collection: 'widgets',
* status: 'active',
* });
*/
o.update = argy('object|string [object] [function]', function MonoxideUpdate(q, qUpdate, callback) {
var o = this;
if (argy.isType(q, 'string')) q = {$collection: q};
_.defaults(q || {}, {
$refetch: true, // Fetch and return the record when updated (false returns null)
});
async()
.set('metaFields', [
'$collection', // Collection to query to find the original record
'$data', // Meta user-defined data
'$refetch',
])
// Sanity checks {{{
.then(function(next) {
if (!q || _.isEmpty(q)) return next('No query given for get operation');
if (!q.$collection) return next('$collection must be specified for get operation');
if (!o.models[q.$collection]) return next('Model not initalized');
next();
})
// }}}
// Calculate $data if it is a function {{{
.then(function(next) {
if (!q.$data) return next();
if (_.isFunction(q.$data)) {
q.$data(function(err, data) {
if (err) return next(err);
q.$data = data;
});
}
next();
})
// }}}
// Fire the 'update' hook {{{
.then(function(next) {
o.models[q.$collection].fire('update', next, q);
})
// }}}
// Peform the update {{{
.then('rawResponse', function(next) {
o.models[q.$collection].$mongooseModel.updateMany(_.omit(q, this.metaFields), _.omit(qUpdate, this.metaFields), {multi: true}, next);
})
// }}}
// End {{{
.end(function(err) {
if (err) {
debug('update() error', err);
if (callback) callback(err);
} else {
if (callback) callback(null, this.newRec);
}
});
// }}}
return o;
});
// }}}
// .create(item, [callback]) {{{
/**
* Create a new Mongo document and return it
* If you wish to save an existing document see the monoxide.save() function.
*
* @name monoxide.create
*
* @param {Object} q The object to process
* @param {string} q.$collection The collection / model to query
* @param {boolean} [q.$refetch=true] Return the newly create record
* @param {boolean} [q.$version=true] Set the `__v` field to 0 when creating the document
* @param {...*} [q.field] Any other field (not beginning with '$') is treated as data to save
*
* @param {function} [callback(err,result)] Optional callback to call on completion or error
*
* @return {Object} This chainable object
*
* @example
* // Create a Widget
* monoxide.save({
* $collection: 'widgets',
* name: 'New widget name',
* }, function(err, widget) {
* console.log('Created widget is', widget);
* });
*/
o.create = argy('object [function]', function MonoxideQuery(q, callback) {
_.defaults(q || {}, {
$refetch: true, // Fetch and return the record when created (false returns null)
$version: true,
});
async()
.set('metaFields', [
'$collection', // Collection to query to find the original record
'$data', // Meta user-defined data
'$refetch',
'$version',
])
// Sanity checks {{{
.then(function(next) {
if (!q || _.isEmpty(q)) return next('No query given for save operation');
if (!q.$collection) return next('$collection must be specified for save operation');
if (!o.models[q.$collection]) return next('Model not initalized');
next();
})
// }}}
// Calculate $data if it is a function {{{
.then(function(next) {
if (!q.$data) return next();
if (_.isFunction(q.$data)) {
q.$data(function(err, data) {
if (err) return next(err);
q.$data = data;
next();
});
} else {
next();
}
})
// }}}
// Coherse all OIDs (or arrays of OIDs) into their correct internal type {{{
.then(function(next) {
_.forEach(o.models[q.$collection].$oids, function(fkType, schemaPath) {
switch(fkType.type) {
case 'objectId': // Convert the field to an OID if it isn't already
if (_.has(q, schemaPath)) {
var newVal = _.get(q, schemaPath);
if (!o.utilities.isObjectID(newVal))
_.set(q, schemaPath, o.utilities.objectID(newVal));
}
break;
case 'objectIdArray': // Convert each item to an OID if it isn't already
if (_.has(q, schemaPath)) {
var gotOIDs = _.get(q, schemaPath);
if (_.isArray(gotOIDs)) {
_.set(q, schemaPath, gotOIDs.map(function(i, idx) {
return (!o.utilities.isObjectID(newVal))
? o.utilities.objectID(i)
: i;
}));
} else {
throw new Error('Expected ' + schemaPath + ' to contain an array of OIDs but got ' + (typeof gotOIDs));
}
}
break;
}
});
next();
})
// }}}
// Add version information if $version==true {{{
.then(function(next) {
if (!q.$version) return next();
q.__v = 0;
next();
})
// }}}
// Create record {{{
.then('createDoc', function(next) { // Compute the document we will create
next(null, new o.monoxideDocument({
$collection: q.$collection,
$dirty: true, // Mark all fields as modified (and not bother to compute the clean markers)
}, _.omit(q, this.metaFields)));
})
.then(function(next) {
o.models[q.$collection].fire('create', next, this.createDoc);
})
.then('rawResponse', function(next) {
o.models[q.$collection].$mongoModel.insertOne(this.createDoc.toMongoObject(), next);
})
.then(function(next) {
o.models[q.$collection].fire('postCreate', next, q, this.createDoc);
})
// }}}
// Refetch record {{{
.then('newRec', function(next) {
if (!q.$refetch) return next(null, null);
o.internal.query({
$collection: q.$collection,
$id: this.rawResponse.insertedId.toString(),
}, function(err, res) {
if (err == 'Not found') return next('Document creation failed');
next(err, res);
});
})
// }}}
// End {{{
.end(function(err) {
if (err) {
debug('create() error', err);
if (_.isFunction(callback)) callback(err);
} else {
if (_.isFunction(callback)) callback(null, this.newRec);
}
});
// }}}
return o;
});
// }}}
// .delete(item, [callback]) {{{
/**
* Delete a Mongo document by its ID
* This function has two behaviours - it will, by default, only delete a single record by its ID. If `q.$multiple` is true it will delete by query.
* If `q.$multiple` is false and the document is not found (by `q.$id`) this function will execute the callback with an error
* Delete will only work with no parameters if monoxide.settings.removeAll is truthy as an extra safety check
*
* @name monoxide.delete
*
* @param {Object} [q] The object to process
* @param {string} [q.$collection] The collection / model to query
* @param {string} [q.$id] The ID of the document to delete (if you wish to do a remove based on query set q.$query=true)
* @param {boolean} [q.$multiple] Allow deletion of multiple records by query
* @param {boolean} [q.$errNotFound] Raise an error if a specifically requested document is not found (requires $id)
*
* @param {function} [callback(err,result)] Optional callback to call on completion or error
*
* @return {Object} This chainable object
*/
o.delete = o.remove = argy('object [function]', function MonoxideQuery(q, callback) {
_.defaults(q || {}, {
$errNotFound: true, // During raise an error if $id is specified but not found to delete
});
async()
.set('metaFields', [
'$id', // Mandatory field to specify while record to update
'$collection', // Collection to query to find the original record
'$data', // Meta user-defined data
'$multiple', // Whether to allow deletion by query
'$errNotFound',
])
// Sanity checks {{{
.then(function(next) {
if (!q || _.isEmpty(q)) return next('No query given for delete operation');
if (!q.$collection) return next('$collection must be specified for delete operation');
if (!q.$id && !q.$multiple) return next('$id or $multiple must be speciied during delete operation');
if (!o.settings.removeAll && !q.$id && _.isEmpty(_.omit(q, this.metaFields))) { // Apply extra checks to make sure we are not nuking everything if we're not allowed
return next('delete operation not allowed with empty query');
}
next();
})
// }}}
// Calculate $data if it is a function {{{
.then(function(next) {
if (!q.$data) return next();
if (_.isFunction(q.$data)) {
q.$data(function(err, data) {
if (err) return next(err);
q.$data = data;
});
}
next();
})
// }}}
// Delete record {{{
.then(function(next) {
if (q.$multiple) { // Multiple delete operation
o.internal.query(_.merge(_.omit(q, this.metaFields), {$collection: q.$collection, $select: 'id'}), function(err, rows) {
async()
.forEach(rows, function(next, row) {
o.internal.delete({$collection: q.$collection, $id: row._id}, next);
})
.end(next);
});
} else { // Single item delete
// Check that the hook returns ok
o.models[q.$collection].fire('delete', function(err) {
// Now actually delete the item
o.models[q.$collection].$mongoModel.deleteOne({_id: o.utilities.objectID(q.$id)}, function(err, res) {
if (err) return next(err);
if (q.$errNotFound && !res.result.ok) return next('Not found');
// Delete was sucessful - call event then move next
o.models[q.$collection].fire('postDelete', next, {_id: q.$id});
});
}, {_id: q.$id});
}
})
// }}}
// End {{{
.end(function(err) {
if (err) {
debug('delete() error', err);
if (callback) callback(err);
} else {
if (callback) callback(null, this.newRec);
}
});
// }}}
return o;
});
// }}}
// .meta(item, [callback]) {{{
/**
* Return information about a Mongo collection schema
*
* @name monoxide.meta
*
* @param {Object} q The object to process
* @param {string} q.$collection The collection / model to examine
* @param {boolean} [q.$collectionEnums=false] Provide all enums as a collection object instead of an array
* @param {boolean} [q.$filterPrivate=true] Ignore all private fields
* @param {boolean} [q.$prototype=false] Provide the $prototype meta object
* @param {boolean} [q.$indexes=false] Include whether a field is indexed
*
* @param {function} [callback(err,result)] Optional callback to call on completion or error
*
* @return {Object} This chainable object
*
* @example
* // Describe a collection
* monoxide.meta({$collection: 'widgets'}, function(err, res) {
* console.log('About the widget collection:', res);
* });
*/
o.meta = argy('[object] function', function MonoxideMeta(q, callback) {
_.defaults(q || {}, {
$filterPrivate: true,
$prototype: false,
$indexes: false,
});
async()
.set('metaFields', [
'$collection', // Collection to query to find the original record
'$data', // Meta user-defined data
'$filterPrivate', // Filter out /^_/ fields
'$collectionEnums', // Convert enums into a collection (with `id` + `title` fields per object)
'$prototype',
'$indexes',
])
// Sanity checks {{{
.then(function(next) {
if (!q || _.isEmpty(q)) return next('No query given for meta operation');
if (!q.$collection) return next('$collection must be specified for meta operation');
if (!o.models[q.$collection]) return next('Cannot find collection to extract its meta information: ' + q.$collection);
next();
})
// }}}
// Retrieve the meta information {{{
.then('meta', function(next) {
var sortedPaths = _(o.models[q.$collection].$mongooseModel.schema.paths)
.map((v,k) => v)
.sortBy('path')
.value();
var meta = {
_id: {type: 'objectid', index: true}, // FIXME: Is it always the case that a doc has an ID?
};
_.forEach(sortedPaths, function(path) {
var id = path.path;
if (q.$filterPrivate && _.last(path.path.split('.')).startsWith('_')) return; // Skip private fields
var info = {};
switch (path.instance.toLowerCase()) {
case 'string':
info.type = 'string';
if (path.enumValues && path.enumValues.length) {
if (q.$collectionEnums) {
info.enum = path.enumValues.map(e => ({
id: e,
title: _.startCase(e),
}));
} else {
info.enum = path.enumValues;
}
}
break;
case 'number':
info.type = 'number';
break;
case 'date':
info.type = 'date';
break;
case 'boolean':
info.type = 'boolean';
break;
case 'array':
info.type = 'array';
break;
case 'object':
info.type = 'object';
break;
case 'objectid':
info.type = 'objectid';
if (_.has(path, 'options.ref')) info.ref = path.options.ref;
break;
default:
debug('Unknown Mongo data type during meta extract on ' + q.$collection + ':', path.instance.toLowerCase());
}
// Extract default value if its not a function (otherwise return [DYNAMIC])
if (path.defaultValue) info.default = argy.isType(path.defaultValue, 'scalar') ? path.defaultValue : '[DYNAMIC]';
if (q.$indexes && path._index) info.index = true;
meta[id] = info;
});
next(null, meta);
})
// }}}
// Construct the prototype if $prototype=true {{{
.then(function(next) {
if (!q.$prototype) return next();
var prototype = this.meta.$prototype = {};
_.forEach(this.meta, function(v, k) {
if (!_.has(v, 'default')) return;
if (v.default == '[DYNAMIC]') return; // Ignore dynamic values
_.set(prototype, k, v.default);
});
next();
})
// }}}
// End {{{
.end(function(err) {
if (err) {
debug('meta() error', err);
if (callback) callback(err);
} else {
if (callback) callback(null, this.meta);
}
});
// }}}
return o;
});
// }}}
// .runCommand(command, [callback]) {{{
/**
* Run an internal MongoDB command and fire an optional callback on the result
*
* @name monoxide.meta
*
* @param {Object} cmd The command to process
* @param {function} [callback(err,result)] Optional callback to call on completion or error
* @return {Object} This chainable object
* @example
*/
o.runCommand = argy('object [function]', function MonoxideRunCommand(cmd, callback) {
o.connection.db.command(cmd, callback);
return o;
});
// }}}
// .queryBuilder() - query builder {{{
/**
* Returns data from a Monoxide model
* @class
* @name monoxide.queryBuilder
* @return {monoxide.queryBuilder}
* @fires queryBuilder Fired as (callback, qb) when a new queryBuilder object is created
*/
o.queryBuilder = function monoxideQueryBuilder() {
var qb = this;
qb.$MONOXIDE = true;
qb.query = {};
// qb.find(q, cb) {{{
/**
* Add a filtering function to an existing query
* @name monoxide.queryBuilder.find
* @memberof monoxide.queryBuilder
* @param {Object|function} [q] Optional filtering object or callback (in which case we act as exec())
* @param {function} [callback] Optional callback. If present this is the equivelent of calling exec()
* @return {monoxide.queryBuilder} This chainable object
*/
qb.find = argy('[object|string] [function]', function(q, callback) {
if (argy.isType(q, 'object')) {
_.merge(qb.query, q);
} else {
q = {$id: q};
}
if (callback) qb.exec(callback);
return qb;
});
// }}}
// qb.select(q, cb) {{{
/**
* Add select criteria to an existing query
* If this function is passed a falsy value it is ignored
* @name monoxide.queryBuilder.select
* @memberof monoxide.queryBuilder
* @param {Object|Array|string} [q] Select criteria, for strings or arrays of strings use the field name optionally prefixed with '-' for omission. For Objects use `{field: 1|-1}`
* @param {function} [callback] Optional callback. If present this is the equivelent of calling exec()
* @return {monoxide.queryBuilder} This chainable object
*/
qb.select = argy('string|array [function]', function(q, callback) {
argy(arguments)
.ifForm(['string', 'string function'], function(id, callback) {
if (qb.query.$select) {
qb.query.$select.push(id);
} else {
qb.query.$select = [id];
}
if (callback) q.exec(callback);
})
.ifForm(['array', 'array function'], function(ids, callback) {
if (qb.query.$select) {
qb.query.$select.push.apply(this, ids);
} else {
qb.query.$select = ids;
}
if (callback) q.exec(callback);
})
return qb;
});
// }}}
// qb.sort(q, cb) {{{
/**
* Add sort criteria to an existing query
* If this function is passed a falsy value it is ignored
* @name monoxide.queryBuilder.sort
* @memberof monoxide.queryBuilder
* @param {Object|Array|string} [q] Sorting criteria, for strings or arrays of strings use the field name optionally prefixed with '-' for decending search order. For Objects use `{ field: 1|-1|'asc'|'desc'}`
* @param {function} [callback] Optional callback. If present this is the equivelent of calling exec()
* @return {monoxide.queryBuilder} This chainable object
*/
qb.sort = argy('string|array|undefined [function]', function(q, callback) {
argy(arguments)
.ifForm('', function() {})
.ifForm('undefined', function() {})
.ifForm(['string', 'string function'], function(field, callback) {
if (qb.query.$sort) {
qb.query.$sort.push(field);
} else {
qb.query.$sort = [field];
}
if (callback) qb.exec(callback);
})
.ifForm(['array', 'array function'], function(fields, callback) {
if (qb.query.$sort) {
qb.query.$sort.push.apply(this, fields);
} else {
qb.query.$sort = fields;
}
if (callback) qb.exec(callback);
})
return qb;
});
// }}}
// qb.limit(q, cb) {{{
/**
* Add limit criteria to an existing query
* If this function is passed a falsy value the limit is removed
* @name monoxide.queryBuilder.limit
* @memberof monoxide.queryBuilder
* @param {number|string} q Limit records to this number (it will be parsed to an Int)
* @param {function} [callback] Optional callback. If present this is the equivelent of calling exec()
* @return {monoxide.queryBuilder} This chainable object
*/
qb.limit = argy('[falsy|string|number] [function]', function(q, callback) {
if (!q) {
delete qb.query.$limit;
} else if (argy.isType(q, 'string')) {
qb.query.$limit = parseInt(q);
} else {
qb.query.$limit = q;
}
if (callback) return qb.exec(callback);
return qb;
});
// }}}
// qb.skip(q, cb) {{{
/**
* Add skip criteria to an existing query
* If this function is passed a falsy value the skip offset is removed
* @name monoxide.queryBuilder.skip
* @memberof monoxide.queryBuilder
* @param {number} q Skip this number of records (it will be parsed to an Int)
* @param {function} [callback] Optional callback. If present this is the equivelent of calling exec()
* @return {monoxide.queryBuilder} This chainable object
*/
qb.skip = argy('[falsy|string|number] [function]', function(q, callback) {
if (!q) {
delete qb.query.$skip;
} else if (argy.isType(q, 'string')) {
qb.query.$skip = parseInt(q);
} else {
qb.query.$skip = q;
}
if (callback) return qb.exec(callback);
return qb;
});
// }}}
// qb.populate(q, cb) {{{
/**
* Add population criteria to an existing query
* If this function is passed a falsy value it is ignored
* @name monoxide.queryBuilder.populate
* @memberof monoxide.queryBuilder
* @param {Array|string} [q] Population criteria, for strings or arrays of strings use the field name
* @param {function} [callback] Optional callback. If present this is the equivelent of calling exec()
* @return {monoxide.queryBuilder} This chainable object
*/
qb.populate = argy('string|array [function]', function(q, callback) {
argy(arguments)
.ifForm('', function() {})
.ifForm(['string', 'string function'], function(field, callback) {
if (qb.query.$populate) {
qb.query.$populate.push(field);
} else {
qb.query.$populate = [field];
}
if (callback) qb.exec(callback);
})
.ifForm(['array', 'array function'], function(fields, callback) {
if (qb.query.$populate) {
qb.query.$populate.push.apply(this, fields);
} else {
qb.query.$populate = fields;
}
if (callback) qb.exec(callback);
})
return qb;
});
// }}}
// qb.exec(cb) {{{
/**
* Execute the query and return the error and any results
* @name monoxide.queryBuilder.exec
* @memberof monoxide.queryBuilder
* @param {function} callback(err,result)
* @return {monoxide.queryBuilder} This chainable object
*/
qb.exec = argy('function', function(callback) {
return o.internal.query(qb.query, callback);
});
// }}}
// qb.optional() {{{
/**
* Convenience function to set $errNotFound
* @name monoxide.queryBuilder.optional
* @memberof monoxide.queryBuilder
* @param {Object|function} [isOptional=true] Whether the return from this query should NOT throw an error if nothing was found
* @param {function} [callback] Optional callback. If present this is the equivelent of calling exec()
* @return {monoxide.queryBuilder} This chainable object
*/
qb.optional = argy('[boolean|null|undefined] [function]', function(isOptional, callback) {
if (argy.isType(isOptional, ['null', 'undefined'])) {
qb.query.$errNotFound = false;
} else {
qb.query.$errNotFound = !! isOptional;
}
if (callback) qb.exec(callback);
return qb;
});
// }}}
// qb.promise() {{{
/**
* Convenience function to execute the query and return a promise with the result
* @name monoxide.queryBuilder.promise
* @memberof monoxide.queryBuilder
* @return {Mongoose.queryBuilder} This chainable object
*/
qb.promise = function(callback) {
return new Promise(function(resolve, reject) {
o.internal.query(qb.query, function(err, result) {
if (err) {
reject(err);
} else {
resolve(result);
}
});
});
};
// Wrap all promise functions in a convnience wrapper
['then', 'catch', 'finally'].forEach(f => {
qb[f] = function() {
var p = qb.promise();
return p[f].apply(p, arguments);
};
});
// }}}
// qb.cursor() {{{
/**
* Convenience function to return the generated cursor back from a queryBuilder object
* @name monoxide.queryBuilder.cursor
* @memberof monoxide.queryBuilder
* @param {function} callback(err, cursor)
* @return {Mongoose.queryBuilder} This chainable object
*/
qb.cursor = function(callback) {
qb.query.$want = 'cursor';
return o.internal.query(qb.query, callback);
};
// }}}
o.fireImmediate('queryBuilder', qb);
return qb;
};
// }}}
// .monoxideModel([options]) - monoxide model instance {{{
/**
* @class
*/
o.monoxideModel = argy('string|object', function monoxideModel(settings) {
var mm = this;
if (argy.isType(settings, 'string')) settings = {$collection: settings};
// Sanity checks {{{
if (!settings.$collection) throw new Error('new MonoxideModel({$collection: <name>}) requires at least \'$collection\' to be specified');
if (!o.connection) throw new Error('Trying to create a MonoxideModel before a connection has been established');
if (!o.connection.db) throw new Error('Connection does not look like a MongoDB-Core object');
// }}}
/**
* The raw MongoDB-Core model
* @var {Object}
*/
mm.$mongoModel = o.connection.db.collection(settings.$collection.toLowerCase());
if (!mm.$mongoModel) throw new Error('Model not found in MongoDB-Core - did you forget to call monoxide.schema(\'name\', <schema>) first?');
/**
* The raw Mongoose model
* @depreciated This will eventually go away and be replaced with raw `mm.$mongoModel` calls
* @var {Object}
*/
mm.$mongooseModel = o.connection.base.models[settings.$collection.toLowerCase()];
/**
* Holder for all OID information
* This can either be the `._id` of the object, sub-documents, array pointers or object pointers
* @see monoxide.utilities.extractFKs
* @var {Object}
*/
mm.$oids = _.has(mm, '$mongooseModel.schema') ? o.utilities.extractFKs(mm.$mongooseModel.schema) : {};
/**
* Optional model schema
* NOTE: This is the user defined schema as-is NOT the computed $monogooseModel.schema
* @var {Object}
*/
mm.$schema = settings.$schema;
mm.$collection = settings.$collection;
mm.$methods = {};
mm.$virtuals = {};
mm.$hooks = {};
mm.$data = {};
/**
* Shortcut function to create a monoxide.queryBuilder object and immediately start filtering
* This also sets $count=true in the queryBuilder
* @name monoxide.monoxideModel.find
* @see monoxide.queryBuilder.find
*
* @param {Object} [q] Optional filtering object
* @param {function} [callback] Optional callback. If present this is the equivelent of calling exec()
* @return {monoxide.queryBuilder}
*/
mm.count = function(q, callback) {
return (new o.queryBuilder())
.find({
$collection: mm.$collection, // Set the collection from the model
$count: true,
})
.find(q, callback); // Then re-parse the find query into the new queryBuilder
};
/**
* Shortcut function to create a monoxide.queryBuilder object and immediately start filtering
* @name monoxide.monoxideModel.find
* @see monoxide.queryBuilder.find
*
* @param {Object} [q] Optional filtering object
* @param {function} [callback] Optional callback. If present this is the equivelent of calling exec()
* @return {monoxide.queryBuilder}
*/
mm.find = function(q, callback) {
return (new o.queryBuilder())
.find({$collection: mm.$collection}) // Set the collection from the model
.find(q, callback); // Then re-parse the find query into the new queryBuilder
};
/**
* Shortcut function to create a monoxide.queryBuilder object and immediately start filtering
* This also sets $one=true in the queryBuilder
* @name monoxide.monoxideModel.findOne
* @see monoxide.queryBuilder.find
*
* @param {Object} [q] Optional filtering object
* @param {function} [callback] Optional callback. If present this is the equivelent of calling exec()
* @return {monoxide.queryBuilder}
*/
mm.findOne = function(q, callback) {
if (argy.isType(q, 'string')) throw new Error('Refusing to allow findOne(String). Use findOneByID if you wish to specify only the ID');
return (new o.queryBuilder())
.find({
$collection: mm.$collection, // Set the collection from the model
$one: true, // Return a single object
})
.find(q, callback); // Then re-parse the find query into the new queryBuilder
};
/**
* Shortcut function to create a monoxide.queryBuilder object and immediately start filtering
* This also sets $id=q in the queryBuilder
* @name monoxide.monoxideModel.findOneByID
* @see monoxide.queryBuilder.find
*
* @param {Object} [q] Optional filtering object
* @param {function} [callback] Optional callback. If present this is the equivelent of calling exec()
* @return {monoxide.queryBuilder}
*/
mm.findOneByID = function(q, callback) {
// Deal with arguments {{{
if (argy.isType(q, 'string')) {
// All ok
} else if (argy.isType(q, 'object') && q.toString().length) { // Input is an object but we can convert it to something useful
q = q.toString();
} else {
throw new Error('Unknown function call pattern');
}
// }}}
return (new o.queryBuilder())
.find({
$collection: mm.$collection, // Set the collection from the model
$id: q,
})
.find(q, callback); // Then re-parse the find query into the new queryBuilder
};
/**
* Alias of findOneByID
* @see monoxide.queryBuilder.find
*/
mm.findOneById = mm.findOneByID;
/**
* Shortcut function to create a new record within a collection
* @name monoxide.monoxideModel.create
* @see monoxide.create
*
* @param {Object} [q] Optional document contents
* @param {function} [callback] Optional callback
* @return {monoxide.monoxideModel} The chainable monoxideModel
*/
mm.create = argy('object [function]', function(q, callback) {
q.$collection = mm.$collection;
o.internal.create(q, callback);
return mm;
});
/**
* Shortcut to invoke update on a given model
* @name monoxide.monoxideMode.update
* @see monoxide.update
* @param {Object} q The filter to query by
* @param {Object} qUpdate The object to update into the found documents
* @param {function} [callback(err,result)] Optional callback to call on completion or error
* @return {Object} This chainable object
*/
mm.update = argy('object object [function]', function(q, qUpdate, callback) {
q.$collection = mm.$collection;
o.internal.update(q, qUpdate, callback);
return mm;
});
/**
* Shortcut function to remove a number of rows based on a query
* @name monoxide.monoxideModel.remove
* @see monoxide.delete
*
* @param {Object} [q] Optional filtering object
* @param {function} [callback] Optional callback
* @return {monoxide}
*/
mm.remove = argy('[object] [function]', function(q, callback) {
return o.internal.delete(_.merge({}, q, {$collection: mm.$collection, $multiple: true}), callback);
});
/**
* Alias of remove()
* @see monoxide.remove()
*/
mm.delete = mm.remove;
/**
* Run an aggregation pipeline on a model
* @param {array} q The aggregation pipeline to process
* @param {function} callback Callback to fire as (err, data)
* @return {Object} This chainable object
*/
mm.aggregate = argy('array function', function(q, callback) {
o.internal.aggregate({
$collection: mm.$collection,
$stages: q,
}, callback)
return mm;
});
/**
* Add a method to a all documents returned from this model
* A method is a user defined function which extends the `monoxide.monoxideDocument` prototype
* @param {string} name The function name to add as a static method
* @param {function} func The function to add as a static method
* @return {monoxide.monoxideModel} The chainable monoxideModel
*/
mm.method = function(name, func) {
mm.$methods[name] = func;
return mm;
};
/**
* Add a static method to a model
* A static is a user defined function which extends the `monoxide.monoxideModel` prototype
* @param {string} name The function name to add as a static method
* @param {function} func The function to add as a static method
* @return {monoxide.monoxideModel} The chainable monoxideModel
*/
mm.static = function(name, func) {
mm[name] = func;
return mm;
};
/**
* Define a virtual (a handler when a property gets set or read)
* @param {string|Object} name The virtual name to apply or the full virtual object (must pretain to the Object.defineProperty descriptor)
* @param {function} getCallback The get function to call when the virtual value is read
* @param {function} setCallback The set function to call when the virtual value changes
* @return {monoxide.monoxideModel} The chainable monoxideModel
*/
mm.virtual = argy('string [function|falsy] [function|falsy]', function(name, getCallback, setCallback) {
var q = {};
if (argy.isType(getCallback, 'function')) q.get = getCallback;
if (argy.isType(setCallback, 'function')) q.set = setCallback;
mm.$virtuals[name] = q;
return mm;
});
/**
* Return whether a model has virtuals
* @return {boolean} Whether any virtuals are present
*/
mm.hasVirtuals = function() {
return (Object.keys(mm.$virtuals).length > 0);
};
/**
* Attach a hook to a model
* A hook is exactly the same as a eventEmitter.on() event but must return a callback
* Multiple hooks can be attached and all will be called in parallel on certain events such as 'save'
* All hooks must return non-errors to proceed with the operation
* @param {string} eventName The event ID to hook against
* @param {function} callback The callback to run when hooked, NOTE: Any falsy callbacks are ignored
* @return {monoxide.monoxideModel} The chainable monoxideModel
*/
mm.hook = function(eventName, callback) {
if (!callback) return mm; // Ignore flasy callbacks
if (!mm.$hooks[eventName]) mm.$hooks[eventName] = [];
mm.$hooks[eventName].push(callback);
return mm;
};
/**
* Return whether a model has a specific hook
* If an array is passed the result is whether the model has none or all of the specified hooks
* @param {string|array|undefined|null} hooks The hook(s) to query, if undefined or null this returns if any hooks are present
* @return {boolean} Whether the hook(s) is present
*/
mm.hasHook = argy('[string|array]', function(hooks) {
var out;
argy(arguments)
.ifForm('', function() {
out = !_.isEmpty(mm.$hooks);
})
.ifForm('string', function(hook) {
out = mm.$hooks[hook] && mm.$hooks[hook].length;
})
.ifForm('array', function(hooks) {
out = hooks.every(function(hook) {
return (mm.$hooks[hook] && mm.$hooks[hook].length);
});
});
return out;
});
/**
* Execute all hooks attached to a model
* This function fires all hooks in parallel and expects all to resolve correctly via callback
* NOTE: Hooks are always fired with the callback as the first argument
* @param {string} name The name of the hook to invoke
* @param {function} callback The callback to invoke on success
* @param {...*} parameters Any other parameters to be passed to each hook
* @return {monoxide.monoxideModel} The chainable monoxideModel
*/
mm.fire = function(name, callback) {
if ( // There is at least one event handler attached
(mm.$hooks[name] && mm.$hooks[name].length)
|| (o.$hooks[name] && o.$hooks[name].length)
) {
var eventArgs = _.values(arguments);
eventArgs.splice(1, 1); // Remove the 'callback' arg as events cant respond to it anyway
mm.emit.apply(mm, eventArgs);
} else {
return callback();
}
// Calculate the args array we will pass to each hook
var hookArgs = _.values(arguments);
hookArgs.shift(); // We will set args[0] to the callback in each case anyway so we only need to shift 1
var eventArgs = _.values(arguments);
eventArgs.splice(1, 1); // Remove the 'callback' arg as events cant respond to it anyway
async()
// Fire hooks attached to this model + global hooks {{{
.forEach([]
.concat(o.$hooks[name], mm.$hooks[name])
.filter(f => !!f) // Actually is a function?
, function(next, hookFunc) {
hookArgs[0] = next;
hookFunc.apply(mm, hookArgs);
})
// }}}
.end(callback);
return mm;
};
/**
* Return the meta structure for a specific model
* @param {Object} Options to return when computing the meta object. See the main meta() function for details
* @param {function} callback The callback to call with (err, layout)
* @return {monoxide.monoxideModel} The chainable monoxideModel
* @see monoxide.meta()
*/
mm.meta = argy('[object] function', function(options, callback) {
var settings = options || {};
settings.$collection = mm.$collection;
o.internal.meta(settings, callback);
return mm;
});
/**
* Run a third party plugin against a model
* This function is really just a shorthand way to pass a Monoxide model into a function
* @param {function|string|array} plugins The plugin(s) to run. Each function is run as (model, callback), strings are assumed to be file paths to JS files if they contain at least one '/' or `.` otherwise they are loaded from the `plugins` directory
* @return {monoxide.monoxideModel} The chainable monoxideModel
*/
mm.use = function(plugins, callback) {
if (!plugins) return callback(); // Do nothing if given falsy
async()
.forEach(_.castArray(plugins), function(next, plugin) {
if (_.isString(plugin)) {
var pluginModule = /[\/\.]/.test(plugin) // Contains at least one slash or dot?
? require(plugin)
: require(__dirname + '/plugins/' + plugin)
pluginModule.call(mm, mm, next);
} else if (_.isFunction(plugin)) {
plugin.call(mm, mm, next);
} else {
next('Unsupported plugin format');
}
})
.end(callback);
return mm;
};
/**
* Return an array of all distinct field values
* @param {string} field The field to return the values of
* @param {function} plugin The plugin to run. This gets the arguments (values)
* @return {monoxide.monoxideModel} The chainable monoxideModel
*/
mm.distinct = function(field, callback) {
o.internal.runCommand({
distinct: mm.$collection,
key: field,
}, function(err, res) {
if (err) return callback(err);
callback(null, res.values);
});
return mm;
};
/**
* Set a simple data key
* This is usually used to store suplemental information about models
* @param {Object|string} key The key to set or a full object of keys
* @param {*} value If `key` is a string the value is the value stored
* @return {monoxide.monoxideModel} The chainable monoxideModel
*/
mm.set = function(key, value) {
if (argy.isType(key, 'object')) {
_.assign(mm.$data, key);
} else if (argy.isType(key, 'string')) {
mm.$data[key] = value;
} else {
throw new Error('Unsupported type storage during set');
}
return mm;
};
/*
* Gets a simple data key or returns a fallback
* @param {string} key The data key to retrieve
* @param {*} [fallback] The fallback to return if the key is not present
*/
mm.get = function(key, fallback) {
return (argy.isType(mm.$data[key], 'undefined') ? fallback : mm.$data[key]);
};
/**
* Retrieve the list of actual on-the-database indexes
* @param {function} callback Callback to fire as (err, indexes)
* @return {monoxide.monoxideModel} The chainable monoxideModel
*/
mm.getIndexes = function(callback) {
mm.$mongoModel.indexes(function(err, res) {
if (err && err.message == 'no collection') {
callback(null, []); // Collection doesn't exist yet - ignore and return that it has no indexes
} else {
callback(err, res);
}
});
return mm;
};
/**
* Return the list of indexes requested by the schema
* @param {function} callback Callback to fire as (err, indexes)
* @return {monoxide.monoxideModel} The chainable monoxideModel
*/
mm.getSchemaIndexes = function(callback) {
mm.meta({$indexes: true}, function(err, res) {
if (err) return callback(err);
callback(null, _(res)
.map(function(v, k) {
return _.assign(v, {id: k});
})
.filter(function(v) {
return !!v.index;
})
.map(function(v) {
var o = {name: v.id == '_id' ? '_id_' : v.id, key: {}};
o.key[v.id] = 1;
return o;
})
.value()
);
});
return mm;
};
/**
* Check this model by a defined list of indexes
* The return is a duplicate of the input indexes with an additional `status` property which can equal to 'ok' or 'missing'
* @param {array} [wantIndexes] The indexes to examine against. If omitted the results of model.getSchemaIndexes() is used
* @param {array} [actualIndexes] The current state of the model to compare against. If omitted the results of model.getIndexes() is used
* @param {function} callback The callback to call as (err, indexes)
* @return {monoxide.monoxideModel} The chainable monoxideModel
*/
mm.checkIndexes = argy('[array] [array] function', function(wantIndexes, actualIndexes, callback) {
async()
// Either use provided indexes or determine them {{{
.parallel({
wantIndexes: function(next) {
if (wantIndexes) return next(null, wantIndexes);
mm.getSchemaIndexes(next);
},
actualIndexes: function(next) {
if (actualIndexes) return next(null, actualIndexes);
mm.getIndexes(next);
},
})
// }}}
// Compare indexes against whats declared {{{
.map('indexReport', 'wantIndexes', function(next, index) {
var foundIndex = this.actualIndexes.find(i => _.isEqual(i.key, index.key));
if (foundIndex) {
index.status = 'ok';
} else {
index.status = 'missing';
}
next(null, index);
})
// }}}
// End {{{
.end(function(err) {
if (err) return callback(err);
callback(null, this.indexReport);
});
// }}}
});
return mm;
});
util.inherits(o.monoxideModel, events.EventEmitter);
// }}}
// .monoxideDocument([setup]) - monoxide document instance {{{
/**
* Returns a single instance of a Monoxide document
* @class
* @name monoxide.monoxideDocument
* @param {Object} setup The prototype fields. Everything in this object is extended into the prototype
* @param {boolean} [setup.$applySchema=true] Whether to enforce the model schema on the object. This includes applying default values
* @param {boolean} [setup.$dirty=false] Whether the entire document contents should be marked as dirty (modified). If true this also skips the computation of modified fields
* @param {boolean [setup.decorate=true] Whether to apply any decoration. If false this function returns data undecorated (i.e. no custom Monoxide functionality)
* @param {string} setup.$collection The collection this document belongs to
* @param {Object} data The initial data
* @return {monoxide.monoxideDocument}
*/
o.monoxideDocument = function monoxideDocument(setup, data) {
if (setup.$decorate === false) return data;
setup.$dirty = !!setup.$dirty;
var model = o.models[setup.$collection];
var proto = {
$MONOXIDE: true,
$collection: setup.$collection,
$populated: {},
/**
* Save a document
* By default this function will only save back modfified data
* If `data` is specified this is used as well as the modified fields (unless `data.$ignoreModified` is falsy, in which case modified fields are ignored)
* @param {Object} [data] An optional data patch to save
* @param {boolean} [data.$ignoreModified=false] Ignore all modified fields and only process save data being passed in the `data` object (use this to directly address what should be saved, ignoring everything else). Setting this drastically speeds up the save operation but at the cost of having to be specific as to what to save
* @param {function} [callback] The callback to invoke on saving
*/
save: argy('[object] [function]', function(data, callback) {
var doc = this;
var mongoDoc = doc.toMongoObject();
var patch = {
$collection: doc.$collection,
$id: doc._id,
$errNoUpdate: true, // Throw an error if we fail to update (i.e. record removed before save)
$returnUpdated: true,
};
if (data && data.$ignoreModified) { // Only save incomming data
delete data.$ignoreModified;
_.assign(patch, data);
} else if (data) { // Data is specified as an object but $ignoreModified is not set - use both inputs
doc.isModified().forEach(function(path) {
patch[path] = _.get(mongoDoc, path);
});
_.assign(patch, data);
} else {
doc.isModified().forEach(function(path) {
patch[path] = _.get(mongoDoc, path);
});
}
o.internal.save(patch, function(err, newRec) {
doc = newRec;
if (_.isFunction(callback)) callback(err, newRec);
});
return doc;
}),
/**
* Remove the document from the collection
* This method is really just a thin wrapper around monoxide.delete()
* @param {function} [callback] Optional callback to invoke on completion
* @see monoxide.delete
*/
remove: function(callback) {
var doc = this;
o.internal.delete({
$collection: doc.$collection,
$id: doc._id,
}, callback);
return doc;
},
/**
* Remove certain fields from the document object
* This method is really just a thin wrapper around monoxide.delete()
* @param {string|regexp|array} fields Either a single field name, regular expression or array of strings/regexps to filter by. Any key matching will be removed from the object
* @return {monoxide.monoxideDocument} This object after the fields have been removed
*/
omit: function(fields) {
var removeFields = _.castArray(fields);
traverse(this).forEach(function(v) {
if (!this.key) return; // Skip array entries
var key = this.key;
if (removeFields.some(function(filter) {
return (
(_.isString(filter) && key == filter) ||
(_.isRegExp(filter) && filter.test(key))
);
})) {
this.remove();
}
});
return this;
},
/**
* Transform a MonoxideDocument into a plain JavaScript object
* @return {Object} Plain JavaScript object with all special properties and other gunk removed
*/
toObject: function() {
var doc = this;
var newDoc = {};
_.forEach(this, function(v, k) {
if (doc.hasOwnProperty(k) && !_.startsWith(k, '$')) newDoc[k] = _.clone(v);
});
return newDoc;
},
/**
* Transform a MonoxideDocument into a Mongo object
* This function transforms all OID strings back into their Mongo equivalent
* @return {Object} Plain JavaScript object with all special properties and other gunk removed
*/
toMongoObject: function() {
var doc = this;
var outDoc = doc.toObject(); // Rely on the toObject() syntax to strip out rubbish
doc.getOIDs().forEach(function(node) {
switch (node.fkType) {
case 'objectId':
var oidLeaf = _.get(doc, node.docPath);
if (_.isUndefined(oidLeaf)) return; // Ignore undefined
if (!o.utilities.isObjectID(oidLeaf)) {
if (_.has(oidLeaf, '_id')) { // Already populated?
_.set(outDoc, node.docPath, o.utilities.objectID(oidLeaf._id));
} else { // Convert to an OID
_.set(outDoc, node.docPath, o.utilities.objectID(oidLeaf));
}
}
break;
case 'objectIdArray':
var oidLeaf = _.get(doc, node.schemaPath);
_.set(outDoc, node.schemaPath, oidLeaf.map(function(leaf) {
return o.utilities.isObjectID(leaf) ? leaf : o.utilities.objectID(leaf);
}));
break;
default:
return; // Ignore unsupported OID types
}
});
return outDoc;
},
isModified: function(path) {
var doc = this;
if (path) {
var v = _.get(doc, path);
var pathJoined = _.isArray(path) ? path.join('.') : path;
if (o.utilities.isObjectID(v)) {
if (doc.$populated[pathJoined]) { // Has been populated
// FIXME; What happens if a populated document changes
throw new Error('Changing populated document objects is not yet supported');
return false;
} else { // Has not been populated
if (doc.$originalValues[pathJoined]) { // Compare against the string value
return doc.$originalValues[pathJoined] != v.toString();
} else if (doc.$originalValues[pathJoined + '.id'] && doc.$originalValues[pathJoined + '._bsontype']) { // Known but its stored as a Mongo OID - look into its values to determine its real comparitor string
// When the lookup is a raw OID we need to pass the binary junk into the objectID THEN get its string value before we can compare it to the one we last saw when we fetched the object
return o.utilities.objectID(doc.$originalValues[pathJoined + '.id']).toString() != v.toString(); // Compare against the string value
} else {
return true; // Otherwise declare it modified
}
}
} else if (_.isObject(v)) { // If its an object (or an array) examine the $clean propertly
return !v.$clean;
} else {
return doc.$originalValues[pathJoined] != v;
}
} else {
var modified = [];
traverse(doc).map(function(v) { // NOTE - We're using traverse().map() here as traverse().forEach() actually mutates the array if we tell it not to recurse with this.remove(true) (needed to stop recursion into complex objects if the parent has been changed)
if (!this.path.length) return; // Root node
if (_.startsWith(this.key, '$') || this.key == '_id') { // Don't scan down hidden elements
return this.remove(true);
} else if (o.utilities.isObjectID(v)) { // Leaf is an object ID
if (doc.isModified(this.path)) modified.push(this.path.join('.'));
this.remove(true); // Don't scan any deeper
} else if (doc.isModified(this.path)) {
if (_.isObject(v)) this.remove(true);
modified.push(this.path.join('.'));
}
});
return modified;
}
},
/**
* Expand given paths into objects
* @param {Object|array|string} populations A single or multiple populations to perform
* @param {function} callback The callback to run on completion
* @param {boolean} [strict=false] Whether to raise errors and agressively retry if a population fails
* @return {Object} This document
*/
populate: function(populations, callback, strict) {
var doc = this;
var populations = _(populations)
.castArray()
.map(function(population) { // Mangle all populations into objects (each object should contain a path and an optional ref)
if (_.isString(population)) {
return {path: population};
} else {
return population;
}
})
.value();
var tryPopulate = function(finish, populations, strict) {
var willPopulate = 0; // Count of items that seem valid that we will try to populate
var failedPopulations = []; // Populations that we couldn't get the end-points of (probably because they are nested)
var populator = async(); // Defered async worker that will actually populate things
async()
.forEach(populations, function(nextPopulation, population) {
try {
doc.getNodesBySchemaPath(population.path, true).forEach(function(node) {
if (!population.ref) {
population.ref = _.get(model, '$mongooseModel.schema.paths.' + node.schemaPath.split('.').join('.schema.paths.') + '.options.ref');
if (!population.ref) throw new Error('Cannot determine collection to use for schemaPath ' + node.schemaPath + '! Specify this is in model with {ref: <collection>}');
}
if (_.isObject(node.node) && node.node._id) { // Object is already populated
willPopulate++; // Say we're going to resolve this anyway even though we have nothing to do - prevents an issue where the error catcher reports it as a null operation (willPopulate==0)
} else if (!node.node) {
// Node is falsy - nothing to populate here
} else {
populator.defer(function(next) {
o.internal.query({
$errNotFound: false,
$collection: population.ref,
$id: o.utilities.isObjectID(node.node) ? node.node.toString() : node.node,
}, function(err, res) {
if (err) return next(err);
_.set(doc, node.docPath, res);
doc.$populated[node.docPath] = true;
next();
});
});
willPopulate++;
}
});
nextPopulation();
} catch (e) {
if (strict) failedPopulations.push(population);
nextPopulation();
}
})
.then(function(next) {
if (willPopulate > 0) {
populator.await().end(next); // Run all population defers
} else if (strict) {
next('Unable to resolve remaining populations: ' + JSON.stringify(populations) + '. In ' + doc.$collection + '#' + doc._id);
} else {
next();
}
})
.end(function(err) {
if (err) {
callback(err);
} else if (failedPopulations.length) {
console.log('SILL MORE POPULATIONS TO RUN', failedPopulations);
setTimeout(function() {
console.log('FIXME: Defered runnable');
//tryPopulate(callback, failedPopulations);
});
} else {
callback(null, doc);
}
});
};
tryPopulate(callback, populations, strict);
return doc;
},
/**
* Retrieves all 'leaf' elements matching a schema path
* Since any segment of the path could be a nested object, array or sub-document collection this function is likely to return multiple elements
* For the nearest approximation of how this function operates think of it like performing the jQuery expression: `$('p').each(function() { ... })`
* @param {string} schemaPath The schema path to iterate down
* @param {boolean} [strict=false] Optional indicator that an error should be thrown if a path cannot be traversed
* @return {array} Array of all found leaf nodes
*/
getNodesBySchemaPath: function(schemaPath, strict) {
var doc = this;
var examineStack = [{
node: doc,
docPath: '',
schemaPath: '',
}];
var segments = schemaPath.split('.');
segments.every(function(pathSegment, pathSegmentIndex) {
return examineStack.every(function(esDoc, esDocIndex) {
if (esDoc === false) { // Skip this subdoc
return true;
} else if (_.isUndefined(esDoc.node[pathSegment]) && pathSegmentIndex == segments.length -1) {
examineStack[esDocIndex] = {
node: esDoc.node[pathSegment],
docPath: esDoc.docPath + '.' + pathSegment,
schemaPath: esDoc.schemaPath + '.' + pathSegment,
};
return true;
} else if (_.isUndefined(esDoc.node[pathSegment])) {
// If we are trying to recurse into a path segment AND we are not at the leaf of the path (as undefined leaves are ok) - raise an error
if (strict) throw new Error('Cannot traverse into path: "' + (esDoc.docPath + '.' + pathSegment).substr(1) + '" for doc ' + doc.$collection + '#' + doc._id);
examineStack[esDocIndex] = false;
return false;
} else if (_.isArray(esDoc.node[pathSegment])) { // Found an array - remove this doc and append each document we need to examine at the next stage
esDoc.node[pathSegment].forEach(function(d,i) {
// Do this in a forEach to break appart the weird DocumentArray structure we get back from Mongoose
examineStack.push({
node: d,
docPath: esDoc.docPath + '.' + pathSegment + '.' + i,
schemaPath: esDoc.schemaPath + '.' + pathSegment,
})
});
examineStack[esDocIndex] = false;
return true;
} else if (_.has(esDoc.node, pathSegment)) { // Traverse into object - replace this nodeerence with the new pointer
examineStack[esDocIndex] = {
node: esDoc.node[pathSegment],
docPath: esDoc.docPath + '.' + pathSegment,
schemaPath: esDoc.schemaPath + '.' + pathSegment,
};
return true;
}
});
});
return _(examineStack)
.filter()
.filter(function(node) {
return !! node.docPath;
})
.map(function(node) {
node.docPath = node.docPath.substr(1);
node.schemaPath = node.schemaPath.substr(1);
return node;
})
.value();
},
/**
* Return an array of all OID leaf nodes within the document
* This function combines the behaviour of monoxide.utilities.extractFKs with monoxide.monoxideDocument.getNodesBySchemaPath)
* @return {array} An array of all leaf nodes
*/
getOIDs: function() {
var doc = this;
var stack = [];
_.forEach(model.$oids, function(fkType, schemaPath) {
if (fkType.type == 'subDocument') return; // Skip sub-documents (as they are stored against the parent anyway)
stack = stack.concat(doc.getNodesBySchemaPath(schemaPath)
.map(function(node) {
node.fkType = fkType.type;
return node;
})
);
});
return stack;
},
$applySchema: true,
};
proto.delete = proto.remove;
_.extend(
proto, // INPUT: Basic prototype
setup, // Merge with the incomming prototype (should contain at least $collection)
model.$methods // Merge with model methods
);
// Create the base document
var doc = Object.create(proto);
// Setup Virtuals
Object.defineProperties(doc, model.$virtuals);
// Convert data to a simple array if its weird Mongoose fluff
if (data instanceof mongoose.Document) data = data.toObject();
_.extend(doc, data);
// Apply schema
if (doc.$applySchema) {
_.forEach(model.$mongooseModel.schema.paths, function(pathSpec, path) {
var docValue = _.get(doc, path, undefined);
if (_.isUndefined(docValue)) {
if (pathSpec.defaultValue) { // Item is blank but SHOULD have a default
_.set(doc, path, _.isFunction(pathSpec.defaultValue) ? pathSpec.defaultValue() : pathSpec.defaultValue);
} else {
_.set(doc, path, undefined);
}
}
});
}
// Sanitize data to remove all ObjectID crap
doc.getOIDs().forEach(function(node) {
if (node.fkType == 'objectId') {
var singleOid = _.get(doc, node.docPath);
if (o.utilities.isObjectID(singleOid))
_.set(doc, node.docPath, singleOid.toString());
} else if (node.fkType == 'objectIdArray') {
var oidArray = _.get(doc, node.docPath);
if (o.utilities.isObjectID(oidArray)) {
_.set(doc, node.docPath, oidArray.toString());
} else if (_.isObject(oidArray) && oidArray._id && o.utilities.isObjectID(oidArray._id)) {
// FIXME: Rather crappy sub-document flattening for now
// This needs to actually scope into the sub-object schema and flatten each ID and not just the _id element
oidArray._id = oidArray._id.toString();
}
}
});
// Break object into component parts and apply the '$clean' marker to arrays and objects
Object.defineProperty(doc, '$originalValues', {
enumerable: false,
value: {},
});
if (!setup.$dirty) {
traverse(doc).forEach(function(v) {
// If its an object (or array) glue the `$clean` property to it to detect writes
if (_.isObject(v)) {
Object.defineProperty(v, '$clean', {
enumerable: false,
value: true,
});
} else if (!_.isPlainObject(v)) { // For everything else - stash the original value in this.parent.$originalValues
doc.$originalValues[this.path.join('.')] = o.utilities.isObjectID(v) ? v.toString() : v;
}
});
}
// Apply population data
doc.getOIDs().forEach(function(node) {
doc.$populated[node.docPath] = o.utilities.isObjectID(node.docPath);
if (!setup.$dirty) doc.$originalValues[node.docPath] = _.get(doc, node.docPath);
});
return doc;
};
// }}}
// .model(name) - helper function to return a declared model {{{
/**
* Return a defined Monoxide model
* The model must have been previously defined by monoxide.schema()
* This function is identical to accessing the model directly via `monoxide.models[modelName]`
*
* @name monoxide.model
* @see monoxide.schema
*
* @param {string} model The model name (generally lowercase plurals e.g. 'users', 'widgets', 'favouriteItems' etc.)
* @returns {Object} The monoxide model of the generated schema
*/
o.model = function(model) {
return o.models[model];
};
// }}}
// .schema - Schema builder {{{
/**
* Construct and return a Mongo model
* This function creates a valid schema specificaion then returns it as if model() were called
*
* @name monoxide.schema
* @see monoxide.model
*
* @param {string} model The model name (generally lowercase plurals e.g. 'users', 'widgets', 'favouriteItems' etc.)
* @param {Object} spec The schema specification composed of a hierarhical object of keys with each value being the specification of that field
* @returns {Object} The monoxide model of the generated schema
* @emits modelCreate Called as (model, instance) when a model gets created
*
* @example
* // Example schema for a widget
* var Widgets = monoxide.schema('widgets', {
* name: String,
* content: String,
* status: {type: String, enum: ['active', 'deleted'], default: 'active'},
* color: {type: String, enum: ['red', 'green', 'blue'], default: 'blue', index: true},
* });
*
* @example
* // Example schema for a user
* var Users = monoxide.schema('users', {
* name: String,
* role: {type: 'string', enum: ['user', 'admin'], default: 'user'},
* favourite: {type: 'pointer', ref: 'widgets'},
* items: [{type: 'pointer', ref: 'widgets'}],
* settings: {type: 'any'},
* mostPurchased: [
* {
* number: {type: 'number', default: 0},
* item: {type: 'pointer', ref: 'widgets'},
* }
* ],
* });
*/
o.schema = function(model, spec) {
if (!argy.isType(model, 'string') || !argy.isType(spec, 'object')) throw new Error('Schema construction requires a model ID + schema object');
var schema = new mongoose.Schema(_.deepMapValues(spec, function(value, path) {
// Rewrite .type leafs {{{
if (_.endsWith(path, '.type')) { // Ignore not type rewrites
if (!_.isString(value)) return value; // Only rewrite string values
switch (value.toLowerCase()) {
case 'oid':
case 'pointer':
case 'objectid':
return mongoose.Schema.ObjectId;
case 'string':
return mongoose.Schema.Types.String;
case 'number':
return mongoose.Schema.Types.Number;
case 'boolean':
case 'bool':
return mongoose.Schema.Types.Boolean;
case 'array':
return mongoose.Schema.Types.Array;
case 'date':
return mongoose.Schema.Types.Date;
case 'object':
case 'mixed':
case 'any':
return mongoose.Schema.Types.Mixed;
case 'buffer':
return mongoose.Schema.Types.Buffer;
default:
throw new Error('Unknown Monoxide data type: ' + value.toLowerCase());
}
// }}}
// Rewrite .ref leafs {{{
} else if (_.endsWith(path, '.ref')) {
if (!_.isString(value)) return value; // Leave complex objects alone
return value.toLowerCase();
// }}}
// Leave everything else unaltered {{{
} else { // Do nothing
return value;
}
// }}}
}));
// Add to model storage
o.models[model] = new o.monoxideModel({
$collection: model,
$mongoose: mongoose.model(model.toLowerCase(), schema), // FIXME: When we implement our own schema def system we can remove the toLowerCase() component that Mongoose insists on using. We can also remove all of the other toLowerCase() calls when we're trying to find the Mongoose schema
$schema: schema.obj,
});
o.emit('modelCreate', model, o.models[model]);
return o.models[model];
};
// }}}
// .aggregate([q], callback) {{{
/**
* Perform a direct aggregation and return the result
*
* @name monoxide.aggregate
* @memberof monoxide
*
* @param {Object} q The object to process
* @param {string} q.$collection The collection / model to query
* @param {boolean} [q.$slurp=true] Attempt to read all results into an array rather than return a cursor
* @param {array} q.$stages The aggregation stages array
* @param {Object} [q.$stages.$project] Fields to be supplied in the aggregation (in the form `{field: true}`)
* @param {boolean} [q.$stages.$project._id=false] If true surpress the output of the `_id` field
* @param {Object} [q.$stages.$match] Specify a filter on fields (in the form `{field: CRITERIA}`)
* @param {Object} [q.$stages.$redract]
* @param {Object} [q.$stages.$limit]
* @param {Object} [q.$stages.$skip]
* @param {Object} [q.$stages.$unwind]
* @param {Object} [q.$stages.$group]
* @param {Object} [q.$stages.$sample]
* @param {Object} [q.$stages.$sort] Specify an object of fields to sort by (in the form `{field: 1|-1}` where 1 is ascending and -1 is decending sort order)
* @param {Object} [q.$stages.$geoNear]
* @param {Object} [q.$stages.$lookup]
* @param {Object} [q.$stages.$out]
* @param {Object} [q.$stages.$indexStats]
*
* @param {function} callback(err, result) the callback to call on completion or error
*
* @return {Object} This chainable object
*/
o.aggregate = argy('string|object function', function MonoxideAggregate(q, callback) {
if (argy.isType(q, 'string')) q = {$collection: q};
async()
// Sanity checks {{{
.then(function(next) {
if (!q || _.isEmpty(q)) return next('No query given for save operation');
if (!q.$stages || !_.isArray(q.$stages)) return next('$stages must be specified as an array');
if (!q.$collection) return next('$collection must be specified for save operation');
if (!o.models[q.$collection]) return next('Model not initalized');
next();
})
// }}}
// Execute and capture return {{{
.then('result', function(next) {
o.models[q.$collection].$mongoModel.aggregate(q.$stages, next);
})
// }}}
// Slurp the cursor? {{{
.then('result', function(next) {
if (q.$slurp || _.isUndefined(q.$slurp)) {
o.utilities.slurpCursor(this.result, next);
} else {
next(null, this.result);
}
})
// }}}
// End {{{
.end(function(err) {
if (err) {
return callback(err);
} else {
callback(null, this.result);
}
});
// }}}
return o;
});
// }}}
// .use([plugins...], [callback]) {{{
/**
* Run a third party plugin against the entire Monoxide structure
* Really this function just registers all given modules against monoxide then fires the callback when done
* Each plugin is called as `(callback, monoxide)`
* @param {function|string|array} plugins The plugin(s) to run. Each function is run as (model, callback), strings are assumed to be file paths to JS files if they contain at least one '/' or `.` otherwise they are loaded from the `plugins` directory
* @param {function} [callback] Optional callback to fire when all plugin have registered
* @return {monoxide.monoxide} The chainable object
*/
o.use = function(plugins, callback) {
if (!plugins) return callback(); // Do nothing if given falsy
async()
.forEach(_.castArray(plugins), function(next, plugin) {
if (o.used.some(i => i === plugin)) {
debug('Plugin already loaded, ignoring');
next();
} else if (_.isString(plugin)) {
var pluginModule = /[\/\.]/.test(plugin) // Contains at least one slash or dot?
? require(plugin)
: require(__dirname + '/plugins/' + plugin)
pluginModule.call(o, next, o);
o.used.push(pluginModule);
} else if (_.isFunction(plugin)) {
plugin.call(o, next, o);
o.used.push(plugin);
} else {
next('Unsupported plugin format');
}
})
.end(callback);
return o;
};
/**
* Storage for modules we have already loaded
* @var {Array <function>} All plugins (as funtions) we have previously loaded
*/
o.used = [];
// }}}
// .hook(hookName, callback) {{{
/**
* Holder for global hooks
* @var {array <function>}
*/
o.$hooks = {};
/**
* Attach a hook to a global event
* A hook is exactly the same as a eventEmitter.on() event but must return a callback
* Multiple hooks can be attached and all will be called in parallel on certain events such as 'save'
* All hooks must return non-errors to proceed with the operation
* @param {string} eventName The event ID to hook against
* @param {function} callback The callback to run when hooked, NOTE: Any falsy callbacks are ignored
* @return {monoxide} The chainable monoxide
*/
o.hook = function(eventName, callback) {
if (!callback) return mm; // Ignore flasy callbacks
if (!o.$hooks[eventName]) o.$hooks[eventName] = [];
o.$hooks[eventName].push(callback);
return o;
};
/**
* Execute global level hooks
* NOTE: This will only fire hooks attached via monoxide.hook() and not individual model hooks
* NOTE: Hooks are always fired with the callback as the first argument
* @param {string} name The name of the hook to invoke
* @param {function} callback The callback to invoke on success
* @param {...*} parameters Any other parameters to be passed to each hook
* @return {monoxide} The chainable monoxide
*/
o.fire = function(name, callback) {
if (o.$hooks[name] && o.$hooks[name].length) { // There is at least one event handler attached
var eventArgs = _.values(arguments);
eventArgs.splice(1, 1); // Remove the 'callback' arg as events cant respond to it anyway
o.emit.apply(o, eventArgs);
} else {
return callback();
}
// Calculate the args array we will pass to each hook
var hookArgs = _.values(arguments);
hookArgs.shift(); // We will set args[0] to the callback in each case anyway so we only need to shift 1
async()
// Fire hooks attached to this model + global hooks {{{
.forEach(
o.$hooks[name]
.filter(f => !!f) // Actually is a function?
, function(next, hookFunc) {
hookArgs[0] = next;
hookFunc.apply(o, hookArgs);
})
// }}}
.end(callback);
return o;
};
/**
* Similar to fire() expect that execution is immediate
* This should only be used by sync functions that require immediate action such as object mutators
* NOTE: Because of the nature of this function a callback CANNOT be accepted when finished - the function is assumed done when it returns
* @param {string} name The name of the hook to invoke
* @param {...*} parameters Any other parameters to be passed to each hook
* @return {monoxide} The chainable monoxide
* @see fire()
*/
o.fireImmediate = function(name, callback) {
if (!o.$hooks[name] || !o.$hooks[name].length) return o; // No hooks to run anyway
for (var i of o.$hooks[name]) {
let hookArgs = _.values(arguments);
hookArgs.shift();
i.apply(o, hookArgs);
}
return o;
};
// }}}
// .utilities structure {{{
o.utilities = {};
// .utilities.extractFKs(schema, prefix, base) {{{
/**
* Extract all FKs in dotted path notation from a Mongoose model
*
* @name monoxide.utilities.extractFKs
*
* @param {Object} schema The schema object to examine (usually monoxide.models[model].$mongooseModel.schema)
* @param {string} prefix existing Path prefix to use (internal use only)
* @param {Object} base Base object to append flat paths to (internal use only)
* @return {Object} A dictionary of foreign keys for the schema (each key will be the info of the object)
*/
o.utilities.extractFKs = function(schema, prefix, base) {
var FKs = {};
if (!prefix) prefix = '';
if (!base) base = FKs;
_.forEach(schema.paths, function(path, id) {
if (id == 'id' || id == '_id') { // Main document ID
FKs[prefix + id] = {type: 'objectId'};
} else if (path.instance && path.instance == 'ObjectID') {
FKs[prefix + id] = {type: 'objectId'};
} else if (path.caster && path.caster.instance == 'ObjectID') { // Array of ObjectIDs
FKs[prefix + id] = {type: 'objectIdArray'};
} else if (path.schema) {
FKs[prefix + id] = {type: 'subDocument'};
_.forEach(o.utilities.extractFKs(path.schema, prefix + id + '.', base), function(val, key) {
base[key] = val;
});
}
});
return FKs;
}
// }}}
// .utilities.objectID(string) {{{
/**
* Construct and return a MongoDB-Core compatible ObjectID object
* This is mainly used within functions that need to convert a string ID into an object
* This has one additional check which will return undefined if the value passed in is falsy
* @name monoxide.utilities.objectID
* @param {string} str The string to convert into an ObjectID
* @return {Object} A MongoDB-Core compatible ObjectID object instance
*/
o.utilities.objectID = function(str) {
if (!str) return undefined;
if (_.isObject(str) && str._id) return new mongoose.Types.ObjectId(str._id); // Is a sub-document - extract its _id and use that
return new mongoose.Types.ObjectId(str);
};
// }}}
// .utilities.isObjectID(string) {{{
/**
* Return if the input is a valid MongoDB-Core compatible ObjectID object
* This is mainly used within functions that need to check that a given variable is a Mongo OID
* @name monoxide.utilities.isObjectID
* @param {mixed} subject The item to examine
* @return {boolean} Whether the subject is a MongoDB-Core compatible ObjectID object instance
*/
o.utilities.isObjectID = function(subject) {
return (subject instanceof mongoose.Types.ObjectId);
};
/**
* Alias of isObjectID
* @see monoxide.utilities.isObjectId
*/
o.utilities.isObjectId = o.utilities.isObjectID;
// }}}
// .utilities.runMiddleware(middleware) {{{
/**
* Run optional middleware
*
* Middleware can be:
* - A function(req, res, next)
* - An array of functions(req, res, next) - Functions will be called in sequence, all functions must call the next method
* - A string - If specified (and `obj` is also specified) the middleware to use will be looked up as a key of the object. This is useful if you need to invoke similar methods on different entry points (e.g. monoxide.express.middleware('widgets', {save: function(req, res, next) { // Check something // }, create: 'save'}) - where the `create` method invokes the same middleware as `save)
*
* @param {null|function|array} middleware The optional middleware to run this can be a function, an array of functions or a string
* @param {function} callback The callback to invoke when completed. This may not be called
* @param {object} obj The parent object to look up inherited functions from (if middleware is a string)
*
* @example
* // Set up a Monoxide express middleware to check user logins on each save or create operaion
* app.use('/api/widgets/:id?', monoxide.express.middleware('widgets', {
* create: function(req, res, next) {
* if (req.user && req.user._id) {
* next();
* } else {
* res.status(403).send('You are not logged in').end();
* }
* },
* save: 'create', // Point to the same checks as the `create` middleware
* }));
*/
o.utilities.runMiddleware = function(req, res, middleware, callback, obj) {
var thisContext = this;
var runnable; // The middleware ARRAY to run
if (_.isBoolean(middleware) && !middleware) { // Boolean=false - deny!
res.status(403).end();
} else if (_.isUndefined(middleware) || _.isNull(middleware)) { // Nothing to do anyway
return callback();
} else if (_.isFunction(middleware)) {
runnable = [middleware];
} else if (_.isArray(middleware)) {
runnable = middleware;
} else if (_.isString(middleware) && _.has(obj, middleware)) {
return o.utilities.runMiddleware(req, res, _.get(obj, middleware), callback, obj); // Defer to the pointer
}
async()
.limit(1)
.forEach(runnable, function(nextMiddleware, middlewareFunc, index) {
middlewareFunc.apply(thisContext, [req, res, nextMiddleware]);
})
.end(function(err) {
if (err) {
o.express.sendError(res, 403, err);
} else {
callback();
}
});
};
// }}}
// .utilities.diff(originalDoc, newDoc) {{{
/**
* Diff two monoxide.monoxideDocument objects and return the changes as an object
* This change object is suitable for passing directly into monoxide.save()
* While originally intended only for comparing monoxide.monoxideDocument objects this function can be used to compare any type of object
* NOTE: If you are comparing MonoxideDocuments call `.toObject()` before passing the object in to strip it of its noise
*
* @name monoxide.utilities.diff
* @see monoxide.save
* @see monoxide.update
*
* @param {Object} originalDoc The original source document to compare to
* @param {Object} newDoc The new document with possible changes
* @return {Object} The patch object
*
* @example
* // Get the patch of two documents
* monoxide.query({$collection: 'widgets', $id: '123'}, function(err, res) {
* var docA = res.toObject();
* var docB = res.toObject();
*
* // Change some fields
* docB.title = 'Hello world';
*
* var patch = monoxide.utilities.diff(docA, docB);
* // => should only return {title: 'Hello World'}
* });
*/
o.utilities.diff = function(originalDoc, newDoc) {
var patch = {};
deepDiff.observableDiff(originalDoc, newDoc, function(diff) {
if (diff.kind == 'N' || diff.kind == 'E') {
_.set(patch, diff.path, diff.rhs);
} else if (diff.kind == 'A') { // Array alterations
// deepDiff will only apply changes onto newDoc - we can't just apply them to the empty patch object
// so we let deepDiff do its thing then copy the new structure across into patch
deepDiff.applyChange(originalDoc, newDoc, diff);
_.set(patch, diff.path, _.get(newDoc, diff.path));
}
});
return patch;
};
// }}}
// .utilities.rewriteQuery(query, settings) {{{
/**
* Returns a rewritten version of an incomming query that obeys various rules
* This usually accepts req.query as a parameter and a complex settings object as a secondary
* This function is used internally by middleware functions to clean up the incomming query
*
* @name monoxide.utilities.rewriteQuery
* @see monoxide.middleware
*
* @param {Object} query The user-provided query object
* @param {Object} settings The settings object to apply (see middleware functions)
* @return {Object} The rewritten query object
*/
o.utilities.rewriteQuery = function(query, settings) {
return _(query)
.mapKeys(function(val, key) {
if (_.has(settings.queryRemaps, key)) return settings.queryRemaps[key];
return key;
})
.mapValues(function(val, key) {
if (settings.queryAllowed && settings.queryAllowed[key]) {
var allowed = settings.queryAllowed[key];
if (!_.isString(val) && !allowed.scalar) {
return null;
} else if (allowed.boolean) {
return (val == 'true' || val == '1');
} else if (_.isString(val) && allowed.scalarCSV) {
return val.split(/\s*,\s*/);
} else if (_.isArray(val) && allowed.array) {
return val;
} else if (_.isString(val) && allowed.number) {
return parseInt(val);
} else {
return val;
}
}
return val;
})
.value();
};
// }}}
// .utilities.slurpCursor(cursor, cb) {{{
/**
* Asyncronously calls a cursor until it is exhausted
*
* @name monoxide.utilities.slurpCursor
*
* @param {Cursor} cursor A mongo compatible cursor object
* @param {function} cb The callback to call as (err, result) when complete
*/
o.utilities.slurpCursor = function(cursor, cb) {
var res = [];
var cursorReady = function(err, result) {
if (result === null) { // Cursor is exhausted
cb(null, res);
} else {
res.push(result);
setTimeout(function() { // Queue fetcher in timeout so we don't stack overflow
cursor.next(cursorReady);
});
}
};
cursor.next(cursorReady);
};
// }}}
// }}}
// Create internals mapping {{{
o.internal = o; // Mapping for the original function handlers (e.g. get() before any mutations)
// }}}
return o;
}
util.inherits(Monoxide, events.EventEmitter);
module.exports = new Monoxide();
| index.js | var _ = require('lodash')
.mixin(require('lodash-deep'));
var argy = require('argy');
var async = require('async-chainable');
var debug = require('debug')('monoxide');
var deepDiff = require('deep-diff');
var events = require('events');
var mongoose = require('mongoose');
var traverse = require('traverse');
var util = require('util');
/**
* @static monoxide
*/
function Monoxide() {
var o = this;
o.mongoose = mongoose;
o.models = {};
o.connection;
o.settings = {
removeAll: true, // Allow db.model.delete() calls with no arguments
versionIncErr: /^MongoError: Cannot apply \$inc to a value of non-numeric type. {.+} has the field '__v' of non-numeric type null$/i, // RegExp error detector used to detect $inc problems when trying to increment `__v` in update operations
};
// .connect {{{
/**
* Connect to a Mongo database
* @param {string} uri The URL of the database to connect to
* @param {function} [callback] Optional callback when connected, if omitted this function is syncronous
* @return {monoxide} The Monoxide chainable object
*/
o.connect = function(uri, callback) {
mongoose.set('useFindAndModify', false);
mongoose.set('useCreateIndex', true);
mongoose.connect(uri, {
promiseLibrary: global.Promise,
useNewUrlParser: true,
})
.then(function() {
o.connection = mongoose.connection;
if (callback) callback();
})
.catch(e => callback(e))
return o;
};
// }}}
// .disconnect {{{
/**
* Disconnect from an active connection
* @return {monoxide} The Monoxide chainable object
*/
o.disconnect = function(callback) {
mongoose.disconnect(callback);
return o;
};
// }}}
// .get(q, [id], callback) {{{
/**
* Retrieve a single record from a model via its ID
* This function will ONLY retrieve via the ID field, all other fields are ignored
* NOTE: Really this function just wraps the monoxide.query() function to provide functionality like populate
*
* @name monoxide.get
* @memberof monoxide
*
* @param {Object} q The object to process
* @param {string} q.$collection The collection / model to query
* @param {string} [q.$id] The ID to return
* @param {(string|string[]|object[])} [q.$populate] Population criteria to apply
*
* @param {string} [id] The ID to return (alternative syntax)
*
* @param {function} callback(err, result) the callback to call on completion or error
*
* @return {Object} This chainable object
*
* @example
* // Return a single widget by its ID (string syntax)
* monoxide.get('widgets', '56e2421f475c1ef4135a1d58', function(err, res) {
* console.log('Widget:', res);
* });
*
* @example
* // Return a single widget by its ID (object syntax)
* monoxide.get({$collection: 'widgets', $id: '56e2421f475c1ef4135a1d58'}, function(err, res) {
* console.log('Widget:', res);
* });
*/
o.get = argy('[object|string|number] [string|number|object] function', function(q, id, callback) {
argy(arguments)
.ifForm('object function', function(aQ, aCallback) {
q = aQ;
callback = aCallback;
})
.ifForm('string string|number function', function(aCollection, aId, aCallback) {
q = {
$collection: aCollection,
$id: aId,
};
})
.ifForm('string object function', function(aCollection, aId, aCallback) { // Probably being passed a Mongoose objectId as the ID
q = {
$collection: aCollection,
$id: aId.toString(),
};
});
if (!q.$id) return callback('No $id specified');
return o.internal.query(q, callback);
});
// }}}
// .query([q], callback) {{{
/**
* Query Mongo directly with the Monoxide query syntax
*
* @name monoxide.query
* @fires query
*
* @param {Object} q The object to process
* @param {string} q.$collection The collection / model to query
* @param {string} [q.$id] If specified return only one record by its master ID (implies $one=true). If present all other conditionals will be ignored and only the object is returned (see $one)
* @param {(string|string[]|object[])} [q.$select] Field selection criteria to apply (implies q.$applySchema=false as we will be dealing with a partial schema). Any fields prefixed with '-' are removed
* @param {(string|string[]|object[])} [q.$sort] Sorting criteria to apply
* @param {(string|string[]|object[])} [q.$populate] Population criteria to apply
* @param {boolean} [q.$one=false] Whether a single object should be returned (implies $limit=1). If enabled an object is returned not an array
* @param {number} [q.$limit] Limit the return to this many rows
* @param {number} [q.$skip] Offset return by this number of rows
* @param {boolean=false} [q.$count=false] Only count the results - do not return them. If enabled a number of returned with the result
* @param {object|function} [q.$data] Set the user-defined data object, if this is a function the callback result is used
* @param {boolean} [q.$decorate=true] Add all Monoxide methods, functions and meta properties
* @param {string} [q.$want='array'] How to return data contents. ENUM: 'array', 'cursor'
* @param {boolean} [q.$plain=false] Return a plain object or object array. This is the equivelent of calling .toObject() on any resultant object. Implies $decorate=true
* @param {boolean} [q.$cacheFKs=true] Cache the foreign keys (objectIDs) within an object so future retrievals dont have to recalculate the model structure
* @param {boolean} [q.$applySchema=true] Apply the schema for each document retrieval - this slows retrieval but means any alterations to the schema are applied to each retrieved record
* @param {boolean} [q.$dirty=false] Whether the entire document contents should be marked as dirty (modified). If true this also skips the computation of modified fields
* @param {boolean} [q.$errNotFound] Raise an error if a specifically requested document is not found (requires $id)
* @param {...*} [q.filter] Any other field (not beginning with '$') is treated as filtering criteria
*
* @param {function} callback(err, result) the callback to call on completion or error. If $one is truthy this returns a single monoxide.monoxideDocument, if not it returns an array of them
*
* @return {Object} This chainable object
*
* @example
* // Return all Widgets, sorted by name
* monoxide.query({$collection: 'widgets', $sort: 'name'}, function(err, res) {
* console.log('Widgets:', res);
* });
* @example
* // Filter Users to only return admins while also populating their country
* monoxide.query({$collection: 'users', $populate: 'country', role: 'admin'}, function(err, res) {
* console.log('Admin users:', res);
* });
*/
o.query = argy('[string|object] function', function MonoxideQuery(q, callback) {
if (argy.isType(q, 'string')) q = {$collection: q};
_.defaults(q || {}, {
$cacheFKs: true, // Cache model Foreign Keys (used for populates) or compute them every time
$want: 'array',
$applySchema: true, // Apply the schema on retrieval - this slows ths record retrieval but means any alterations to the schema are applied to each retrieved record
$errNotFound: true, // During $id / $one operations raise an error if the record is not found
});
if (!_.isEmpty(q.$select)) q.$applySchema = false; // Turn off schema application when using $select as we wont be grabbing the full object
async()
.set('metaFields', [
'$collection', // Collection to query
'$data', // Meta user-defined data object
'$dirty', // Whether the document is unclean
'$id', // If specified return only one record by its master ID (implies $one=true). If present all other conditionals will be ignored and only the object is returned (see $one)
'$select', // Field selection criteria to apply
'$sort', // Sorting criteria to apply
'$populate', // Population criteria to apply
'$one', // Whether a single object should be returned (implies $limit=1). If enabled an object is returned not an array
'$limit', // Limit the return to this many rows
'$skip', // Offset return by this number of rows
'$count', // Only count the results - do not return them
'$want', // What result we are looking for from the query
'$cacheFKs', // Cache model Foreign Keys (used for populates) or compute them every time
'$applySchema', // Apply the schema on retrieval - this slows ths record retrieval but means any alterations to the schema are applied to each retrieved record
'$decorate',
'$plain',
'$errNotFound', // During $id / $one operations raise an error if the record is not found
])
// Sanity checks {{{
.then(function(next) {
if (!q || _.isEmpty(q)) return next('No query given for get operation');
if (!q.$collection) return next('$collection must be specified for get operation');
if (!o.models[q.$collection]) return next('Model not initalized: "' + q.$collection + '"');
next();
})
// }}}
// .query - start the find query {{{
.set('filterPostPopulate', {}) // Filter by these fields post populate
.then('query', function(next) {
var me = this;
var fields;
if (q.$id) { // Search by one ID only - ignore other fields
fields = {_id: q.$id};
q.$one = true;
} else { // Search by query
fields = _(q)
.omit(this.metaFields) // Remove all meta fields
// FIXME: Ensure all fields are flat
.omitBy(function(val, key) { // Remove all fields that will need populating later
if (_.some(q.$collection.$oids, function(FK) {
return _.startsWith(key, FK);
})) {
me.filterPostPopulate[key] = val;
return true;
} else {
return false;
}
})
.value();
}
//console.log('FIELDS', fields);
//console.log('POSTPOPFIELDS', o.filterPostPopulate);
if (q.$count) {
next(null, o.models[q.$collection].$mongooseModel.countDocuments(fields));
} else if (q.$one) {
next(null, o.models[q.$collection].$mongooseModel.findOne(fields));
} else {
next(null, o.models[q.$collection].$mongooseModel.find(fields));
}
})
// }}}
// Apply various simple criteria {{{
.then(function(next) {
if (q.$count) return next(); // No point doing anything else if just counting
if (q.$limit) this.query.limit(q.$limit);
if (q.$skip) this.query.skip(q.$skip);
// q.$populate {{{
if (q.$populate) {
if (_.isArray(q.$populate)) {
this.query.populate(q.$populate);
} else if (_.isString(q.$populate) || _.isObject(q.$populate)) {
this.query.populate(q.$populate);
q.$populate = [q.$populate]; // Also rewrite into an array so we can destructure later
} else {
throw new Error('Invalid sort type: ' + (typeof q.$sort));
}
}
// }}}
// q.$select {{{
if (q.$select) {
if (_.isArray(q.$select)) {
var query = this.query;
q.$select.forEach(function(s) {
query.select(s);
});
} else if (_.isString(q.$select) || _.isObject(q.$select)) {
this.query.select(q.$select);
} else {
throw new Error('Invalid select type: ' + (typeof q.$select));
}
}
// }}}
// q.$sort {{{
if (q.$sort) {
if (_.isArray(q.$sort)) {
var query = this.query;
q.$sort.forEach(function(s) {
query.sort(s);
});
} else if (_.isString(q.$sort) || _.isObject(q.$sort)) {
this.query.sort(q.$sort);
} else {
throw new Error('Invalid sort type: ' + (typeof q.$sort));
}
}
// }}}
next();
})
// }}}
// Calculate $data if it is a function {{{
.then('data', function(next) {
if (!q.$data) return next();
if (_.isFunction(q.$data)) {
q.$data(function(err, data) {
if (err) return next(err);
q.$data = data;
});
}
next();
})
// }}}
// Fire hooks {{{
.then(function(next) {
o.models[q.$collection].fire('query', next, q);
})
// }}}
// Execute and capture return {{{
.then('result', function(next) {
switch (q.$want) {
case 'array':
this.query.exec(function(err, res) {
if (err) return next(err);
if (q.$one) {
if (_.isEmpty(res)) {
if (q.$errNotFound) {
next('Not found');
} else {
next(null, undefined);
}
} else {
next(null, res);
}
} else if (q.$count) {
next(null, res);
} else {
next(null, res);
}
});
break;
case 'cursor':
next(null, this.query.cursor());
break;
default:
next('Unknown $want type');
}
})
// }}}
// Convert Mongoose Documents into Monoxide Documents {{{
.then('result', function(next) {
// Not wanting an array of data? - pass though the result
if (q.$want != 'array') return next(null, this.result);
if (this.result === undefined) {
next(null, undefined);
} else if (q.$one) {
if (q.$decorate) return next(null, this.result.toObject());
next(null, new o.monoxideDocument({
$collection: q.$collection,
$applySchema: q.$applySchema,
$decorate: q.$decorate,
$dirty: q.$dirty,
}, this.result));
} else if (q.$count) {
next(null, this.result);
} else {
next(null, this.result.map(function(doc) {
if (q.$decorate) return doc.toObject();
return new o.monoxideDocument({
$collection: q.$collection,
$applySchema: q.$applySchema,
$decorate: q.$decorate,
$dirty: q.$dirty,
}, doc.toObject());
}));
}
})
// }}}
// Apply populates {{{
.then(function(next) {
// Not wanting an array of data? - pass though the result
if (q.$want != 'array') return next(null, this.result);
if (!q.$populate || !q.$populate.length || q.$count || q.$decorate === false || q.$plain === false || this.result === undefined) return next(); // Skip
async()
.forEach(_.castArray(this.result), (next, doc) => {
async()
.forEach(q.$populate, (next, pop) => {
var path = _.isString(pop) ? pop : pop.path;
if (!o.utilities.isObjectId(_.get(doc, path))) return next(); // Already populated
doc.populate(path, next);
})
.end(next);
})
.end(next);
})
// }}}
// End {{{
.end(function(err) {
if (err) {
debug('get() error', err);
return callback(err);
} else if (q.$count) {
callback(null, this.result);
} else {
callback(null, this.result);
}
});
// }}}
return o;
});
// }}}
// .count([q], callback) {{{
/**
* Similar to query() but only return the count of possible results rather than the results themselves
*
* @name monoxide.count
* @see monoxide.query
*
* @param {Object} q The object to process
* @param {string} q.$collection The collection / model to query
* @param {...*} [q.filter] Any other field (not beginning with '$') is treated as filtering criteria
*
* @param {function} callback(err,count) the callback to call on completion or error
*
* @return {Object} This chainable object
*
* @example
* // Count all Widgets
* monoxide.count({$collection: 'widgets'}, function(err, count) {
* console.log('Number of Widgets:', count);
* });
*
* @example
* // Count all admin Users
* monoxide.query({$collection: 'users', role: 'admin'}, function(err, count) {
* console.log('Number of Admin Users:', count);
* });
*/
o.count = argy('[string|object] function', function MonoxideCount(q, callback) {
if (argy.isType(q, 'string')) q = {$collection: q};
// Glue count functionality to query
q.$count = true;
return o.internal.query(q, callback);
});
// }}}
// .save(item, [callback]) {{{
/**
* Save an existing Mongo document by its ID
* If you wish to create a new document see the monoxide.create() function.
* If the existing document ID is not found this function will execute the callback with an error
*
* @name monoxide.save
* @fires save
* @fires postSave
*
* @param {Object} q The object to process
* @param {string} q.$collection The collection / model to query
* @param {string} q.$id The ID of the document to save
* @param {boolean} [q.$refetch=true] Whether to refetch the record after update, false returns `null` in the callback
* @param {boolean} [q.$errNoUpdate=false] Raise an error if no documents were actually updated
* @param {boolean} [q.$errBlankUpdate=false] Raise an error if no fields are updated
* @param {boolean} [q.$returnUpdated=true] If true returns the updated document, if false it returns the document that was replaced
* @param {boolean} [q.$version=true] Increment the `__v` property when updating
* @param {...*} [q.field] Any other field (not beginning with '$') is treated as data to save
*
* @param {function} [callback(err,result)] Optional callback to call on completion or error
*
* @return {Object} This chainable object
*
* @example
* // Save a Widget
* monoxide.save({
* $collection: 'widgets',
* $id: 1234,
* name: 'New name',
* }, function(err, widget) {
* console.log('Saved widget is now', widget);
* });
*/
o.save = argy('object [function]', function(q, callback) {
_.defaults(q || {}, {
$refetch: true, // Fetch and return the record when updated (false returns null)
$errNoUpdate: false,
$errBlankUpdate: false,
$returnUpdated: true,
$version: true,
});
async()
.set('metaFields', [
'$id', // Mandatory field to specify while record to update
'_id', // We also need to clip this from the output (as we cant write to it), but we need to pass it to hooks
'$collection', // Collection to query to find the original record
'$data', // Meta user-defined data
'$refetch',
'$errNoUpdate',
'$errBlankUpdate',
'$version',
'$returnUpdated',
])
// Sanity checks {{{
.then(function(next) {
if (!q || _.isEmpty(q)) return next('No query given for save operation');
if (!q.$collection) return next('$collection must be specified for save operation');
if (!q.$id) return next('ID not specified');
if (!o.models[q.$collection]) return next('Model not initalized');
q._id = q.$id;
next();
})
// }}}
// Calculate $data if it is a function {{{
.then(function(next) {
if (!q.$data) return next();
if (_.isFunction(q.$data)) {
q.$data(function(err, data) {
if (err) return next(err);
q.$data = data;
});
}
next();
})
// }}}
// Fire the 'save' hook on the model {{{
.then(function(next) {
o.models[q.$collection].fire('save', next, q);
})
// }}}
// Peform the update {{{
.then('newRec', function(next) {
var patch = _.omit(q, this.metaFields);
if (_.isEmpty(patch)) {
if (q.$errBlankUpdate) return next('Nothing to update');
if (q.$refetch) {
return o.internal.get({$collection: q.$collection, $id: q.$id}, next);
} else {
return next(null, {});
}
}
_.forEach(o.models[q.$collection].$oids, function(fkType, schemaPath) {
if (!_.has(patch, schemaPath)) return; // Not patching this field anyway
switch(fkType.type) {
case 'objectId': // Convert the field to an OID if it isn't already
if (_.has(q, schemaPath)) {
var newVal = _.get(q, schemaPath);
if (!o.utilities.isObjectID(newVal))
_.set(patch, schemaPath, o.utilities.objectID(newVal));
}
break;
case 'objectIdArray': // Convert each item to an OID if it isn't already
if (_.has(q, schemaPath)) {
var gotOIDs = _.get(q, schemaPath);
if (_.isArray(gotOIDs)) {
_.set(patch, schemaPath, gotOIDs.map(function(i, idx) {
return (!o.utilities.isObjectID(newVal))
? o.utilities.objectID(i)
: i;
}));
} else {
throw new Error('Expected ' + schemaPath + ' to contain an array of OIDs but got ' + (typeof gotOIDs));
}
}
break;
}
});
var updateQuery = { _id: o.utilities.objectID(q.$id) };
var updatePayload = {$set: patch};
var updateOptions = { returnOriginal: !q.$returnUpdated };
var updateCallback = function(err, res) {
if (q.$version && err && o.settings.versionIncErr.test(err.toString())) { // Error while setting `__v`
// Remove __v as an increment operator + retry the operation
// It would be good if $inc could assume `0` when null, but Mongo doesn't support that
updatePayload.$set.__v = 1;
delete updatePayload.$inc;
o.models[q.$collection].$mongoModel.findOneAndUpdate(updateQuery, updatePayload, updateOptions, updateCallback);
} else if (err) {
next(err);
} else {
// This would only really happen if the record has gone away since we started updating
if (q.$errNoUpdate && !res.ok) return next('No documents updated');
if (!q.$refetch) return next(null, null);
next(null, new o.monoxideDocument({$collection: q.$collection}, res.value));
}
};
if (q.$version) {
updatePayload.$inc = {'__v': 1};
delete updatePayload.$set.__v; // Remove user updates of __v
}
// Actually perform the action
o.models[q.$collection].$mongoModel.findOneAndUpdate(
updateQuery, // What we are writing to
updatePayload, // What we are saving
updateOptions, // Options passed to Mongo
updateCallback
);
})
// }}}
// Fire the 'postSave' hook {{{
.then(function(next) {
o.models[q.$collection].fire('postSave', next, q, this.newRec);
})
// }}}
// End {{{
.end(function(err) {
if (err) {
debug('save() error', err);
if (_.isFunction(callback)) callback(err);
} else {
if (_.isFunction(callback)) callback(null, this.newRec);
}
});
// }}}
return o;
});
// }}}
// .update(q, [with], [callback]) {{{
/**
* Update multiple documents
*
* @name monoxide.update
* @fires update
*
* @param {Object} q The object to query by
* @param {string} q.$collection The collection / model to query
* @param {boolean} [q.$refetch=true] Return the newly updated record
* @param {...*} [q.field] Any other field (not beginning with '$') is treated as filter data
*
* @param {Object} qUpdate The object to update into the found documents
* @param {...*} [qUpdate.field] Data to save into every record found by `q`
*
* @param {function} [callback(err,result)] Optional callback to call on completion or error
*
* @return {Object} This chainable object
*
* @example
* // Set all widgets to active
* monoxide.update({
* $collection: 'widgets',
* status: 'active',
* });
*/
o.update = argy('object|string [object] [function]', function MonoxideUpdate(q, qUpdate, callback) {
var o = this;
if (argy.isType(q, 'string')) q = {$collection: q};
_.defaults(q || {}, {
$refetch: true, // Fetch and return the record when updated (false returns null)
});
async()
.set('metaFields', [
'$collection', // Collection to query to find the original record
'$data', // Meta user-defined data
'$refetch',
])
// Sanity checks {{{
.then(function(next) {
if (!q || _.isEmpty(q)) return next('No query given for get operation');
if (!q.$collection) return next('$collection must be specified for get operation');
if (!o.models[q.$collection]) return next('Model not initalized');
next();
})
// }}}
// Calculate $data if it is a function {{{
.then(function(next) {
if (!q.$data) return next();
if (_.isFunction(q.$data)) {
q.$data(function(err, data) {
if (err) return next(err);
q.$data = data;
});
}
next();
})
// }}}
// Fire the 'update' hook {{{
.then(function(next) {
o.models[q.$collection].fire('update', next, q);
})
// }}}
// Peform the update {{{
.then('rawResponse', function(next) {
o.models[q.$collection].$mongooseModel.updateMany(_.omit(q, this.metaFields), _.omit(qUpdate, this.metaFields), {multi: true}, next);
})
// }}}
// End {{{
.end(function(err) {
if (err) {
debug('update() error', err);
if (callback) callback(err);
} else {
if (callback) callback(null, this.newRec);
}
});
// }}}
return o;
});
// }}}
// .create(item, [callback]) {{{
/**
* Create a new Mongo document and return it
* If you wish to save an existing document see the monoxide.save() function.
*
* @name monoxide.create
*
* @param {Object} q The object to process
* @param {string} q.$collection The collection / model to query
* @param {boolean} [q.$refetch=true] Return the newly create record
* @param {boolean} [q.$version=true] Set the `__v` field to 0 when creating the document
* @param {...*} [q.field] Any other field (not beginning with '$') is treated as data to save
*
* @param {function} [callback(err,result)] Optional callback to call on completion or error
*
* @return {Object} This chainable object
*
* @example
* // Create a Widget
* monoxide.save({
* $collection: 'widgets',
* name: 'New widget name',
* }, function(err, widget) {
* console.log('Created widget is', widget);
* });
*/
o.create = argy('object [function]', function MonoxideQuery(q, callback) {
_.defaults(q || {}, {
$refetch: true, // Fetch and return the record when created (false returns null)
$version: true,
});
async()
.set('metaFields', [
'$collection', // Collection to query to find the original record
'$data', // Meta user-defined data
'$refetch',
'$version',
])
// Sanity checks {{{
.then(function(next) {
if (!q || _.isEmpty(q)) return next('No query given for save operation');
if (!q.$collection) return next('$collection must be specified for save operation');
if (!o.models[q.$collection]) return next('Model not initalized');
next();
})
// }}}
// Calculate $data if it is a function {{{
.then(function(next) {
if (!q.$data) return next();
if (_.isFunction(q.$data)) {
q.$data(function(err, data) {
if (err) return next(err);
q.$data = data;
next();
});
} else {
next();
}
})
// }}}
// Coherse all OIDs (or arrays of OIDs) into their correct internal type {{{
.then(function(next) {
_.forEach(o.models[q.$collection].$oids, function(fkType, schemaPath) {
switch(fkType.type) {
case 'objectId': // Convert the field to an OID if it isn't already
if (_.has(q, schemaPath)) {
var newVal = _.get(q, schemaPath);
if (!o.utilities.isObjectID(newVal))
_.set(q, schemaPath, o.utilities.objectID(newVal));
}
break;
case 'objectIdArray': // Convert each item to an OID if it isn't already
if (_.has(q, schemaPath)) {
var gotOIDs = _.get(q, schemaPath);
if (_.isArray(gotOIDs)) {
_.set(q, schemaPath, gotOIDs.map(function(i, idx) {
return (!o.utilities.isObjectID(newVal))
? o.utilities.objectID(i)
: i;
}));
} else {
throw new Error('Expected ' + schemaPath + ' to contain an array of OIDs but got ' + (typeof gotOIDs));
}
}
break;
}
});
next();
})
// }}}
// Add version information if $version==true {{{
.then(function(next) {
if (!q.$version) return next();
q.__v = 0;
next();
})
// }}}
// Create record {{{
.then('createDoc', function(next) { // Compute the document we will create
next(null, new o.monoxideDocument({
$collection: q.$collection,
$dirty: true, // Mark all fields as modified (and not bother to compute the clean markers)
}, _.omit(q, this.metaFields)));
})
.then(function(next) {
o.models[q.$collection].fire('create', next, this.createDoc);
})
.then('rawResponse', function(next) {
o.models[q.$collection].$mongoModel.insertOne(this.createDoc.toMongoObject(), next);
})
.then(function(next) {
o.models[q.$collection].fire('postCreate', next, q, this.createDoc);
})
// }}}
// Refetch record {{{
.then('newRec', function(next) {
if (!q.$refetch) return next(null, null);
o.internal.query({
$collection: q.$collection,
$id: this.rawResponse.insertedId.toString(),
}, function(err, res) {
if (err == 'Not found') return next('Document creation failed');
next(err, res);
});
})
// }}}
// End {{{
.end(function(err) {
if (err) {
debug('create() error', err);
if (_.isFunction(callback)) callback(err);
} else {
if (_.isFunction(callback)) callback(null, this.newRec);
}
});
// }}}
return o;
});
// }}}
// .delete(item, [callback]) {{{
/**
* Delete a Mongo document by its ID
* This function has two behaviours - it will, by default, only delete a single record by its ID. If `q.$multiple` is true it will delete by query.
* If `q.$multiple` is false and the document is not found (by `q.$id`) this function will execute the callback with an error
* Delete will only work with no parameters if monoxide.settings.removeAll is truthy as an extra safety check
*
* @name monoxide.delete
*
* @param {Object} [q] The object to process
* @param {string} [q.$collection] The collection / model to query
* @param {string} [q.$id] The ID of the document to delete (if you wish to do a remove based on query set q.$query=true)
* @param {boolean} [q.$multiple] Allow deletion of multiple records by query
* @param {boolean} [q.$errNotFound] Raise an error if a specifically requested document is not found (requires $id)
*
* @param {function} [callback(err,result)] Optional callback to call on completion or error
*
* @return {Object} This chainable object
*/
o.delete = o.remove = argy('object [function]', function MonoxideQuery(q, callback) {
_.defaults(q || {}, {
$errNotFound: true, // During raise an error if $id is specified but not found to delete
});
async()
.set('metaFields', [
'$id', // Mandatory field to specify while record to update
'$collection', // Collection to query to find the original record
'$data', // Meta user-defined data
'$multiple', // Whether to allow deletion by query
'$errNotFound',
])
// Sanity checks {{{
.then(function(next) {
if (!q || _.isEmpty(q)) return next('No query given for delete operation');
if (!q.$collection) return next('$collection must be specified for delete operation');
if (!q.$id && !q.$multiple) return next('$id or $multiple must be speciied during delete operation');
if (!o.settings.removeAll && !q.$id && _.isEmpty(_.omit(q, this.metaFields))) { // Apply extra checks to make sure we are not nuking everything if we're not allowed
return next('delete operation not allowed with empty query');
}
next();
})
// }}}
// Calculate $data if it is a function {{{
.then(function(next) {
if (!q.$data) return next();
if (_.isFunction(q.$data)) {
q.$data(function(err, data) {
if (err) return next(err);
q.$data = data;
});
}
next();
})
// }}}
// Delete record {{{
.then(function(next) {
if (q.$multiple) { // Multiple delete operation
o.internal.query(_.merge(_.omit(q, this.metaFields), {$collection: q.$collection, $select: 'id'}), function(err, rows) {
async()
.forEach(rows, function(next, row) {
o.internal.delete({$collection: q.$collection, $id: row._id}, next);
})
.end(next);
});
} else { // Single item delete
// Check that the hook returns ok
o.models[q.$collection].fire('delete', function(err) {
// Now actually delete the item
o.models[q.$collection].$mongoModel.deleteOne({_id: o.utilities.objectID(q.$id)}, function(err, res) {
if (err) return next(err);
if (q.$errNotFound && !res.result.ok) return next('Not found');
// Delete was sucessful - call event then move next
o.models[q.$collection].fire('postDelete', next, {_id: q.$id});
});
}, {_id: q.$id});
}
})
// }}}
// End {{{
.end(function(err) {
if (err) {
debug('delete() error', err);
if (callback) callback(err);
} else {
if (callback) callback(null, this.newRec);
}
});
// }}}
return o;
});
// }}}
// .meta(item, [callback]) {{{
/**
* Return information about a Mongo collection schema
*
* @name monoxide.meta
*
* @param {Object} q The object to process
* @param {string} q.$collection The collection / model to examine
* @param {boolean} [q.$collectionEnums=false] Provide all enums as a collection object instead of an array
* @param {boolean} [q.$filterPrivate=true] Ignore all private fields
* @param {boolean} [q.$prototype=false] Provide the $prototype meta object
* @param {boolean} [q.$indexes=false] Include whether a field is indexed
*
* @param {function} [callback(err,result)] Optional callback to call on completion or error
*
* @return {Object} This chainable object
*
* @example
* // Describe a collection
* monoxide.meta({$collection: 'widgets'}, function(err, res) {
* console.log('About the widget collection:', res);
* });
*/
o.meta = argy('[object] function', function MonoxideMeta(q, callback) {
_.defaults(q || {}, {
$filterPrivate: true,
$prototype: false,
$indexes: false,
});
async()
.set('metaFields', [
'$collection', // Collection to query to find the original record
'$data', // Meta user-defined data
'$filterPrivate', // Filter out /^_/ fields
'$collectionEnums', // Convert enums into a collection (with `id` + `title` fields per object)
'$prototype',
'$indexes',
])
// Sanity checks {{{
.then(function(next) {
if (!q || _.isEmpty(q)) return next('No query given for meta operation');
if (!q.$collection) return next('$collection must be specified for meta operation');
if (!o.models[q.$collection]) return next('Cannot find collection to extract its meta information: ' + q.$collection);
next();
})
// }}}
// Retrieve the meta information {{{
.then('meta', function(next) {
var sortedPaths = _(o.models[q.$collection].$mongooseModel.schema.paths)
.map((v,k) => v)
.sortBy('path')
.value();
var meta = {
_id: {type: 'objectid', index: true}, // FIXME: Is it always the case that a doc has an ID?
};
_.forEach(sortedPaths, function(path) {
var id = path.path;
if (q.$filterPrivate && _.last(path.path.split('.')).startsWith('_')) return; // Skip private fields
var info = {};
switch (path.instance.toLowerCase()) {
case 'string':
info.type = 'string';
if (path.enumValues && path.enumValues.length) {
if (q.$collectionEnums) {
info.enum = path.enumValues.map(e => ({
id: e,
title: _.startCase(e),
}));
} else {
info.enum = path.enumValues;
}
}
break;
case 'number':
info.type = 'number';
break;
case 'date':
info.type = 'date';
break;
case 'boolean':
info.type = 'boolean';
break;
case 'array':
info.type = 'array';
break;
case 'object':
info.type = 'object';
break;
case 'objectid':
info.type = 'objectid';
if (_.has(path, 'options.ref')) info.ref = path.options.ref;
break;
default:
debug('Unknown Mongo data type during meta extract on ' + q.$collection + ':', path.instance.toLowerCase());
}
// Extract default value if its not a function (otherwise return [DYNAMIC])
if (path.defaultValue) info.default = argy.isType(path.defaultValue, 'scalar') ? path.defaultValue : '[DYNAMIC]';
if (q.$indexes && path._index) info.index = true;
meta[id] = info;
});
next(null, meta);
})
// }}}
// Construct the prototype if $prototype=true {{{
.then(function(next) {
if (!q.$prototype) return next();
var prototype = this.meta.$prototype = {};
_.forEach(this.meta, function(v, k) {
if (!_.has(v, 'default')) return;
if (v.default == '[DYNAMIC]') return; // Ignore dynamic values
_.set(prototype, k, v.default);
});
next();
})
// }}}
// End {{{
.end(function(err) {
if (err) {
debug('meta() error', err);
if (callback) callback(err);
} else {
if (callback) callback(null, this.meta);
}
});
// }}}
return o;
});
// }}}
// .runCommand(command, [callback]) {{{
/**
* Run an internal MongoDB command and fire an optional callback on the result
*
* @name monoxide.meta
*
* @param {Object} cmd The command to process
* @param {function} [callback(err,result)] Optional callback to call on completion or error
* @return {Object} This chainable object
* @example
*/
o.runCommand = argy('object [function]', function MonoxideRunCommand(cmd, callback) {
o.connection.db.command(cmd, callback);
return o;
});
// }}}
// .queryBuilder() - query builder {{{
/**
* Returns data from a Monoxide model
* @class
* @name monoxide.queryBuilder
* @return {monoxide.queryBuilder}
* @fires queryBuilder Fired as (callback, qb) when a new queryBuilder object is created
*/
o.queryBuilder = function monoxideQueryBuilder() {
var qb = this;
qb.$MONOXIDE = true;
qb.query = {};
// qb.find(q, cb) {{{
/**
* Add a filtering function to an existing query
* @name monoxide.queryBuilder.find
* @memberof monoxide.queryBuilder
* @param {Object|function} [q] Optional filtering object or callback (in which case we act as exec())
* @param {function} [callback] Optional callback. If present this is the equivelent of calling exec()
* @return {monoxide.queryBuilder} This chainable object
*/
qb.find = argy('[object|string] [function]', function(q, callback) {
if (argy.isType(q, 'object')) {
_.merge(qb.query, q);
} else {
q = {$id: q};
}
if (callback) qb.exec(callback);
return qb;
});
// }}}
// qb.select(q, cb) {{{
/**
* Add select criteria to an existing query
* If this function is passed a falsy value it is ignored
* @name monoxide.queryBuilder.select
* @memberof monoxide.queryBuilder
* @param {Object|Array|string} [q] Select criteria, for strings or arrays of strings use the field name optionally prefixed with '-' for omission. For Objects use `{field: 1|-1}`
* @param {function} [callback] Optional callback. If present this is the equivelent of calling exec()
* @return {monoxide.queryBuilder} This chainable object
*/
qb.select = argy('string|array [function]', function(q, callback) {
argy(arguments)
.ifForm(['string', 'string function'], function(id, callback) {
if (qb.query.$select) {
qb.query.$select.push(id);
} else {
qb.query.$select = [id];
}
if (callback) q.exec(callback);
})
.ifForm(['array', 'array function'], function(ids, callback) {
if (qb.query.$select) {
qb.query.$select.push.apply(this, ids);
} else {
qb.query.$select = ids;
}
if (callback) q.exec(callback);
})
return qb;
});
// }}}
// qb.sort(q, cb) {{{
/**
* Add sort criteria to an existing query
* If this function is passed a falsy value it is ignored
* @name monoxide.queryBuilder.sort
* @memberof monoxide.queryBuilder
* @param {Object|Array|string} [q] Sorting criteria, for strings or arrays of strings use the field name optionally prefixed with '-' for decending search order. For Objects use `{ field: 1|-1|'asc'|'desc'}`
* @param {function} [callback] Optional callback. If present this is the equivelent of calling exec()
* @return {monoxide.queryBuilder} This chainable object
*/
qb.sort = argy('string|array|undefined [function]', function(q, callback) {
argy(arguments)
.ifForm('', function() {})
.ifForm('undefined', function() {})
.ifForm(['string', 'string function'], function(field, callback) {
if (qb.query.$sort) {
qb.query.$sort.push(field);
} else {
qb.query.$sort = [field];
}
if (callback) qb.exec(callback);
})
.ifForm(['array', 'array function'], function(fields, callback) {
if (qb.query.$sort) {
qb.query.$sort.push.apply(this, fields);
} else {
qb.query.$sort = fields;
}
if (callback) qb.exec(callback);
})
return qb;
});
// }}}
// qb.limit(q, cb) {{{
/**
* Add limit criteria to an existing query
* If this function is passed a falsy value the limit is removed
* @name monoxide.queryBuilder.limit
* @memberof monoxide.queryBuilder
* @param {number|string} q Limit records to this number (it will be parsed to an Int)
* @param {function} [callback] Optional callback. If present this is the equivelent of calling exec()
* @return {monoxide.queryBuilder} This chainable object
*/
qb.limit = argy('[falsy|string|number] [function]', function(q, callback) {
if (!q) {
delete qb.query.$limit;
} else if (argy.isType(q, 'string')) {
qb.query.$limit = parseInt(q);
} else {
qb.query.$limit = q;
}
if (callback) return qb.exec(callback);
return qb;
});
// }}}
// qb.skip(q, cb) {{{
/**
* Add skip criteria to an existing query
* If this function is passed a falsy value the skip offset is removed
* @name monoxide.queryBuilder.skip
* @memberof monoxide.queryBuilder
* @param {number} q Skip this number of records (it will be parsed to an Int)
* @param {function} [callback] Optional callback. If present this is the equivelent of calling exec()
* @return {monoxide.queryBuilder} This chainable object
*/
qb.skip = argy('[falsy|string|number] [function]', function(q, callback) {
if (!q) {
delete qb.query.$skip;
} else if (argy.isType(q, 'string')) {
qb.query.$skip = parseInt(q);
} else {
qb.query.$skip = q;
}
if (callback) return qb.exec(callback);
return qb;
});
// }}}
// qb.populate(q, cb) {{{
/**
* Add population criteria to an existing query
* If this function is passed a falsy value it is ignored
* @name monoxide.queryBuilder.populate
* @memberof monoxide.queryBuilder
* @param {Array|string} [q] Population criteria, for strings or arrays of strings use the field name
* @param {function} [callback] Optional callback. If present this is the equivelent of calling exec()
* @return {monoxide.queryBuilder} This chainable object
*/
qb.populate = argy('string|array [function]', function(q, callback) {
argy(arguments)
.ifForm('', function() {})
.ifForm(['string', 'string function'], function(field, callback) {
if (qb.query.$populate) {
qb.query.$populate.push(field);
} else {
qb.query.$populate = [field];
}
if (callback) qb.exec(callback);
})
.ifForm(['array', 'array function'], function(fields, callback) {
if (qb.query.$populate) {
qb.query.$populate.push.apply(this, fields);
} else {
qb.query.$populate = fields;
}
if (callback) qb.exec(callback);
})
return qb;
});
// }}}
// qb.exec(cb) {{{
/**
* Execute the query and return the error and any results
* @name monoxide.queryBuilder.exec
* @memberof monoxide.queryBuilder
* @param {function} callback(err,result)
* @return {monoxide.queryBuilder} This chainable object
*/
qb.exec = argy('function', function(callback) {
return o.internal.query(qb.query, callback);
});
// }}}
// qb.optional() {{{
/**
* Convenience function to set $errNotFound
* @name monoxide.queryBuilder.optional
* @memberof monoxide.queryBuilder
* @param {Object|function} [isOptional=true] Whether the return from this query should NOT throw an error if nothing was found
* @param {function} [callback] Optional callback. If present this is the equivelent of calling exec()
* @return {monoxide.queryBuilder} This chainable object
*/
qb.optional = argy('[boolean|null|undefined] [function]', function(isOptional, callback) {
if (argy.isType(isOptional, ['null', 'undefined'])) {
qb.query.$errNotFound = false;
} else {
qb.query.$errNotFound = !! isOptional;
}
if (callback) qb.exec(callback);
return qb;
});
// }}}
// qb.promise() {{{
/**
* Convenience function to execute the query and return a promise with the result
* @name monoxide.queryBuilder.promise
* @memberof monoxide.queryBuilder
* @return {Mongoose.queryBuilder} This chainable object
*/
qb.promise = function(callback) {
return new Promise(function(resolve, reject) {
o.internal.query(qb.query, function(err, result) {
if (err) {
reject(err);
} else {
resolve(result);
}
});
});
};
// Wrap all promise functions in a convnience wrapper
['then', 'catch', 'finally'].forEach(f => {
qb[f] = function() {
var p = qb.promise();
return p[f].apply(p, arguments);
};
});
// }}}
// qb.cursor() {{{
/**
* Convenience function to return the generated cursor back from a queryBuilder object
* @name monoxide.queryBuilder.cursor
* @memberof monoxide.queryBuilder
* @param {function} callback(err, cursor)
* @return {Mongoose.queryBuilder} This chainable object
*/
qb.cursor = function(callback) {
qb.query.$want = 'cursor';
return o.internal.query(qb.query, callback);
};
// }}}
o.fireImmediate('queryBuilder', qb);
return qb;
};
// }}}
// .monoxideModel([options]) - monoxide model instance {{{
/**
* @class
*/
o.monoxideModel = argy('string|object', function monoxideModel(settings) {
var mm = this;
if (argy.isType(settings, 'string')) settings = {$collection: settings};
// Sanity checks {{{
if (!settings.$collection) throw new Error('new MonoxideModel({$collection: <name>}) requires at least \'$collection\' to be specified');
if (!o.connection) throw new Error('Trying to create a MonoxideModel before a connection has been established');
if (!o.connection.db) throw new Error('Connection does not look like a MongoDB-Core object');
// }}}
/**
* The raw MongoDB-Core model
* @var {Object}
*/
mm.$mongoModel = o.connection.db.collection(settings.$collection.toLowerCase());
if (!mm.$mongoModel) throw new Error('Model not found in MongoDB-Core - did you forget to call monoxide.schema(\'name\', <schema>) first?');
/**
* The raw Mongoose model
* @depreciated This will eventually go away and be replaced with raw `mm.$mongoModel` calls
* @var {Object}
*/
mm.$mongooseModel = o.connection.base.models[settings.$collection.toLowerCase()];
/**
* Holder for all OID information
* This can either be the `._id` of the object, sub-documents, array pointers or object pointers
* @see monoxide.utilities.extractFKs
* @var {Object}
*/
mm.$oids = _.has(mm, '$mongooseModel.schema') ? o.utilities.extractFKs(mm.$mongooseModel.schema) : {};
/**
* Optional model schema
* NOTE: This is the user defined schema as-is NOT the computed $monogooseModel.schema
* @var {Object}
*/
mm.$schema = settings.$schema;
mm.$collection = settings.$collection;
mm.$methods = {};
mm.$virtuals = {};
mm.$hooks = {};
mm.$data = {};
/**
* Shortcut function to create a monoxide.queryBuilder object and immediately start filtering
* This also sets $count=true in the queryBuilder
* @name monoxide.monoxideModel.find
* @see monoxide.queryBuilder.find
*
* @param {Object} [q] Optional filtering object
* @param {function} [callback] Optional callback. If present this is the equivelent of calling exec()
* @return {monoxide.queryBuilder}
*/
mm.count = function(q, callback) {
return (new o.queryBuilder())
.find({
$collection: mm.$collection, // Set the collection from the model
$count: true,
})
.find(q, callback); // Then re-parse the find query into the new queryBuilder
};
/**
* Shortcut function to create a monoxide.queryBuilder object and immediately start filtering
* @name monoxide.monoxideModel.find
* @see monoxide.queryBuilder.find
*
* @param {Object} [q] Optional filtering object
* @param {function} [callback] Optional callback. If present this is the equivelent of calling exec()
* @return {monoxide.queryBuilder}
*/
mm.find = function(q, callback) {
return (new o.queryBuilder())
.find({$collection: mm.$collection}) // Set the collection from the model
.find(q, callback); // Then re-parse the find query into the new queryBuilder
};
/**
* Shortcut function to create a monoxide.queryBuilder object and immediately start filtering
* This also sets $one=true in the queryBuilder
* @name monoxide.monoxideModel.findOne
* @see monoxide.queryBuilder.find
*
* @param {Object} [q] Optional filtering object
* @param {function} [callback] Optional callback. If present this is the equivelent of calling exec()
* @return {monoxide.queryBuilder}
*/
mm.findOne = function(q, callback) {
if (argy.isType(q, 'string')) throw new Error('Refusing to allow findOne(String). Use findOneByID if you wish to specify only the ID');
return (new o.queryBuilder())
.find({
$collection: mm.$collection, // Set the collection from the model
$one: true, // Return a single object
})
.find(q, callback); // Then re-parse the find query into the new queryBuilder
};
/**
* Shortcut function to create a monoxide.queryBuilder object and immediately start filtering
* This also sets $id=q in the queryBuilder
* @name monoxide.monoxideModel.findOneByID
* @see monoxide.queryBuilder.find
*
* @param {Object} [q] Optional filtering object
* @param {function} [callback] Optional callback. If present this is the equivelent of calling exec()
* @return {monoxide.queryBuilder}
*/
mm.findOneByID = function(q, callback) {
// Deal with arguments {{{
if (argy.isType(q, 'string')) {
// All ok
} else if (argy.isType(q, 'object') && q.toString().length) { // Input is an object but we can convert it to something useful
q = q.toString();
} else {
throw new Error('Unknown function call pattern');
}
// }}}
return (new o.queryBuilder())
.find({
$collection: mm.$collection, // Set the collection from the model
$id: q,
})
.find(q, callback); // Then re-parse the find query into the new queryBuilder
};
/**
* Alias of findOneByID
* @see monoxide.queryBuilder.find
*/
mm.findOneById = mm.findOneByID;
/**
* Shortcut function to create a new record within a collection
* @name monoxide.monoxideModel.create
* @see monoxide.create
*
* @param {Object} [q] Optional document contents
* @param {function} [callback] Optional callback
* @return {monoxide.monoxideModel} The chainable monoxideModel
*/
mm.create = argy('object [function]', function(q, callback) {
q.$collection = mm.$collection;
o.internal.create(q, callback);
return mm;
});
/**
* Shortcut to invoke update on a given model
* @name monoxide.monoxideMode.update
* @see monoxide.update
* @param {Object} q The filter to query by
* @param {Object} qUpdate The object to update into the found documents
* @param {function} [callback(err,result)] Optional callback to call on completion or error
* @return {Object} This chainable object
*/
mm.update = argy('object object [function]', function(q, qUpdate, callback) {
q.$collection = mm.$collection;
o.internal.update(q, qUpdate, callback);
return mm;
});
/**
* Shortcut function to remove a number of rows based on a query
* @name monoxide.monoxideModel.remove
* @see monoxide.delete
*
* @param {Object} [q] Optional filtering object
* @param {function} [callback] Optional callback
* @return {monoxide}
*/
mm.remove = argy('[object] [function]', function(q, callback) {
return o.internal.delete(_.merge({}, q, {$collection: mm.$collection, $multiple: true}), callback);
});
/**
* Alias of remove()
* @see monoxide.remove()
*/
mm.delete = mm.remove;
/**
* Run an aggregation pipeline on a model
* @param {array} q The aggregation pipeline to process
* @param {function} callback Callback to fire as (err, data)
* @return {Object} This chainable object
*/
mm.aggregate = argy('array function', function(q, callback) {
o.internal.aggregate({
$collection: mm.$collection,
$stages: q,
}, callback)
return mm;
});
/**
* Add a method to a all documents returned from this model
* A method is a user defined function which extends the `monoxide.monoxideDocument` prototype
* @param {string} name The function name to add as a static method
* @param {function} func The function to add as a static method
* @return {monoxide.monoxideModel} The chainable monoxideModel
*/
mm.method = function(name, func) {
mm.$methods[name] = func;
return mm;
};
/**
* Add a static method to a model
* A static is a user defined function which extends the `monoxide.monoxideModel` prototype
* @param {string} name The function name to add as a static method
* @param {function} func The function to add as a static method
* @return {monoxide.monoxideModel} The chainable monoxideModel
*/
mm.static = function(name, func) {
mm[name] = func;
return mm;
};
/**
* Define a virtual (a handler when a property gets set or read)
* @param {string|Object} name The virtual name to apply or the full virtual object (must pretain to the Object.defineProperty descriptor)
* @param {function} getCallback The get function to call when the virtual value is read
* @param {function} setCallback The set function to call when the virtual value changes
* @return {monoxide.monoxideModel} The chainable monoxideModel
*/
mm.virtual = argy('string [function|falsy] [function|falsy]', function(name, getCallback, setCallback) {
var q = {};
if (argy.isType(getCallback, 'function')) q.get = getCallback;
if (argy.isType(setCallback, 'function')) q.set = setCallback;
mm.$virtuals[name] = q;
return mm;
});
/**
* Return whether a model has virtuals
* @return {boolean} Whether any virtuals are present
*/
mm.hasVirtuals = function() {
return (Object.keys(mm.$virtuals).length > 0);
};
/**
* Attach a hook to a model
* A hook is exactly the same as a eventEmitter.on() event but must return a callback
* Multiple hooks can be attached and all will be called in parallel on certain events such as 'save'
* All hooks must return non-errors to proceed with the operation
* @param {string} eventName The event ID to hook against
* @param {function} callback The callback to run when hooked, NOTE: Any falsy callbacks are ignored
* @return {monoxide.monoxideModel} The chainable monoxideModel
*/
mm.hook = function(eventName, callback) {
if (!callback) return mm; // Ignore flasy callbacks
if (!mm.$hooks[eventName]) mm.$hooks[eventName] = [];
mm.$hooks[eventName].push(callback);
return mm;
};
/**
* Return whether a model has a specific hook
* If an array is passed the result is whether the model has none or all of the specified hooks
* @param {string|array|undefined|null} hooks The hook(s) to query, if undefined or null this returns if any hooks are present
* @return {boolean} Whether the hook(s) is present
*/
mm.hasHook = argy('[string|array]', function(hooks) {
var out;
argy(arguments)
.ifForm('', function() {
out = !_.isEmpty(mm.$hooks);
})
.ifForm('string', function(hook) {
out = mm.$hooks[hook] && mm.$hooks[hook].length;
})
.ifForm('array', function(hooks) {
out = hooks.every(function(hook) {
return (mm.$hooks[hook] && mm.$hooks[hook].length);
});
});
return out;
});
/**
* Execute all hooks attached to a model
* This function fires all hooks in parallel and expects all to resolve correctly via callback
* NOTE: Hooks are always fired with the callback as the first argument
* @param {string} name The name of the hook to invoke
* @param {function} callback The callback to invoke on success
* @param {...*} parameters Any other parameters to be passed to each hook
* @return {monoxide.monoxideModel} The chainable monoxideModel
*/
mm.fire = function(name, callback) {
if ( // There is at least one event handler attached
(mm.$hooks[name] && mm.$hooks[name].length)
|| (o.$hooks[name] && o.$hooks[name].length)
) {
var eventArgs = _.values(arguments);
eventArgs.splice(1, 1); // Remove the 'callback' arg as events cant respond to it anyway
mm.emit.apply(mm, eventArgs);
} else {
return callback();
}
// Calculate the args array we will pass to each hook
var hookArgs = _.values(arguments);
hookArgs.shift(); // We will set args[0] to the callback in each case anyway so we only need to shift 1
var eventArgs = _.values(arguments);
eventArgs.splice(1, 1); // Remove the 'callback' arg as events cant respond to it anyway
async()
// Fire hooks attached to this model + global hooks {{{
.forEach([]
.concat(o.$hooks[name], mm.$hooks[name])
.filter(f => !!f) // Actually is a function?
, function(next, hookFunc) {
hookArgs[0] = next;
hookFunc.apply(mm, hookArgs);
})
// }}}
.end(callback);
return mm;
};
/**
* Return the meta structure for a specific model
* @param {Object} Options to return when computing the meta object. See the main meta() function for details
* @param {function} callback The callback to call with (err, layout)
* @return {monoxide.monoxideModel} The chainable monoxideModel
* @see monoxide.meta()
*/
mm.meta = argy('[object] function', function(options, callback) {
var settings = options || {};
settings.$collection = mm.$collection;
o.internal.meta(settings, callback);
return mm;
});
/**
* Run a third party plugin against a model
* This function is really just a shorthand way to pass a Monoxide model into a function
* @param {function|string|array} plugins The plugin(s) to run. Each function is run as (model, callback), strings are assumed to be file paths to JS files if they contain at least one '/' or `.` otherwise they are loaded from the `plugins` directory
* @return {monoxide.monoxideModel} The chainable monoxideModel
*/
mm.use = function(plugins, callback) {
if (!plugins) return callback(); // Do nothing if given falsy
async()
.forEach(_.castArray(plugins), function(next, plugin) {
if (_.isString(plugin)) {
var pluginModule = /[\/\.]/.test(plugin) // Contains at least one slash or dot?
? require(plugin)
: require(__dirname + '/plugins/' + plugin)
pluginModule.call(mm, mm, next);
} else if (_.isFunction(plugin)) {
plugin.call(mm, mm, next);
} else {
next('Unsupported plugin format');
}
})
.end(callback);
return mm;
};
/**
* Return an array of all distinct field values
* @param {string} field The field to return the values of
* @param {function} plugin The plugin to run. This gets the arguments (values)
* @return {monoxide.monoxideModel} The chainable monoxideModel
*/
mm.distinct = function(field, callback) {
o.internal.runCommand({
distinct: mm.$collection,
key: field,
}, function(err, res) {
if (err) return callback(err);
callback(null, res.values);
});
return mm;
};
/**
* Set a simple data key
* This is usually used to store suplemental information about models
* @param {Object|string} key The key to set or a full object of keys
* @param {*} value If `key` is a string the value is the value stored
* @return {monoxide.monoxideModel} The chainable monoxideModel
*/
mm.set = function(key, value) {
if (argy.isType(key, 'object')) {
_.assign(mm.$data, key);
} else if (argy.isType(key, 'string')) {
mm.$data[key] = value;
} else {
throw new Error('Unsupported type storage during set');
}
return mm;
};
/*
* Gets a simple data key or returns a fallback
* @param {string} key The data key to retrieve
* @param {*} [fallback] The fallback to return if the key is not present
*/
mm.get = function(key, fallback) {
return (argy.isType(mm.$data[key], 'undefined') ? fallback : mm.$data[key]);
};
/**
* Retrieve the list of actual on-the-database indexes
* @param {function} callback Callback to fire as (err, indexes)
* @return {monoxide.monoxideModel} The chainable monoxideModel
*/
mm.getIndexes = function(callback) {
mm.$mongoModel.indexes(function(err, res) {
if (err && err.message == 'no collection') {
callback(null, []); // Collection doesn't exist yet - ignore and return that it has no indexes
} else {
callback(err, res);
}
});
return mm;
};
/**
* Return the list of indexes requested by the schema
* @param {function} callback Callback to fire as (err, indexes)
* @return {monoxide.monoxideModel} The chainable monoxideModel
*/
mm.getSchemaIndexes = function(callback) {
mm.meta({$indexes: true}, function(err, res) {
if (err) return callback(err);
callback(null, _(res)
.map(function(v, k) {
return _.assign(v, {id: k});
})
.filter(function(v) {
return !!v.index;
})
.map(function(v) {
var o = {name: v.id == '_id' ? '_id_' : v.id, key: {}};
o.key[v.id] = 1;
return o;
})
.value()
);
});
return mm;
};
/**
* Check this model by a defined list of indexes
* The return is a duplicate of the input indexes with an additional `status` property which can equal to 'ok' or 'missing'
* @param {array} [wantIndexes] The indexes to examine against. If omitted the results of model.getSchemaIndexes() is used
* @param {array} [actualIndexes] The current state of the model to compare against. If omitted the results of model.getIndexes() is used
* @param {function} callback The callback to call as (err, indexes)
* @return {monoxide.monoxideModel} The chainable monoxideModel
*/
mm.checkIndexes = argy('[array] [array] function', function(wantIndexes, actualIndexes, callback) {
async()
// Either use provided indexes or determine them {{{
.parallel({
wantIndexes: function(next) {
if (wantIndexes) return next(null, wantIndexes);
mm.getSchemaIndexes(next);
},
actualIndexes: function(next) {
if (actualIndexes) return next(null, actualIndexes);
mm.getIndexes(next);
},
})
// }}}
// Compare indexes against whats declared {{{
.map('indexReport', 'wantIndexes', function(next, index) {
var foundIndex = this.actualIndexes.find(i => _.isEqual(i.key, index.key));
if (foundIndex) {
index.status = 'ok';
} else {
index.status = 'missing';
}
next(null, index);
})
// }}}
// End {{{
.end(function(err) {
if (err) return callback(err);
callback(null, this.indexReport);
});
// }}}
});
return mm;
});
util.inherits(o.monoxideModel, events.EventEmitter);
// }}}
// .monoxideDocument([setup]) - monoxide document instance {{{
/**
* Returns a single instance of a Monoxide document
* @class
* @name monoxide.monoxideDocument
* @param {Object} setup The prototype fields. Everything in this object is extended into the prototype
* @param {boolean} [setup.$applySchema=true] Whether to enforce the model schema on the object. This includes applying default values
* @param {boolean} [setup.$dirty=false] Whether the entire document contents should be marked as dirty (modified). If true this also skips the computation of modified fields
* @param {boolean [setup.decorate=true] Whether to apply any decoration. If false this function returns data undecorated (i.e. no custom Monoxide functionality)
* @param {string} setup.$collection The collection this document belongs to
* @param {Object} data The initial data
* @return {monoxide.monoxideDocument}
*/
o.monoxideDocument = function monoxideDocument(setup, data) {
if (setup.$decorate === false) return data;
setup.$dirty = !!setup.$dirty;
var model = o.models[setup.$collection];
var proto = {
$MONOXIDE: true,
$collection: setup.$collection,
$populated: {},
/**
* Save a document
* By default this function will only save back modfified data
* If `data` is specified this is used as well as the modified fields (unless `data.$ignoreModified` is falsy, in which case modified fields are ignored)
* @param {Object} [data] An optional data patch to save
* @param {boolean} [data.$ignoreModified=false] Ignore all modified fields and only process save data being passed in the `data` object (use this to directly address what should be saved, ignoring everything else). Setting this drastically speeds up the save operation but at the cost of having to be specific as to what to save
* @param {function} [callback] The callback to invoke on saving
*/
save: argy('[object] [function]', function(data, callback) {
var doc = this;
var mongoDoc = doc.toMongoObject();
var patch = {
$collection: doc.$collection,
$id: doc._id,
$errNoUpdate: true, // Throw an error if we fail to update (i.e. record removed before save)
$returnUpdated: true,
};
if (data && data.$ignoreModified) { // Only save incomming data
delete data.$ignoreModified;
_.assign(patch, data);
} else if (data) { // Data is specified as an object but $ignoreModified is not set - use both inputs
doc.isModified().forEach(function(path) {
patch[path] = _.get(mongoDoc, path);
});
_.assign(patch, data);
} else {
doc.isModified().forEach(function(path) {
patch[path] = _.get(mongoDoc, path);
});
}
o.internal.save(patch, function(err, newRec) {
doc = newRec;
if (_.isFunction(callback)) callback(err, newRec);
});
return doc;
}),
/**
* Remove the document from the collection
* This method is really just a thin wrapper around monoxide.delete()
* @param {function} [callback] Optional callback to invoke on completion
* @see monoxide.delete
*/
remove: function(callback) {
var doc = this;
o.internal.delete({
$collection: doc.$collection,
$id: doc._id,
}, callback);
return doc;
},
/**
* Remove certain fields from the document object
* This method is really just a thin wrapper around monoxide.delete()
* @param {string|regexp|array} fields Either a single field name, regular expression or array of strings/regexps to filter by. Any key matching will be removed from the object
* @return {monoxide.monoxideDocument} This object after the fields have been removed
*/
omit: function(fields) {
var removeFields = _.castArray(fields);
traverse(this).forEach(function(v) {
if (!this.key) return; // Skip array entries
var key = this.key;
if (removeFields.some(function(filter) {
return (
(_.isString(filter) && key == filter) ||
(_.isRegExp(filter) && filter.test(key))
);
})) {
this.remove();
}
});
return this;
},
/**
* Transform a MonoxideDocument into a plain JavaScript object
* @return {Object} Plain JavaScript object with all special properties and other gunk removed
*/
toObject: function() {
var doc = this;
var newDoc = {};
_.forEach(this, function(v, k) {
if (doc.hasOwnProperty(k) && !_.startsWith(k, '$')) newDoc[k] = _.clone(v);
});
return newDoc;
},
/**
* Transform a MonoxideDocument into a Mongo object
* This function transforms all OID strings back into their Mongo equivalent
* @return {Object} Plain JavaScript object with all special properties and other gunk removed
*/
toMongoObject: function() {
var doc = this;
var outDoc = doc.toObject(); // Rely on the toObject() syntax to strip out rubbish
doc.getOIDs().forEach(function(node) {
switch (node.fkType) {
case 'objectId':
var oidLeaf = _.get(doc, node.docPath);
if (_.isUndefined(oidLeaf)) return; // Ignore undefined
if (!o.utilities.isObjectID(oidLeaf)) {
if (_.has(oidLeaf, '_id')) { // Already populated?
_.set(outDoc, node.docPath, o.utilities.objectID(oidLeaf._id));
} else { // Convert to an OID
_.set(outDoc, node.docPath, o.utilities.objectID(oidLeaf));
}
}
break;
case 'objectIdArray':
var oidLeaf = _.get(doc, node.schemaPath);
_.set(outDoc, node.schemaPath, oidLeaf.map(function(leaf) {
return o.utilities.isObjectID(leaf) ? leaf : o.utilities.objectID(leaf);
}));
break;
default:
return; // Ignore unsupported OID types
}
});
return outDoc;
},
isModified: function(path) {
var doc = this;
if (path) {
var v = _.get(doc, path);
var pathJoined = _.isArray(path) ? path.join('.') : path;
if (o.utilities.isObjectID(v)) {
if (doc.$populated[pathJoined]) { // Has been populated
// FIXME; What happens if a populated document changes
throw new Error('Changing populated document objects is not yet supported');
return false;
} else { // Has not been populated
if (doc.$originalValues[pathJoined]) { // Compare against the string value
return doc.$originalValues[pathJoined] != v.toString();
} else if (doc.$originalValues[pathJoined + '.id'] && doc.$originalValues[pathJoined + '._bsontype']) { // Known but its stored as a Mongo OID - look into its values to determine its real comparitor string
// When the lookup is a raw OID we need to pass the binary junk into the objectID THEN get its string value before we can compare it to the one we last saw when we fetched the object
return o.utilities.objectID(doc.$originalValues[pathJoined + '.id']).toString() != v.toString(); // Compare against the string value
} else {
return true; // Otherwise declare it modified
}
}
} else if (_.isObject(v)) { // If its an object (or an array) examine the $clean propertly
return !v.$clean;
} else {
return doc.$originalValues[pathJoined] != v;
}
} else {
var modified = [];
traverse(doc).map(function(v) { // NOTE - We're using traverse().map() here as traverse().forEach() actually mutates the array if we tell it not to recurse with this.remove(true) (needed to stop recursion into complex objects if the parent has been changed)
if (!this.path.length) return; // Root node
if (_.startsWith(this.key, '$') || this.key == '_id') { // Don't scan down hidden elements
return this.remove(true);
} else if (o.utilities.isObjectID(v)) { // Leaf is an object ID
if (doc.isModified(this.path)) modified.push(this.path.join('.'));
this.remove(true); // Don't scan any deeper
} else if (doc.isModified(this.path)) {
if (_.isObject(v)) this.remove(true);
modified.push(this.path.join('.'));
}
});
return modified;
}
},
/**
* Expand given paths into objects
* @param {Object|array|string} populations A single or multiple populations to perform
* @param {function} callback The callback to run on completion
* @param {boolean} [strict=false] Whether to raise errors and agressively retry if a population fails
* @return {Object} This document
*/
populate: function(populations, callback, strict) {
var doc = this;
var populations = _(populations)
.castArray()
.map(function(population) { // Mangle all populations into objects (each object should contain a path and an optional ref)
if (_.isString(population)) {
return {path: population};
} else {
return population;
}
})
.value();
var tryPopulate = function(finish, populations, strict) {
var willPopulate = 0; // Count of items that seem valid that we will try to populate
var failedPopulations = []; // Populations that we couldn't get the end-points of (probably because they are nested)
var populator = async(); // Defered async worker that will actually populate things
async()
.forEach(populations, function(nextPopulation, population) {
try {
doc.getNodesBySchemaPath(population.path, true).forEach(function(node) {
if (!population.ref) {
population.ref = _.get(model, '$mongooseModel.schema.paths.' + node.schemaPath.split('.').join('.schema.paths.') + '.options.ref');
if (!population.ref) throw new Error('Cannot determine collection to use for schemaPath ' + node.schemaPath + '! Specify this is in model with {ref: <collection>}');
}
if (_.isObject(node.node) && node.node._id) { // Object is already populated
willPopulate++; // Say we're going to resolve this anyway even though we have nothing to do - prevents an issue where the error catcher reports it as a null operation (willPopulate==0)
} else if (!node.node) {
// Node is falsy - nothing to populate here
} else {
populator.defer(function(next) {
o.internal.query({
$errNotFound: false,
$collection: population.ref,
$id: o.utilities.isObjectID(node.node) ? node.node.toString() : node.node,
}, function(err, res) {
if (err) return next(err);
_.set(doc, node.docPath, res);
doc.$populated[node.docPath] = true;
next();
});
});
willPopulate++;
}
});
nextPopulation();
} catch (e) {
if (strict) failedPopulations.push(population);
nextPopulation();
}
})
.then(function(next) {
if (willPopulate > 0) {
populator.await().end(next); // Run all population defers
} else if (strict) {
next('Unable to resolve remaining populations: ' + JSON.stringify(populations) + '. In ' + doc.$collection + '#' + doc._id);
} else {
next();
}
})
.end(function(err) {
if (err) {
callback(err);
} else if (failedPopulations.length) {
console.log('SILL MORE POPULATIONS TO RUN', failedPopulations);
setTimeout(function() {
console.log('FIXME: Defered runnable');
//tryPopulate(callback, failedPopulations);
});
} else {
callback(null, doc);
}
});
};
tryPopulate(callback, populations, strict);
return doc;
},
/**
* Retrieves all 'leaf' elements matching a schema path
* Since any segment of the path could be a nested object, array or sub-document collection this function is likely to return multiple elements
* For the nearest approximation of how this function operates think of it like performing the jQuery expression: `$('p').each(function() { ... })`
* @param {string} schemaPath The schema path to iterate down
* @param {boolean} [strict=false] Optional indicator that an error should be thrown if a path cannot be traversed
* @return {array} Array of all found leaf nodes
*/
getNodesBySchemaPath: function(schemaPath, strict) {
var doc = this;
var examineStack = [{
node: doc,
docPath: '',
schemaPath: '',
}];
var segments = schemaPath.split('.');
segments.every(function(pathSegment, pathSegmentIndex) {
return examineStack.every(function(esDoc, esDocIndex) {
if (esDoc === false) { // Skip this subdoc
return true;
} else if (_.isUndefined(esDoc.node[pathSegment]) && pathSegmentIndex == segments.length -1) {
examineStack[esDocIndex] = {
node: esDoc.node[pathSegment],
docPath: esDoc.docPath + '.' + pathSegment,
schemaPath: esDoc.schemaPath + '.' + pathSegment,
};
return true;
} else if (_.isUndefined(esDoc.node[pathSegment])) {
// If we are trying to recurse into a path segment AND we are not at the leaf of the path (as undefined leaves are ok) - raise an error
if (strict) throw new Error('Cannot traverse into path: "' + (esDoc.docPath + '.' + pathSegment).substr(1) + '" for doc ' + doc.$collection + '#' + doc._id);
examineStack[esDocIndex] = false;
return false;
} else if (_.isArray(esDoc.node[pathSegment])) { // Found an array - remove this doc and append each document we need to examine at the next stage
esDoc.node[pathSegment].forEach(function(d,i) {
// Do this in a forEach to break appart the weird DocumentArray structure we get back from Mongoose
examineStack.push({
node: d,
docPath: esDoc.docPath + '.' + pathSegment + '.' + i,
schemaPath: esDoc.schemaPath + '.' + pathSegment,
})
});
examineStack[esDocIndex] = false;
return true;
} else if (_.has(esDoc.node, pathSegment)) { // Traverse into object - replace this nodeerence with the new pointer
examineStack[esDocIndex] = {
node: esDoc.node[pathSegment],
docPath: esDoc.docPath + '.' + pathSegment,
schemaPath: esDoc.schemaPath + '.' + pathSegment,
};
return true;
}
});
});
return _(examineStack)
.filter()
.filter(function(node) {
return !! node.docPath;
})
.map(function(node) {
node.docPath = node.docPath.substr(1);
node.schemaPath = node.schemaPath.substr(1);
return node;
})
.value();
},
/**
* Return an array of all OID leaf nodes within the document
* This function combines the behaviour of monoxide.utilities.extractFKs with monoxide.monoxideDocument.getNodesBySchemaPath)
* @return {array} An array of all leaf nodes
*/
getOIDs: function() {
var doc = this;
var stack = [];
_.forEach(model.$oids, function(fkType, schemaPath) {
if (fkType.type == 'subDocument') return; // Skip sub-documents (as they are stored against the parent anyway)
stack = stack.concat(doc.getNodesBySchemaPath(schemaPath)
.map(function(node) {
node.fkType = fkType.type;
return node;
})
);
});
return stack;
},
$applySchema: true,
};
proto.delete = proto.remove;
_.extend(
proto, // INPUT: Basic prototype
setup, // Merge with the incomming prototype (should contain at least $collection)
model.$methods // Merge with model methods
);
// Create the base document
var doc = Object.create(proto);
// Setup Virtuals
Object.defineProperties(doc, model.$virtuals);
// Convert data to a simple array if its weird Mongoose fluff
if (data instanceof mongoose.Document) data = data.toObject();
_.extend(doc, data);
// Apply schema
if (doc.$applySchema) {
_.forEach(model.$mongooseModel.schema.paths, function(pathSpec, path) {
var docValue = _.get(doc, path, undefined);
if (_.isUndefined(docValue)) {
if (pathSpec.defaultValue) { // Item is blank but SHOULD have a default
_.set(doc, path, _.isFunction(pathSpec.defaultValue) ? pathSpec.defaultValue() : pathSpec.defaultValue);
} else {
_.set(doc, path, undefined);
}
}
});
}
// Sanitize data to remove all ObjectID crap
doc.getOIDs().forEach(function(node) {
if (node.fkType == 'objectId') {
var singleOid = _.get(doc, node.docPath);
if (o.utilities.isObjectID(singleOid))
_.set(doc, node.docPath, singleOid.toString());
} else if (node.fkType == 'objectIdArray') {
var oidArray = _.get(doc, node.docPath);
if (o.utilities.isObjectID(oidArray)) {
_.set(doc, node.docPath, oidArray.toString());
} else if (_.isObject(oidArray) && oidArray._id && o.utilities.isObjectID(oidArray._id)) {
// FIXME: Rather crappy sub-document flattening for now
// This needs to actually scope into the sub-object schema and flatten each ID and not just the _id element
oidArray._id = oidArray._id.toString();
}
}
});
// Break object into component parts and apply the '$clean' marker to arrays and objects
Object.defineProperty(doc, '$originalValues', {
enumerable: false,
value: {},
});
if (!setup.$dirty) {
traverse(doc).forEach(function(v) {
// If its an object (or array) glue the `$clean` property to it to detect writes
if (_.isObject(v)) {
Object.defineProperty(v, '$clean', {
enumerable: false,
value: true,
});
} else if (!_.isPlainObject(v)) { // For everything else - stash the original value in this.parent.$originalValues
doc.$originalValues[this.path.join('.')] = o.utilities.isObjectID(v) ? v.toString() : v;
}
});
}
// Apply population data
doc.getOIDs().forEach(function(node) {
doc.$populated[node.docPath] = o.utilities.isObjectID(node.docPath);
if (!setup.$dirty) doc.$originalValues[node.docPath] = _.get(doc, node.docPath);
});
return doc;
};
// }}}
// .model(name) - helper function to return a declared model {{{
/**
* Return a defined Monoxide model
* The model must have been previously defined by monoxide.schema()
* This function is identical to accessing the model directly via `monoxide.models[modelName]`
*
* @name monoxide.model
* @see monoxide.schema
*
* @param {string} model The model name (generally lowercase plurals e.g. 'users', 'widgets', 'favouriteItems' etc.)
* @returns {Object} The monoxide model of the generated schema
*/
o.model = function(model) {
return o.models[model];
};
// }}}
// .schema - Schema builder {{{
/**
* Construct and return a Mongo model
* This function creates a valid schema specificaion then returns it as if model() were called
*
* @name monoxide.schema
* @see monoxide.model
*
* @param {string} model The model name (generally lowercase plurals e.g. 'users', 'widgets', 'favouriteItems' etc.)
* @param {Object} spec The schema specification composed of a hierarhical object of keys with each value being the specification of that field
* @returns {Object} The monoxide model of the generated schema
* @emits modelCreate Called as (model, instance) when a model gets created
*
* @example
* // Example schema for a widget
* var Widgets = monoxide.schema('widgets', {
* name: String,
* content: String,
* status: {type: String, enum: ['active', 'deleted'], default: 'active'},
* color: {type: String, enum: ['red', 'green', 'blue'], default: 'blue', index: true},
* });
*
* @example
* // Example schema for a user
* var Users = monoxide.schema('users', {
* name: String,
* role: {type: 'string', enum: ['user', 'admin'], default: 'user'},
* favourite: {type: 'pointer', ref: 'widgets'},
* items: [{type: 'pointer', ref: 'widgets'}],
* settings: {type: 'any'},
* mostPurchased: [
* {
* number: {type: 'number', default: 0},
* item: {type: 'pointer', ref: 'widgets'},
* }
* ],
* });
*/
o.schema = function(model, spec) {
if (!argy.isType(model, 'string') || !argy.isType(spec, 'object')) throw new Error('Schema construction requires a model ID + schema object');
var schema = new mongoose.Schema(_.deepMapValues(spec, function(value, path) {
// Rewrite .type leafs {{{
if (_.endsWith(path, '.type')) { // Ignore not type rewrites
if (!_.isString(value)) return value; // Only rewrite string values
switch (value.toLowerCase()) {
case 'oid':
case 'pointer':
case 'objectid':
return mongoose.Schema.ObjectId;
case 'string':
return mongoose.Schema.Types.String;
case 'number':
return mongoose.Schema.Types.Number;
case 'boolean':
case 'bool':
return mongoose.Schema.Types.Boolean;
case 'array':
return mongoose.Schema.Types.Array;
case 'date':
return mongoose.Schema.Types.Date;
case 'object':
case 'mixed':
case 'any':
return mongoose.Schema.Types.Mixed;
case 'buffer':
return mongoose.Schema.Types.Buffer;
default:
throw new Error('Unknown Monoxide data type: ' + value.toLowerCase());
}
// }}}
// Rewrite .ref leafs {{{
} else if (_.endsWith(path, '.ref')) {
if (!_.isString(value)) return value; // Leave complex objects alone
return value.toLowerCase();
// }}}
// Leave everything else unaltered {{{
} else { // Do nothing
return value;
}
// }}}
}));
// Add to model storage
o.models[model] = new o.monoxideModel({
$collection: model,
$mongoose: mongoose.model(model.toLowerCase(), schema), // FIXME: When we implement our own schema def system we can remove the toLowerCase() component that Mongoose insists on using. We can also remove all of the other toLowerCase() calls when we're trying to find the Mongoose schema
$schema: schema.obj,
});
o.emit('modelCreate', model, o.models[model]);
return o.models[model];
};
// }}}
// .aggregate([q], callback) {{{
/**
* Perform a direct aggregation and return the result
*
* @name monoxide.aggregate
* @memberof monoxide
*
* @param {Object} q The object to process
* @param {string} q.$collection The collection / model to query
* @param {boolean} [q.$slurp=true] Attempt to read all results into an array rather than return a cursor
* @param {array} q.$stages The aggregation stages array
* @param {Object} [q.$stages.$project] Fields to be supplied in the aggregation (in the form `{field: true}`)
* @param {boolean} [q.$stages.$project._id=false] If true surpress the output of the `_id` field
* @param {Object} [q.$stages.$match] Specify a filter on fields (in the form `{field: CRITERIA}`)
* @param {Object} [q.$stages.$redract]
* @param {Object} [q.$stages.$limit]
* @param {Object} [q.$stages.$skip]
* @param {Object} [q.$stages.$unwind]
* @param {Object} [q.$stages.$group]
* @param {Object} [q.$stages.$sample]
* @param {Object} [q.$stages.$sort] Specify an object of fields to sort by (in the form `{field: 1|-1}` where 1 is ascending and -1 is decending sort order)
* @param {Object} [q.$stages.$geoNear]
* @param {Object} [q.$stages.$lookup]
* @param {Object} [q.$stages.$out]
* @param {Object} [q.$stages.$indexStats]
*
* @param {function} callback(err, result) the callback to call on completion or error
*
* @return {Object} This chainable object
*/
o.aggregate = argy('string|object function', function MonoxideAggregate(q, callback) {
if (argy.isType(q, 'string')) q = {$collection: q};
async()
// Sanity checks {{{
.then(function(next) {
if (!q || _.isEmpty(q)) return next('No query given for save operation');
if (!q.$stages || !_.isArray(q.$stages)) return next('$stages must be specified as an array');
if (!q.$collection) return next('$collection must be specified for save operation');
if (!o.models[q.$collection]) return next('Model not initalized');
next();
})
// }}}
// Execute and capture return {{{
.then('result', function(next) {
o.models[q.$collection].$mongoModel.aggregate(q.$stages, next);
})
// }}}
// Slurp the cursor? {{{
.then('result', function(next) {
if (q.$slurp || _.isUndefined(q.$slurp)) {
o.utilities.slurpCursor(this.result, next);
} else {
next(null, this.result);
}
})
// }}}
// End {{{
.end(function(err) {
if (err) {
return callback(err);
} else {
callback(null, this.result);
}
});
// }}}
return o;
});
// }}}
// .use([plugins...], [callback]) {{{
/**
* Run a third party plugin against the entire Monoxide structure
* Really this function just registers all given modules against monoxide then fires the callback when done
* Each plugin is called as `(callback, monoxide)`
* @param {function|string|array} plugins The plugin(s) to run. Each function is run as (model, callback), strings are assumed to be file paths to JS files if they contain at least one '/' or `.` otherwise they are loaded from the `plugins` directory
* @param {function} [callback] Optional callback to fire when all plugin have registered
* @return {monoxide.monoxide} The chainable object
*/
o.use = function(plugins, callback) {
if (!plugins) return callback(); // Do nothing if given falsy
async()
.forEach(_.castArray(plugins), function(next, plugin) {
if (o.used.some(i => i === plugin)) {
debug('Plugin already loaded, ignoring');
next();
} else if (_.isString(plugin)) {
var pluginModule = /[\/\.]/.test(plugin) // Contains at least one slash or dot?
? require(plugin)
: require(__dirname + '/plugins/' + plugin)
pluginModule.call(o, next, o);
o.used.push(pluginModule);
} else if (_.isFunction(plugin)) {
plugin.call(o, next, o);
o.used.push(plugin);
} else {
next('Unsupported plugin format');
}
})
.end(callback);
return o;
};
/**
* Storage for modules we have already loaded
* @var {Array <function>} All plugins (as funtions) we have previously loaded
*/
o.used = [];
// }}}
// .hook(hookName, callback) {{{
/**
* Holder for global hooks
* @var {array <function>}
*/
o.$hooks = {};
/**
* Attach a hook to a global event
* A hook is exactly the same as a eventEmitter.on() event but must return a callback
* Multiple hooks can be attached and all will be called in parallel on certain events such as 'save'
* All hooks must return non-errors to proceed with the operation
* @param {string} eventName The event ID to hook against
* @param {function} callback The callback to run when hooked, NOTE: Any falsy callbacks are ignored
* @return {monoxide} The chainable monoxide
*/
o.hook = function(eventName, callback) {
if (!callback) return mm; // Ignore flasy callbacks
if (!o.$hooks[eventName]) o.$hooks[eventName] = [];
o.$hooks[eventName].push(callback);
return o;
};
/**
* Execute global level hooks
* NOTE: This will only fire hooks attached via monoxide.hook() and not individual model hooks
* NOTE: Hooks are always fired with the callback as the first argument
* @param {string} name The name of the hook to invoke
* @param {function} callback The callback to invoke on success
* @param {...*} parameters Any other parameters to be passed to each hook
* @return {monoxide} The chainable monoxide
*/
o.fire = function(name, callback) {
if (o.$hooks[name] && o.$hooks[name].length) { // There is at least one event handler attached
var eventArgs = _.values(arguments);
eventArgs.splice(1, 1); // Remove the 'callback' arg as events cant respond to it anyway
o.emit.apply(o, eventArgs);
} else {
return callback();
}
// Calculate the args array we will pass to each hook
var hookArgs = _.values(arguments);
hookArgs.shift(); // We will set args[0] to the callback in each case anyway so we only need to shift 1
async()
// Fire hooks attached to this model + global hooks {{{
.forEach(
o.$hooks[name]
.filter(f => !!f) // Actually is a function?
, function(next, hookFunc) {
hookArgs[0] = next;
hookFunc.apply(o, hookArgs);
})
// }}}
.end(callback);
return o;
};
/**
* Similar to fire() expect that execution is immediate
* This should only be used by sync functions that require immediate action such as object mutators
* NOTE: Because of the nature of this function a callback CANNOT be accepted when finished - the function is assumed done when it returns
* @param {string} name The name of the hook to invoke
* @param {...*} parameters Any other parameters to be passed to each hook
* @return {monoxide} The chainable monoxide
* @see fire()
*/
o.fireImmediate = function(name, callback) {
if (!o.$hooks[name] || !o.$hooks[name].length) return o; // No hooks to run anyway
for (var i of o.$hooks[name]) {
let hookArgs = _.values(arguments);
hookArgs.shift();
i.apply(o, hookArgs);
}
return o;
};
// }}}
// .utilities structure {{{
o.utilities = {};
// .utilities.extractFKs(schema, prefix, base) {{{
/**
* Extract all FKs in dotted path notation from a Mongoose model
*
* @name monoxide.utilities.extractFKs
*
* @param {Object} schema The schema object to examine (usually monoxide.models[model].$mongooseModel.schema)
* @param {string} prefix existing Path prefix to use (internal use only)
* @param {Object} base Base object to append flat paths to (internal use only)
* @return {Object} A dictionary of foreign keys for the schema (each key will be the info of the object)
*/
o.utilities.extractFKs = function(schema, prefix, base) {
var FKs = {};
if (!prefix) prefix = '';
if (!base) base = FKs;
_.forEach(schema.paths, function(path, id) {
if (id == 'id' || id == '_id') { // Main document ID
FKs[prefix + id] = {type: 'objectId'};
} else if (path.instance && path.instance == 'ObjectID') {
FKs[prefix + id] = {type: 'objectId'};
} else if (path.caster && path.caster.instance == 'ObjectID') { // Array of ObjectIDs
FKs[prefix + id] = {type: 'objectIdArray'};
} else if (path.schema) {
FKs[prefix + id] = {type: 'subDocument'};
_.forEach(o.utilities.extractFKs(path.schema, prefix + id + '.', base), function(val, key) {
base[key] = val;
});
}
});
return FKs;
}
// }}}
// .utilities.objectID(string) {{{
/**
* Construct and return a MongoDB-Core compatible ObjectID object
* This is mainly used within functions that need to convert a string ID into an object
* This has one additional check which will return undefined if the value passed in is falsy
* @name monoxide.utilities.objectID
* @param {string} str The string to convert into an ObjectID
* @return {Object} A MongoDB-Core compatible ObjectID object instance
*/
o.utilities.objectID = function(str) {
if (!str) return undefined;
if (_.isObject(str) && str._id) return new mongoose.Types.ObjectId(str._id); // Is a sub-document - extract its _id and use that
return new mongoose.Types.ObjectId(str);
};
// }}}
// .utilities.isObjectID(string) {{{
/**
* Return if the input is a valid MongoDB-Core compatible ObjectID object
* This is mainly used within functions that need to check that a given variable is a Mongo OID
* @name monoxide.utilities.isObjectID
* @param {mixed} subject The item to examine
* @return {boolean} Whether the subject is a MongoDB-Core compatible ObjectID object instance
*/
o.utilities.isObjectID = function(subject) {
return (subject instanceof mongoose.Types.ObjectId);
};
/**
* Alias of isObjectID
* @see monoxide.utilities.isObjectId
*/
o.utilities.isObjectId = o.utilities.isObjectID;
// }}}
// .utilities.runMiddleware(middleware) {{{
/**
* Run optional middleware
*
* Middleware can be:
* - A function(req, res, next)
* - An array of functions(req, res, next) - Functions will be called in sequence, all functions must call the next method
* - A string - If specified (and `obj` is also specified) the middleware to use will be looked up as a key of the object. This is useful if you need to invoke similar methods on different entry points (e.g. monoxide.express.middleware('widgets', {save: function(req, res, next) { // Check something // }, create: 'save'}) - where the `create` method invokes the same middleware as `save)
*
* @param {null|function|array} middleware The optional middleware to run this can be a function, an array of functions or a string
* @param {function} callback The callback to invoke when completed. This may not be called
* @param {object} obj The parent object to look up inherited functions from (if middleware is a string)
*
* @example
* // Set up a Monoxide express middleware to check user logins on each save or create operaion
* app.use('/api/widgets/:id?', monoxide.express.middleware('widgets', {
* create: function(req, res, next) {
* if (req.user && req.user._id) {
* next();
* } else {
* res.status(403).send('You are not logged in').end();
* }
* },
* save: 'create', // Point to the same checks as the `create` middleware
* }));
*/
o.utilities.runMiddleware = function(req, res, middleware, callback, obj) {
var thisContext = this;
var runnable; // The middleware ARRAY to run
if (_.isBoolean(middleware) && !middleware) { // Boolean=false - deny!
res.status(403).end();
} else if (_.isUndefined(middleware) || _.isNull(middleware)) { // Nothing to do anyway
return callback();
} else if (_.isFunction(middleware)) {
runnable = [middleware];
} else if (_.isArray(middleware)) {
runnable = middleware;
} else if (_.isString(middleware) && _.has(obj, middleware)) {
return o.utilities.runMiddleware(req, res, _.get(obj, middleware), callback, obj); // Defer to the pointer
}
async()
.limit(1)
.forEach(runnable, function(nextMiddleware, middlewareFunc, index) {
middlewareFunc.apply(thisContext, [req, res, nextMiddleware]);
})
.end(function(err) {
if (err) {
o.express.sendError(res, 403, err);
} else {
callback();
}
});
};
// }}}
// .utilities.diff(originalDoc, newDoc) {{{
/**
* Diff two monoxide.monoxideDocument objects and return the changes as an object
* This change object is suitable for passing directly into monoxide.save()
* While originally intended only for comparing monoxide.monoxideDocument objects this function can be used to compare any type of object
* NOTE: If you are comparing MonoxideDocuments call `.toObject()` before passing the object in to strip it of its noise
*
* @name monoxide.utilities.diff
* @see monoxide.save
* @see monoxide.update
*
* @param {Object} originalDoc The original source document to compare to
* @param {Object} newDoc The new document with possible changes
* @return {Object} The patch object
*
* @example
* // Get the patch of two documents
* monoxide.query({$collection: 'widgets', $id: '123'}, function(err, res) {
* var docA = res.toObject();
* var docB = res.toObject();
*
* // Change some fields
* docB.title = 'Hello world';
*
* var patch = monoxide.utilities.diff(docA, docB);
* // => should only return {title: 'Hello World'}
* });
*/
o.utilities.diff = function(originalDoc, newDoc) {
var patch = {};
deepDiff.observableDiff(originalDoc, newDoc, function(diff) {
if (diff.kind == 'N' || diff.kind == 'E') {
_.set(patch, diff.path, diff.rhs);
} else if (diff.kind == 'A') { // Array alterations
// deepDiff will only apply changes onto newDoc - we can't just apply them to the empty patch object
// so we let deepDiff do its thing then copy the new structure across into patch
deepDiff.applyChange(originalDoc, newDoc, diff);
_.set(patch, diff.path, _.get(newDoc, diff.path));
}
});
return patch;
};
// }}}
// .utilities.rewriteQuery(query, settings) {{{
/**
* Returns a rewritten version of an incomming query that obeys various rules
* This usually accepts req.query as a parameter and a complex settings object as a secondary
* This function is used internally by middleware functions to clean up the incomming query
*
* @name monoxide.utilities.rewriteQuery
* @see monoxide.middleware
*
* @param {Object} query The user-provided query object
* @param {Object} settings The settings object to apply (see middleware functions)
* @return {Object} The rewritten query object
*/
o.utilities.rewriteQuery = function(query, settings) {
return _(query)
.mapKeys(function(val, key) {
if (_.has(settings.queryRemaps, key)) return settings.queryRemaps[key];
return key;
})
.mapValues(function(val, key) {
if (settings.queryAllowed && settings.queryAllowed[key]) {
var allowed = settings.queryAllowed[key];
if (!_.isString(val) && !allowed.scalar) {
return null;
} else if (allowed.boolean) {
return (val == 'true' || val == '1');
} else if (_.isString(val) && allowed.scalarCSV) {
return val.split(/\s*,\s*/);
} else if (_.isArray(val) && allowed.array) {
return val;
} else if (_.isString(val) && allowed.number) {
return parseInt(val);
} else {
return val;
}
}
return val;
})
.value();
};
// }}}
// .utilities.slurpCursor(cursor, cb) {{{
/**
* Asyncronously calls a cursor until it is exhausted
*
* @name monoxide.utilities.slurpCursor
*
* @param {Cursor} cursor A mongo compatible cursor object
* @param {function} cb The callback to call as (err, result) when complete
*/
o.utilities.slurpCursor = function(cursor, cb) {
var res = [];
var cursorReady = function(err, result) {
if (result === null) { // Cursor is exhausted
cb(null, res);
} else {
res.push(result);
setTimeout(function() { // Queue fetcher in timeout so we don't stack overflow
cursor.next(cursorReady);
});
}
};
cursor.next(cursorReady);
};
// }}}
// }}}
// Create internals mapping {{{
o.internal = o; // Mapping for the original function handlers (e.g. get() before any mutations)
// }}}
return o;
}
util.inherits(Monoxide, events.EventEmitter);
module.exports = new Monoxide();
| BUGFIX: Better connection handling
| index.js | BUGFIX: Better connection handling | <ide><path>ndex.js
<ide> mongoose.connect(uri, {
<ide> promiseLibrary: global.Promise,
<ide> useNewUrlParser: true,
<add> }, function(err) {
<add> if (err) {
<add> if (_.isFunction(callback)) callback(err);
<add> } else {
<add> o.connection = mongoose.connection;
<add> if (_.isFunction(callback)) callback();
<add> }
<ide> })
<del> .then(function() {
<del> o.connection = mongoose.connection;
<del> if (callback) callback();
<del> })
<del> .catch(e => callback(e))
<ide>
<ide> return o;
<ide> }; |
|
Java | apache-2.0 | 00a75d7c99e87f543a4e0a4390732bb2eaa286fe | 0 | chrislusf/seaweedfs,chrislusf/seaweedfs,chrislusf/seaweedfs,chrislusf/seaweedfs | package seaweedfs.client;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.client.entity.GzipDecompressingEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.*;
public class SeaweedRead {
private static final Logger LOG = LoggerFactory.getLogger(SeaweedRead.class);
static ChunkCache chunkCache = new ChunkCache(4);
// returns bytesRead
public static long read(FilerGrpcClient filerGrpcClient, List<VisibleInterval> visibleIntervals,
final long position, final byte[] buffer, final int bufferOffset,
final int bufferLength, final long fileSize) throws IOException {
List<ChunkView> chunkViews = viewFromVisibles(visibleIntervals, position, bufferLength);
FilerProto.LookupVolumeRequest.Builder lookupRequest = FilerProto.LookupVolumeRequest.newBuilder();
for (ChunkView chunkView : chunkViews) {
String vid = parseVolumeId(chunkView.fileId);
lookupRequest.addVolumeIds(vid);
}
FilerProto.LookupVolumeResponse lookupResponse = filerGrpcClient
.getBlockingStub().lookupVolume(lookupRequest.build());
Map<String, FilerProto.Locations> vid2Locations = lookupResponse.getLocationsMapMap();
//TODO parallel this
long readCount = 0;
long startOffset = position;
for (ChunkView chunkView : chunkViews) {
if (startOffset < chunkView.logicOffset) {
long gap = chunkView.logicOffset - startOffset;
LOG.debug("zero [{},{})", startOffset, startOffset + gap);
readCount += gap;
startOffset += gap;
}
FilerProto.Locations locations = vid2Locations.get(parseVolumeId(chunkView.fileId));
if (locations == null || locations.getLocationsCount() == 0) {
LOG.error("failed to locate {}", chunkView.fileId);
// log here!
return 0;
}
int len = readChunkView(startOffset, buffer, bufferOffset + readCount, chunkView, locations);
LOG.debug("read [{},{}) {} size {}", startOffset, startOffset + len, chunkView.fileId, chunkView.size);
readCount += len;
startOffset += len;
}
long limit = Math.min(bufferOffset + bufferLength, fileSize);
if (startOffset < limit) {
long gap = limit - startOffset;
LOG.debug("zero2 [{},{})", startOffset, startOffset + gap);
readCount += gap;
startOffset += gap;
}
return readCount;
}
private static int readChunkView(long startOffset, byte[] buffer, long bufOffset, ChunkView chunkView, FilerProto.Locations locations) throws IOException {
byte[] chunkData = chunkCache.getChunk(chunkView.fileId);
if (chunkData == null) {
chunkData = doFetchFullChunkData(chunkView, locations);
chunkCache.setChunk(chunkView.fileId, chunkData);
}
int len = (int) chunkView.size;
LOG.debug("readChunkView fid:{} chunkData.length:{} chunkView[{};{}) buf[{},{})/{} startOffset:{}",
chunkView.fileId, chunkData.length, chunkView.offset, chunkView.offset+chunkView.size, bufOffset, bufOffset+len, buffer.length, startOffset);
System.arraycopy(chunkData, (int) (startOffset - chunkView.logicOffset + chunkView.offset), buffer, (int)bufOffset, len);
return len;
}
public static byte[] doFetchFullChunkData(ChunkView chunkView, FilerProto.Locations locations) throws IOException {
byte[] data = null;
IOException lastException = null;
for (long waitTime = 1000L; waitTime < 10 * 1000; waitTime += waitTime / 2) {
for (FilerProto.Location location : locations.getLocationsList()) {
String url = String.format("http://%s/%s", location.getUrl(), chunkView.fileId);
try {
data = doFetchOneFullChunkData(chunkView, url);
break;
} catch (IOException ioe) {
LOG.debug("doFetchFullChunkData {} :{}", url, ioe);
lastException = ioe;
}
}
if (data != null) {
break;
}
try {
Thread.sleep(waitTime);
} catch (InterruptedException e) {
}
}
if (data == null) {
throw lastException;
}
LOG.debug("doFetchFullChunkData fid:{} chunkData.length:{}", chunkView.fileId, data.length);
return data;
}
public static byte[] doFetchOneFullChunkData(ChunkView chunkView, String url) throws IOException {
HttpGet request = new HttpGet(url);
request.setHeader(HttpHeaders.ACCEPT_ENCODING, "gzip");
byte[] data = null;
CloseableHttpResponse response = SeaweedUtil.getClosableHttpClient().execute(request);
try {
HttpEntity entity = response.getEntity();
Header contentEncodingHeader = entity.getContentEncoding();
if (contentEncodingHeader != null) {
HeaderElement[] encodings = contentEncodingHeader.getElements();
for (int i = 0; i < encodings.length; i++) {
if (encodings[i].getName().equalsIgnoreCase("gzip")) {
entity = new GzipDecompressingEntity(entity);
break;
}
}
}
data = EntityUtils.toByteArray(entity);
EntityUtils.consume(entity);
} finally {
response.close();
request.releaseConnection();
}
if (chunkView.cipherKey != null && chunkView.cipherKey.length != 0) {
try {
data = SeaweedCipher.decrypt(data, chunkView.cipherKey);
} catch (Exception e) {
throw new IOException("fail to decrypt", e);
}
}
if (chunkView.isCompressed) {
data = Gzip.decompress(data);
}
LOG.debug("doFetchOneFullChunkData url:{} chunkData.length:{}", url, data.length);
return data;
}
protected static List<ChunkView> viewFromVisibles(List<VisibleInterval> visibleIntervals, long offset, long size) {
List<ChunkView> views = new ArrayList<>();
long stop = offset + size;
for (VisibleInterval chunk : visibleIntervals) {
long chunkStart = Math.max(offset, chunk.start);
long chunkStop = Math.min(stop, chunk.stop);
if (chunkStart < chunkStop) {
boolean isFullChunk = chunk.isFullChunk && chunk.start == offset && chunk.stop <= stop;
views.add(new ChunkView(
chunk.fileId,
chunkStart - chunk.start + chunk.chunkOffset,
chunkStop - chunkStart,
chunkStart,
isFullChunk,
chunk.cipherKey,
chunk.isCompressed
));
}
}
return views;
}
public static List<VisibleInterval> nonOverlappingVisibleIntervals(
final FilerGrpcClient filerGrpcClient, List<FilerProto.FileChunk> chunkList) throws IOException {
chunkList = FileChunkManifest.resolveChunkManifest(filerGrpcClient, chunkList);
FilerProto.FileChunk[] chunks = chunkList.toArray(new FilerProto.FileChunk[0]);
Arrays.sort(chunks, new Comparator<FilerProto.FileChunk>() {
@Override
public int compare(FilerProto.FileChunk a, FilerProto.FileChunk b) {
// if just a.getMtime() - b.getMtime(), it will overflow!
if (a.getMtime() < b.getMtime()) {
return -1;
} else if (a.getMtime() > b.getMtime()) {
return 1;
}
return 0;
}
});
List<VisibleInterval> visibles = new ArrayList<>();
for (FilerProto.FileChunk chunk : chunks) {
List<VisibleInterval> newVisibles = new ArrayList<>();
visibles = mergeIntoVisibles(visibles, newVisibles, chunk);
}
return visibles;
}
private static List<VisibleInterval> mergeIntoVisibles(List<VisibleInterval> visibles,
List<VisibleInterval> newVisibles,
FilerProto.FileChunk chunk) {
VisibleInterval newV = new VisibleInterval(
chunk.getOffset(),
chunk.getOffset() + chunk.getSize(),
chunk.getFileId(),
chunk.getMtime(),
0,
true,
chunk.getCipherKey().toByteArray(),
chunk.getIsCompressed()
);
// easy cases to speed up
if (visibles.size() == 0) {
visibles.add(newV);
return visibles;
}
if (visibles.get(visibles.size() - 1).stop <= chunk.getOffset()) {
visibles.add(newV);
return visibles;
}
for (VisibleInterval v : visibles) {
if (v.start < chunk.getOffset() && chunk.getOffset() < v.stop) {
newVisibles.add(new VisibleInterval(
v.start,
chunk.getOffset(),
v.fileId,
v.modifiedTime,
v.chunkOffset,
false,
v.cipherKey,
v.isCompressed
));
}
long chunkStop = chunk.getOffset() + chunk.getSize();
if (v.start < chunkStop && chunkStop < v.stop) {
newVisibles.add(new VisibleInterval(
chunkStop,
v.stop,
v.fileId,
v.modifiedTime,
v.chunkOffset + (chunkStop - v.start),
false,
v.cipherKey,
v.isCompressed
));
}
if (chunkStop <= v.start || v.stop <= chunk.getOffset()) {
newVisibles.add(v);
}
}
newVisibles.add(newV);
// keep everything sorted
for (int i = newVisibles.size() - 1; i >= 0; i--) {
if (i > 0 && newV.start < newVisibles.get(i - 1).start) {
newVisibles.set(i, newVisibles.get(i - 1));
} else {
newVisibles.set(i, newV);
break;
}
}
return newVisibles;
}
public static String parseVolumeId(String fileId) {
int commaIndex = fileId.lastIndexOf(',');
if (commaIndex > 0) {
return fileId.substring(0, commaIndex);
}
return fileId;
}
public static long fileSize(FilerProto.Entry entry) {
return Math.max(totalSize(entry.getChunksList()), entry.getAttributes().getFileSize());
}
public static long totalSize(List<FilerProto.FileChunk> chunksList) {
long size = 0;
for (FilerProto.FileChunk chunk : chunksList) {
long t = chunk.getOffset() + chunk.getSize();
if (size < t) {
size = t;
}
}
return size;
}
public static class VisibleInterval {
public final long start;
public final long stop;
public final long modifiedTime;
public final String fileId;
public final long chunkOffset;
public final boolean isFullChunk;
public final byte[] cipherKey;
public final boolean isCompressed;
public VisibleInterval(long start, long stop, String fileId, long modifiedTime, long chunkOffset, boolean isFullChunk, byte[] cipherKey, boolean isCompressed) {
this.start = start;
this.stop = stop;
this.modifiedTime = modifiedTime;
this.fileId = fileId;
this.chunkOffset = chunkOffset;
this.isFullChunk = isFullChunk;
this.cipherKey = cipherKey;
this.isCompressed = isCompressed;
}
@Override
public String toString() {
return "VisibleInterval{" +
"start=" + start +
", stop=" + stop +
", modifiedTime=" + modifiedTime +
", fileId='" + fileId + '\'' +
", isFullChunk=" + isFullChunk +
", cipherKey=" + Arrays.toString(cipherKey) +
", isCompressed=" + isCompressed +
'}';
}
}
public static class ChunkView {
public final String fileId;
public final long offset;
public final long size;
public final long logicOffset;
public final boolean isFullChunk;
public final byte[] cipherKey;
public final boolean isCompressed;
public ChunkView(String fileId, long offset, long size, long logicOffset, boolean isFullChunk, byte[] cipherKey, boolean isCompressed) {
this.fileId = fileId;
this.offset = offset;
this.size = size;
this.logicOffset = logicOffset;
this.isFullChunk = isFullChunk;
this.cipherKey = cipherKey;
this.isCompressed = isCompressed;
}
@Override
public String toString() {
return "ChunkView{" +
"fileId='" + fileId + '\'' +
", offset=" + offset +
", size=" + size +
", logicOffset=" + logicOffset +
", isFullChunk=" + isFullChunk +
", cipherKey=" + Arrays.toString(cipherKey) +
", isCompressed=" + isCompressed +
'}';
}
}
}
| other/java/client/src/main/java/seaweedfs/client/SeaweedRead.java | package seaweedfs.client;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.client.entity.GzipDecompressingEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.*;
public class SeaweedRead {
private static final Logger LOG = LoggerFactory.getLogger(SeaweedRead.class);
static ChunkCache chunkCache = new ChunkCache(4);
// returns bytesRead
public static long read(FilerGrpcClient filerGrpcClient, List<VisibleInterval> visibleIntervals,
final long position, final byte[] buffer, final int bufferOffset,
final int bufferLength, final long fileSize) throws IOException {
List<ChunkView> chunkViews = viewFromVisibles(visibleIntervals, position, bufferLength);
FilerProto.LookupVolumeRequest.Builder lookupRequest = FilerProto.LookupVolumeRequest.newBuilder();
for (ChunkView chunkView : chunkViews) {
String vid = parseVolumeId(chunkView.fileId);
lookupRequest.addVolumeIds(vid);
}
FilerProto.LookupVolumeResponse lookupResponse = filerGrpcClient
.getBlockingStub().lookupVolume(lookupRequest.build());
Map<String, FilerProto.Locations> vid2Locations = lookupResponse.getLocationsMapMap();
//TODO parallel this
long readCount = 0;
int startOffset = bufferOffset;
for (ChunkView chunkView : chunkViews) {
if (startOffset < chunkView.logicOffset) {
long gap = chunkView.logicOffset - startOffset;
LOG.debug("zero [{},{})", startOffset, startOffset + gap);
readCount += gap;
startOffset += gap;
}
FilerProto.Locations locations = vid2Locations.get(parseVolumeId(chunkView.fileId));
if (locations == null || locations.getLocationsCount() == 0) {
LOG.error("failed to locate {}", chunkView.fileId);
// log here!
return 0;
}
int len = readChunkView(position, buffer, startOffset, chunkView, locations);
LOG.debug("read [{},{}) {} size {}", startOffset, startOffset + len, chunkView.fileId, chunkView.size);
readCount += len;
startOffset += len;
}
long limit = Math.min(bufferLength, fileSize);
if (startOffset < limit) {
long gap = limit - startOffset;
LOG.debug("zero2 [{},{})", startOffset, startOffset + gap);
readCount += gap;
startOffset += gap;
}
return readCount;
}
private static int readChunkView(long position, byte[] buffer, int startOffset, ChunkView chunkView, FilerProto.Locations locations) throws IOException {
byte[] chunkData = chunkCache.getChunk(chunkView.fileId);
if (chunkData == null) {
chunkData = doFetchFullChunkData(chunkView, locations);
chunkCache.setChunk(chunkView.fileId, chunkData);
}
int len = (int) chunkView.size;
LOG.debug("readChunkView fid:{} chunkData.length:{} chunkView.offset:{} buffer.length:{} startOffset:{} len:{}",
chunkView.fileId, chunkData.length, chunkView.offset, buffer.length, startOffset, len);
System.arraycopy(chunkData, startOffset - (int) (chunkView.logicOffset - chunkView.offset), buffer, startOffset, len);
return len;
}
public static byte[] doFetchFullChunkData(ChunkView chunkView, FilerProto.Locations locations) throws IOException {
byte[] data = null;
for (long waitTime = 230L; waitTime < 20 * 1000; waitTime += waitTime / 2) {
for (FilerProto.Location location : locations.getLocationsList()) {
String url = String.format("http://%s/%s", location.getUrl(), chunkView.fileId);
try {
data = doFetchOneFullChunkData(chunkView, url);
break;
} catch (IOException ioe) {
LOG.debug("doFetchFullChunkData {} :{}", url, ioe);
}
}
if (data != null) {
break;
}
try {
Thread.sleep(waitTime);
} catch (InterruptedException e) {
}
}
LOG.debug("doFetchFullChunkData fid:{} chunkData.length:{}", chunkView.fileId, data.length);
return data;
}
public static byte[] doFetchOneFullChunkData(ChunkView chunkView, String url) throws IOException {
HttpGet request = new HttpGet(url);
request.setHeader(HttpHeaders.ACCEPT_ENCODING, "gzip");
byte[] data = null;
CloseableHttpResponse response = SeaweedUtil.getClosableHttpClient().execute(request);
try {
HttpEntity entity = response.getEntity();
Header contentEncodingHeader = entity.getContentEncoding();
if (contentEncodingHeader != null) {
HeaderElement[] encodings = contentEncodingHeader.getElements();
for (int i = 0; i < encodings.length; i++) {
if (encodings[i].getName().equalsIgnoreCase("gzip")) {
entity = new GzipDecompressingEntity(entity);
break;
}
}
}
data = EntityUtils.toByteArray(entity);
EntityUtils.consume(entity);
} finally {
response.close();
request.releaseConnection();
}
if (chunkView.cipherKey != null && chunkView.cipherKey.length != 0) {
try {
data = SeaweedCipher.decrypt(data, chunkView.cipherKey);
} catch (Exception e) {
throw new IOException("fail to decrypt", e);
}
}
if (chunkView.isCompressed) {
data = Gzip.decompress(data);
}
LOG.debug("doFetchOneFullChunkData url:{} chunkData.length:{}", url, data.length);
return data;
}
protected static List<ChunkView> viewFromVisibles(List<VisibleInterval> visibleIntervals, long offset, long size) {
List<ChunkView> views = new ArrayList<>();
long stop = offset + size;
for (VisibleInterval chunk : visibleIntervals) {
long chunkStart = Math.max(offset, chunk.start);
long chunkStop = Math.min(stop, chunk.stop);
if (chunkStart < chunkStop) {
boolean isFullChunk = chunk.isFullChunk && chunk.start == offset && chunk.stop <= stop;
views.add(new ChunkView(
chunk.fileId,
chunkStart - chunk.start + chunk.chunkOffset,
chunkStop - chunkStart,
chunkStart,
isFullChunk,
chunk.cipherKey,
chunk.isCompressed
));
}
}
return views;
}
public static List<VisibleInterval> nonOverlappingVisibleIntervals(
final FilerGrpcClient filerGrpcClient, List<FilerProto.FileChunk> chunkList) throws IOException {
chunkList = FileChunkManifest.resolveChunkManifest(filerGrpcClient, chunkList);
FilerProto.FileChunk[] chunks = chunkList.toArray(new FilerProto.FileChunk[0]);
Arrays.sort(chunks, new Comparator<FilerProto.FileChunk>() {
@Override
public int compare(FilerProto.FileChunk a, FilerProto.FileChunk b) {
// if just a.getMtime() - b.getMtime(), it will overflow!
if (a.getMtime() < b.getMtime()) {
return -1;
} else if (a.getMtime() > b.getMtime()) {
return 1;
}
return 0;
}
});
List<VisibleInterval> visibles = new ArrayList<>();
for (FilerProto.FileChunk chunk : chunks) {
List<VisibleInterval> newVisibles = new ArrayList<>();
visibles = mergeIntoVisibles(visibles, newVisibles, chunk);
}
return visibles;
}
private static List<VisibleInterval> mergeIntoVisibles(List<VisibleInterval> visibles,
List<VisibleInterval> newVisibles,
FilerProto.FileChunk chunk) {
VisibleInterval newV = new VisibleInterval(
chunk.getOffset(),
chunk.getOffset() + chunk.getSize(),
chunk.getFileId(),
chunk.getMtime(),
0,
true,
chunk.getCipherKey().toByteArray(),
chunk.getIsCompressed()
);
// easy cases to speed up
if (visibles.size() == 0) {
visibles.add(newV);
return visibles;
}
if (visibles.get(visibles.size() - 1).stop <= chunk.getOffset()) {
visibles.add(newV);
return visibles;
}
for (VisibleInterval v : visibles) {
if (v.start < chunk.getOffset() && chunk.getOffset() < v.stop) {
newVisibles.add(new VisibleInterval(
v.start,
chunk.getOffset(),
v.fileId,
v.modifiedTime,
v.chunkOffset,
false,
v.cipherKey,
v.isCompressed
));
}
long chunkStop = chunk.getOffset() + chunk.getSize();
if (v.start < chunkStop && chunkStop < v.stop) {
newVisibles.add(new VisibleInterval(
chunkStop,
v.stop,
v.fileId,
v.modifiedTime,
v.chunkOffset + (chunkStop - v.start),
false,
v.cipherKey,
v.isCompressed
));
}
if (chunkStop <= v.start || v.stop <= chunk.getOffset()) {
newVisibles.add(v);
}
}
newVisibles.add(newV);
// keep everything sorted
for (int i = newVisibles.size() - 1; i >= 0; i--) {
if (i > 0 && newV.start < newVisibles.get(i - 1).start) {
newVisibles.set(i, newVisibles.get(i - 1));
} else {
newVisibles.set(i, newV);
break;
}
}
return newVisibles;
}
public static String parseVolumeId(String fileId) {
int commaIndex = fileId.lastIndexOf(',');
if (commaIndex > 0) {
return fileId.substring(0, commaIndex);
}
return fileId;
}
public static long fileSize(FilerProto.Entry entry) {
return Math.max(totalSize(entry.getChunksList()), entry.getAttributes().getFileSize());
}
public static long totalSize(List<FilerProto.FileChunk> chunksList) {
long size = 0;
for (FilerProto.FileChunk chunk : chunksList) {
long t = chunk.getOffset() + chunk.getSize();
if (size < t) {
size = t;
}
}
return size;
}
public static class VisibleInterval {
public final long start;
public final long stop;
public final long modifiedTime;
public final String fileId;
public final long chunkOffset;
public final boolean isFullChunk;
public final byte[] cipherKey;
public final boolean isCompressed;
public VisibleInterval(long start, long stop, String fileId, long modifiedTime, long chunkOffset, boolean isFullChunk, byte[] cipherKey, boolean isCompressed) {
this.start = start;
this.stop = stop;
this.modifiedTime = modifiedTime;
this.fileId = fileId;
this.chunkOffset = chunkOffset;
this.isFullChunk = isFullChunk;
this.cipherKey = cipherKey;
this.isCompressed = isCompressed;
}
@Override
public String toString() {
return "VisibleInterval{" +
"start=" + start +
", stop=" + stop +
", modifiedTime=" + modifiedTime +
", fileId='" + fileId + '\'' +
", isFullChunk=" + isFullChunk +
", cipherKey=" + Arrays.toString(cipherKey) +
", isCompressed=" + isCompressed +
'}';
}
}
public static class ChunkView {
public final String fileId;
public final long offset;
public final long size;
public final long logicOffset;
public final boolean isFullChunk;
public final byte[] cipherKey;
public final boolean isCompressed;
public ChunkView(String fileId, long offset, long size, long logicOffset, boolean isFullChunk, byte[] cipherKey, boolean isCompressed) {
this.fileId = fileId;
this.offset = offset;
this.size = size;
this.logicOffset = logicOffset;
this.isFullChunk = isFullChunk;
this.cipherKey = cipherKey;
this.isCompressed = isCompressed;
}
@Override
public String toString() {
return "ChunkView{" +
"fileId='" + fileId + '\'' +
", offset=" + offset +
", size=" + size +
", logicOffset=" + logicOffset +
", isFullChunk=" + isFullChunk +
", cipherKey=" + Arrays.toString(cipherKey) +
", isCompressed=" + isCompressed +
'}';
}
}
}
| Hadoop: fix reading file tail
| other/java/client/src/main/java/seaweedfs/client/SeaweedRead.java | Hadoop: fix reading file tail | <ide><path>ther/java/client/src/main/java/seaweedfs/client/SeaweedRead.java
<ide>
<ide> //TODO parallel this
<ide> long readCount = 0;
<del> int startOffset = bufferOffset;
<add> long startOffset = position;
<ide> for (ChunkView chunkView : chunkViews) {
<ide>
<ide> if (startOffset < chunkView.logicOffset) {
<ide> return 0;
<ide> }
<ide>
<del> int len = readChunkView(position, buffer, startOffset, chunkView, locations);
<add> int len = readChunkView(startOffset, buffer, bufferOffset + readCount, chunkView, locations);
<ide>
<ide> LOG.debug("read [{},{}) {} size {}", startOffset, startOffset + len, chunkView.fileId, chunkView.size);
<ide>
<ide>
<ide> }
<ide>
<del> long limit = Math.min(bufferLength, fileSize);
<add> long limit = Math.min(bufferOffset + bufferLength, fileSize);
<ide>
<ide> if (startOffset < limit) {
<ide> long gap = limit - startOffset;
<ide> return readCount;
<ide> }
<ide>
<del> private static int readChunkView(long position, byte[] buffer, int startOffset, ChunkView chunkView, FilerProto.Locations locations) throws IOException {
<add> private static int readChunkView(long startOffset, byte[] buffer, long bufOffset, ChunkView chunkView, FilerProto.Locations locations) throws IOException {
<ide>
<ide> byte[] chunkData = chunkCache.getChunk(chunkView.fileId);
<ide>
<ide> }
<ide>
<ide> int len = (int) chunkView.size;
<del> LOG.debug("readChunkView fid:{} chunkData.length:{} chunkView.offset:{} buffer.length:{} startOffset:{} len:{}",
<del> chunkView.fileId, chunkData.length, chunkView.offset, buffer.length, startOffset, len);
<del> System.arraycopy(chunkData, startOffset - (int) (chunkView.logicOffset - chunkView.offset), buffer, startOffset, len);
<add> LOG.debug("readChunkView fid:{} chunkData.length:{} chunkView[{};{}) buf[{},{})/{} startOffset:{}",
<add> chunkView.fileId, chunkData.length, chunkView.offset, chunkView.offset+chunkView.size, bufOffset, bufOffset+len, buffer.length, startOffset);
<add> System.arraycopy(chunkData, (int) (startOffset - chunkView.logicOffset + chunkView.offset), buffer, (int)bufOffset, len);
<ide>
<ide> return len;
<ide> }
<ide> public static byte[] doFetchFullChunkData(ChunkView chunkView, FilerProto.Locations locations) throws IOException {
<ide>
<ide> byte[] data = null;
<del> for (long waitTime = 230L; waitTime < 20 * 1000; waitTime += waitTime / 2) {
<add> IOException lastException = null;
<add> for (long waitTime = 1000L; waitTime < 10 * 1000; waitTime += waitTime / 2) {
<ide> for (FilerProto.Location location : locations.getLocationsList()) {
<ide> String url = String.format("http://%s/%s", location.getUrl(), chunkView.fileId);
<ide> try {
<ide> break;
<ide> } catch (IOException ioe) {
<ide> LOG.debug("doFetchFullChunkData {} :{}", url, ioe);
<add> lastException = ioe;
<ide> }
<ide> }
<ide> if (data != null) {
<ide> Thread.sleep(waitTime);
<ide> } catch (InterruptedException e) {
<ide> }
<add> }
<add>
<add> if (data == null) {
<add> throw lastException;
<ide> }
<ide>
<ide> LOG.debug("doFetchFullChunkData fid:{} chunkData.length:{}", chunkView.fileId, data.length); |
|
Java | apache-2.0 | ca109e788525cf1fbd881a17a01d6b646c4d1c2b | 0 | pombredanne/lz4-java,czietsman/lz4-java,lz4/lz4-java,lz4/lz4-java,pranjalpatil/lz4-java,jpountz/lz4-java,pranjalpatil/lz4-java,lz4/lz4-java,jpountz/lz4-java,pombredanne/lz4-java,pombredanne/lz4-java,czietsman/lz4-java,jpountz/lz4-java,pranjalpatil/lz4-java | package net.jpountz.lz4;
/*
* 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.
*/
import static net.jpountz.lz4.Instances.COMPRESSORS;
import static net.jpountz.lz4.Instances.UNCOMPRESSORS;
import static net.jpountz.lz4.Instances.UNCOMPRESSORS2;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.carrotsearch.randomizedtesting.RandomizedRunner;
import com.carrotsearch.randomizedtesting.RandomizedTest;
import com.carrotsearch.randomizedtesting.annotations.Repeat;
@RunWith(RandomizedRunner.class)
public class LZ4Test extends RandomizedTest {
@Test
@Repeat(iterations=20)
public void testMaxCompressedLength() {
final int len = randomBoolean() ? randomInt(16) : randomInt(1 << 30);
final LZ4Compressor refCompressor = LZ4Factory.nativeInstance().fastCompressor();
for (LZ4Compressor compressor : COMPRESSORS) {
assertEquals(refCompressor.maxCompressedLength(len), compressor.maxCompressedLength(len));
}
}
private static byte[] getCompressedWorstCase(byte[] decompressed) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int len = decompressed.length;
if (len >= LZ4Utils.RUN_MASK) {
baos.write(LZ4Utils.RUN_MASK << LZ4Utils.ML_BITS);
len -= LZ4Utils.RUN_MASK;
}
while (len >= 255) {
baos.write(255);
len -= 255;
}
baos.write(len);
try {
baos.write(decompressed);
} catch (IOException e) {
throw new AssertionError();
}
return baos.toByteArray();
}
private static byte[] randomArray(int len, int max) {
byte[] result = new byte[len];
for (int i = 0; i < result.length; ++i) {
result[i] = (byte) randomInt(max);
}
return result;
}
@Test
public void testEmpty() {
testRoundTrip(new byte[0]);
}
public void testUncompressWorstCase(LZ4Decompressor decompressor) {
final int len = randomInt(100 * 1024);
final int max = randomInt(256);
byte[] decompressed = randomArray(len, max);
byte[] compressed = getCompressedWorstCase(decompressed);
byte[] restored = new byte[decompressed.length];
int cpLen = decompressor.decompress(compressed, 0, restored, 0, decompressed.length);
assertEquals(compressed.length, cpLen);
assertArrayEquals(decompressed, restored);
}
@Test
public void testUncompressWorstCase() {
for (LZ4Decompressor decompressor : UNCOMPRESSORS) {
testUncompressWorstCase(decompressor);
}
}
public void testUncompressWorstCase(LZ4UnknownSizeDecompressor decompressor) {
final int len = randomInt(100 * 1024);
final int max = randomInt(256);
byte[] decompressed = randomArray(len, max);
byte[] compressed = getCompressedWorstCase(decompressed);
byte[] restored = new byte[decompressed.length];
int uncpLen = decompressor.decompress(compressed, 0, compressed.length, restored, 0);
assertEquals(decompressed.length, uncpLen);
assertArrayEquals(decompressed, restored);
}
@Test
public void testUncompressUnknownSizeWorstCase() {
for (LZ4UnknownSizeDecompressor decompressor : UNCOMPRESSORS2) {
testUncompressWorstCase(decompressor);
}
}
@Test(expected=LZ4Exception.class)
@Repeat(iterations=10)
public void testUncompressUnknownSizeUnderflow() {
final LZ4UnknownSizeDecompressor decompressor = randomFrom(UNCOMPRESSORS2);
final int len = randomInt(100000);
final int max = randomInt(256);
final byte[] data = new byte[len];
for (int i = 0; i < data.length; ++i) {
data[i] = (byte) randomInt(max);
}
final int maxCompressedLength = LZ4JNICompressor.FAST.maxCompressedLength(len);
final byte[] compressed = new byte[maxCompressedLength];
final int compressedLength = LZ4JNICompressor.FAST.compress(data, 0, data.length, compressed, 0, compressed.length);
decompressor.decompress(compressed, 0, compressedLength, new byte[data.length - 1], 0);
}
private static byte[] readResource(String resource) throws IOException {
InputStream is = LZ4Test.class.getResourceAsStream(resource);
if (is == null) {
throw new IllegalStateException("Cannot find " + resource);
}
byte[] buf = new byte[4096];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
while (true) {
final int read = is.read(buf);
if (read == -1) {
break;
}
baos.write(buf, 0, read);
}
} finally {
is.close();
}
return baos.toByteArray();
}
public void testRoundTrip(byte[] data, int off, int len,
LZ4Compressor compressor,
LZ4Decompressor decompressor,
LZ4UnknownSizeDecompressor decompressor2) {
final byte[] compressed = new byte[LZ4Utils.maxCompressedLength(len)];
final int compressedLen = compressor.compress(
data, off, len,
compressed, 0, compressed.length);
final byte[] restored = new byte[len];
assertEquals(compressedLen, decompressor.decompress(compressed, 0, restored, 0, len));
assertArrayEquals(data, restored);
if (len > 0) {
Arrays.fill(restored, (byte) 0);
decompressor2.decompress(compressed, 0, compressedLen, restored, 0);
assertEquals(len, decompressor2.decompress(compressed, 0, compressedLen, restored, 0));
} else {
assertEquals(0, decompressor2.decompress(compressed, 0, compressedLen, new byte[1], 0));
}
LZ4Compressor refCompressor = null;
if (compressor == LZ4Factory.unsafeInstance().fastCompressor()
|| compressor == LZ4Factory.safeInstance().fastCompressor()) {
refCompressor = LZ4Factory.nativeInstance().fastCompressor();
} else if (compressor == LZ4Factory.unsafeInstance().highCompressor()
|| compressor == LZ4Factory.safeInstance().highCompressor()) {
refCompressor = LZ4Factory.nativeInstance().highCompressor();
}
if (refCompressor != null) {
final byte[] compressed2 = new byte[refCompressor.maxCompressedLength(len)];
final int compressedLen2 = refCompressor.compress(data, off, len, compressed2, 0, compressed2.length);
assertCompressedArrayEquals(compressor.toString(),
Arrays.copyOf(compressed2, compressedLen2),
Arrays.copyOf(compressed, compressedLen));
}
}
public void testRoundTrip(byte[] data, int off, int len, LZ4Factory lz4) {
for (LZ4Compressor compressor : Arrays.asList(
lz4.fastCompressor(), lz4.highCompressor())) {
testRoundTrip(data, off, len, compressor, lz4.decompressor(), lz4.unknwonSizeDecompressor());
}
}
public void testRoundTrip(byte[] data, int off, int len) {
for (LZ4Factory lz4 : Arrays.asList(
LZ4Factory.nativeInstance(),
LZ4Factory.unsafeInstance(),
LZ4Factory.safeInstance())) {
testRoundTrip(data, off, len, lz4);
}
}
public void testRoundTrip(byte[] data) {
testRoundTrip(data, 0, data.length);
}
public void testRoundTrip(String resource) throws IOException {
final byte[] data = readResource(resource);
testRoundTrip(data);
}
@Test
public void testRoundtripGeo() throws IOException {
testRoundTrip("/calgary/geo");
}
@Test
public void testRoundtripBook1() throws IOException {
testRoundTrip("/calgary/book1");
}
@Test
public void testRoundtripPic() throws IOException {
testRoundTrip("/calgary/pic");
}
@Test
public void testNullMatchDec() {
// 1 literal, 4 matchs with matchDec=0, 5 literals
final byte[] invalid = new byte[] { 16, 42, 0, 0, 42, 42, 42, 42, 42 };
for (LZ4Decompressor decompressor : UNCOMPRESSORS) {
try {
decompressor.decompress(invalid, 0, new byte[10], 0, 10);
// free not to fail, but do not throw something else than a LZ4Exception
} catch (LZ4Exception e) {
// OK
}
}
for (LZ4UnknownSizeDecompressor decompressor : UNCOMPRESSORS2) {
try {
decompressor.decompress(invalid, 0, invalid.length, new byte[10], 0);
assertTrue(decompressor.toString(), false);
} catch (LZ4Exception e) {
// OK
}
}
}
@Test
public void testEndsWithMatch() {
// 6 literals, 4 matchs
final byte[] invalid = new byte[] { 96, 42, 43, 44, 45, 46, 47, 5, 0 };
final int decompressedLength = 10;
for (LZ4Decompressor decompressor : UNCOMPRESSORS) {
try {
// it is invalid to end with a match, should be at least 5 literals
decompressor.decompress(invalid, 0, new byte[decompressedLength], 0, decompressedLength);
assertTrue(decompressor.toString(), false);
} catch (LZ4Exception e) {
// OK
}
}
for (LZ4UnknownSizeDecompressor decompressor : UNCOMPRESSORS2) {
try {
// it is invalid to end with a match, should be at least 5 literals
decompressor.decompress(invalid, 0, invalid.length, new byte[20], 0);
assertTrue(false);
} catch (LZ4Exception e) {
// OK
}
}
}
@Test
public void testEndsWithLessThan5Literals() {
// 6 literals, 4 matchs
final byte[] invalidBase = new byte[] { 96, 42, 43, 44, 45, 46, 47, 5, 0 };
for (int i = 1; i < 5; ++i) {
final byte[] invalid = Arrays.copyOf(invalidBase, invalidBase.length + 1 + i);
invalid[invalidBase.length] = (byte) (i << 4); // i literals at the end
for (LZ4Decompressor decompressor : UNCOMPRESSORS) {
try {
// it is invalid to end with a match, should be at least 5 literals
decompressor.decompress(invalid, 0, new byte[20], 0, 20);
assertTrue(decompressor.toString(), false);
} catch (LZ4Exception e) {
// OK
}
}
for (LZ4UnknownSizeDecompressor decompressor : UNCOMPRESSORS2) {
try {
// it is invalid to end with a match, should be at least 5 literals
decompressor.decompress(invalid, 0, invalid.length, new byte[20], 0);
assertTrue(false);
} catch (LZ4Exception e) {
// OK
}
}
}
}
@Test
@Repeat(iterations=50)
public void testCompressExactSize() {
final byte[] data = randomArray(randomInt(rarely() ? 100000 : 200), randomIntBetween(1, 10));
for (LZ4Compressor compressor : COMPRESSORS) {
final byte[] buf = new byte[compressor.maxCompressedLength(data.length)];
final int compressedLength = compressor.compress(data, 0, data.length, buf, 0, buf.length);
final byte[] buf2 = new byte[compressedLength];
try {
final int compressedLength2 = compressor.compress(data, 0, data.length, buf2, 0, buf2.length);
assertEquals(compressedLength, compressedLength2);
assertArrayEquals(Arrays.copyOf(buf, compressedLength), buf2);
try {
compressor.compress(data, 0, data.length, buf2, 0, buf2.length - 1);
assertFalse(true);
} catch (LZ4Exception e) {
// ok
}
} catch (IllegalArgumentException e) {
// the JNI high compressor does not support exact size compression
assert compressor == LZ4Factory.nativeInstance().highCompressor();
}
}
}
@Test
@Repeat(iterations=5)
public void testAllEqual() {
final int len = randomBoolean() ? randomInt(20) : randomInt(100000);
final byte[] buf = new byte[len];
Arrays.fill(buf, randomByte());
testRoundTrip(buf);
}
@Test
public void testMaxDistance() {
final int len = randomIntBetween(1 << 17, 1 << 18);
final int off = 0;//randomInt(len - (1 << 16) - (1 << 15));
final byte[] buf = new byte[len];
for (int i = 0; i < (1 << 15); ++i) {
buf[off + i] = randomByte();
}
System.arraycopy(buf, off, buf, off + 65535, 1 << 15);
testRoundTrip(buf);
}
@Test
@Repeat(iterations=10)
public void testCompressedArrayEqualsJNI() {
final int max = randomIntBetween(1, 15);
final int len = randomInt(1 << 18);
final byte[] data = new byte[len];
for (int i = 0; i < len; ++i) {
data[i] = (byte) randomInt(max);
}
testRoundTrip(data);
}
private static void assertCompressedArrayEquals(String message, byte[] expected, byte[] actual) {
int off = 0;
int decompressedOff = 0;
while (true) {
if (off == expected.length) {
break;
}
final Sequence sequence1 = readSequence(expected, off);
final Sequence sequence2 = readSequence(actual, off);
assertEquals(message + ", off=" + off + ", decompressedOff=" + decompressedOff, sequence1, sequence2);
off += sequence1.length;
decompressedOff += sequence1.literalLen + sequence1.matchLen;
}
}
private static Sequence readSequence(byte[] buf, int off) {
final int start = off;
final int token = buf[off++] & 0xFF;
int literalLen = token >>> 4;
if (literalLen >= 0x0F) {
int len;
while ((len = buf[off++] & 0xFF) == 0xFF) {
literalLen += 0xFF;
}
literalLen += len;
}
off += literalLen;
if (off == buf.length) {
return new Sequence(literalLen, -1, -1, off - start);
}
int matchDec = (buf[off++] & 0xFF) | ((buf[off++] & 0xFF) << 8);
int matchLen = token & 0x0F;
if (matchLen >= 0x0F) {
int len;
while ((len = buf[off++] & 0xFF) == 0xFF) {
matchLen += 0xFF;
}
matchLen += len;
}
matchLen += 4;
return new Sequence(literalLen, matchDec, matchLen, off - start);
}
private static class Sequence {
final int literalLen, matchDec, matchLen, length;
public Sequence(int literalLen, int matchDec, int matchLen, int length) {
this.literalLen = literalLen;
this.matchDec = matchDec;
this.matchLen = matchLen;
this.length = length;
}
@Override
public String toString() {
return "Sequence [literalLen=" + literalLen + ", matchDec=" + matchDec
+ ", matchLen=" + matchLen + "]";
}
@Override
public int hashCode() {
return 42;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Sequence other = (Sequence) obj;
if (literalLen != other.literalLen)
return false;
if (matchDec != other.matchDec)
return false;
if (matchLen != other.matchLen)
return false;
return true;
}
}
}
| src/test/net/jpountz/lz4/LZ4Test.java | package net.jpountz.lz4;
/*
* 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.
*/
import static net.jpountz.lz4.Instances.COMPRESSORS;
import static net.jpountz.lz4.Instances.UNCOMPRESSORS;
import static net.jpountz.lz4.Instances.UNCOMPRESSORS2;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.carrotsearch.randomizedtesting.RandomizedRunner;
import com.carrotsearch.randomizedtesting.RandomizedTest;
import com.carrotsearch.randomizedtesting.annotations.Repeat;
@RunWith(RandomizedRunner.class)
public class LZ4Test extends RandomizedTest {
private static byte[] getCompressedWorstCase(byte[] decompressed) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int len = decompressed.length;
if (len >= LZ4Utils.RUN_MASK) {
baos.write(LZ4Utils.RUN_MASK << LZ4Utils.ML_BITS);
len -= LZ4Utils.RUN_MASK;
}
while (len >= 255) {
baos.write(255);
len -= 255;
}
baos.write(len);
try {
baos.write(decompressed);
} catch (IOException e) {
throw new AssertionError();
}
return baos.toByteArray();
}
private static byte[] randomArray(int len, int max) {
byte[] result = new byte[len];
for (int i = 0; i < result.length; ++i) {
result[i] = (byte) randomInt(max);
}
return result;
}
@Test
public void testEmpty() {
testRoundTrip(new byte[0]);
}
public void testUncompressWorstCase(LZ4Decompressor decompressor) {
final int len = randomInt(100 * 1024);
final int max = randomInt(256);
byte[] decompressed = randomArray(len, max);
byte[] compressed = getCompressedWorstCase(decompressed);
byte[] restored = new byte[decompressed.length];
int cpLen = decompressor.decompress(compressed, 0, restored, 0, decompressed.length);
assertEquals(compressed.length, cpLen);
assertArrayEquals(decompressed, restored);
}
@Test
public void testUncompressWorstCase() {
for (LZ4Decompressor decompressor : UNCOMPRESSORS) {
testUncompressWorstCase(decompressor);
}
}
public void testUncompressWorstCase(LZ4UnknownSizeDecompressor decompressor) {
final int len = randomInt(100 * 1024);
final int max = randomInt(256);
byte[] decompressed = randomArray(len, max);
byte[] compressed = getCompressedWorstCase(decompressed);
byte[] restored = new byte[decompressed.length];
int uncpLen = decompressor.decompress(compressed, 0, compressed.length, restored, 0);
assertEquals(decompressed.length, uncpLen);
assertArrayEquals(decompressed, restored);
}
@Test
public void testUncompressUnknownSizeWorstCase() {
for (LZ4UnknownSizeDecompressor decompressor : UNCOMPRESSORS2) {
testUncompressWorstCase(decompressor);
}
}
@Test(expected=LZ4Exception.class)
@Repeat(iterations=10)
public void testUncompressUnknownSizeUnderflow() {
final LZ4UnknownSizeDecompressor decompressor = randomFrom(UNCOMPRESSORS2);
final int len = randomInt(100000);
final int max = randomInt(256);
final byte[] data = new byte[len];
for (int i = 0; i < data.length; ++i) {
data[i] = (byte) randomInt(max);
}
final int maxCompressedLength = LZ4JNICompressor.FAST.maxCompressedLength(len);
final byte[] compressed = new byte[maxCompressedLength];
final int compressedLength = LZ4JNICompressor.FAST.compress(data, 0, data.length, compressed, 0, compressed.length);
decompressor.decompress(compressed, 0, compressedLength, new byte[data.length - 1], 0);
}
private static byte[] readResource(String resource) throws IOException {
InputStream is = LZ4Test.class.getResourceAsStream(resource);
if (is == null) {
throw new IllegalStateException("Cannot find " + resource);
}
byte[] buf = new byte[4096];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
while (true) {
final int read = is.read(buf);
if (read == -1) {
break;
}
baos.write(buf, 0, read);
}
} finally {
is.close();
}
return baos.toByteArray();
}
public void testRoundTrip(byte[] data, int off, int len,
LZ4Compressor compressor,
LZ4Decompressor decompressor,
LZ4UnknownSizeDecompressor decompressor2) {
final byte[] compressed = new byte[LZ4Utils.maxCompressedLength(len)];
final int compressedLen = compressor.compress(
data, off, len,
compressed, 0, compressed.length);
final byte[] restored = new byte[len];
assertEquals(compressedLen, decompressor.decompress(compressed, 0, restored, 0, len));
assertArrayEquals(data, restored);
if (len > 0) {
Arrays.fill(restored, (byte) 0);
decompressor2.decompress(compressed, 0, compressedLen, restored, 0);
assertEquals(len, decompressor2.decompress(compressed, 0, compressedLen, restored, 0));
} else {
assertEquals(0, decompressor2.decompress(compressed, 0, compressedLen, new byte[1], 0));
}
LZ4Compressor refCompressor = null;
if (compressor == LZ4Factory.unsafeInstance().fastCompressor()
|| compressor == LZ4Factory.safeInstance().fastCompressor()) {
refCompressor = LZ4Factory.nativeInstance().fastCompressor();
} else if (compressor == LZ4Factory.unsafeInstance().highCompressor()
|| compressor == LZ4Factory.safeInstance().highCompressor()) {
refCompressor = LZ4Factory.nativeInstance().highCompressor();
}
if (refCompressor != null) {
final byte[] compressed2 = new byte[refCompressor.maxCompressedLength(len)];
final int compressedLen2 = refCompressor.compress(data, off, len, compressed2, 0, compressed2.length);
assertCompressedArrayEquals(compressor.toString(),
Arrays.copyOf(compressed2, compressedLen2),
Arrays.copyOf(compressed, compressedLen));
}
}
public void testRoundTrip(byte[] data, int off, int len, LZ4Factory lz4) {
for (LZ4Compressor compressor : Arrays.asList(
lz4.fastCompressor(), lz4.highCompressor())) {
testRoundTrip(data, off, len, compressor, lz4.decompressor(), lz4.unknwonSizeDecompressor());
}
}
public void testRoundTrip(byte[] data, int off, int len) {
for (LZ4Factory lz4 : Arrays.asList(
LZ4Factory.nativeInstance(),
LZ4Factory.unsafeInstance(),
LZ4Factory.safeInstance())) {
testRoundTrip(data, off, len, lz4);
}
}
public void testRoundTrip(byte[] data) {
testRoundTrip(data, 0, data.length);
}
public void testRoundTrip(String resource) throws IOException {
final byte[] data = readResource(resource);
testRoundTrip(data);
}
@Test
public void testRoundtripGeo() throws IOException {
testRoundTrip("/calgary/geo");
}
@Test
public void testRoundtripBook1() throws IOException {
testRoundTrip("/calgary/book1");
}
@Test
public void testRoundtripPic() throws IOException {
testRoundTrip("/calgary/pic");
}
@Test
public void testNullMatchDec() {
// 1 literal, 4 matchs with matchDec=0, 5 literals
final byte[] invalid = new byte[] { 16, 42, 0, 0, 42, 42, 42, 42, 42 };
for (LZ4Decompressor decompressor : UNCOMPRESSORS) {
try {
decompressor.decompress(invalid, 0, new byte[10], 0, 10);
// free not to fail, but do not throw something else than a LZ4Exception
} catch (LZ4Exception e) {
// OK
}
}
for (LZ4UnknownSizeDecompressor decompressor : UNCOMPRESSORS2) {
try {
decompressor.decompress(invalid, 0, invalid.length, new byte[10], 0);
assertTrue(decompressor.toString(), false);
} catch (LZ4Exception e) {
// OK
}
}
}
@Test
public void testEndsWithMatch() {
// 6 literals, 4 matchs
final byte[] invalid = new byte[] { 96, 42, 43, 44, 45, 46, 47, 5, 0 };
final int decompressedLength = 10;
for (LZ4Decompressor decompressor : UNCOMPRESSORS) {
try {
// it is invalid to end with a match, should be at least 5 literals
decompressor.decompress(invalid, 0, new byte[decompressedLength], 0, decompressedLength);
assertTrue(decompressor.toString(), false);
} catch (LZ4Exception e) {
// OK
}
}
for (LZ4UnknownSizeDecompressor decompressor : UNCOMPRESSORS2) {
try {
// it is invalid to end with a match, should be at least 5 literals
decompressor.decompress(invalid, 0, invalid.length, new byte[20], 0);
assertTrue(false);
} catch (LZ4Exception e) {
// OK
}
}
}
@Test
public void testEndsWithLessThan5Literals() {
// 6 literals, 4 matchs
final byte[] invalidBase = new byte[] { 96, 42, 43, 44, 45, 46, 47, 5, 0 };
for (int i = 1; i < 5; ++i) {
final byte[] invalid = Arrays.copyOf(invalidBase, invalidBase.length + 1 + i);
invalid[invalidBase.length] = (byte) (i << 4); // i literals at the end
for (LZ4Decompressor decompressor : UNCOMPRESSORS) {
try {
// it is invalid to end with a match, should be at least 5 literals
decompressor.decompress(invalid, 0, new byte[20], 0, 20);
assertTrue(decompressor.toString(), false);
} catch (LZ4Exception e) {
// OK
}
}
for (LZ4UnknownSizeDecompressor decompressor : UNCOMPRESSORS2) {
try {
// it is invalid to end with a match, should be at least 5 literals
decompressor.decompress(invalid, 0, invalid.length, new byte[20], 0);
assertTrue(false);
} catch (LZ4Exception e) {
// OK
}
}
}
}
@Test
@Repeat(iterations=50)
public void testCompressExactSize() {
final byte[] data = randomArray(randomInt(rarely() ? 100000 : 200), randomIntBetween(1, 10));
for (LZ4Compressor compressor : COMPRESSORS) {
final byte[] buf = new byte[compressor.maxCompressedLength(data.length)];
final int compressedLength = compressor.compress(data, 0, data.length, buf, 0, buf.length);
final byte[] buf2 = new byte[compressedLength];
try {
final int compressedLength2 = compressor.compress(data, 0, data.length, buf2, 0, buf2.length);
assertEquals(compressedLength, compressedLength2);
assertArrayEquals(Arrays.copyOf(buf, compressedLength), buf2);
try {
compressor.compress(data, 0, data.length, buf2, 0, buf2.length - 1);
assertFalse(true);
} catch (LZ4Exception e) {
// ok
}
} catch (IllegalArgumentException e) {
// the JNI high compressor does not support exact size compression
assert compressor == LZ4Factory.nativeInstance().highCompressor();
}
}
}
@Test
@Repeat(iterations=5)
public void testAllEqual() {
final int len = randomBoolean() ? randomInt(20) : randomInt(100000);
final byte[] buf = new byte[len];
Arrays.fill(buf, randomByte());
testRoundTrip(buf);
}
@Test
public void testMaxDistance() {
final int len = randomIntBetween(1 << 17, 1 << 18);
final int off = 0;//randomInt(len - (1 << 16) - (1 << 15));
final byte[] buf = new byte[len];
for (int i = 0; i < (1 << 15); ++i) {
buf[off + i] = randomByte();
}
System.arraycopy(buf, off, buf, off + 65535, 1 << 15);
testRoundTrip(buf);
}
@Test
@Repeat(iterations=10)
public void testCompressedArrayEqualsJNI() {
final int max = randomIntBetween(1, 15);
final int len = randomInt(1 << 18);
final byte[] data = new byte[len];
for (int i = 0; i < len; ++i) {
data[i] = (byte) randomInt(max);
}
testRoundTrip(data);
}
private static void assertCompressedArrayEquals(String message, byte[] expected, byte[] actual) {
int off = 0;
int decompressedOff = 0;
while (true) {
if (off == expected.length) {
break;
}
final Sequence sequence1 = readSequence(expected, off);
final Sequence sequence2 = readSequence(actual, off);
assertEquals(message + ", off=" + off + ", decompressedOff=" + decompressedOff, sequence1, sequence2);
off += sequence1.length;
decompressedOff += sequence1.literalLen + sequence1.matchLen;
}
}
private static Sequence readSequence(byte[] buf, int off) {
final int start = off;
final int token = buf[off++] & 0xFF;
int literalLen = token >>> 4;
if (literalLen >= 0x0F) {
int len;
while ((len = buf[off++] & 0xFF) == 0xFF) {
literalLen += 0xFF;
}
literalLen += len;
}
off += literalLen;
if (off == buf.length) {
return new Sequence(literalLen, -1, -1, off - start);
}
int matchDec = (buf[off++] & 0xFF) | ((buf[off++] & 0xFF) << 8);
int matchLen = token & 0x0F;
if (matchLen >= 0x0F) {
int len;
while ((len = buf[off++] & 0xFF) == 0xFF) {
matchLen += 0xFF;
}
matchLen += len;
}
matchLen += 4;
return new Sequence(literalLen, matchDec, matchLen, off - start);
}
private static class Sequence {
final int literalLen, matchDec, matchLen, length;
public Sequence(int literalLen, int matchDec, int matchLen, int length) {
this.literalLen = literalLen;
this.matchDec = matchDec;
this.matchLen = matchLen;
this.length = length;
}
@Override
public String toString() {
return "Sequence [literalLen=" + literalLen + ", matchDec=" + matchDec
+ ", matchLen=" + matchLen + "]";
}
@Override
public int hashCode() {
return 42;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Sequence other = (Sequence) obj;
if (literalLen != other.literalLen)
return false;
if (matchDec != other.matchDec)
return false;
if (matchLen != other.matchLen)
return false;
return true;
}
}
}
| Test maxCompressedLength.
| src/test/net/jpountz/lz4/LZ4Test.java | Test maxCompressedLength. | <ide><path>rc/test/net/jpountz/lz4/LZ4Test.java
<ide> @RunWith(RandomizedRunner.class)
<ide> public class LZ4Test extends RandomizedTest {
<ide>
<add> @Test
<add> @Repeat(iterations=20)
<add> public void testMaxCompressedLength() {
<add> final int len = randomBoolean() ? randomInt(16) : randomInt(1 << 30);
<add> final LZ4Compressor refCompressor = LZ4Factory.nativeInstance().fastCompressor();
<add> for (LZ4Compressor compressor : COMPRESSORS) {
<add> assertEquals(refCompressor.maxCompressedLength(len), compressor.maxCompressedLength(len));
<add> }
<add> }
<add>
<ide> private static byte[] getCompressedWorstCase(byte[] decompressed) {
<ide> ByteArrayOutputStream baos = new ByteArrayOutputStream();
<ide> int len = decompressed.length; |
|
Java | apache-2.0 | d9e8af15806b9fd53f41d62d744db67f88533594 | 0 | b2ihealthcare/snow-owl,IHTSDO/snow-owl,IHTSDO/snow-owl,b2ihealthcare/snow-owl,b2ihealthcare/snow-owl,b2ihealthcare/snow-owl,IHTSDO/snow-owl,IHTSDO/snow-owl | /*
* Copyright 2011-2017 B2i Healthcare Pte Ltd, http://b2i.sg
*
* 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.b2international.snowowl.snomed.datastore.index.entry;
import static com.b2international.index.query.Expressions.exactMatch;
import static com.b2international.index.query.Expressions.matchAny;
import static com.b2international.index.query.Expressions.matchAnyDecimal;
import static com.b2international.index.query.Expressions.matchAnyInt;
import static com.b2international.index.query.Expressions.matchRange;
import static com.b2international.snowowl.snomed.common.SnomedTerminologyComponentConstants.CONCEPT_NUMBER;
import static com.b2international.snowowl.snomed.common.SnomedTerminologyComponentConstants.DESCRIPTION_NUMBER;
import static com.b2international.snowowl.snomed.common.SnomedTerminologyComponentConstants.RELATIONSHIP_NUMBER;
import static com.google.common.base.Preconditions.checkArgument;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.Date;
import java.util.Map;
import java.util.Map.Entry;
import com.b2international.commons.StringUtils;
import com.b2international.index.Doc;
import com.b2international.index.query.Expression;
import com.b2international.snowowl.core.CoreTerminologyBroker;
import com.b2international.snowowl.core.date.DateFormats;
import com.b2international.snowowl.core.date.EffectiveTimes;
import com.b2international.snowowl.datastore.cdo.CDOIDUtils;
import com.b2international.snowowl.snomed.common.SnomedRf2Headers;
import com.b2international.snowowl.snomed.core.domain.Acceptability;
import com.b2international.snowowl.snomed.core.domain.InactivationIndicator;
import com.b2international.snowowl.snomed.core.domain.RelationshipRefinability;
import com.b2international.snowowl.snomed.core.domain.SnomedConcept;
import com.b2international.snowowl.snomed.core.domain.SnomedCoreComponent;
import com.b2international.snowowl.snomed.core.domain.SnomedDescription;
import com.b2international.snowowl.snomed.core.domain.SnomedRelationship;
import com.b2international.snowowl.snomed.core.domain.refset.SnomedReferenceSetMember;
import com.b2international.snowowl.snomed.datastore.SnomedRefSetUtil;
import com.b2international.snowowl.snomed.snomedrefset.DataType;
import com.b2international.snowowl.snomed.snomedrefset.SnomedAssociationRefSetMember;
import com.b2international.snowowl.snomed.snomedrefset.SnomedAttributeValueRefSetMember;
import com.b2international.snowowl.snomed.snomedrefset.SnomedComplexMapRefSetMember;
import com.b2international.snowowl.snomed.snomedrefset.SnomedConcreteDataTypeRefSetMember;
import com.b2international.snowowl.snomed.snomedrefset.SnomedDescriptionTypeRefSetMember;
import com.b2international.snowowl.snomed.snomedrefset.SnomedLanguageRefSetMember;
import com.b2international.snowowl.snomed.snomedrefset.SnomedModuleDependencyRefSetMember;
import com.b2international.snowowl.snomed.snomedrefset.SnomedQueryRefSetMember;
import com.b2international.snowowl.snomed.snomedrefset.SnomedRefSetMember;
import com.b2international.snowowl.snomed.snomedrefset.SnomedRefSetType;
import com.b2international.snowowl.snomed.snomedrefset.SnomedSimpleMapRefSetMember;
import com.b2international.snowowl.snomed.snomedrefset.util.SnomedRefSetSwitch;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
import com.google.common.base.Function;
import com.google.common.base.Objects.ToStringHelper;
import com.google.common.base.Strings;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableMap;
/**
* Lightweight representation of a SNOMED CT reference set member.
*/
@Doc
@JsonDeserialize(builder = SnomedRefSetMemberIndexEntry.Builder.class)
public final class SnomedRefSetMemberIndexEntry extends SnomedDocument {
private static final long serialVersionUID = 5198766293865046258L;
public static class Fields extends SnomedDocument.Fields {
// known RF2 fields
public static final String REFERENCE_SET_ID = "referenceSetId"; // XXX different than the RF2 header field name
public static final String REFERENCED_COMPONENT_ID = SnomedRf2Headers.FIELD_REFERENCED_COMPONENT_ID;
public static final String ACCEPTABILITY_ID = SnomedRf2Headers.FIELD_ACCEPTABILITY_ID;
public static final String VALUE_ID = SnomedRf2Headers.FIELD_VALUE_ID;
public static final String TARGET_COMPONENT = SnomedRf2Headers.FIELD_TARGET_COMPONENT;
public static final String MAP_TARGET = SnomedRf2Headers.FIELD_MAP_TARGET;
public static final String MAP_TARGET_DESCRIPTION = SnomedRf2Headers.FIELD_MAP_TARGET_DESCRIPTION;
public static final String MAP_GROUP = SnomedRf2Headers.FIELD_MAP_GROUP;
public static final String MAP_PRIORITY = SnomedRf2Headers.FIELD_MAP_PRIORITY;
public static final String MAP_RULE = SnomedRf2Headers.FIELD_MAP_RULE;
public static final String MAP_ADVICE = SnomedRf2Headers.FIELD_MAP_ADVICE;
public static final String MAP_CATEGORY_ID = SnomedRf2Headers.FIELD_MAP_CATEGORY_ID;
public static final String CORRELATION_ID = SnomedRf2Headers.FIELD_CORRELATION_ID;
public static final String DESCRIPTION_FORMAT = SnomedRf2Headers.FIELD_DESCRIPTION_FORMAT;
public static final String DESCRIPTION_LENGTH = SnomedRf2Headers.FIELD_DESCRIPTION_LENGTH;
public static final String OPERATOR_ID = SnomedRf2Headers.FIELD_OPERATOR_ID;
public static final String UNIT_ID = SnomedRf2Headers.FIELD_UNIT_ID;
public static final String QUERY = SnomedRf2Headers.FIELD_QUERY;
public static final String CHARACTERISTIC_TYPE_ID = SnomedRf2Headers.FIELD_CHARACTERISTIC_TYPE_ID;
public static final String SOURCE_EFFECTIVE_TIME = SnomedRf2Headers.FIELD_SOURCE_EFFECTIVE_TIME;
public static final String TARGET_EFFECTIVE_TIME = SnomedRf2Headers.FIELD_TARGET_EFFECTIVE_TIME;
private static final String DATA_VALUE = SnomedRf2Headers.FIELD_VALUE;
public static final String ATTRIBUTE_NAME = SnomedRf2Headers.FIELD_ATTRIBUTE_NAME;
// extra index fields to store datatype and map target type
public static final String DATA_TYPE = "dataType";
public static final String REFSET_TYPE = "referenceSetType";
public static final String REFERENCED_COMPONENT_TYPE = "referencedComponentType";
// CD value fields per type
public static final String BOOLEAN_VALUE = "booleanValue";
public static final String STRING_VALUE = "stringValue";
public static final String INTEGER_VALUE = "integerValue";
public static final String DECIMAL_VALUE = "decimalValue";
}
public static Builder builder() {
return new Builder();
}
public static Builder builder(final SnomedRefSetMemberIndexEntry source) {
return builder()
.storageKey(source.getStorageKey())
.active(source.isActive())
.effectiveTime(source.getEffectiveTime())
.id(source.getId())
.moduleId(source.getModuleId())
.referencedComponentId(source.getReferencedComponentId())
.referencedComponentType(source.getReferencedComponentType())
.referenceSetId(source.getReferenceSetId())
.referenceSetType(source.getReferenceSetType())
.released(source.isReleased())
.fields(source.getAdditionalFields());
}
public static final Builder builder(final SnomedReferenceSetMember input) {
final Builder builder = builder()
.storageKey(input.getStorageKey())
.active(input.isActive())
.effectiveTime(EffectiveTimes.getEffectiveTime(input.getEffectiveTime()))
.id(input.getId())
.moduleId(input.getModuleId())
.referencedComponentId(input.getReferencedComponent().getId())
.referenceSetId(input.getReferenceSetId())
.referenceSetType(input.type())
.released(input.isReleased());
if (input.getReferencedComponent() instanceof SnomedConcept) {
builder.referencedComponentType(CONCEPT_NUMBER);
} else if (input.getReferencedComponent() instanceof SnomedDescription) {
builder.referencedComponentType(DESCRIPTION_NUMBER);
} else if (input.getReferencedComponent() instanceof SnomedRelationship) {
builder.referencedComponentType(RELATIONSHIP_NUMBER);
} else {
builder.referencedComponentType(CoreTerminologyBroker.UNSPECIFIED_NUMBER_SHORT);
}
for (Entry<String, Object> entry : input.getProperties().entrySet()) {
final Object value = entry.getValue();
final String fieldName = entry.getKey();
// certain RF2 fields can be expanded into full blown representation class, get the ID in this case
if (value instanceof SnomedCoreComponent) {
builder.field(fieldName, ((SnomedCoreComponent) value).getId());
} else {
builder.field(fieldName, convertValue(entry.getKey(), value));
}
}
return builder;
}
public static Builder builder(SnomedRefSetMember refSetMember) {
final Builder builder = SnomedRefSetMemberIndexEntry.builder()
.storageKey(CDOIDUtils.asLong(refSetMember.cdoID()))
.id(refSetMember.getUuid())
.moduleId(refSetMember.getModuleId())
.active(refSetMember.isActive())
.released(refSetMember.isReleased())
.effectiveTime(refSetMember.isSetEffectiveTime() ? refSetMember.getEffectiveTime().getTime() : EffectiveTimes.UNSET_EFFECTIVE_TIME)
.referenceSetId(refSetMember.getRefSetIdentifierId())
.referenceSetType(refSetMember.getRefSet().getType())
.referencedComponentType(refSetMember.getReferencedComponentType())
.referencedComponentId(refSetMember.getReferencedComponentId());
return new SnomedRefSetSwitch<Builder>() {
@Override
public Builder caseSnomedAssociationRefSetMember(final SnomedAssociationRefSetMember associationMember) {
return builder.targetComponent(associationMember.getTargetComponentId());
}
@Override
public Builder caseSnomedAttributeValueRefSetMember(final SnomedAttributeValueRefSetMember attributeValueMember) {
return builder.field(Fields.VALUE_ID, attributeValueMember.getValueId());
}
@Override
public Builder caseSnomedConcreteDataTypeRefSetMember(final SnomedConcreteDataTypeRefSetMember concreteDataTypeMember) {
return builder.field(Fields.ATTRIBUTE_NAME, concreteDataTypeMember.getLabel())
.field(Fields.DATA_TYPE, concreteDataTypeMember.getDataType())
.field(Fields.DATA_VALUE, concreteDataTypeMember.getSerializedValue())
.field(Fields.CHARACTERISTIC_TYPE_ID, concreteDataTypeMember.getCharacteristicTypeId())
.field(Fields.OPERATOR_ID, concreteDataTypeMember.getOperatorComponentId())
.field(Fields.UNIT_ID, Strings.nullToEmpty(concreteDataTypeMember.getUomComponentId()));
}
@Override
public Builder caseSnomedDescriptionTypeRefSetMember(final SnomedDescriptionTypeRefSetMember descriptionTypeMember) {
return builder
.field(Fields.DESCRIPTION_FORMAT, descriptionTypeMember.getDescriptionFormat())
.field(Fields.DESCRIPTION_LENGTH, descriptionTypeMember.getDescriptionLength());
}
@Override
public Builder caseSnomedLanguageRefSetMember(final SnomedLanguageRefSetMember languageMember) {
return builder.field(Fields.ACCEPTABILITY_ID, languageMember.getAcceptabilityId());
}
@Override
public Builder caseSnomedQueryRefSetMember(final SnomedQueryRefSetMember queryMember) {
return builder.field(Fields.QUERY, queryMember.getQuery());
}
@Override
public Builder caseSnomedSimpleMapRefSetMember(final SnomedSimpleMapRefSetMember mapRefSetMember) {
return builder
.field(Fields.MAP_TARGET, mapRefSetMember.getMapTargetComponentId())
.field(Fields.MAP_TARGET_DESCRIPTION, mapRefSetMember.getMapTargetComponentDescription());
}
@Override
public Builder caseSnomedComplexMapRefSetMember(final SnomedComplexMapRefSetMember mapRefSetMember) {
return builder
.field(Fields.MAP_TARGET, mapRefSetMember.getMapTargetComponentId())
.field(Fields.CORRELATION_ID, mapRefSetMember.getCorrelationId())
.field(Fields.MAP_GROUP, Integer.valueOf(mapRefSetMember.getMapGroup()))
.field(Fields.MAP_ADVICE, Strings.nullToEmpty(mapRefSetMember.getMapAdvice()))
.field(Fields.MAP_PRIORITY, Integer.valueOf(mapRefSetMember.getMapPriority()))
.field(Fields.MAP_RULE, Strings.nullToEmpty(mapRefSetMember.getMapRule()))
// extended refset
.field(Fields.MAP_CATEGORY_ID, Strings.nullToEmpty(mapRefSetMember.getMapCategoryId()));
}
@Override
public Builder caseSnomedModuleDependencyRefSetMember(SnomedModuleDependencyRefSetMember member) {
return builder
.field(Fields.SOURCE_EFFECTIVE_TIME, EffectiveTimes.getEffectiveTime(member.getSourceEffectiveTime()))
.field(Fields.TARGET_EFFECTIVE_TIME, EffectiveTimes.getEffectiveTime(member.getTargetEffectiveTime()));
}
@Override
public Builder caseSnomedRefSetMember(SnomedRefSetMember object) {
return builder;
};
}.doSwitch(refSetMember);
}
private static Object convertValue(String rf2Field, Object value) {
switch (rf2Field) {
case SnomedRf2Headers.FIELD_SOURCE_EFFECTIVE_TIME:
case SnomedRf2Headers.FIELD_TARGET_EFFECTIVE_TIME:
if (value instanceof String && !StringUtils.isEmpty((String) value)) {
Date parsedDate = EffectiveTimes.parse((String) value, DateFormats.SHORT);
return EffectiveTimes.getEffectiveTime(parsedDate);
} else {
return EffectiveTimes.UNSET_EFFECTIVE_TIME;
}
default:
return value;
}
}
public static Collection<SnomedRefSetMemberIndexEntry> from(final Iterable<SnomedReferenceSetMember> refSetMembers) {
return FluentIterable.from(refSetMembers).transform(new Function<SnomedReferenceSetMember, SnomedRefSetMemberIndexEntry>() {
@Override
public SnomedRefSetMemberIndexEntry apply(final SnomedReferenceSetMember refSetMember) {
return builder(refSetMember).build();
}
}).toList();
}
public static final class Expressions extends SnomedDocument.Expressions {
public static Expression referenceSetId(String referenceSetId) {
return exactMatch(Fields.REFERENCE_SET_ID, referenceSetId);
}
public static Expression referenceSetId(Collection<String> referenceSetIds) {
return matchAny(Fields.REFERENCE_SET_ID, referenceSetIds);
}
public static Expression referencedComponentId(String referencedComponentId) {
return exactMatch(Fields.REFERENCED_COMPONENT_ID, referencedComponentId);
}
public static Expression mapTargets(Collection<String> mapTargets) {
return matchAny(Fields.MAP_TARGET, mapTargets);
}
public static Expression referencedComponentIds(Collection<String> referencedComponentIds) {
return matchAny(Fields.REFERENCED_COMPONENT_ID, referencedComponentIds);
}
public static Expression targetComponents(Collection<String> targetComponentIds) {
return matchAny(Fields.TARGET_COMPONENT, targetComponentIds);
}
public static Expression acceptabilityIds(Collection<String> acceptabilityIds) {
return matchAny(Fields.ACCEPTABILITY_ID, acceptabilityIds);
}
public static Expression characteristicTypeIds(Collection<String> characteristicTypeIds) {
return matchAny(Fields.CHARACTERISTIC_TYPE_ID, characteristicTypeIds);
}
public static Expression correlationIds(Collection<String> correlationIds) {
return matchAny(Fields.CORRELATION_ID, correlationIds);
}
public static Expression descriptionFormats(Collection<String> descriptionFormats) {
return matchAny(Fields.DESCRIPTION_FORMAT, descriptionFormats);
}
public static Expression mapCategoryIds(Collection<String> mapCategoryIds) {
return matchAny(Fields.MAP_CATEGORY_ID, mapCategoryIds);
}
public static Expression operatorIds(Collection<String> operatorIds) {
return matchAny(Fields.OPERATOR_ID, operatorIds);
}
public static Expression unitIds(Collection<String> unitIds) {
return matchAny(Fields.UNIT_ID, unitIds);
}
public static Expression valueIds(Collection<String> valueIds) {
return matchAny(Fields.VALUE_ID, valueIds);
}
public static Expression values(DataType type, Collection<? extends Object> values) {
switch (type) {
case STRING:
return matchAny(Fields.STRING_VALUE, FluentIterable.from(values).filter(String.class).toSet());
case INTEGER:
return matchAnyInt(Fields.INTEGER_VALUE, FluentIterable.from(values).filter(Integer.class).toSet());
case DECIMAL:
return matchAnyDecimal(Fields.DECIMAL_VALUE, FluentIterable.from(values).filter(BigDecimal.class).toSet());
default:
throw new UnsupportedOperationException("Unsupported data type when filtering by values, " + type);
}
}
public static Expression valueRange(DataType type, final Object lower, final Object upper, boolean includeLower, boolean includeUpper) {
switch (type) {
case STRING:
return matchRange(Fields.STRING_VALUE, (String) lower, (String) upper, includeLower, includeUpper);
case INTEGER:
return matchRange(Fields.INTEGER_VALUE, (Integer) lower, (Integer) upper, includeLower, includeUpper);
case DECIMAL:
return matchRange(Fields.DECIMAL_VALUE, (BigDecimal) lower, (BigDecimal) upper, includeLower, includeUpper);
default:
throw new UnsupportedOperationException("Unsupported data type when filtering by values, " + type);
}
}
public static Expression dataTypes(Collection<DataType> dataTypes) {
return matchAny(Fields.DATA_TYPE, FluentIterable.from(dataTypes).transform(new Function<DataType, String>() {
@Override
public String apply(DataType input) {
return input.name();
}
}).toSet());
}
public static Expression attributeNames(Collection<String> attributeNames) {
return matchAny(Fields.ATTRIBUTE_NAME, attributeNames);
}
public static Expression sourceEffectiveTime(long effectiveTime) {
return exactMatch(Fields.SOURCE_EFFECTIVE_TIME, effectiveTime);
}
public static Expression targetEffectiveTime(long effectiveTime) {
return exactMatch(Fields.TARGET_EFFECTIVE_TIME, effectiveTime);
}
public static Expression refSetTypes(Collection<SnomedRefSetType> refSetTypes) {
return matchAny(Fields.REFSET_TYPE, FluentIterable.from(refSetTypes).transform(new Function<SnomedRefSetType, String>() {
@Override
public String apply(SnomedRefSetType input) {
return input.name();
}
}).toSet());
}
}
@JsonPOJOBuilder(withPrefix="")
public static final class Builder extends SnomedDocumentBuilder<Builder> {
private String referencedComponentId;
private String referenceSetId;
private SnomedRefSetType referenceSetType;
private short referencedComponentType;
// Member specific fields, they can be null or emptyish values
// ASSOCIATION reference set members
private String targetComponent;
// ATTRIBUTE VALUE
private String valueId;
// CONCRETE DOMAIN reference set members
private DataType dataType;
private String attributeName;
private Object value;
private String operatorId;
private String characteristicTypeId;
private String unitId;
// DESCRIPTION
private Integer descriptionLength;
private String descriptionFormat;
// LANGUAGE
private String acceptabilityId;
// MODULE
private Long sourceEffectiveTime;
private Long targetEffectiveTime;
// SIMPLE MAP reference set members
private String mapTarget;
private String mapTargetDescription;
// COMPLEX MAP
private String mapCategoryId;
private String correlationId;
private String mapAdvice;
private String mapRule;
private Integer mapGroup;
private Integer mapPriority;
// QUERY
private String query;
@JsonCreator
private Builder() {
// Disallow instantiation outside static method
}
public Builder fields(Map<String, Object> fields) {
for (Entry<String, Object> entry : fields.entrySet()) {
field(entry.getKey(), entry.getValue());
}
return this;
}
public Builder field(String fieldName, Object value) {
switch (fieldName) {
case Fields.ACCEPTABILITY_ID: this.acceptabilityId = (String) value; break;
case Fields.ATTRIBUTE_NAME: this.attributeName = (String) value; break;
case Fields.CHARACTERISTIC_TYPE_ID: this.characteristicTypeId = (String) value; break;
case Fields.CORRELATION_ID: this.correlationId = (String) value; break;
case Fields.DATA_TYPE: this.dataType = (DataType) value; break;
case Fields.DATA_VALUE: this.value = value; break;
case Fields.DESCRIPTION_FORMAT: this.descriptionFormat = (String) value; break;
case Fields.DESCRIPTION_LENGTH: this.descriptionLength = (Integer) value; break;
case Fields.MAP_ADVICE: this.mapAdvice = (String) value; break;
case Fields.MAP_CATEGORY_ID: this.mapCategoryId = (String) value; break;
case Fields.MAP_GROUP: this.mapGroup = (Integer) value; break;
case Fields.MAP_PRIORITY: this.mapPriority = (Integer) value; break;
case Fields.MAP_RULE: this.mapRule = (String) value; break;
case Fields.MAP_TARGET: this.mapTarget = (String) value; break;
case Fields.MAP_TARGET_DESCRIPTION: this.mapTargetDescription = (String) value; break;
case Fields.OPERATOR_ID: this.operatorId = (String) value; break;
case Fields.QUERY: this.query = (String) value; break;
case Fields.SOURCE_EFFECTIVE_TIME: this.sourceEffectiveTime = (Long) value; break;
case Fields.TARGET_COMPONENT: this.targetComponent = (String) value; break;
case Fields.TARGET_EFFECTIVE_TIME: this.targetEffectiveTime = (Long) value; break;
case Fields.UNIT_ID: this.unitId = (String) value; break;
case Fields.VALUE_ID: this.valueId = (String) value; break;
default: throw new UnsupportedOperationException("Unknown RF2 member field: " + fieldName);
}
return this;
}
@Override
protected Builder getSelf() {
return this;
}
public Builder referencedComponentId(final String referencedComponentId) {
this.referencedComponentId = referencedComponentId;
return this;
}
public Builder referenceSetId(final String referenceSetId) {
this.referenceSetId = referenceSetId;
return this;
}
public Builder referenceSetType(final SnomedRefSetType referenceSetType) {
this.referenceSetType = referenceSetType;
return this;
}
public Builder referencedComponentType(final short referencedComponentType) {
this.referencedComponentType = referencedComponentType;
return this;
}
public Builder targetComponent(String targetComponent) {
this.targetComponent = targetComponent;
return this;
}
Builder acceptabilityId(String acceptabilityId) {
this.acceptabilityId = acceptabilityId;
return getSelf();
}
Builder attributeName(String attributeName) {
this.attributeName = attributeName;
return getSelf();
}
Builder characteristicTypeId(final String characteristicTypeId) {
this.characteristicTypeId = characteristicTypeId;
return getSelf();
}
Builder correlationId(final String correlationId) {
this.correlationId = correlationId;
return getSelf();
}
Builder dataType(final DataType dataType) {
this.dataType = dataType;
return getSelf();
}
Builder descriptionFormat(final String descriptionFormat) {
this.descriptionFormat = descriptionFormat;
return getSelf();
}
Builder descriptionLength(final Integer descriptionLength) {
this.descriptionLength = descriptionLength;
return getSelf();
}
Builder mapAdvice(final String mapAdvice) {
this.mapAdvice = mapAdvice;
return getSelf();
}
Builder mapCategoryId(final String mapCategoryId) {
this.mapCategoryId = mapCategoryId;
return getSelf();
}
Builder mapGroup(final Integer mapGroup) {
this.mapGroup = mapGroup;
return getSelf();
}
Builder mapPriority(final Integer mapPriority) {
this.mapPriority = mapPriority;
return getSelf();
}
Builder mapRule(final String mapRule) {
this.mapRule = mapRule;
return getSelf();
}
Builder mapTarget(final String mapTarget) {
this.mapTarget = mapTarget;
return getSelf();
}
Builder mapTargetDescription(final String mapTargetDescription) {
this.mapTargetDescription = mapTargetDescription;
return getSelf();
}
Builder operatorId(final String operatorId) {
this.operatorId = operatorId;
return getSelf();
}
Builder query(final String query) {
this.query = query;
return getSelf();
}
Builder sourceEffectiveTime(final Long sourceEffectiveTime) {
this.sourceEffectiveTime = sourceEffectiveTime;
return getSelf();
}
Builder targetEffectiveTime(final Long targetEffectiveTime) {
this.targetEffectiveTime = targetEffectiveTime;
return getSelf();
}
Builder unitId(final String unitId) {
this.unitId = unitId;
return getSelf();
}
/**
* @deprecated - this is no longer a valid refset member index field, but required to make pre-5.4 dataset work with 5.4 without migration
*/
Builder value(final Object value) {
this.value = value;
return getSelf();
}
Builder decimalValue(final BigDecimal value) {
this.value = value;
return getSelf();
}
Builder booleanValue(final Boolean value) {
this.value = value;
return getSelf();
}
Builder integerValue(final Integer value) {
this.value = value;
return getSelf();
}
Builder stringValue(final String value) {
this.value = value;
return getSelf();
}
Builder valueId(String valueId) {
this.valueId = valueId;
return getSelf();
}
public SnomedRefSetMemberIndexEntry build() {
final SnomedRefSetMemberIndexEntry doc = new SnomedRefSetMemberIndexEntry(id,
label,
moduleId,
released,
active,
effectiveTime,
referencedComponentId,
referenceSetId,
referenceSetType,
referencedComponentType);
// association members
doc.targetComponent = targetComponent;
// attribute value
doc.valueId = valueId;
// concrete domain members
doc.dataType = dataType;
doc.attributeName = attributeName;
if (dataType != null) {
switch (dataType) {
case BOOLEAN:
if (value instanceof Boolean) {
doc.booleanValue = (Boolean) value;
} else if (value instanceof String) {
doc.booleanValue = SnomedRefSetUtil.deserializeValue(dataType, (String) value);
}
break;
case DECIMAL:
if (value instanceof BigDecimal) {
doc.decimalValue = (BigDecimal) value;
} else if (value instanceof String) {
doc.decimalValue = SnomedRefSetUtil.deserializeValue(dataType, (String) value);
}
break;
case INTEGER:
if (value instanceof Integer) {
doc.integerValue = (Integer) value;
} else if (value instanceof String) {
doc.integerValue = SnomedRefSetUtil.deserializeValue(dataType, (String) value);
}
break;
case STRING:
doc.stringValue = (String) value;
break;
default: throw new UnsupportedOperationException("Unsupported concrete domain data type: " + dataType);
}
}
doc.characteristicTypeId = characteristicTypeId;
doc.operatorId = operatorId;
doc.unitId = unitId;
// description
doc.descriptionFormat = descriptionFormat;
doc.descriptionLength = descriptionLength;
// language reference set
doc.acceptabilityId = acceptabilityId;
// module
doc.sourceEffectiveTime = sourceEffectiveTime;
doc.targetEffectiveTime = targetEffectiveTime;
// simple map
doc.mapTarget = mapTarget;
doc.mapTargetDescription = mapTargetDescription;
// complex map
doc.mapCategoryId = mapCategoryId;
doc.mapAdvice = mapAdvice;
doc.correlationId = correlationId;
doc.mapGroup = mapGroup;
doc.mapPriority = mapPriority;
doc.mapRule = mapRule;
// query
doc.query = query;
doc.setScore(score);
// metadata
doc.setBranchPath(branchPath);
doc.setCommitTimestamp(commitTimestamp);
doc.setStorageKey(storageKey);
doc.setReplacedIns(replacedIns);
doc.setSegmentId(segmentId);
return doc;
}
}
private final String referencedComponentId;
private final String referenceSetId;
private final SnomedRefSetType referenceSetType;
private final short referencedComponentType;
// Member specific fields, they can be null or emptyish values
// ASSOCIATION reference set members
private String targetComponent;
// ATTRIBUTE VALUE
private String valueId;
// CONCRETE DOMAIN reference set members
private DataType dataType;
private String attributeName;
// only one of these value fields should be set when this represents a concrete domain member
private String stringValue;
private Boolean booleanValue;
private Integer integerValue;
private BigDecimal decimalValue;
private String operatorId;
private String characteristicTypeId;
private String unitId;
// DESCRIPTION
private Integer descriptionLength;
private String descriptionFormat;
// LANGUAGE
private String acceptabilityId;
// MODULE
private Long sourceEffectiveTime;
private Long targetEffectiveTime;
// SIMPLE MAP reference set members
private String mapTarget;
private String mapTargetDescription;
// COMPLEX MAP
private String mapCategoryId;
private String correlationId;
private String mapAdvice;
private String mapRule;
private Integer mapGroup;
private Integer mapPriority;
// QUERY
private String query;
private SnomedRefSetMemberIndexEntry(final String id,
final String label,
final String moduleId,
final boolean released,
final boolean active,
final long effectiveTimeLong,
final String referencedComponentId,
final String referenceSetId,
final SnomedRefSetType referenceSetType,
final short referencedComponentType) {
super(id,
label,
referencedComponentId, // XXX: iconId is the referenced component identifier
moduleId,
released,
active,
effectiveTimeLong);
checkArgument(referencedComponentType >= CoreTerminologyBroker.UNSPECIFIED_NUMBER_SHORT, "Referenced component type '%s' is invalid.", referencedComponentType);
this.referencedComponentId = referencedComponentId;
this.referenceSetId = referenceSetId;
this.referenceSetType = referenceSetType;
this.referencedComponentType = referencedComponentType;
}
@Override
public String getContainerId() {
// XXX hack to make IHTSDO merge review API tests pass and work as before in 4.5
if (getReferenceSetType() == SnomedRefSetType.MODULE_DEPENDENCY) {
return null;
} else {
return getReferencedComponentId();
}
}
/**
* @return the referenced component identifier
*/
public String getReferencedComponentId() {
return referencedComponentId;
}
/**
* @return the identifier of the member's reference set
*/
public String getReferenceSetId() {
return referenceSetId;
}
/**
* @return the type of the member's reference set
*/
public SnomedRefSetType getReferenceSetType() {
return referenceSetType;
}
@JsonIgnore
@SuppressWarnings("unchecked")
public <T> T getValueAs() {
return (T) getValue();
}
@JsonIgnore
public Object getValue() {
if (dataType == null) {
return null;
} else {
switch (dataType) {
case BOOLEAN: return booleanValue;
case DECIMAL: return decimalValue;
case INTEGER: return integerValue;
case STRING: return stringValue;
default: throw new UnsupportedOperationException("Unsupported concrete domain data type: " + dataType);
}
}
}
@JsonProperty
BigDecimal getDecimalValue() {
return decimalValue;
}
@JsonProperty
Boolean getBooleanValue() {
return booleanValue;
}
@JsonProperty
Integer getIntegerValue() {
return integerValue;
}
@JsonProperty
String getStringValue() {
return stringValue;
}
public DataType getDataType() {
return dataType;
}
public String getUnitId() {
return unitId;
}
public String getAttributeName() {
return attributeName;
}
public String getOperatorId() {
return operatorId;
}
public String getCharacteristicTypeId() {
return characteristicTypeId;
}
public String getAcceptabilityId() {
return acceptabilityId;
}
public Integer getDescriptionLength() {
return descriptionLength;
}
public String getDescriptionFormat() {
return descriptionFormat;
}
public String getMapTarget() {
return mapTarget;
}
public Integer getMapGroup() {
return mapGroup;
}
public Integer getMapPriority() {
return mapPriority;
}
public String getMapRule() {
return mapRule;
}
public String getMapAdvice() {
return mapAdvice;
}
public String getMapCategoryId() {
return mapCategoryId;
}
public String getCorrelationId() {
return correlationId;
}
public String getMapTargetDescription() {
return mapTargetDescription;
}
public String getQuery() {
return query;
}
public String getTargetComponent() {
return targetComponent;
}
public String getValueId() {
return valueId;
}
public Long getSourceEffectiveTime() {
return sourceEffectiveTime;
}
public Long getTargetEffectiveTime() {
return targetEffectiveTime;
}
public short getReferencedComponentType() {
return referencedComponentType;
}
// model helper methods
@JsonIgnore
public Acceptability getAcceptability() {
return Acceptability.getByConceptId(getAcceptabilityId());
}
@JsonIgnore
public RelationshipRefinability getRefinability() {
return RelationshipRefinability.getByConceptId(getValueId());
}
@JsonIgnore
public InactivationIndicator getInactivationIndicator() {
return InactivationIndicator.getByConceptId(getValueId());
}
@JsonIgnore
public String getSourceEffectiveTimeAsString() {
return EffectiveTimes.format(getSourceEffectiveTime(), DateFormats.SHORT);
}
@JsonIgnore
public String getTargetEffectiveTimeAsString() {
return EffectiveTimes.format(getTargetEffectiveTime(), DateFormats.SHORT);
}
/**
* @return the {@code String} terminology component identifier of the component referenced in this member
*/
@JsonIgnore
public String getReferencedComponentTypeAsString() {
return CoreTerminologyBroker.getInstance().getTerminologyComponentId(referencedComponentType);
}
/**
* Helper which converts all non-null/empty additional fields to a values {@link Map} keyed by their field name;
* @return
*/
@JsonIgnore
public Map<String, Object> getAdditionalFields() {
final ImmutableMap.Builder<String, Object> builder = ImmutableMap.builder();
// ASSOCIATION refset members
putIfPresent(builder, Fields.TARGET_COMPONENT, getTargetComponent());
// ATTRIBUTE_VALUE refset members
putIfPresent(builder, Fields.VALUE_ID, getValueId());
// CONCRETE DOMAIN reference set members
putIfPresent(builder, Fields.DATA_TYPE, getDataType());
putIfPresent(builder, Fields.ATTRIBUTE_NAME, getAttributeName());
putIfPresent(builder, Fields.DATA_VALUE, getValue());
putIfPresent(builder, Fields.OPERATOR_ID, getOperatorId());
putIfPresent(builder, Fields.CHARACTERISTIC_TYPE_ID, getCharacteristicTypeId());
putIfPresent(builder, Fields.UNIT_ID, getUnitId());
// DESCRIPTION
putIfPresent(builder, Fields.DESCRIPTION_LENGTH, getDescriptionLength());
putIfPresent(builder, Fields.DESCRIPTION_FORMAT, getDescriptionFormat());
// LANGUAGE
putIfPresent(builder, Fields.ACCEPTABILITY_ID, getAcceptabilityId());
// MODULE
putIfPresent(builder, Fields.SOURCE_EFFECTIVE_TIME, getSourceEffectiveTime());
putIfPresent(builder, Fields.TARGET_EFFECTIVE_TIME, getTargetEffectiveTime());
// SIMPLE MAP reference set members
putIfPresent(builder, Fields.MAP_TARGET, getMapTarget());
putIfPresent(builder, Fields.MAP_TARGET_DESCRIPTION, getMapTargetDescription());
// COMPLEX MAP
putIfPresent(builder, Fields.MAP_CATEGORY_ID, getMapCategoryId());
putIfPresent(builder, Fields.CORRELATION_ID, getCorrelationId());
putIfPresent(builder, Fields.MAP_ADVICE, getMapAdvice());
putIfPresent(builder, Fields.MAP_RULE, getMapRule());
putIfPresent(builder, Fields.MAP_GROUP, getMapGroup());
putIfPresent(builder, Fields.MAP_PRIORITY, getMapPriority());
// QUERY
putIfPresent(builder, Fields.QUERY, getQuery());
return builder.build();
}
private static void putIfPresent(ImmutableMap.Builder<String, Object> builder, String key, Object value) {
if (key != null && value != null) {
builder.put(key, value);
}
}
@Override
protected ToStringHelper doToString() {
return super.doToString()
.add("referencedComponentId", referencedComponentId)
.add("referenceSetId", referenceSetId)
.add("referenceSetType", referenceSetType)
.add("referencedComponentType", referencedComponentType)
.add("targetComponent", targetComponent)
.add("valueId", valueId)
.add("dataType", dataType)
.add("attributeName", attributeName)
.add("value", getValue())
.add("operatorId", operatorId)
.add("characteristicTypeId", characteristicTypeId)
.add("unitId", unitId)
.add("descriptionLength", descriptionLength)
.add("descriptionFormat", descriptionFormat)
.add("acceptabilityId", acceptabilityId)
.add("sourceEffectiveTime", sourceEffectiveTime)
.add("targetEffectiveTime", targetEffectiveTime)
.add("mapTarget", mapTarget)
.add("mapTargetDescription", mapTargetDescription)
.add("mapCategoryId", mapCategoryId)
.add("correlationId", correlationId)
.add("mapAdvice", mapAdvice)
.add("mapRule", mapRule)
.add("mapGroup", mapGroup)
.add("mapPriority", mapPriority)
.add("query", query);
}
}
| snomed/com.b2international.snowowl.snomed.datastore/src/com/b2international/snowowl/snomed/datastore/index/entry/SnomedRefSetMemberIndexEntry.java | /*
* Copyright 2011-2017 B2i Healthcare Pte Ltd, http://b2i.sg
*
* 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.b2international.snowowl.snomed.datastore.index.entry;
import static com.b2international.index.query.Expressions.exactMatch;
import static com.b2international.index.query.Expressions.matchAny;
import static com.b2international.index.query.Expressions.matchAnyDecimal;
import static com.b2international.index.query.Expressions.matchAnyInt;
import static com.b2international.index.query.Expressions.matchRange;
import static com.b2international.snowowl.snomed.common.SnomedTerminologyComponentConstants.CONCEPT_NUMBER;
import static com.b2international.snowowl.snomed.common.SnomedTerminologyComponentConstants.DESCRIPTION_NUMBER;
import static com.b2international.snowowl.snomed.common.SnomedTerminologyComponentConstants.RELATIONSHIP_NUMBER;
import static com.google.common.base.Preconditions.checkArgument;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.Date;
import java.util.Map;
import java.util.Map.Entry;
import com.b2international.commons.StringUtils;
import com.b2international.index.Doc;
import com.b2international.index.query.Expression;
import com.b2international.snowowl.core.CoreTerminologyBroker;
import com.b2international.snowowl.core.date.DateFormats;
import com.b2international.snowowl.core.date.EffectiveTimes;
import com.b2international.snowowl.datastore.cdo.CDOIDUtils;
import com.b2international.snowowl.snomed.common.SnomedRf2Headers;
import com.b2international.snowowl.snomed.core.domain.Acceptability;
import com.b2international.snowowl.snomed.core.domain.InactivationIndicator;
import com.b2international.snowowl.snomed.core.domain.RelationshipRefinability;
import com.b2international.snowowl.snomed.core.domain.SnomedConcept;
import com.b2international.snowowl.snomed.core.domain.SnomedCoreComponent;
import com.b2international.snowowl.snomed.core.domain.SnomedDescription;
import com.b2international.snowowl.snomed.core.domain.SnomedRelationship;
import com.b2international.snowowl.snomed.core.domain.refset.SnomedReferenceSetMember;
import com.b2international.snowowl.snomed.datastore.SnomedRefSetUtil;
import com.b2international.snowowl.snomed.snomedrefset.DataType;
import com.b2international.snowowl.snomed.snomedrefset.SnomedAssociationRefSetMember;
import com.b2international.snowowl.snomed.snomedrefset.SnomedAttributeValueRefSetMember;
import com.b2international.snowowl.snomed.snomedrefset.SnomedComplexMapRefSetMember;
import com.b2international.snowowl.snomed.snomedrefset.SnomedConcreteDataTypeRefSetMember;
import com.b2international.snowowl.snomed.snomedrefset.SnomedDescriptionTypeRefSetMember;
import com.b2international.snowowl.snomed.snomedrefset.SnomedLanguageRefSetMember;
import com.b2international.snowowl.snomed.snomedrefset.SnomedModuleDependencyRefSetMember;
import com.b2international.snowowl.snomed.snomedrefset.SnomedQueryRefSetMember;
import com.b2international.snowowl.snomed.snomedrefset.SnomedRefSetMember;
import com.b2international.snowowl.snomed.snomedrefset.SnomedRefSetType;
import com.b2international.snowowl.snomed.snomedrefset.SnomedSimpleMapRefSetMember;
import com.b2international.snowowl.snomed.snomedrefset.util.SnomedRefSetSwitch;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
import com.google.common.base.Function;
import com.google.common.base.Objects.ToStringHelper;
import com.google.common.base.Strings;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableMap;
/**
* Lightweight representation of a SNOMED CT reference set member.
*/
@Doc
@JsonDeserialize(builder = SnomedRefSetMemberIndexEntry.Builder.class)
public final class SnomedRefSetMemberIndexEntry extends SnomedDocument {
private static final long serialVersionUID = 5198766293865046258L;
public static class Fields {
// known RF2 fields
public static final String REFERENCE_SET_ID = "referenceSetId"; // XXX different than the RF2 header field name
public static final String REFERENCED_COMPONENT_ID = SnomedRf2Headers.FIELD_REFERENCED_COMPONENT_ID;
public static final String ACCEPTABILITY_ID = SnomedRf2Headers.FIELD_ACCEPTABILITY_ID;
public static final String VALUE_ID = SnomedRf2Headers.FIELD_VALUE_ID;
public static final String TARGET_COMPONENT = SnomedRf2Headers.FIELD_TARGET_COMPONENT;
public static final String MAP_TARGET = SnomedRf2Headers.FIELD_MAP_TARGET;
public static final String MAP_TARGET_DESCRIPTION = SnomedRf2Headers.FIELD_MAP_TARGET_DESCRIPTION;
public static final String MAP_GROUP = SnomedRf2Headers.FIELD_MAP_GROUP;
public static final String MAP_PRIORITY = SnomedRf2Headers.FIELD_MAP_PRIORITY;
public static final String MAP_RULE = SnomedRf2Headers.FIELD_MAP_RULE;
public static final String MAP_ADVICE = SnomedRf2Headers.FIELD_MAP_ADVICE;
public static final String MAP_CATEGORY_ID = SnomedRf2Headers.FIELD_MAP_CATEGORY_ID;
public static final String CORRELATION_ID = SnomedRf2Headers.FIELD_CORRELATION_ID;
public static final String DESCRIPTION_FORMAT = SnomedRf2Headers.FIELD_DESCRIPTION_FORMAT;
public static final String DESCRIPTION_LENGTH = SnomedRf2Headers.FIELD_DESCRIPTION_LENGTH;
public static final String OPERATOR_ID = SnomedRf2Headers.FIELD_OPERATOR_ID;
public static final String UNIT_ID = SnomedRf2Headers.FIELD_UNIT_ID;
public static final String QUERY = SnomedRf2Headers.FIELD_QUERY;
public static final String CHARACTERISTIC_TYPE_ID = SnomedRf2Headers.FIELD_CHARACTERISTIC_TYPE_ID;
public static final String SOURCE_EFFECTIVE_TIME = SnomedRf2Headers.FIELD_SOURCE_EFFECTIVE_TIME;
public static final String TARGET_EFFECTIVE_TIME = SnomedRf2Headers.FIELD_TARGET_EFFECTIVE_TIME;
private static final String DATA_VALUE = SnomedRf2Headers.FIELD_VALUE;
public static final String ATTRIBUTE_NAME = SnomedRf2Headers.FIELD_ATTRIBUTE_NAME;
// extra index fields to store datatype and map target type
public static final String DATA_TYPE = "dataType";
public static final String REFSET_TYPE = "referenceSetType";
public static final String REFERENCED_COMPONENT_TYPE = "referencedComponentType";
// CD value fields per type
public static final String BOOLEAN_VALUE = "booleanValue";
public static final String STRING_VALUE = "stringValue";
public static final String INTEGER_VALUE = "integerValue";
public static final String DECIMAL_VALUE = "decimalValue";
}
public static Builder builder() {
return new Builder();
}
public static Builder builder(final SnomedRefSetMemberIndexEntry source) {
return builder()
.storageKey(source.getStorageKey())
.active(source.isActive())
.effectiveTime(source.getEffectiveTime())
.id(source.getId())
.moduleId(source.getModuleId())
.referencedComponentId(source.getReferencedComponentId())
.referencedComponentType(source.getReferencedComponentType())
.referenceSetId(source.getReferenceSetId())
.referenceSetType(source.getReferenceSetType())
.released(source.isReleased())
.fields(source.getAdditionalFields());
}
public static final Builder builder(final SnomedReferenceSetMember input) {
final Builder builder = builder()
.storageKey(input.getStorageKey())
.active(input.isActive())
.effectiveTime(EffectiveTimes.getEffectiveTime(input.getEffectiveTime()))
.id(input.getId())
.moduleId(input.getModuleId())
.referencedComponentId(input.getReferencedComponent().getId())
.referenceSetId(input.getReferenceSetId())
.referenceSetType(input.type())
.released(input.isReleased());
if (input.getReferencedComponent() instanceof SnomedConcept) {
builder.referencedComponentType(CONCEPT_NUMBER);
} else if (input.getReferencedComponent() instanceof SnomedDescription) {
builder.referencedComponentType(DESCRIPTION_NUMBER);
} else if (input.getReferencedComponent() instanceof SnomedRelationship) {
builder.referencedComponentType(RELATIONSHIP_NUMBER);
} else {
builder.referencedComponentType(CoreTerminologyBroker.UNSPECIFIED_NUMBER_SHORT);
}
for (Entry<String, Object> entry : input.getProperties().entrySet()) {
final Object value = entry.getValue();
final String fieldName = entry.getKey();
// certain RF2 fields can be expanded into full blown representation class, get the ID in this case
if (value instanceof SnomedCoreComponent) {
builder.field(fieldName, ((SnomedCoreComponent) value).getId());
} else {
builder.field(fieldName, convertValue(entry.getKey(), value));
}
}
return builder;
}
public static Builder builder(SnomedRefSetMember refSetMember) {
final Builder builder = SnomedRefSetMemberIndexEntry.builder()
.storageKey(CDOIDUtils.asLong(refSetMember.cdoID()))
.id(refSetMember.getUuid())
.moduleId(refSetMember.getModuleId())
.active(refSetMember.isActive())
.released(refSetMember.isReleased())
.effectiveTime(refSetMember.isSetEffectiveTime() ? refSetMember.getEffectiveTime().getTime() : EffectiveTimes.UNSET_EFFECTIVE_TIME)
.referenceSetId(refSetMember.getRefSetIdentifierId())
.referenceSetType(refSetMember.getRefSet().getType())
.referencedComponentType(refSetMember.getReferencedComponentType())
.referencedComponentId(refSetMember.getReferencedComponentId());
return new SnomedRefSetSwitch<Builder>() {
@Override
public Builder caseSnomedAssociationRefSetMember(final SnomedAssociationRefSetMember associationMember) {
return builder.targetComponent(associationMember.getTargetComponentId());
}
@Override
public Builder caseSnomedAttributeValueRefSetMember(final SnomedAttributeValueRefSetMember attributeValueMember) {
return builder.field(Fields.VALUE_ID, attributeValueMember.getValueId());
}
@Override
public Builder caseSnomedConcreteDataTypeRefSetMember(final SnomedConcreteDataTypeRefSetMember concreteDataTypeMember) {
return builder.field(Fields.ATTRIBUTE_NAME, concreteDataTypeMember.getLabel())
.field(Fields.DATA_TYPE, concreteDataTypeMember.getDataType())
.field(Fields.DATA_VALUE, concreteDataTypeMember.getSerializedValue())
.field(Fields.CHARACTERISTIC_TYPE_ID, concreteDataTypeMember.getCharacteristicTypeId())
.field(Fields.OPERATOR_ID, concreteDataTypeMember.getOperatorComponentId())
.field(Fields.UNIT_ID, Strings.nullToEmpty(concreteDataTypeMember.getUomComponentId()));
}
@Override
public Builder caseSnomedDescriptionTypeRefSetMember(final SnomedDescriptionTypeRefSetMember descriptionTypeMember) {
return builder
.field(Fields.DESCRIPTION_FORMAT, descriptionTypeMember.getDescriptionFormat())
.field(Fields.DESCRIPTION_LENGTH, descriptionTypeMember.getDescriptionLength());
}
@Override
public Builder caseSnomedLanguageRefSetMember(final SnomedLanguageRefSetMember languageMember) {
return builder.field(Fields.ACCEPTABILITY_ID, languageMember.getAcceptabilityId());
}
@Override
public Builder caseSnomedQueryRefSetMember(final SnomedQueryRefSetMember queryMember) {
return builder.field(Fields.QUERY, queryMember.getQuery());
}
@Override
public Builder caseSnomedSimpleMapRefSetMember(final SnomedSimpleMapRefSetMember mapRefSetMember) {
return builder
.field(Fields.MAP_TARGET, mapRefSetMember.getMapTargetComponentId())
.field(Fields.MAP_TARGET_DESCRIPTION, mapRefSetMember.getMapTargetComponentDescription());
}
@Override
public Builder caseSnomedComplexMapRefSetMember(final SnomedComplexMapRefSetMember mapRefSetMember) {
return builder
.field(Fields.MAP_TARGET, mapRefSetMember.getMapTargetComponentId())
.field(Fields.CORRELATION_ID, mapRefSetMember.getCorrelationId())
.field(Fields.MAP_GROUP, Integer.valueOf(mapRefSetMember.getMapGroup()))
.field(Fields.MAP_ADVICE, Strings.nullToEmpty(mapRefSetMember.getMapAdvice()))
.field(Fields.MAP_PRIORITY, Integer.valueOf(mapRefSetMember.getMapPriority()))
.field(Fields.MAP_RULE, Strings.nullToEmpty(mapRefSetMember.getMapRule()))
// extended refset
.field(Fields.MAP_CATEGORY_ID, Strings.nullToEmpty(mapRefSetMember.getMapCategoryId()));
}
@Override
public Builder caseSnomedModuleDependencyRefSetMember(SnomedModuleDependencyRefSetMember member) {
return builder
.field(Fields.SOURCE_EFFECTIVE_TIME, EffectiveTimes.getEffectiveTime(member.getSourceEffectiveTime()))
.field(Fields.TARGET_EFFECTIVE_TIME, EffectiveTimes.getEffectiveTime(member.getTargetEffectiveTime()));
}
@Override
public Builder caseSnomedRefSetMember(SnomedRefSetMember object) {
return builder;
};
}.doSwitch(refSetMember);
}
private static Object convertValue(String rf2Field, Object value) {
switch (rf2Field) {
case SnomedRf2Headers.FIELD_SOURCE_EFFECTIVE_TIME:
case SnomedRf2Headers.FIELD_TARGET_EFFECTIVE_TIME:
if (value instanceof String && !StringUtils.isEmpty((String) value)) {
Date parsedDate = EffectiveTimes.parse((String) value, DateFormats.SHORT);
return EffectiveTimes.getEffectiveTime(parsedDate);
} else {
return EffectiveTimes.UNSET_EFFECTIVE_TIME;
}
default:
return value;
}
}
public static Collection<SnomedRefSetMemberIndexEntry> from(final Iterable<SnomedReferenceSetMember> refSetMembers) {
return FluentIterable.from(refSetMembers).transform(new Function<SnomedReferenceSetMember, SnomedRefSetMemberIndexEntry>() {
@Override
public SnomedRefSetMemberIndexEntry apply(final SnomedReferenceSetMember refSetMember) {
return builder(refSetMember).build();
}
}).toList();
}
public static final class Expressions extends SnomedDocument.Expressions {
public static Expression referenceSetId(String referenceSetId) {
return exactMatch(Fields.REFERENCE_SET_ID, referenceSetId);
}
public static Expression referenceSetId(Collection<String> referenceSetIds) {
return matchAny(Fields.REFERENCE_SET_ID, referenceSetIds);
}
public static Expression referencedComponentId(String referencedComponentId) {
return exactMatch(Fields.REFERENCED_COMPONENT_ID, referencedComponentId);
}
public static Expression mapTargets(Collection<String> mapTargets) {
return matchAny(Fields.MAP_TARGET, mapTargets);
}
public static Expression referencedComponentIds(Collection<String> referencedComponentIds) {
return matchAny(Fields.REFERENCED_COMPONENT_ID, referencedComponentIds);
}
public static Expression targetComponents(Collection<String> targetComponentIds) {
return matchAny(Fields.TARGET_COMPONENT, targetComponentIds);
}
public static Expression acceptabilityIds(Collection<String> acceptabilityIds) {
return matchAny(Fields.ACCEPTABILITY_ID, acceptabilityIds);
}
public static Expression characteristicTypeIds(Collection<String> characteristicTypeIds) {
return matchAny(Fields.CHARACTERISTIC_TYPE_ID, characteristicTypeIds);
}
public static Expression correlationIds(Collection<String> correlationIds) {
return matchAny(Fields.CORRELATION_ID, correlationIds);
}
public static Expression descriptionFormats(Collection<String> descriptionFormats) {
return matchAny(Fields.DESCRIPTION_FORMAT, descriptionFormats);
}
public static Expression mapCategoryIds(Collection<String> mapCategoryIds) {
return matchAny(Fields.MAP_CATEGORY_ID, mapCategoryIds);
}
public static Expression operatorIds(Collection<String> operatorIds) {
return matchAny(Fields.OPERATOR_ID, operatorIds);
}
public static Expression unitIds(Collection<String> unitIds) {
return matchAny(Fields.UNIT_ID, unitIds);
}
public static Expression valueIds(Collection<String> valueIds) {
return matchAny(Fields.VALUE_ID, valueIds);
}
public static Expression values(DataType type, Collection<? extends Object> values) {
switch (type) {
case STRING:
return matchAny(Fields.STRING_VALUE, FluentIterable.from(values).filter(String.class).toSet());
case INTEGER:
return matchAnyInt(Fields.INTEGER_VALUE, FluentIterable.from(values).filter(Integer.class).toSet());
case DECIMAL:
return matchAnyDecimal(Fields.DECIMAL_VALUE, FluentIterable.from(values).filter(BigDecimal.class).toSet());
default:
throw new UnsupportedOperationException("Unsupported data type when filtering by values, " + type);
}
}
public static Expression valueRange(DataType type, final Object lower, final Object upper, boolean includeLower, boolean includeUpper) {
switch (type) {
case STRING:
return matchRange(Fields.STRING_VALUE, (String) lower, (String) upper, includeLower, includeUpper);
case INTEGER:
return matchRange(Fields.INTEGER_VALUE, (Integer) lower, (Integer) upper, includeLower, includeUpper);
case DECIMAL:
return matchRange(Fields.DECIMAL_VALUE, (BigDecimal) lower, (BigDecimal) upper, includeLower, includeUpper);
default:
throw new UnsupportedOperationException("Unsupported data type when filtering by values, " + type);
}
}
public static Expression dataTypes(Collection<DataType> dataTypes) {
return matchAny(Fields.DATA_TYPE, FluentIterable.from(dataTypes).transform(new Function<DataType, String>() {
@Override
public String apply(DataType input) {
return input.name();
}
}).toSet());
}
public static Expression attributeNames(Collection<String> attributeNames) {
return matchAny(Fields.ATTRIBUTE_NAME, attributeNames);
}
public static Expression sourceEffectiveTime(long effectiveTime) {
return exactMatch(Fields.SOURCE_EFFECTIVE_TIME, effectiveTime);
}
public static Expression targetEffectiveTime(long effectiveTime) {
return exactMatch(Fields.TARGET_EFFECTIVE_TIME, effectiveTime);
}
public static Expression refSetTypes(Collection<SnomedRefSetType> refSetTypes) {
return matchAny(Fields.REFSET_TYPE, FluentIterable.from(refSetTypes).transform(new Function<SnomedRefSetType, String>() {
@Override
public String apply(SnomedRefSetType input) {
return input.name();
}
}).toSet());
}
}
@JsonPOJOBuilder(withPrefix="")
public static final class Builder extends SnomedDocumentBuilder<Builder> {
private String referencedComponentId;
private String referenceSetId;
private SnomedRefSetType referenceSetType;
private short referencedComponentType;
// Member specific fields, they can be null or emptyish values
// ASSOCIATION reference set members
private String targetComponent;
// ATTRIBUTE VALUE
private String valueId;
// CONCRETE DOMAIN reference set members
private DataType dataType;
private String attributeName;
private Object value;
private String operatorId;
private String characteristicTypeId;
private String unitId;
// DESCRIPTION
private Integer descriptionLength;
private String descriptionFormat;
// LANGUAGE
private String acceptabilityId;
// MODULE
private Long sourceEffectiveTime;
private Long targetEffectiveTime;
// SIMPLE MAP reference set members
private String mapTarget;
private String mapTargetDescription;
// COMPLEX MAP
private String mapCategoryId;
private String correlationId;
private String mapAdvice;
private String mapRule;
private Integer mapGroup;
private Integer mapPriority;
// QUERY
private String query;
@JsonCreator
private Builder() {
// Disallow instantiation outside static method
}
public Builder fields(Map<String, Object> fields) {
for (Entry<String, Object> entry : fields.entrySet()) {
field(entry.getKey(), entry.getValue());
}
return this;
}
public Builder field(String fieldName, Object value) {
switch (fieldName) {
case Fields.ACCEPTABILITY_ID: this.acceptabilityId = (String) value; break;
case Fields.ATTRIBUTE_NAME: this.attributeName = (String) value; break;
case Fields.CHARACTERISTIC_TYPE_ID: this.characteristicTypeId = (String) value; break;
case Fields.CORRELATION_ID: this.correlationId = (String) value; break;
case Fields.DATA_TYPE: this.dataType = (DataType) value; break;
case Fields.DATA_VALUE: this.value = value; break;
case Fields.DESCRIPTION_FORMAT: this.descriptionFormat = (String) value; break;
case Fields.DESCRIPTION_LENGTH: this.descriptionLength = (Integer) value; break;
case Fields.MAP_ADVICE: this.mapAdvice = (String) value; break;
case Fields.MAP_CATEGORY_ID: this.mapCategoryId = (String) value; break;
case Fields.MAP_GROUP: this.mapGroup = (Integer) value; break;
case Fields.MAP_PRIORITY: this.mapPriority = (Integer) value; break;
case Fields.MAP_RULE: this.mapRule = (String) value; break;
case Fields.MAP_TARGET: this.mapTarget = (String) value; break;
case Fields.MAP_TARGET_DESCRIPTION: this.mapTargetDescription = (String) value; break;
case Fields.OPERATOR_ID: this.operatorId = (String) value; break;
case Fields.QUERY: this.query = (String) value; break;
case Fields.SOURCE_EFFECTIVE_TIME: this.sourceEffectiveTime = (Long) value; break;
case Fields.TARGET_COMPONENT: this.targetComponent = (String) value; break;
case Fields.TARGET_EFFECTIVE_TIME: this.targetEffectiveTime = (Long) value; break;
case Fields.UNIT_ID: this.unitId = (String) value; break;
case Fields.VALUE_ID: this.valueId = (String) value; break;
default: throw new UnsupportedOperationException("Unknown RF2 member field: " + fieldName);
}
return this;
}
@Override
protected Builder getSelf() {
return this;
}
public Builder referencedComponentId(final String referencedComponentId) {
this.referencedComponentId = referencedComponentId;
return this;
}
public Builder referenceSetId(final String referenceSetId) {
this.referenceSetId = referenceSetId;
return this;
}
public Builder referenceSetType(final SnomedRefSetType referenceSetType) {
this.referenceSetType = referenceSetType;
return this;
}
public Builder referencedComponentType(final short referencedComponentType) {
this.referencedComponentType = referencedComponentType;
return this;
}
public Builder targetComponent(String targetComponent) {
this.targetComponent = targetComponent;
return this;
}
Builder acceptabilityId(String acceptabilityId) {
this.acceptabilityId = acceptabilityId;
return getSelf();
}
Builder attributeName(String attributeName) {
this.attributeName = attributeName;
return getSelf();
}
Builder characteristicTypeId(final String characteristicTypeId) {
this.characteristicTypeId = characteristicTypeId;
return getSelf();
}
Builder correlationId(final String correlationId) {
this.correlationId = correlationId;
return getSelf();
}
Builder dataType(final DataType dataType) {
this.dataType = dataType;
return getSelf();
}
Builder descriptionFormat(final String descriptionFormat) {
this.descriptionFormat = descriptionFormat;
return getSelf();
}
Builder descriptionLength(final Integer descriptionLength) {
this.descriptionLength = descriptionLength;
return getSelf();
}
Builder mapAdvice(final String mapAdvice) {
this.mapAdvice = mapAdvice;
return getSelf();
}
Builder mapCategoryId(final String mapCategoryId) {
this.mapCategoryId = mapCategoryId;
return getSelf();
}
Builder mapGroup(final Integer mapGroup) {
this.mapGroup = mapGroup;
return getSelf();
}
Builder mapPriority(final Integer mapPriority) {
this.mapPriority = mapPriority;
return getSelf();
}
Builder mapRule(final String mapRule) {
this.mapRule = mapRule;
return getSelf();
}
Builder mapTarget(final String mapTarget) {
this.mapTarget = mapTarget;
return getSelf();
}
Builder mapTargetDescription(final String mapTargetDescription) {
this.mapTargetDescription = mapTargetDescription;
return getSelf();
}
Builder operatorId(final String operatorId) {
this.operatorId = operatorId;
return getSelf();
}
Builder query(final String query) {
this.query = query;
return getSelf();
}
Builder sourceEffectiveTime(final Long sourceEffectiveTime) {
this.sourceEffectiveTime = sourceEffectiveTime;
return getSelf();
}
Builder targetEffectiveTime(final Long targetEffectiveTime) {
this.targetEffectiveTime = targetEffectiveTime;
return getSelf();
}
Builder unitId(final String unitId) {
this.unitId = unitId;
return getSelf();
}
/**
* @deprecated - this is no longer a valid refset member index field, but required to make pre-5.4 dataset work with 5.4 without migration
*/
Builder value(final Object value) {
this.value = value;
return getSelf();
}
Builder decimalValue(final BigDecimal value) {
this.value = value;
return getSelf();
}
Builder booleanValue(final Boolean value) {
this.value = value;
return getSelf();
}
Builder integerValue(final Integer value) {
this.value = value;
return getSelf();
}
Builder stringValue(final String value) {
this.value = value;
return getSelf();
}
Builder valueId(String valueId) {
this.valueId = valueId;
return getSelf();
}
public SnomedRefSetMemberIndexEntry build() {
final SnomedRefSetMemberIndexEntry doc = new SnomedRefSetMemberIndexEntry(id,
label,
moduleId,
released,
active,
effectiveTime,
referencedComponentId,
referenceSetId,
referenceSetType,
referencedComponentType);
// association members
doc.targetComponent = targetComponent;
// attribute value
doc.valueId = valueId;
// concrete domain members
doc.dataType = dataType;
doc.attributeName = attributeName;
if (dataType != null) {
switch (dataType) {
case BOOLEAN:
if (value instanceof Boolean) {
doc.booleanValue = (Boolean) value;
} else if (value instanceof String) {
doc.booleanValue = SnomedRefSetUtil.deserializeValue(dataType, (String) value);
}
break;
case DECIMAL:
if (value instanceof BigDecimal) {
doc.decimalValue = (BigDecimal) value;
} else if (value instanceof String) {
doc.decimalValue = SnomedRefSetUtil.deserializeValue(dataType, (String) value);
}
break;
case INTEGER:
if (value instanceof Integer) {
doc.integerValue = (Integer) value;
} else if (value instanceof String) {
doc.integerValue = SnomedRefSetUtil.deserializeValue(dataType, (String) value);
}
break;
case STRING:
doc.stringValue = (String) value;
break;
default: throw new UnsupportedOperationException("Unsupported concrete domain data type: " + dataType);
}
}
doc.characteristicTypeId = characteristicTypeId;
doc.operatorId = operatorId;
doc.unitId = unitId;
// description
doc.descriptionFormat = descriptionFormat;
doc.descriptionLength = descriptionLength;
// language reference set
doc.acceptabilityId = acceptabilityId;
// module
doc.sourceEffectiveTime = sourceEffectiveTime;
doc.targetEffectiveTime = targetEffectiveTime;
// simple map
doc.mapTarget = mapTarget;
doc.mapTargetDescription = mapTargetDescription;
// complex map
doc.mapCategoryId = mapCategoryId;
doc.mapAdvice = mapAdvice;
doc.correlationId = correlationId;
doc.mapGroup = mapGroup;
doc.mapPriority = mapPriority;
doc.mapRule = mapRule;
// query
doc.query = query;
doc.setScore(score);
// metadata
doc.setBranchPath(branchPath);
doc.setCommitTimestamp(commitTimestamp);
doc.setStorageKey(storageKey);
doc.setReplacedIns(replacedIns);
doc.setSegmentId(segmentId);
return doc;
}
}
private final String referencedComponentId;
private final String referenceSetId;
private final SnomedRefSetType referenceSetType;
private final short referencedComponentType;
// Member specific fields, they can be null or emptyish values
// ASSOCIATION reference set members
private String targetComponent;
// ATTRIBUTE VALUE
private String valueId;
// CONCRETE DOMAIN reference set members
private DataType dataType;
private String attributeName;
// only one of these value fields should be set when this represents a concrete domain member
private String stringValue;
private Boolean booleanValue;
private Integer integerValue;
private BigDecimal decimalValue;
private String operatorId;
private String characteristicTypeId;
private String unitId;
// DESCRIPTION
private Integer descriptionLength;
private String descriptionFormat;
// LANGUAGE
private String acceptabilityId;
// MODULE
private Long sourceEffectiveTime;
private Long targetEffectiveTime;
// SIMPLE MAP reference set members
private String mapTarget;
private String mapTargetDescription;
// COMPLEX MAP
private String mapCategoryId;
private String correlationId;
private String mapAdvice;
private String mapRule;
private Integer mapGroup;
private Integer mapPriority;
// QUERY
private String query;
private SnomedRefSetMemberIndexEntry(final String id,
final String label,
final String moduleId,
final boolean released,
final boolean active,
final long effectiveTimeLong,
final String referencedComponentId,
final String referenceSetId,
final SnomedRefSetType referenceSetType,
final short referencedComponentType) {
super(id,
label,
referencedComponentId, // XXX: iconId is the referenced component identifier
moduleId,
released,
active,
effectiveTimeLong);
checkArgument(referencedComponentType >= CoreTerminologyBroker.UNSPECIFIED_NUMBER_SHORT, "Referenced component type '%s' is invalid.", referencedComponentType);
this.referencedComponentId = referencedComponentId;
this.referenceSetId = referenceSetId;
this.referenceSetType = referenceSetType;
this.referencedComponentType = referencedComponentType;
}
@Override
public String getContainerId() {
// XXX hack to make IHTSDO merge review API tests pass and work as before in 4.5
if (getReferenceSetType() == SnomedRefSetType.MODULE_DEPENDENCY) {
return null;
} else {
return getReferencedComponentId();
}
}
/**
* @return the referenced component identifier
*/
public String getReferencedComponentId() {
return referencedComponentId;
}
/**
* @return the identifier of the member's reference set
*/
public String getReferenceSetId() {
return referenceSetId;
}
/**
* @return the type of the member's reference set
*/
public SnomedRefSetType getReferenceSetType() {
return referenceSetType;
}
@JsonIgnore
@SuppressWarnings("unchecked")
public <T> T getValueAs() {
return (T) getValue();
}
@JsonIgnore
public Object getValue() {
if (dataType == null) {
return null;
} else {
switch (dataType) {
case BOOLEAN: return booleanValue;
case DECIMAL: return decimalValue;
case INTEGER: return integerValue;
case STRING: return stringValue;
default: throw new UnsupportedOperationException("Unsupported concrete domain data type: " + dataType);
}
}
}
@JsonProperty
BigDecimal getDecimalValue() {
return decimalValue;
}
@JsonProperty
Boolean getBooleanValue() {
return booleanValue;
}
@JsonProperty
Integer getIntegerValue() {
return integerValue;
}
@JsonProperty
String getStringValue() {
return stringValue;
}
public DataType getDataType() {
return dataType;
}
public String getUnitId() {
return unitId;
}
public String getAttributeName() {
return attributeName;
}
public String getOperatorId() {
return operatorId;
}
public String getCharacteristicTypeId() {
return characteristicTypeId;
}
public String getAcceptabilityId() {
return acceptabilityId;
}
public Integer getDescriptionLength() {
return descriptionLength;
}
public String getDescriptionFormat() {
return descriptionFormat;
}
public String getMapTarget() {
return mapTarget;
}
public Integer getMapGroup() {
return mapGroup;
}
public Integer getMapPriority() {
return mapPriority;
}
public String getMapRule() {
return mapRule;
}
public String getMapAdvice() {
return mapAdvice;
}
public String getMapCategoryId() {
return mapCategoryId;
}
public String getCorrelationId() {
return correlationId;
}
public String getMapTargetDescription() {
return mapTargetDescription;
}
public String getQuery() {
return query;
}
public String getTargetComponent() {
return targetComponent;
}
public String getValueId() {
return valueId;
}
public Long getSourceEffectiveTime() {
return sourceEffectiveTime;
}
public Long getTargetEffectiveTime() {
return targetEffectiveTime;
}
public short getReferencedComponentType() {
return referencedComponentType;
}
// model helper methods
@JsonIgnore
public Acceptability getAcceptability() {
return Acceptability.getByConceptId(getAcceptabilityId());
}
@JsonIgnore
public RelationshipRefinability getRefinability() {
return RelationshipRefinability.getByConceptId(getValueId());
}
@JsonIgnore
public InactivationIndicator getInactivationIndicator() {
return InactivationIndicator.getByConceptId(getValueId());
}
@JsonIgnore
public String getSourceEffectiveTimeAsString() {
return EffectiveTimes.format(getSourceEffectiveTime(), DateFormats.SHORT);
}
@JsonIgnore
public String getTargetEffectiveTimeAsString() {
return EffectiveTimes.format(getTargetEffectiveTime(), DateFormats.SHORT);
}
/**
* @return the {@code String} terminology component identifier of the component referenced in this member
*/
@JsonIgnore
public String getReferencedComponentTypeAsString() {
return CoreTerminologyBroker.getInstance().getTerminologyComponentId(referencedComponentType);
}
/**
* Helper which converts all non-null/empty additional fields to a values {@link Map} keyed by their field name;
* @return
*/
@JsonIgnore
public Map<String, Object> getAdditionalFields() {
final ImmutableMap.Builder<String, Object> builder = ImmutableMap.builder();
// ASSOCIATION refset members
putIfPresent(builder, Fields.TARGET_COMPONENT, getTargetComponent());
// ATTRIBUTE_VALUE refset members
putIfPresent(builder, Fields.VALUE_ID, getValueId());
// CONCRETE DOMAIN reference set members
putIfPresent(builder, Fields.DATA_TYPE, getDataType());
putIfPresent(builder, Fields.ATTRIBUTE_NAME, getAttributeName());
putIfPresent(builder, Fields.DATA_VALUE, getValue());
putIfPresent(builder, Fields.OPERATOR_ID, getOperatorId());
putIfPresent(builder, Fields.CHARACTERISTIC_TYPE_ID, getCharacteristicTypeId());
putIfPresent(builder, Fields.UNIT_ID, getUnitId());
// DESCRIPTION
putIfPresent(builder, Fields.DESCRIPTION_LENGTH, getDescriptionLength());
putIfPresent(builder, Fields.DESCRIPTION_FORMAT, getDescriptionFormat());
// LANGUAGE
putIfPresent(builder, Fields.ACCEPTABILITY_ID, getAcceptabilityId());
// MODULE
putIfPresent(builder, Fields.SOURCE_EFFECTIVE_TIME, getSourceEffectiveTime());
putIfPresent(builder, Fields.TARGET_EFFECTIVE_TIME, getTargetEffectiveTime());
// SIMPLE MAP reference set members
putIfPresent(builder, Fields.MAP_TARGET, getMapTarget());
putIfPresent(builder, Fields.MAP_TARGET_DESCRIPTION, getMapTargetDescription());
// COMPLEX MAP
putIfPresent(builder, Fields.MAP_CATEGORY_ID, getMapCategoryId());
putIfPresent(builder, Fields.CORRELATION_ID, getCorrelationId());
putIfPresent(builder, Fields.MAP_ADVICE, getMapAdvice());
putIfPresent(builder, Fields.MAP_RULE, getMapRule());
putIfPresent(builder, Fields.MAP_GROUP, getMapGroup());
putIfPresent(builder, Fields.MAP_PRIORITY, getMapPriority());
// QUERY
putIfPresent(builder, Fields.QUERY, getQuery());
return builder.build();
}
private static void putIfPresent(ImmutableMap.Builder<String, Object> builder, String key, Object value) {
if (key != null && value != null) {
builder.put(key, value);
}
}
@Override
protected ToStringHelper doToString() {
return super.doToString()
.add("referencedComponentId", referencedComponentId)
.add("referenceSetId", referenceSetId)
.add("referenceSetType", referenceSetType)
.add("referencedComponentType", referencedComponentType)
.add("targetComponent", targetComponent)
.add("valueId", valueId)
.add("dataType", dataType)
.add("attributeName", attributeName)
.add("value", getValue())
.add("operatorId", operatorId)
.add("characteristicTypeId", characteristicTypeId)
.add("unitId", unitId)
.add("descriptionLength", descriptionLength)
.add("descriptionFormat", descriptionFormat)
.add("acceptabilityId", acceptabilityId)
.add("sourceEffectiveTime", sourceEffectiveTime)
.add("targetEffectiveTime", targetEffectiveTime)
.add("mapTarget", mapTarget)
.add("mapTargetDescription", mapTargetDescription)
.add("mapCategoryId", mapCategoryId)
.add("correlationId", correlationId)
.add("mapAdvice", mapAdvice)
.add("mapRule", mapRule)
.add("mapGroup", mapGroup)
.add("mapPriority", mapPriority)
.add("query", query);
}
}
| [snomed] extends SnomedDocument.Fields in SnomedRefSetMemberIndexEntry | snomed/com.b2international.snowowl.snomed.datastore/src/com/b2international/snowowl/snomed/datastore/index/entry/SnomedRefSetMemberIndexEntry.java | [snomed] extends SnomedDocument.Fields in SnomedRefSetMemberIndexEntry | <ide><path>nomed/com.b2international.snowowl.snomed.datastore/src/com/b2international/snowowl/snomed/datastore/index/entry/SnomedRefSetMemberIndexEntry.java
<ide>
<ide> private static final long serialVersionUID = 5198766293865046258L;
<ide>
<del> public static class Fields {
<add> public static class Fields extends SnomedDocument.Fields {
<ide> // known RF2 fields
<ide> public static final String REFERENCE_SET_ID = "referenceSetId"; // XXX different than the RF2 header field name
<ide> public static final String REFERENCED_COMPONENT_ID = SnomedRf2Headers.FIELD_REFERENCED_COMPONENT_ID; |
|
Java | mit | d1ca56ee0d2a9fe37e42dd4f4b4a459f3225e4cc | 0 | bin-liu/TYComponent,bin-liu/TYComponent,bin-liu/TYComponent | /**
* The MIT License (MIT)
* Copyright (c) 2012-2014 唐虞科技(TangyuSoft) Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.tangyu.component.service.remind;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.TextUtils;
import com.tangyu.component.Util;
import com.tangyu.component.util.ICopyFrom;
import java.util.Calendar;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;
/**
* The data of remind service.<br>
* Demo : {@link com.tangyu.component.demo.service.remind.RemindData}
* @author bin
*/
public class TYRemindData implements Parcelable, ICopyFrom {
public static final String TABCOL_ID = "_id";
public static final String TABCOL_TIME = "time";
public static final String TABCOL_REMINDSTATE = "REMIND_STATE";
public static final String TABCOL_ENABLE = "enable";
public static final String TABCOL_UUID = "uuid";
public static final int REMIND_STATE_REMINDED = -1;
public static final int REMIND_STATE_UNREMIND = 0;
public static final int REMIND_STATE_REMINDDING = 1;
public static final int REMIND_STATE_INVALID = -2;
public static Comparator<? super TYRemindData> COMPARATOR_FOR_REMIND_TIME = new Comparator<TYRemindData>() {
@Override
public int compare(TYRemindData lhs, TYRemindData rhs) {
return lhs.getmRemindTime() == rhs.getmRemindTime() ? 0 : lhs.getmRemindTime() < rhs.getmRemindTime() ? -1 : 1;
}
};
protected int mRemindId;
protected long mRemindTime;
protected int mRemindState;
protected boolean mEnable = true;
protected String mUUID = UUID.randomUUID().toString();
protected TYRemindData() {
}
protected TYRemindData(TYRemindData r) {
mRemindId = r.mRemindId;
mRemindTime = r.mRemindTime;
mRemindState = r.mRemindState;
mEnable = r.mEnable;
mUUID = r.mUUID;
}
protected TYRemindData(Parcel in) {
mRemindId = in.readInt();
mRemindTime = in.readLong();
mRemindState = in.readInt();
mEnable = in.readInt() == 0 ? false : true;
mUUID = in.readString();
}
public int getmRemindId() {
return mRemindId;
}
public void setmRemindId(int mRemindId) {
this.mRemindId = mRemindId;
}
public long getmRemindTime() {
return mRemindTime;
}
public void setmRemindTime(long mRemindTime) {
this.mRemindTime = mRemindTime;
}
public int getmRemindState() {
return mRemindState;
}
public void setmRemindState(int mRemindState) {
this.mRemindState = mRemindState;
}
public boolean ismEnable() {
return mEnable;
}
public void setmEnable(boolean mEnable) {
this.mEnable = mEnable;
}
public String getmUUID() {
return mUUID;
}
public void setmUUID(String mUUID) {
this.mUUID = mUUID;
}
@Override
public boolean equals(Object o) {
TYRemindData data = (TYRemindData) o;
if (mRemindId == data.mRemindId && mRemindTime == data.mRemindTime &&
mRemindState == data.mRemindState && mEnable == data.mEnable &&
mUUID.equals(data.mUUID)) {
return true;
}
return false;
}
@Override
public int hashCode() {
int res = 17;
res = 37 * res + mRemindId;
res = 37 * res + (int) (mRemindTime ^ mRemindTime >>> 32);
res = 37 * res + mRemindState;
res = 37 * res + (mEnable ? 0 : 1);
res = 37 * res + mUUID.hashCode();
return res;
}
public void clone(TYRemindData r) {
r.mRemindId = mRemindId;
r.mRemindState = mRemindState;
r.mRemindTime = mRemindTime;
r.mEnable = mEnable;
r.mUUID = mUUID;
}
@Override
public void copyFrom(Object obj) {
if (obj instanceof TYRemindData) {
TYRemindData source = (TYRemindData) obj;
mRemindId = source.mRemindId;
mRemindState = source.mRemindState;
mRemindTime = source.mRemindTime;
mEnable = source.mEnable;
mUUID = source.mUUID;
}
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(mRemindId);
dest.writeLong(mRemindTime);
dest.writeInt(mRemindState);
dest.writeInt(mEnable ? 1 : 0);
dest.writeString(mUUID);
}
@Override
public int describeContents() {
return 0;
}
public static final Creator<TYRemindData> CREATOR = new Creator<TYRemindData>() {
@Override
public TYRemindData createFromParcel(Parcel source) {
return new TYRemindData(source);
}
@Override
public TYRemindData[] newArray(int size) {
return new TYRemindData[size];
}
};
@Override
public String toString() {
return "[ID = " + mRemindId + "][Time = " + mRemindTime +
"][RemindState =" + mRemindState + "][enable = " + mEnable +
"][UUID = " + mUUID + "]";
}
public boolean isSameData(TYRemindData other) {
if (other == null) return false;
return RemindDataUtil.isSameDate(mRemindTime, other.mRemindTime);
}
public boolean isCompletedState() {
return mRemindState == REMIND_STATE_REMINDED;
}
public static class RemindDataUtil<T extends TYRemindData> {
/**
* is same date.
*
* @param c1
* @param c2
* @return
*/
public static boolean isSameDate(Calendar c1, Calendar c2) {
if (c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR) &&
c1.get(Calendar.MONTH) == c2.get(Calendar.MONTH) &&
c1.get(Calendar.DATE) == c2.get(Calendar.DATE)) {
return true;
}
return false;
}
public static boolean isSameDate(long timeMills1, long timeMills2) {
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
c1.setTimeInMillis(timeMills1);
c2.setTimeInMillis(timeMills2);
return isSameDate(c1, c2);
}
public static Calendar toDate(Calendar source, Calendar destiny) {
Calendar res = (Calendar) source.clone();
res.set(Calendar.YEAR, destiny.get(Calendar.YEAR));
res.set(Calendar.MONTH, destiny.get(Calendar.MONTH));
res.set(Calendar.DATE, destiny.get(Calendar.DATE));
return res;
}
public final int indexOf(List<T> source, TYRemindData target) {
if (!Util.isNull(source) && !TextUtils.isEmpty(target.getmUUID())) {
for (int i = 0; i < source.size(); ++i) {
TYRemindData e = source.get(i);
if (TextUtils.isEmpty(e.getmUUID())) continue;
if (target.getmUUID().equals(e.getmUUID())) return i;
}
}
return -1;
}
public boolean isAllCompleted(List<T> source) {
if (null != source) {
for (T remind : source) {
if (!remind.isCompletedState()) {
return false;
}
}
}
return true;
}
/**
* find out next remind data.
* @param reminds be sorted by remind time.
* @param c2 base time line.
* @return the data that later than param c2. if null means not found.
* @see com.tangyu.component.service.remind.TYRemindData#COMPARATOR_FOR_REMIND_TIME
*/
public T filterNextRemindsPassingTest(List<T> reminds,
Calendar c2,
PassingTest<T> passing) {
if (Util.isNull(reminds)) return null;
final long baseline = c2.getTimeInMillis();
for (T rd : reminds) {
if (!rd.ismEnable()) continue;
boolean isPass = null != passing ? passing.passingTestStep(rd) : true;
if (!isPass) continue;
if (rd.getmRemindTime() >= baseline) {
return rd;
}
}
return null;
}
/**
* change the remind time of reminds to destiny date.
* @param reminds
* @param destiny
* @param passing
* @return
*/
public List<T> filterToCalendarPassingTest(List<T> reminds,
Calendar destiny,
PassingTest<T> passing) {
List<T> result = new LinkedList<T>();
if (!Util.isNull(reminds)) {
for (T rd : reminds) {
boolean isPass = null != passing ? passing.passingTestStep(rd) : true;
if (!isPass) continue;
Calendar c1 = Calendar.getInstance();
c1.setTimeInMillis(rd.getmRemindTime());
rd.setmRemindTime(toDate(c1, destiny).getTimeInMillis());
result.add(rd);
}
}
return result;
}
public static interface PassingTest<T extends TYRemindData> {
/**
* will to be invoked in loop every step.
* @param obj
* @return if false, the param will not add to result.
*/
public boolean passingTestStep(T obj);
}
}
}
| TangyuComponentProject/Source/src/com/tangyu/component/service/remind/TYRemindData.java | /**
* The MIT License (MIT)
* Copyright (c) 2012-2014 唐虞科技(TangyuSoft) Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.tangyu.component.service.remind;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.TextUtils;
import com.tangyu.component.Util;
import com.tangyu.component.util.ICopyFrom;
import java.util.Calendar;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;
/**
* The data of remind service.<br>
* Demo : {@link com.tangyu.component.demo.service.remind.RemindData}
* @author bin
*/
public class TYRemindData implements Parcelable, ICopyFrom {
public static final String TABCOL_ID = "_id";
public static final String TABCOL_TIME = "time";
public static final String TABCOL_REMINDSTATE = "REMIND_STATE";
public static final String TABCOL_ENABLE = "enable";
public static final String TABCOL_UUID = "uuid";
public static final int REMIND_STATE_REMINDED = -1;
public static final int REMIND_STATE_UNREMIND = 0;
public static final int REMIND_STATE_REMINDDING = 1;
public static final int REMIND_STATE_INVALID = -2;
public static Comparator<? super TYRemindData> COMPARATOR_FOR_REMIND_TIME = new Comparator<TYRemindData>() {
@Override
public int compare(TYRemindData lhs, TYRemindData rhs) {
return lhs.getmRemindTime() == rhs.getmRemindTime() ? 0 : lhs.getmRemindTime() < rhs.getmRemindTime() ? -1 : 1;
}
};
protected int mRemindId;
protected long mRemindTime;
protected int mRemindState;
protected boolean mEnable = true;
protected String mUUID = UUID.randomUUID().toString();
protected TYRemindData() {
}
protected TYRemindData(TYRemindData r) {
mRemindId = r.mRemindId;
mRemindTime = r.mRemindTime;
mRemindState = r.mRemindState;
mEnable = r.mEnable;
mUUID = r.mUUID;
}
protected TYRemindData(Parcel in) {
mRemindId = in.readInt();
mRemindTime = in.readLong();
mRemindState = in.readInt();
mEnable = in.readInt() == 0 ? false : true;
mUUID = in.readString();
}
public int getmRemindId() {
return mRemindId;
}
public void setmRemindId(int mRemindId) {
this.mRemindId = mRemindId;
}
public long getmRemindTime() {
return mRemindTime;
}
public void setmRemindTime(long mRemindTime) {
this.mRemindTime = mRemindTime;
}
public int getmRemindState() {
return mRemindState;
}
public void setmRemindState(int mRemindState) {
this.mRemindState = mRemindState;
}
public boolean ismEnable() {
return mEnable;
}
public void setmEnable(boolean mEnable) {
this.mEnable = mEnable;
}
public String getmUUID() {
return mUUID;
}
public void setmUUID(String mUUID) {
this.mUUID = mUUID;
}
@Override
public boolean equals(Object o) {
TYRemindData data = (TYRemindData) o;
if (mRemindId == data.mRemindId && mRemindTime == data.mRemindTime &&
mRemindState == data.mRemindState && mEnable == data.mEnable &&
mUUID.equals(data.mUUID)) {
return true;
}
return false;
}
@Override
public int hashCode() {
int res = 17;
res = 37 * res + mRemindId;
res = 37 * res + (int) (mRemindTime ^ mRemindTime >>> 32);
res = 37 * res + mRemindState;
res = 37 * res + (mEnable ? 0 : 1);
res = 37 * res + mUUID.hashCode();
return res;
}
public void clone(TYRemindData r) {
r.mRemindId = mRemindId;
r.mRemindState = mRemindState;
r.mRemindTime = mRemindTime;
r.mEnable = mEnable;
r.mUUID = mUUID;
}
@Override
public void copyFrom(Object obj) {
if (obj instanceof TYRemindData) {
TYRemindData source = (TYRemindData) obj;
mRemindId = source.mRemindId;
mRemindState = source.mRemindState;
mRemindTime = source.mRemindTime;
mEnable = source.mEnable;
mUUID = source.mUUID;
}
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(mRemindId);
dest.writeLong(mRemindTime);
dest.writeInt(mRemindState);
dest.writeInt(mEnable ? 1 : 0);
dest.writeString(mUUID);
}
@Override
public int describeContents() {
return 0;
}
public static final Creator<TYRemindData> CREATOR = new Creator<TYRemindData>() {
@Override
public TYRemindData createFromParcel(Parcel source) {
return new TYRemindData(source);
}
@Override
public TYRemindData[] newArray(int size) {
return new TYRemindData[size];
}
};
@Override
public String toString() {
return "[ID = " + mRemindId + "][Time = " + mRemindTime +
"][RemindState =" + mRemindState + "][enable = " + mEnable +
"][UUID = " + mUUID + "]";
}
public boolean isSameData(TYRemindData other) {
if (other == null) return false;
return RemindDataUtil.isSameDate(mRemindTime, other.mRemindTime);
}
public boolean isCompleted() {
return mRemindState == REMIND_STATE_REMINDED;
}
public static class RemindDataUtil<T extends TYRemindData> {
/**
* is same date.
*
* @param c1
* @param c2
* @return
*/
public static boolean isSameDate(Calendar c1, Calendar c2) {
if (c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR) &&
c1.get(Calendar.MONTH) == c2.get(Calendar.MONTH) &&
c1.get(Calendar.DATE) == c2.get(Calendar.DATE)) {
return true;
}
return false;
}
public static boolean isSameDate(long timeMills1, long timeMills2) {
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
c1.setTimeInMillis(timeMills1);
c2.setTimeInMillis(timeMills2);
return isSameDate(c1, c2);
}
public static Calendar toDate(Calendar source, Calendar destiny) {
Calendar res = (Calendar) source.clone();
res.set(Calendar.YEAR, destiny.get(Calendar.YEAR));
res.set(Calendar.MONTH, destiny.get(Calendar.MONTH));
res.set(Calendar.DATE, destiny.get(Calendar.DATE));
return res;
}
public final int indexOf(List<T> source, TYRemindData target) {
if (!Util.isNull(source) && !TextUtils.isEmpty(target.getmUUID())) {
for (int i = 0; i < source.size(); ++i) {
TYRemindData e = source.get(i);
if (TextUtils.isEmpty(e.getmUUID())) continue;
if (target.getmUUID().equals(e.getmUUID())) return i;
}
}
return -1;
}
public boolean isAllCompleted(List<T> source) {
if (null != source) {
for (T remind : source) {
if (!remind.isCompleted()) {
return false;
}
}
}
return true;
}
/**
* find out next remind data.
* @param reminds be sorted by remind time.
* @param c2 base time line.
* @return the data that later than param c2. if null means not found.
* @see com.tangyu.component.service.remind.TYRemindData#COMPARATOR_FOR_REMIND_TIME
*/
public T filterNextRemindsPassingTest(List<T> reminds,
Calendar c2,
PassingTest<T> passing) {
if (Util.isNull(reminds)) return null;
final long baseline = c2.getTimeInMillis();
for (T rd : reminds) {
if (!rd.ismEnable()) continue;
boolean isPass = null != passing ? passing.passingTestStep(rd) : true;
if (!isPass) continue;
if (rd.getmRemindTime() >= baseline) {
return rd;
}
}
return null;
}
/**
* change the remind time of reminds to destiny date.
* @param reminds
* @param destiny
* @param passing
* @return
*/
public List<T> filterToCalendarPassingTest(List<T> reminds,
Calendar destiny,
PassingTest<T> passing) {
List<T> result = new LinkedList<T>();
if (!Util.isNull(reminds)) {
for (T rd : reminds) {
boolean isPass = null != passing ? passing.passingTestStep(rd) : true;
if (!isPass) continue;
Calendar c1 = Calendar.getInstance();
c1.setTimeInMillis(rd.getmRemindTime());
rd.setmRemindTime(toDate(c1, destiny).getTimeInMillis());
result.add(rd);
}
}
return result;
}
public static interface PassingTest<T extends TYRemindData> {
/**
* will to be invoked in loop every step.
* @param obj
* @return if false, the param will not add to result.
*/
public boolean passingTestStep(T obj);
}
}
}
| test for rebase in master
| TangyuComponentProject/Source/src/com/tangyu/component/service/remind/TYRemindData.java | test for rebase in master | <ide><path>angyuComponentProject/Source/src/com/tangyu/component/service/remind/TYRemindData.java
<ide> return RemindDataUtil.isSameDate(mRemindTime, other.mRemindTime);
<ide> }
<ide>
<del> public boolean isCompleted() {
<add> public boolean isCompletedState() {
<ide> return mRemindState == REMIND_STATE_REMINDED;
<ide> }
<ide>
<ide> public boolean isAllCompleted(List<T> source) {
<ide> if (null != source) {
<ide> for (T remind : source) {
<del> if (!remind.isCompleted()) {
<add> if (!remind.isCompletedState()) {
<ide> return false;
<ide> }
<ide> } |
|
Java | bsd-3-clause | e53a790784b57c0dc6f66ed91feb0bdcbf02371d | 0 | NCIP/catissue-advanced-query,NCIP/catissue-advanced-query | package edu.wustl.query.action;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import edu.common.dynamicextensions.domaininterface.EntityGroupInterface;
import edu.common.dynamicextensions.domaininterface.EntityInterface;
import edu.wustl.cab2b.server.cache.EntityCache;
import edu.wustl.common.beans.NameValueBean;
import edu.wustl.common.exception.BizLogicException;
import edu.wustl.common.query.queryobject.impl.metadata.SelectedColumnsMetadata;
import edu.wustl.common.querysuite.queryobject.IQuery;
import edu.wustl.common.querysuite.queryobject.impl.ParameterizedQuery;
import edu.wustl.common.util.logger.Logger;
import edu.wustl.query.actionForm.CategorySearchForm;
import edu.wustl.query.bizlogic.DefineGridViewBizLogic;
import edu.wustl.query.bizlogic.ValidateQueryBizLogic;
import edu.wustl.query.util.global.Constants;
import edu.wustl.query.util.querysuite.AddContainmentsUtil;
import edu.wustl.query.util.querysuite.IQueryTreeGenerationUtil;
import edu.wustl.query.util.querysuite.IQueryUpdationUtil;
import edu.wustl.query.util.querysuite.QueryDetails;
import edu.wustl.query.util.querysuite.QueryModuleUtil;
/**
* This is a action class to load Define Search Results View screen.
* @author deepti_shelar
*
*/
/**
* @author baljeet_dhindhwal
*
*/
public class DefineSearchResultsViewAction extends Action
{
private static org.apache.log4j.Logger logger =Logger.getLogger(IQueryUpdationUtil.class);
/**
* This method loads define search results view jsp.
* @param mapping mapping
* @param form form
* @param request request
* @param response response
* @throws Exception Exception
* @return ActionForward actionForward
*/
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response) throws Exception
{
request.setAttribute(Constants.CURRENT_PAGE, Constants.DEFINE_RESULTS_VIEW);
CategorySearchForm searchForm = (CategorySearchForm) form;
searchForm = QueryModuleUtil.setDefaultSelections(searchForm);
HttpSession session = request.getSession();
String workflow=request.getParameter(Constants.IS_WORKFLOW);
if(Constants.TRUE.equals(workflow))
{
request.setAttribute(Constants.IS_WORKFLOW,Constants.TRUE);
String workflowName= (String)request.getSession().getAttribute(Constants.WORKFLOW_NAME);
request.setAttribute(Constants.WORKFLOW_NAME,workflowName);
}
IQuery query = (IQuery) session.getAttribute(Constants.QUERY_OBJECT);
String entityId = request.getParameter(Constants.MAIN_ENTITY_ID);
/*if(entityId == null)
{
AddContainmentsUtil.updateIQueryForContainments(session, query);
}
else
{
AddContainmentsUtil.updateIQueryForContainments(session, query, entityId);
}*/
List<EntityInterface> mainEntityList = IQueryUpdationUtil.getAllMainObjects(query);
session.setAttribute(Constants.MAIN_ENTITY_LIST, mainEntityList);
List<NameValueBean> prevSelectedColumnNVBList = setSelectedColumnList(session);
ValidateQueryBizLogic.getValidationMessage(request,query);
QueryDetails queryDetailsObject = new QueryDetails(session);
IQueryTreeGenerationUtil.parseIQueryToCreateTree(queryDetailsObject);
StringBuilder xmlString = getConatinmentTreeXML(queryDetailsObject);
setMainEntityList(request);
//Set the selected column name value bean list to Form
setSelectedColumnsNVBeanList(searchForm, prevSelectedColumnNVBList);
session.setAttribute(Constants.SELECTED_COLUMN_NAME_VALUE_BEAN_LIST,searchForm.getSelectedColumnNameValueBeanList());
/*
* changes made for defined Query
*/
((ParameterizedQuery)query).setName(searchForm.getQueryTitle());
session.setAttribute(Constants.QUERY_OBJECT,query);
String fileName = getFileName();
writeXMLToTempFile(xmlString.toString(), fileName);
ActionForward target = null;
if(entityId != null)
{
response.setContentType(Constants.CONTENT_TYPE_TEXT);
response.getWriter().write(fileName);
target = null;
}
else
{
request.setAttribute(Constants.XML_FILE_NAME, fileName);
target = mapping.findForward(Constants.SUCCESS);
}
return target;
}
/**
* This method sets the selected column name value bean list
* @param searchForm
* @param prevSelectedColumnNVBList
*/
private void setSelectedColumnsNVBeanList(CategorySearchForm searchForm,
List<NameValueBean> prevSelectedColumnNVBList)
{
List<NameValueBean> defaultSelectedColumnNameValueBeanList = searchForm.getSelectedColumnNameValueBeanList();
if(defaultSelectedColumnNameValueBeanList==null)
{
defaultSelectedColumnNameValueBeanList = new ArrayList<NameValueBean>();
}
if (prevSelectedColumnNVBList != null)
{
searchForm.setSelectedColumnNameValueBeanList(prevSelectedColumnNVBList);
}
else
{
searchForm.setSelectedColumnNameValueBeanList(defaultSelectedColumnNameValueBeanList);
}
}
/**
* This method creates XML string to create containment tree
* @param searchForm
* @param prevSelectedColumnNVBList
* @param queryDetailsObject
* @return XML String
*/
private StringBuilder getConatinmentTreeXML(QueryDetails queryDetailsObject)
{
DefineGridViewBizLogic defineGridViewBizLogic = new DefineGridViewBizLogic();
//Create XML String instead of populating the tree data vector
StringBuilder xmlString = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\" ?> ");
xmlString = defineGridViewBizLogic.createContainmentTree(queryDetailsObject,xmlString);
//This string is appended for the root node of the tree
xmlString.append("</item></tree>");
return xmlString;
}
/**
* This method returns Unique file name
* @return Unique file name
*/
private String getFileName()
{
return "loadXML_"+System.currentTimeMillis()+".xml";
}
/**
* This method writes XML tree to create tree to a temporary file
* @param xmlString
* @param fileName
* @throws BizLogicException
*/
private void writeXMLToTempFile(String xmlString,String fileName) throws BizLogicException
{
try
{
String path=edu.wustl.query.util.global.Variables.applicationHome+System.getProperty("file.separator");
OutputStream fout= new FileOutputStream(path+fileName);
OutputStream bout= new BufferedOutputStream(fout);
OutputStreamWriter out = new OutputStreamWriter(bout, "8859_1");
out.write(xmlString);
out.flush();
out.close();
}
catch (IOException e)
{
logger.info("Couldn't create XML file");
}
}
/**
* This method returns prevSelectedColumnNVBList
* @param session
* @return prevSelectedColumnNVBList
*/
private List<NameValueBean> setSelectedColumnList(HttpSession session)
{
List<NameValueBean> prevSelectedColumnNVBList;
SelectedColumnsMetadata selectedColumnsMetadata = (SelectedColumnsMetadata) session.getAttribute(Constants.SELECTED_COLUMN_META_DATA);
if (selectedColumnsMetadata==null)
{
prevSelectedColumnNVBList=null;
}
else
{
prevSelectedColumnNVBList = selectedColumnsMetadata.getSelectedColumnNameValueBeanList();
}
return prevSelectedColumnNVBList;
}
/**
* This method returns list of all main entities present in Model
* @param request
*/
private void setMainEntityList(HttpServletRequest request)
{
Collection<EntityGroupInterface> entityGroups = EntityCache.getCache().getEntityGroups();
ArrayList<EntityInterface> entityList = new ArrayList<EntityInterface>();
for (EntityGroupInterface entityGroupInterface : entityGroups)
{
Collection<EntityInterface> entityInterface =entityGroupInterface.getEntityCollection();
for(EntityInterface entity : entityInterface)
{
if (edu.wustl.query.util.global.Utility.isMainEntity(entity))
{
entityList.add(entity);
}
}
}
request.setAttribute(edu.wustl.query.util.global.Constants.ENTITY_LIST,entityList);
}
}
| WEB-INF/src/edu/wustl/query/action/DefineSearchResultsViewAction.java | package edu.wustl.query.action;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import edu.common.dynamicextensions.domaininterface.EntityGroupInterface;
import edu.common.dynamicextensions.domaininterface.EntityInterface;
import edu.wustl.cab2b.server.cache.EntityCache;
import edu.wustl.common.beans.NameValueBean;
import edu.wustl.common.exception.BizLogicException;
import edu.wustl.common.query.queryobject.impl.metadata.SelectedColumnsMetadata;
import edu.wustl.common.querysuite.queryobject.IQuery;
import edu.wustl.common.querysuite.queryobject.impl.ParameterizedQuery;
import edu.wustl.common.util.logger.Logger;
import edu.wustl.query.actionForm.CategorySearchForm;
import edu.wustl.query.bizlogic.DefineGridViewBizLogic;
import edu.wustl.query.bizlogic.ValidateQueryBizLogic;
import edu.wustl.query.util.global.Constants;
import edu.wustl.query.util.querysuite.AddContainmentsUtil;
import edu.wustl.query.util.querysuite.IQueryTreeGenerationUtil;
import edu.wustl.query.util.querysuite.IQueryUpdationUtil;
import edu.wustl.query.util.querysuite.QueryDetails;
import edu.wustl.query.util.querysuite.QueryModuleUtil;
/**
* This is a action class to load Define Search Results View screen.
* @author deepti_shelar
*
*/
/**
* @author baljeet_dhindhwal
*
*/
public class DefineSearchResultsViewAction extends Action
{
private static org.apache.log4j.Logger logger =Logger.getLogger(IQueryUpdationUtil.class);
/**
* This method loads define search results view jsp.
* @param mapping mapping
* @param form form
* @param request request
* @param response response
* @throws Exception Exception
* @return ActionForward actionForward
*/
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response) throws Exception
{
request.setAttribute(Constants.CURRENT_PAGE, Constants.DEFINE_RESULTS_VIEW);
CategorySearchForm searchForm = (CategorySearchForm) form;
searchForm = QueryModuleUtil.setDefaultSelections(searchForm);
HttpSession session = request.getSession();
String workflow=request.getParameter(Constants.IS_WORKFLOW);
if(Constants.TRUE.equals(workflow))
{
request.setAttribute(Constants.IS_WORKFLOW,Constants.TRUE);
String workflowName= (String)request.getSession().getAttribute(Constants.WORKFLOW_NAME);
request.setAttribute(Constants.WORKFLOW_NAME,workflowName);
}
IQuery query = (IQuery) session.getAttribute(Constants.QUERY_OBJECT);
String entityId = request.getParameter(Constants.MAIN_ENTITY_ID);
if(entityId == null)
{
AddContainmentsUtil.updateIQueryForContainments(session, query);
}
else
{
AddContainmentsUtil.updateIQueryForContainments(session, query, entityId);
}
List<NameValueBean> prevSelectedColumnNVBList = setSelectedColumnList(session);
ValidateQueryBizLogic.getValidationMessage(request,query);
QueryDetails queryDetailsObject = new QueryDetails(session);
IQueryTreeGenerationUtil.parseIQueryToCreateTree(queryDetailsObject);
StringBuilder xmlString = getConatinmentTreeXML(queryDetailsObject);
setMainEntityList(request);
//Set the selected column name value bean list to Form
setSelectedColumnsNVBeanList(searchForm, prevSelectedColumnNVBList);
session.setAttribute(Constants.SELECTED_COLUMN_NAME_VALUE_BEAN_LIST,searchForm.getSelectedColumnNameValueBeanList());
/*
* changes made for defined Query
*/
((ParameterizedQuery)query).setName(searchForm.getQueryTitle());
session.setAttribute(Constants.QUERY_OBJECT,query);
String fileName = getFileName();
writeXMLToTempFile(xmlString.toString(), fileName);
ActionForward target = null;
if(entityId != null)
{
response.setContentType(Constants.CONTENT_TYPE_TEXT);
response.getWriter().write(fileName);
target = null;
}
else
{
request.setAttribute(Constants.XML_FILE_NAME, fileName);
target = mapping.findForward(Constants.SUCCESS);
}
return target;
}
/**
* This method sets the selected column name value bean list
* @param searchForm
* @param prevSelectedColumnNVBList
*/
private void setSelectedColumnsNVBeanList(CategorySearchForm searchForm,
List<NameValueBean> prevSelectedColumnNVBList)
{
List<NameValueBean> defaultSelectedColumnNameValueBeanList = searchForm.getSelectedColumnNameValueBeanList();
if(defaultSelectedColumnNameValueBeanList==null)
{
defaultSelectedColumnNameValueBeanList = new ArrayList<NameValueBean>();
}
if (prevSelectedColumnNVBList != null)
{
searchForm.setSelectedColumnNameValueBeanList(prevSelectedColumnNVBList);
}
else
{
searchForm.setSelectedColumnNameValueBeanList(defaultSelectedColumnNameValueBeanList);
}
}
/**
* This method creates XML string to create containment tree
* @param searchForm
* @param prevSelectedColumnNVBList
* @param queryDetailsObject
* @return XML String
*/
private StringBuilder getConatinmentTreeXML(QueryDetails queryDetailsObject)
{
DefineGridViewBizLogic defineGridViewBizLogic = new DefineGridViewBizLogic();
//Create XML String instead of populating the tree data vector
StringBuilder xmlString = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\" ?> ");
xmlString = defineGridViewBizLogic.createContainmentTree(queryDetailsObject,xmlString);
//This string is appended for the root node of the tree
xmlString.append("</item></tree>");
return xmlString;
}
/**
* This method returns Unique file name
* @return Unique file name
*/
private String getFileName()
{
return "loadXML_"+System.currentTimeMillis()+".xml";
}
/**
* This method writes XML tree to create tree to a temporary file
* @param xmlString
* @param fileName
* @throws BizLogicException
*/
private void writeXMLToTempFile(String xmlString,String fileName) throws BizLogicException
{
try
{
String path=edu.wustl.query.util.global.Variables.applicationHome+System.getProperty("file.separator");
OutputStream fout= new FileOutputStream(path+fileName);
OutputStream bout= new BufferedOutputStream(fout);
OutputStreamWriter out = new OutputStreamWriter(bout, "8859_1");
out.write(xmlString);
out.flush();
out.close();
}
catch (IOException e)
{
logger.info("Couldn't create XML file");
}
}
/**
* This method returns prevSelectedColumnNVBList
* @param session
* @return prevSelectedColumnNVBList
*/
private List<NameValueBean> setSelectedColumnList(HttpSession session)
{
List<NameValueBean> prevSelectedColumnNVBList;
SelectedColumnsMetadata selectedColumnsMetadata = (SelectedColumnsMetadata) session.getAttribute(Constants.SELECTED_COLUMN_META_DATA);
if (selectedColumnsMetadata==null)
{
prevSelectedColumnNVBList=null;
}
else
{
prevSelectedColumnNVBList = selectedColumnsMetadata.getSelectedColumnNameValueBeanList();
}
return prevSelectedColumnNVBList;
}
/**
* This method returns list of all main entities present in Model
* @param request
*/
private void setMainEntityList(HttpServletRequest request)
{
Collection<EntityGroupInterface> entityGroups = EntityCache.getCache().getEntityGroups();
ArrayList<EntityInterface> entityList = new ArrayList<EntityInterface>();
for (EntityGroupInterface entityGroupInterface : entityGroups)
{
Collection<EntityInterface> entityInterface =entityGroupInterface.getEntityCollection();
for(EntityInterface entity : entityInterface)
{
if (edu.wustl.query.util.global.Utility.isMainEntity(entity))
{
entityList.add(entity);
}
}
}
request.setAttribute(edu.wustl.query.util.global.Constants.ENTITY_LIST,entityList);
}
}
| Adding containments related code commented out
SVN-Revision: 5361
| WEB-INF/src/edu/wustl/query/action/DefineSearchResultsViewAction.java | Adding containments related code commented out | <ide><path>EB-INF/src/edu/wustl/query/action/DefineSearchResultsViewAction.java
<ide>
<ide> IQuery query = (IQuery) session.getAttribute(Constants.QUERY_OBJECT);
<ide> String entityId = request.getParameter(Constants.MAIN_ENTITY_ID);
<del> if(entityId == null)
<add> /*if(entityId == null)
<ide> {
<ide> AddContainmentsUtil.updateIQueryForContainments(session, query);
<ide> }
<ide> else
<ide> {
<ide> AddContainmentsUtil.updateIQueryForContainments(session, query, entityId);
<del> }
<add> }*/
<add>
<add> List<EntityInterface> mainEntityList = IQueryUpdationUtil.getAllMainObjects(query);
<add> session.setAttribute(Constants.MAIN_ENTITY_LIST, mainEntityList);
<add>
<ide> List<NameValueBean> prevSelectedColumnNVBList = setSelectedColumnList(session);
<ide> ValidateQueryBizLogic.getValidationMessage(request,query);
<ide> QueryDetails queryDetailsObject = new QueryDetails(session); |
|
Java | apache-2.0 | 5cd00a5f5bde281aeae95482c947c4b3a91a59ce | 0 | wso2/carbon-data,wso2/carbon-data,wso2/carbon-data | /*
* Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.dataservices.sql.driver.query.insert;
import org.wso2.carbon.dataservices.sql.driver.TDriverUtil;
import org.wso2.carbon.dataservices.sql.driver.parser.Constants;
import org.wso2.carbon.dataservices.sql.driver.parser.ParserUtil;
import org.wso2.carbon.dataservices.sql.driver.query.ColumnInfo;
import org.wso2.carbon.dataservices.sql.driver.query.Query;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;
import java.util.Queue;
public abstract class InsertQuery extends Query {
private String targetTableName;
private Map<Integer, String> columns;
private Map<Integer, Object> columnValues;
public InsertQuery(Statement stmt) throws SQLException {
super(stmt);
this.targetTableName = this.extractTargetTableName(getProcessedTokens());
this.columns = this.extractTargetColumns(getProcessedTokens());
this.columnValues = this.extractTargetColumnValues(getProcessedTokens());
if (this.getColumns().size() != this.getColumnValues().size()) {
throw new SQLException("Parameter index is out of range. The column count does not " +
"match the value count");
}
}
private String extractTargetTableName(Queue<String> tokens) throws SQLException {
if (tokens == null || tokens.isEmpty()) {
throw new SQLException("Unable to populate attributes");
}
/* Drops INSERT keyword */
tokens.poll();
/* Drops INTO keyword */
tokens.poll();
if (!Constants.TABLE.equalsIgnoreCase(tokens.peek())) {
throw new SQLException("Table name is missing");
}
tokens.poll();
if (!ParserUtil.isStringLiteral(tokens.peek())) {
throw new SQLException("Table name is missing");
}
return tokens.poll();
}
private Map<Integer, String> extractTargetColumns(Queue<String> tokens) throws SQLException {
Map<Integer, String> targetColumns = new HashMap<Integer, String>();
if (Constants.COLUMN.equals(tokens.peek())) {
this.processColumnNames(tokens, targetColumns, 0);
} else {
targetColumns = this.getColumnMap();
}
return targetColumns;
}
private Map<Integer, Object> extractTargetColumnValues(Queue<String> tokens) throws
SQLException {
Map<Integer, Object> targetColumnValues = new HashMap<Integer, Object>();
if (!(Constants.VALUES.equalsIgnoreCase(tokens.peek()) ||
Constants.VALUE.equalsIgnoreCase(tokens.peek()))) {
throw new SQLException("VALUE/VALUES keyword is missing");
}
tokens.poll();
processColumnValues(tokens, targetColumnValues, 0, false, false, true);
return targetColumnValues;
}
private void processColumnNames(Queue<String> tokens, Map<Integer, String> targetColumns,
int colCount) throws SQLException {
if (!Constants.COLUMN.equalsIgnoreCase(tokens.peek())) {
return;
}
tokens.poll();
if (!ParserUtil.isStringLiteral(tokens.peek())) {
throw new SQLException("Syntax Error : String literal expected");
}
targetColumns.put(colCount, tokens.poll());
if (Constants.COLUMN.equalsIgnoreCase(tokens.peek())) {
processColumnNames(tokens, targetColumns, colCount + 1);
}
}
private void processColumnValues(Queue<String> tokens, Map<Integer, Object> targetColumnValues,
int valCount, boolean isParameterized, boolean isEnd,
boolean isInit) throws SQLException {
if (!isEnd) {
if (!Constants.PARAM_VALUE.equalsIgnoreCase(tokens.peek())) {
throw new SQLException("Syntax Error : 'PARAM_VALUE' is expected");
}
tokens.poll();
if ("?".equalsIgnoreCase(tokens.peek())) {
if (isInit) {
isParameterized = true;
isInit = false;
}
if (!isParameterized) {
throw new SQLException("Both parameters and inline parameter values are not " +
"allowed to exist together");
}
isParameterized = true;
targetColumnValues.put(valCount, tokens.poll());
} else if (Constants.SINGLE_QUOTATION.equalsIgnoreCase(tokens.peek())) {
if (isInit) {
isInit = false;
isParameterized = false;
}
if (isParameterized) {
throw new SQLException("Both parameters and inline parameter values are not " +
"allowed to exist together");
}
tokens.poll();
StringBuilder b = new StringBuilder();
while (Constants.SINGLE_QUOTATION.equalsIgnoreCase(tokens.peek()) ||
tokens.isEmpty()) {
b.append(tokens.poll());
}
targetColumnValues.put(valCount, b.toString());
tokens.poll();
} else {
if (isInit) {
isInit = false;
isParameterized = false;
}
if (isParameterized) {
throw new SQLException("Both parameters and inline parameter values are not " +
"allowed to exist together");
}
targetColumnValues.put(valCount, tokens.poll());
}
if (!Constants.PARAM_VALUE.equalsIgnoreCase(tokens.peek())) {
isEnd = true;
}
processColumnValues(tokens, targetColumnValues, valCount + 1, isParameterized, isEnd,
isInit);
}
}
public String getTargetTableName() {
return targetTableName;
}
public Map<Integer, String> getColumns() {
return columns;
}
public Map<Integer, Object> getColumnValues() {
return columnValues;
}
private Map<Integer, String> getColumnMap() throws SQLException {
ColumnInfo[] headers =
TDriverUtil.getHeaders(this.getConnection(), this.getTargetTableName());
Map<Integer, String> columns = new HashMap<Integer, String>();
for (ColumnInfo column : headers) {
columns.put(column.getId(), column.getName());
}
return columns;
}
}
| components/data-services/org.wso2.carbon.dataservices.sql.driver/src/main/java/org/wso2/carbon/dataservices/sql/driver/query/insert/InsertQuery.java | /*
* Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.dataservices.sql.driver.query.insert;
import org.wso2.carbon.dataservices.sql.driver.TDriverUtil;
import org.wso2.carbon.dataservices.sql.driver.parser.Constants;
import org.wso2.carbon.dataservices.sql.driver.parser.ParserUtil;
import org.wso2.carbon.dataservices.sql.driver.query.ColumnInfo;
import org.wso2.carbon.dataservices.sql.driver.query.Query;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;
import java.util.Queue;
public abstract class InsertQuery extends Query {
private String targetTableName;
private Map<Integer, String> columns;
private Map<Integer, Object> columnValues;
public InsertQuery(Statement stmt) throws SQLException {
super(stmt);
this.targetTableName = this.extractTargetTableName(getProcessedTokens());
this.columns = this.extractTargetColumns(getProcessedTokens());
this.columnValues = this.extractTargetColumnValues(getProcessedTokens());
if (this.getColumns().size() != this.getColumnValues().size()) {
throw new SQLException("Parameter index is out of range. The column count does not " +
"match the value count");
}
}
private String extractTargetTableName(Queue<String> tokens) throws SQLException {
if (tokens == null || tokens.isEmpty()) {
throw new SQLException("Unable to populate attributes");
}
/* Drops INSERT keyword */
tokens.poll();
/* Drops INTO keyword */
tokens.poll();
if (!Constants.TABLE.equalsIgnoreCase(tokens.peek())) {
throw new SQLException("Table name is missing");
}
tokens.poll();
if (!ParserUtil.isStringLiteral(tokens.peek())) {
throw new SQLException("Table name is missing");
}
return tokens.poll();
}
private Map<Integer, String> extractTargetColumns(Queue<String> tokens) throws SQLException {
Map<Integer, String> targetColumns = new HashMap<Integer, String>();
if (Constants.COLUMN.equals(tokens.peek())) {
this.processColumnNames(tokens, targetColumns, 0);
} else {
targetColumns = this.getColumnMap();
}
return targetColumns;
}
private Map<Integer, Object> extractTargetColumnValues(Queue<String> tokens) throws
SQLException {
Map<Integer, Object> targetColumnValues = new HashMap<Integer, Object>();
if (!(Constants.VALUES.equalsIgnoreCase(tokens.peek()) ||
Constants.VALUE.equalsIgnoreCase(tokens.peek()))) {
throw new SQLException("VALUE/VALUES keyword is missing");
}
tokens.poll();
processColumnValues(tokens, targetColumnValues, 0, false, false, true);
return targetColumnValues;
}
private void processColumnNames(Queue<String> tokens, Map<Integer, String> targetColumns,
int colCount) throws SQLException {
if (!Constants.COLUMN.equalsIgnoreCase(tokens.peek())) {
return;
}
tokens.poll();
if (!ParserUtil.isStringLiteral(tokens.peek())) {
throw new SQLException("Syntax Error : String literal expected");
}
targetColumns.put(colCount, tokens.poll());
if (Constants.COLUMN.equalsIgnoreCase(tokens.peek())) {
processColumnNames(tokens, targetColumns, colCount + 1);
}
}
private void processColumnValues(Queue<String> tokens, Map<Integer, Object> targetColumnValues,
int valCount, boolean isParameterized, boolean isEnd,
boolean isInit) throws SQLException {
if (!isEnd) {
if (!Constants.PARAM_VALUE.equalsIgnoreCase(tokens.peek())) {
throw new SQLException("Syntax Error : 'PARAM_VALUE' is expected");
}
tokens.poll();
if (!ParserUtil.isStringLiteral(tokens.peek())) {
throw new SQLException("Syntax Error : String literal expected");
}
if ("?".equalsIgnoreCase(tokens.peek())) {
if (isInit) {
isParameterized = true;
isInit = false;
}
if (!isParameterized) {
throw new SQLException("Both parameters and inline parameter values are not " +
"allowed to exist together");
}
isParameterized = true;
targetColumnValues.put(valCount, tokens.poll());
} else if (Constants.SINGLE_QUOTATION.equalsIgnoreCase(tokens.peek())) {
if (isInit) {
isInit = false;
isParameterized = false;
}
if (isParameterized) {
throw new SQLException("Both parameters and inline parameter values are not " +
"allowed to exist together");
}
tokens.poll();
StringBuilder b = new StringBuilder();
while (Constants.SINGLE_QUOTATION.equalsIgnoreCase(tokens.peek()) ||
tokens.isEmpty()) {
b.append(tokens.poll());
}
targetColumnValues.put(valCount, b.toString());
tokens.poll();
} else if (ParserUtil.isStringLiteral(tokens.peek())) {
if (isInit) {
isInit = false;
isParameterized = false;
}
if (isParameterized) {
throw new SQLException("Both parameters and inline parameter values are not " +
"allowed to exist together");
}
targetColumnValues.put(valCount, tokens.poll());
}
if (!Constants.PARAM_VALUE.equalsIgnoreCase(tokens.peek())) {
isEnd = true;
}
processColumnValues(tokens, targetColumnValues, valCount + 1, isParameterized, isEnd,
isInit);
}
}
public String getTargetTableName() {
return targetTableName;
}
public Map<Integer, String> getColumns() {
return columns;
}
public Map<Integer, Object> getColumnValues() {
return columnValues;
}
private Map<Integer, String> getColumnMap() throws SQLException {
ColumnInfo[] headers =
TDriverUtil.getHeaders(this.getConnection(), this.getTargetTableName());
Map<Integer, String> columns = new HashMap<Integer, String>();
for (ColumnInfo column : headers) {
columns.put(column.getId(), column.getName());
}
return columns;
}
}
| Fix excel keyword issue
| components/data-services/org.wso2.carbon.dataservices.sql.driver/src/main/java/org/wso2/carbon/dataservices/sql/driver/query/insert/InsertQuery.java | Fix excel keyword issue | <ide><path>omponents/data-services/org.wso2.carbon.dataservices.sql.driver/src/main/java/org/wso2/carbon/dataservices/sql/driver/query/insert/InsertQuery.java
<ide> throw new SQLException("Syntax Error : 'PARAM_VALUE' is expected");
<ide> }
<ide> tokens.poll();
<del> if (!ParserUtil.isStringLiteral(tokens.peek())) {
<del> throw new SQLException("Syntax Error : String literal expected");
<del> }
<ide> if ("?".equalsIgnoreCase(tokens.peek())) {
<ide> if (isInit) {
<ide> isParameterized = true;
<ide> }
<ide> targetColumnValues.put(valCount, b.toString());
<ide> tokens.poll();
<del> } else if (ParserUtil.isStringLiteral(tokens.peek())) {
<add> } else {
<ide> if (isInit) {
<ide> isInit = false;
<ide> isParameterized = false; |
|
Java | epl-1.0 | 83f579aba8460a9ea2fcd58b3a4e64c4068025d1 | 0 | phat-trien-phan-mem-phan-tan/dynamicpool,phat-trien-phan-mem-phan-tan/dynamicpool,phat-trien-phan-mem-phan-tan/dynamicpool,phat-trien-phan-mem-phan-tan/dynamicpool | package vn.edu.hust.student.dynamicpool.dal;
import vn.edu.hust.student.dynamicpool.bll.BusinessLogicDataCallback;
import vn.edu.hust.student.dynamicpool.bll.Fish;
import vn.edu.hust.student.dynamicpool.bll.FishManager;
import vn.edu.hust.student.dynamicpool.model.DeviceInfo;
public interface DataAccessLayer {
String getClientName();
void joinHost(int key, BusinessLogicDataCallback callback);
void createHost(BusinessLogicDataCallback callback);
// them thiet bi va dua ket qua tra ve cua server la mot mang danh sach cac Segment cua be
void addDevice(DeviceInfo deviceInfo,BusinessLogicDataCallback callback);
void exit(BusinessLogicDataCallback callback);
void createFish(Fish fish,BusinessLogicDataCallback callback);
void synchronization(BusinessLogicDataCallback callback);
// gui thong tin ca nen server khi chuan bi ra khoi be
void removeFish(Fish fish,BusinessLogicDataCallback callback);
void synchronous(FishManager fishManager, String clientName);
}
| DynamicPool/core/src/vn/edu/hust/student/dynamicpool/dal/DataAccessLayer.java | package vn.edu.hust.student.dynamicpool.dal;
import java.util.List;
import vn.edu.hust.student.dynamicpool.bll.BusinessLogicDataCallback;
import vn.edu.hust.student.dynamicpool.bll.Fish;
import vn.edu.hust.student.dynamicpool.bll.FishManager;
import vn.edu.hust.student.dynamicpool.model.DeviceInfo;
public interface DataAccessLayer {
String getClientName();
void joinHost(int key, BusinessLogicDataCallback callback);
void createHost(BusinessLogicDataCallback callback);
// them thiet bi va dua ket qua tra ve cua server la mot mang danh sach cac Segment cua be
void addDevice(DeviceInfo deviceInfo,BusinessLogicDataCallback callback);
void exit(BusinessLogicDataCallback callback);
void createFish(Fish fish,BusinessLogicDataCallback callback);
void synchronization(BusinessLogicDataCallback callback);
// gui thong tin ca nen server khi chuan bi ra khoi be
void removeFish(Fish fish,BusinessLogicDataCallback callback);
void synchronous(FishManager fishManager, String clientName);
}
| sua data access layer
| DynamicPool/core/src/vn/edu/hust/student/dynamicpool/dal/DataAccessLayer.java | sua data access layer | <ide><path>ynamicPool/core/src/vn/edu/hust/student/dynamicpool/dal/DataAccessLayer.java
<ide> package vn.edu.hust.student.dynamicpool.dal;
<del>
<del>import java.util.List;
<ide>
<ide> import vn.edu.hust.student.dynamicpool.bll.BusinessLogicDataCallback;
<ide> import vn.edu.hust.student.dynamicpool.bll.Fish; |
|
Java | apache-2.0 | 837d26e9fd2e8994974dbb0f1ec968beab5717af | 0 | EvilMcJerkface/Aeron,mikeb01/Aeron,EvilMcJerkface/Aeron,mikeb01/Aeron,mikeb01/Aeron,mikeb01/Aeron,real-logic/Aeron,real-logic/Aeron,EvilMcJerkface/Aeron,real-logic/Aeron,EvilMcJerkface/Aeron,real-logic/Aeron | /*
* Copyright 2014-2020 Real Logic 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
*
* 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 io.aeron.archive;
import io.aeron.Aeron;
import io.aeron.AeronCloseHelper;
import io.aeron.Publication;
import io.aeron.Subscription;
import io.aeron.archive.codecs.ControlResponseCode;
import io.aeron.archive.codecs.RecordingSignal;
import io.aeron.archive.codecs.SourceLocation;
import io.aeron.security.Authenticator;
import org.agrona.concurrent.CachedEpochClock;
import org.agrona.concurrent.CountedErrorHandler;
import org.agrona.concurrent.UnsafeBuffer;
import java.util.ArrayDeque;
import java.util.function.BooleanSupplier;
import static io.aeron.archive.client.ArchiveException.AUTHENTICATION_REJECTED;
import static io.aeron.archive.client.ArchiveException.GENERIC;
import static io.aeron.archive.codecs.ControlResponseCode.*;
/**
* Control sessions are interacted with from the {@link ArchiveConductor}. The interaction may result in pending
* send actions being queued for execution by the {@link ArchiveConductor}.
*/
class ControlSession implements Session
{
private static final long RESEND_INTERVAL_MS = 200L;
private static final String SESSION_REJECTED_MSG = "authentication rejected";
enum State
{
INIT, CONNECTED, CHALLENGED, AUTHENTICATED, ACTIVE, INACTIVE, REJECTED, CLOSED
}
private final int majorVersion;
private final long controlSessionId;
private final long connectTimeoutMs;
private long correlationId;
private long resendDeadlineMs;
private long activityDeadlineMs;
private Session activeListing = null;
private final ArchiveConductor conductor;
private final CachedEpochClock cachedEpochClock;
private final ControlResponseProxy controlResponseProxy;
private final Authenticator authenticator;
private final ControlSessionProxy controlSessionProxy;
private final ArrayDeque<BooleanSupplier> queuedResponses = new ArrayDeque<>(8);
private final ControlSessionDemuxer demuxer;
private final Publication controlPublication;
private final String invalidVersionMessage;
private State state = State.INIT;
ControlSession(
final int majorVersion,
final long controlSessionId,
final long correlationId,
final long connectTimeoutMs,
final String invalidVersionMessage,
final ControlSessionDemuxer demuxer,
final Publication controlPublication,
final ArchiveConductor conductor,
final CachedEpochClock cachedEpochClock,
final ControlResponseProxy controlResponseProxy,
final Authenticator authenticator,
final ControlSessionProxy controlSessionProxy)
{
this.majorVersion = majorVersion;
this.controlSessionId = controlSessionId;
this.correlationId = correlationId;
this.connectTimeoutMs = connectTimeoutMs;
this.invalidVersionMessage = invalidVersionMessage;
this.demuxer = demuxer;
this.controlPublication = controlPublication;
this.conductor = conductor;
this.cachedEpochClock = cachedEpochClock;
this.controlResponseProxy = controlResponseProxy;
this.authenticator = authenticator;
this.controlSessionProxy = controlSessionProxy;
this.activityDeadlineMs = cachedEpochClock.time() + connectTimeoutMs;
}
public int majorVersion()
{
return majorVersion;
}
public long sessionId()
{
return controlSessionId;
}
public long correlationId()
{
return correlationId;
}
public void abort()
{
state(State.INACTIVE);
if (null != activeListing)
{
activeListing.abort();
}
}
public void close()
{
final CountedErrorHandler errorHandler = conductor.context().countedErrorHandler();
if (null != activeListing)
{
AeronCloseHelper.close(errorHandler, activeListing::abort);
}
AeronCloseHelper.close(errorHandler, controlPublication);
state(State.CLOSED);
demuxer.removeControlSession(this);
}
public boolean isDone()
{
return state == State.INACTIVE;
}
public int doWork()
{
int workCount = 0;
final long nowMs = cachedEpochClock.time();
switch (state)
{
case INIT:
workCount += waitForConnection(nowMs);
break;
case CONNECTED:
workCount += sendConnectResponse(nowMs);
break;
case CHALLENGED:
workCount += waitForChallengeResponse(nowMs);
break;
case AUTHENTICATED:
workCount += waitForRequest(nowMs);
break;
case ACTIVE:
workCount += sendQueuedResponses(nowMs);
break;
case REJECTED:
workCount += sendReject(nowMs);
break;
}
return workCount;
}
ArchiveConductor archiveConductor()
{
return conductor;
}
Publication controlPublication()
{
return controlPublication;
}
boolean hasActiveListing()
{
return null != activeListing;
}
void activeListing(final Session activeListing)
{
this.activeListing = activeListing;
}
@SuppressWarnings("unused")
void onChallengeResponse(final long correlationId, final byte[] encodedCredentials)
{
if (State.CHALLENGED == state)
{
authenticator.onChallengeResponse(controlSessionId, encodedCredentials, cachedEpochClock.time());
this.correlationId = correlationId;
}
}
@SuppressWarnings("unused")
void onKeepAlive(final long correlationId)
{
attemptToGoActive();
}
void onStopRecording(final long correlationId, final int streamId, final String channel)
{
attemptToGoActive();
if (State.ACTIVE == state)
{
conductor.stopRecording(correlationId, streamId, channel, this);
}
}
void onStopRecordingSubscription(final long correlationId, final long subscriptionId)
{
attemptToGoActive();
if (State.ACTIVE == state)
{
conductor.stopRecordingSubscription(correlationId, subscriptionId, this);
}
}
void onStartRecording(
final long correlationId, final int streamId, final SourceLocation sourceLocation, final String channel)
{
attemptToGoActive();
if (State.ACTIVE == state)
{
conductor.startRecording(correlationId, streamId, sourceLocation, channel, this);
}
}
void onListRecordingsForUri(
final long correlationId,
final long fromRecordingId,
final int recordCount,
final int streamId,
final byte[] channelFragment)
{
attemptToGoActive();
if (State.ACTIVE == state)
{
conductor.newListRecordingsForUriSession(
correlationId,
fromRecordingId,
recordCount,
streamId,
channelFragment,
this);
}
}
void onListRecordings(final long correlationId, final long fromRecordingId, final int recordCount)
{
attemptToGoActive();
if (State.ACTIVE == state)
{
conductor.newListRecordingsSession(correlationId, fromRecordingId, recordCount, this);
}
}
void onListRecording(final long correlationId, final long recordingId)
{
attemptToGoActive();
if (State.ACTIVE == state)
{
conductor.listRecording(correlationId, recordingId, this);
}
}
void onFindLastMatchingRecording(
final long correlationId,
final long minRecordingId,
final int sessionId,
final int streamId,
final byte[] channelFragment)
{
attemptToGoActive();
if (State.ACTIVE == state)
{
conductor.findLastMatchingRecording(
correlationId,
minRecordingId,
sessionId,
streamId,
channelFragment,
this);
}
}
void onStartReplay(
final long correlationId,
final long recordingId,
final long position,
final long length,
final int replayStreamId,
final String replayChannel)
{
attemptToGoActive();
if (State.ACTIVE == state)
{
conductor.startReplay(
correlationId, recordingId, position, length, replayStreamId, replayChannel, this);
}
}
void onStartBoundedReplay(
final long correlationId,
final long recordingId,
final long position,
final long length,
final int limitCounterId,
final int replayStreamId,
final String replayChannel)
{
attemptToGoActive();
if (State.ACTIVE == state)
{
conductor.startBoundedReplay(
correlationId,
recordingId,
position,
length,
limitCounterId,
replayStreamId,
replayChannel,
this);
}
}
void onStopReplay(final long correlationId, final long replaySessionId)
{
attemptToGoActive();
if (State.ACTIVE == state)
{
conductor.stopReplay(correlationId, replaySessionId, this);
}
}
void onStopAllReplays(final long correlationId, final long recordingId)
{
attemptToGoActive();
if (State.ACTIVE == state)
{
conductor.stopAllReplays(correlationId, recordingId, this);
}
}
void onExtendRecording(
final long correlationId,
final long recordingId,
final int streamId,
final SourceLocation sourceLocation,
final String channel)
{
attemptToGoActive();
if (State.ACTIVE == state)
{
conductor.extendRecording(correlationId, recordingId, streamId, sourceLocation, channel, this);
}
}
void onGetRecordingPosition(final long correlationId, final long recordingId)
{
attemptToGoActive();
if (State.ACTIVE == state)
{
conductor.getRecordingPosition(correlationId, recordingId, this);
}
}
void onTruncateRecording(final long correlationId, final long recordingId, final long position)
{
attemptToGoActive();
if (State.ACTIVE == state)
{
conductor.truncateRecording(correlationId, recordingId, position, this);
}
}
void onGetStopPosition(final long correlationId, final long recordingId)
{
attemptToGoActive();
if (State.ACTIVE == state)
{
conductor.getStopPosition(correlationId, recordingId, this);
}
}
void onListRecordingSubscriptions(
final long correlationId,
final int pseudoIndex,
final int subscriptionCount,
final boolean applyStreamId,
final int streamId,
final String channelFragment)
{
attemptToGoActive();
if (State.ACTIVE == state)
{
conductor.listRecordingSubscriptions(
correlationId,
pseudoIndex,
subscriptionCount,
applyStreamId,
streamId,
channelFragment,
this);
}
}
void onReplicate(
final long correlationId,
final long srcRecordingId,
final long dstRecordingId,
final int srcControlStreamId,
final String srcControlChannel,
final String liveDestination)
{
attemptToGoActive();
if (State.ACTIVE == state)
{
conductor.replicate(
correlationId,
srcRecordingId,
dstRecordingId,
Aeron.NULL_VALUE,
Aeron.NULL_VALUE,
srcControlStreamId,
srcControlChannel,
liveDestination,
this);
}
}
void onStopReplication(final long correlationId, final long replicationId)
{
attemptToGoActive();
if (State.ACTIVE == state)
{
conductor.stopReplication(correlationId, replicationId, this);
}
}
void onGetStartPosition(final long correlationId, final long recordingId)
{
attemptToGoActive();
if (State.ACTIVE == state)
{
conductor.getStartPosition(correlationId, recordingId, this);
}
}
void onDetachSegments(final long correlationId, final long recordingId, final long newStartPosition)
{
attemptToGoActive();
if (State.ACTIVE == state)
{
conductor.detachSegments(correlationId, recordingId, newStartPosition, this);
}
}
void onDeleteDetachedSegments(final long correlationId, final long recordingId)
{
attemptToGoActive();
if (State.ACTIVE == state)
{
conductor.deleteDetachedSegments(correlationId, recordingId, this);
}
}
void onPurgeSegments(final long correlationId, final long recordingId, final long newStartPosition)
{
attemptToGoActive();
if (State.ACTIVE == state)
{
conductor.purgeSegments(correlationId, recordingId, newStartPosition, this);
}
}
void onAttachSegments(final long correlationId, final long recordingId)
{
attemptToGoActive();
if (State.ACTIVE == state)
{
conductor.attachSegments(correlationId, recordingId, this);
}
}
void onMigrateSegments(final long correlationId, final long srcRecordingId, final long dstRecordingId)
{
attemptToGoActive();
if (State.ACTIVE == state)
{
conductor.migrateSegments(correlationId, srcRecordingId, dstRecordingId, this);
}
}
void onReplicateTagged(
final long correlationId,
final long srcRecordingId,
final long dstRecordingId,
final long channelTagId,
final long subscriptionTagId,
final int srcControlStreamId,
final String srcControlChannel,
final String liveDestination)
{
attemptToGoActive();
if (State.ACTIVE == state)
{
conductor.replicate(
correlationId,
srcRecordingId,
dstRecordingId,
channelTagId,
subscriptionTagId,
srcControlStreamId,
srcControlChannel,
liveDestination,
this);
}
}
void sendOkResponse(final long correlationId, final ControlResponseProxy proxy)
{
sendResponse(correlationId, 0L, OK, null, proxy);
}
void sendOkResponse(final long correlationId, final long relevantId, final ControlResponseProxy proxy)
{
sendResponse(correlationId, relevantId, OK, null, proxy);
}
void sendErrorResponse(final long correlationId, final String errorMessage, final ControlResponseProxy proxy)
{
sendResponse(correlationId, 0L, ERROR, errorMessage, proxy);
}
void sendErrorResponse(
final long correlationId, final long relevantId, final String errorMessage, final ControlResponseProxy proxy)
{
sendResponse(correlationId, relevantId, ERROR, errorMessage, proxy);
}
void sendRecordingUnknown(final long correlationId, final long recordingId, final ControlResponseProxy proxy)
{
sendResponse(correlationId, recordingId, RECORDING_UNKNOWN, null, proxy);
}
void sendSubscriptionUnknown(final long correlationId, final ControlResponseProxy proxy)
{
sendResponse(correlationId, 0L, SUBSCRIPTION_UNKNOWN, null, proxy);
}
void sendResponse(
final long correlationId,
final long relevantId,
final ControlResponseCode code,
final String errorMessage,
final ControlResponseProxy proxy)
{
if (!proxy.sendResponse(controlSessionId, correlationId, relevantId, code, errorMessage, this))
{
queueResponse(correlationId, relevantId, code, errorMessage);
}
}
void attemptErrorResponse(final long correlationId, final String errorMessage, final ControlResponseProxy proxy)
{
proxy.sendResponse(controlSessionId, correlationId, GENERIC, ERROR, errorMessage, this);
}
void attemptErrorResponse(
final long correlationId, final long relevantId, final String errorMessage, final ControlResponseProxy proxy)
{
proxy.sendResponse(controlSessionId, correlationId, relevantId, ERROR, errorMessage, this);
}
int sendDescriptor(final long correlationId, final UnsafeBuffer descriptorBuffer, final ControlResponseProxy proxy)
{
return proxy.sendDescriptor(controlSessionId, correlationId, descriptorBuffer, this);
}
boolean sendSubscriptionDescriptor(
final long correlationId, final Subscription subscription, final ControlResponseProxy proxy)
{
return proxy.sendSubscriptionDescriptor(controlSessionId, correlationId, subscription, this);
}
void attemptSignal(
final long correlationId,
final long recordingId,
final long subscriptionId,
final long position,
final RecordingSignal recordingSignal)
{
controlResponseProxy.attemptSendSignal(
controlSessionId,
correlationId,
recordingId,
subscriptionId,
position,
recordingSignal,
controlPublication);
}
int maxPayloadLength()
{
return controlPublication.maxPayloadLength();
}
void challenged()
{
state(State.CHALLENGED);
}
@SuppressWarnings("unused")
void authenticate(final byte[] encodedPrincipal)
{
activityDeadlineMs = Aeron.NULL_VALUE;
state(State.AUTHENTICATED);
}
void reject()
{
state(State.REJECTED);
}
State state()
{
return state;
}
private void queueResponse(
final long correlationId, final long relevantId, final ControlResponseCode code, final String message)
{
queuedResponses.offer(() -> controlResponseProxy.sendResponse(
controlSessionId,
correlationId,
relevantId,
code,
message,
this));
}
private int waitForConnection(final long nowMs)
{
int workCount = 0;
if (controlPublication.isConnected())
{
state(State.CONNECTED);
workCount += 1;
}
else if (hasNoActivity(nowMs))
{
state(State.INACTIVE);
workCount += 1;
}
return workCount;
}
private int sendConnectResponse(final long nowMs)
{
int workCount = 0;
if (hasNoActivity(nowMs))
{
state(State.INACTIVE);
workCount += 1;
}
else if (nowMs > resendDeadlineMs)
{
resendDeadlineMs = nowMs + RESEND_INTERVAL_MS;
if (null != invalidVersionMessage)
{
controlResponseProxy.sendResponse(
controlSessionId,
correlationId,
controlSessionId,
ERROR,
invalidVersionMessage,
this);
}
else
{
authenticator.onConnectedSession(controlSessionProxy.controlSession(this), nowMs);
}
workCount += 1;
}
return workCount;
}
private int waitForChallengeResponse(final long nowMs)
{
if (hasNoActivity(nowMs))
{
state(State.INACTIVE);
}
else
{
authenticator.onChallengedSession(controlSessionProxy.controlSession(this), nowMs);
}
return 1;
}
private int waitForRequest(final long nowMs)
{
int workCount = 0;
if (hasNoActivity(nowMs))
{
state(State.INACTIVE);
workCount += 1;
}
else if (nowMs > resendDeadlineMs)
{
resendDeadlineMs = nowMs + RESEND_INTERVAL_MS;
if (controlResponseProxy.sendResponse(
controlSessionId,
correlationId,
controlSessionId,
OK,
null,
this))
{
activityDeadlineMs = Aeron.NULL_VALUE;
workCount += 1;
}
}
return workCount;
}
private int sendQueuedResponses(final long nowMs)
{
int workCount = 0;
if (!controlPublication.isConnected())
{
state(State.INACTIVE);
}
else
{
if (!queuedResponses.isEmpty())
{
if (queuedResponses.peekFirst().getAsBoolean())
{
queuedResponses.pollFirst();
activityDeadlineMs = Aeron.NULL_VALUE;
workCount++;
}
else if (activityDeadlineMs == Aeron.NULL_VALUE)
{
activityDeadlineMs = nowMs + connectTimeoutMs;
}
else if (hasNoActivity(nowMs))
{
state(State.INACTIVE);
}
}
}
return workCount;
}
private int sendReject(final long nowMs)
{
int workCount = 0;
if (hasNoActivity(nowMs))
{
state(State.INACTIVE);
workCount += 1;
}
else if (nowMs > resendDeadlineMs)
{
resendDeadlineMs = nowMs + RESEND_INTERVAL_MS;
controlResponseProxy.sendResponse(
controlSessionId,
correlationId,
AUTHENTICATION_REJECTED,
ERROR,
SESSION_REJECTED_MSG,
this);
workCount += 1;
}
return workCount;
}
private boolean hasNoActivity(final long nowMs)
{
return Aeron.NULL_VALUE != activityDeadlineMs & nowMs > activityDeadlineMs;
}
private void attemptToGoActive()
{
if (State.AUTHENTICATED == state && null == invalidVersionMessage)
{
state(State.ACTIVE);
}
}
private void state(final State state)
{
//System.out.println(controlSessionId + ": " + this.state + " -> " + state);
this.state = state;
}
public String toString()
{
return "ControlSession{" +
"controlSessionId=" + controlSessionId +
", correlationId=" + correlationId +
", state=" + state +
", controlPublication=" + controlPublication +
'}';
}
}
| aeron-archive/src/main/java/io/aeron/archive/ControlSession.java | /*
* Copyright 2014-2020 Real Logic 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
*
* 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 io.aeron.archive;
import io.aeron.Aeron;
import io.aeron.AeronCloseHelper;
import io.aeron.Publication;
import io.aeron.Subscription;
import io.aeron.archive.codecs.ControlResponseCode;
import io.aeron.archive.codecs.RecordingSignal;
import io.aeron.archive.codecs.SourceLocation;
import io.aeron.security.Authenticator;
import org.agrona.concurrent.CachedEpochClock;
import org.agrona.concurrent.CountedErrorHandler;
import org.agrona.concurrent.UnsafeBuffer;
import java.util.ArrayDeque;
import java.util.function.BooleanSupplier;
import static io.aeron.archive.client.ArchiveException.AUTHENTICATION_REJECTED;
import static io.aeron.archive.client.ArchiveException.GENERIC;
import static io.aeron.archive.codecs.ControlResponseCode.*;
/**
* Control sessions are interacted with from the {@link ArchiveConductor}. The interaction may result in pending
* send actions being queued for execution by the {@link ArchiveConductor}.
*/
class ControlSession implements Session
{
private static final long RESEND_INTERVAL_MS = 200L;
private static final String SESSION_REJECTED_MSG = "authentication rejected";
enum State
{
INIT, CONNECTED, CHALLENGED, AUTHENTICATED, ACTIVE, INACTIVE, REJECTED, CLOSED
}
private final int majorVersion;
private final long controlSessionId;
private final long connectTimeoutMs;
private long correlationId;
private long resendDeadlineMs;
private long activityDeadlineMs;
private Session activeListing = null;
private final ArchiveConductor conductor;
private final CachedEpochClock cachedEpochClock;
private final ControlResponseProxy controlResponseProxy;
private final Authenticator authenticator;
private final ControlSessionProxy controlSessionProxy;
private final ArrayDeque<BooleanSupplier> queuedResponses = new ArrayDeque<>(8);
private final ControlSessionDemuxer demuxer;
private final Publication controlPublication;
private final String invalidVersionMessage;
private State state = State.INIT;
ControlSession(
final int majorVersion,
final long controlSessionId,
final long correlationId,
final long connectTimeoutMs,
final String invalidVersionMessage,
final ControlSessionDemuxer demuxer,
final Publication controlPublication,
final ArchiveConductor conductor,
final CachedEpochClock cachedEpochClock,
final ControlResponseProxy controlResponseProxy,
final Authenticator authenticator,
final ControlSessionProxy controlSessionProxy)
{
this.majorVersion = majorVersion;
this.controlSessionId = controlSessionId;
this.correlationId = correlationId;
this.connectTimeoutMs = connectTimeoutMs;
this.invalidVersionMessage = invalidVersionMessage;
this.demuxer = demuxer;
this.controlPublication = controlPublication;
this.conductor = conductor;
this.cachedEpochClock = cachedEpochClock;
this.controlResponseProxy = controlResponseProxy;
this.authenticator = authenticator;
this.controlSessionProxy = controlSessionProxy;
this.activityDeadlineMs = cachedEpochClock.time() + connectTimeoutMs;
}
public int majorVersion()
{
return majorVersion;
}
public long sessionId()
{
return controlSessionId;
}
public long correlationId()
{
return correlationId;
}
public void abort()
{
state(State.INACTIVE);
if (null != activeListing)
{
activeListing.abort();
}
}
public void close()
{
final CountedErrorHandler errorHandler = conductor.context().countedErrorHandler();
if (null != activeListing)
{
AeronCloseHelper.close(errorHandler, activeListing::abort);
}
AeronCloseHelper.close(errorHandler, controlPublication);
state(State.CLOSED);
demuxer.removeControlSession(this);
}
public boolean isDone()
{
return state == State.INACTIVE;
}
public int doWork()
{
int workCount = 0;
final long nowMs = cachedEpochClock.time();
switch (state)
{
case INIT:
workCount += waitForConnection(nowMs);
break;
case CONNECTED:
workCount += sendConnectResponse(nowMs);
break;
case CHALLENGED:
workCount += waitForChallengeResponse(nowMs);
break;
case AUTHENTICATED:
workCount += waitForRequest(nowMs);
break;
case ACTIVE:
workCount += sendQueuedResponses(nowMs);
break;
case REJECTED:
workCount += sendReject(nowMs);
break;
}
return workCount;
}
ArchiveConductor archiveConductor()
{
return conductor;
}
Publication controlPublication()
{
return controlPublication;
}
boolean hasActiveListing()
{
return null != activeListing;
}
void activeListing(final Session activeListing)
{
this.activeListing = activeListing;
}
@SuppressWarnings("unused")
void onChallengeResponse(final long correlationId, final byte[] encodedCredentials)
{
if (State.CHALLENGED == state)
{
authenticator.onChallengeResponse(controlSessionId, encodedCredentials, cachedEpochClock.time());
this.correlationId = correlationId;
}
}
@SuppressWarnings("unused")
void onKeepAlive(final long correlationId)
{
attemptToGoActive();
}
void onStopRecording(final long correlationId, final int streamId, final String channel)
{
attemptToGoActive();
if (State.ACTIVE == state)
{
conductor.stopRecording(correlationId, streamId, channel, this);
}
}
void onStopRecordingSubscription(final long correlationId, final long subscriptionId)
{
attemptToGoActive();
if (State.ACTIVE == state)
{
conductor.stopRecordingSubscription(correlationId, subscriptionId, this);
}
}
void onStartRecording(
final long correlationId, final int streamId, final SourceLocation sourceLocation, final String channel)
{
attemptToGoActive();
if (State.ACTIVE == state)
{
conductor.startRecording(correlationId, streamId, sourceLocation, channel, this);
}
}
void onListRecordingsForUri(
final long correlationId,
final long fromRecordingId,
final int recordCount,
final int streamId,
final byte[] channelFragment)
{
attemptToGoActive();
if (State.ACTIVE == state)
{
conductor.newListRecordingsForUriSession(
correlationId,
fromRecordingId,
recordCount,
streamId,
channelFragment,
this);
}
}
void onListRecordings(final long correlationId, final long fromRecordingId, final int recordCount)
{
attemptToGoActive();
if (State.ACTIVE == state)
{
conductor.newListRecordingsSession(correlationId, fromRecordingId, recordCount, this);
}
}
void onListRecording(final long correlationId, final long recordingId)
{
attemptToGoActive();
if (State.ACTIVE == state)
{
conductor.listRecording(correlationId, recordingId, this);
}
}
void onFindLastMatchingRecording(
final long correlationId,
final long minRecordingId,
final int sessionId,
final int streamId,
final byte[] channelFragment)
{
attemptToGoActive();
if (State.ACTIVE == state)
{
conductor.findLastMatchingRecording(
correlationId,
minRecordingId,
sessionId,
streamId,
channelFragment,
this);
}
}
void onStartReplay(
final long correlationId,
final long recordingId,
final long position,
final long length,
final int replayStreamId,
final String replayChannel)
{
attemptToGoActive();
if (State.ACTIVE == state)
{
conductor.startReplay(
correlationId, recordingId, position, length, replayStreamId, replayChannel, this);
}
}
void onStartBoundedReplay(
final long correlationId,
final long recordingId,
final long position,
final long length,
final int limitCounterId,
final int replayStreamId,
final String replayChannel)
{
attemptToGoActive();
if (State.ACTIVE == state)
{
conductor.startBoundedReplay(
correlationId,
recordingId,
position,
length,
limitCounterId,
replayStreamId,
replayChannel,
this);
}
}
void onStopReplay(final long correlationId, final long replaySessionId)
{
attemptToGoActive();
if (State.ACTIVE == state)
{
conductor.stopReplay(correlationId, replaySessionId, this);
}
}
void onStopAllReplays(final long correlationId, final long recordingId)
{
attemptToGoActive();
if (State.ACTIVE == state)
{
conductor.stopAllReplays(correlationId, recordingId, this);
}
}
void onExtendRecording(
final long correlationId,
final long recordingId,
final int streamId,
final SourceLocation sourceLocation,
final String channel)
{
attemptToGoActive();
if (State.ACTIVE == state)
{
conductor.extendRecording(correlationId, recordingId, streamId, sourceLocation, channel, this);
}
}
void onGetRecordingPosition(final long correlationId, final long recordingId)
{
attemptToGoActive();
if (State.ACTIVE == state)
{
conductor.getRecordingPosition(correlationId, recordingId, this);
}
}
void onTruncateRecording(final long correlationId, final long recordingId, final long position)
{
attemptToGoActive();
if (State.ACTIVE == state)
{
conductor.truncateRecording(correlationId, recordingId, position, this);
}
}
void onGetStopPosition(final long correlationId, final long recordingId)
{
attemptToGoActive();
if (State.ACTIVE == state)
{
conductor.getStopPosition(correlationId, recordingId, this);
}
}
void onListRecordingSubscriptions(
final long correlationId,
final int pseudoIndex,
final int subscriptionCount,
final boolean applyStreamId,
final int streamId,
final String channelFragment)
{
attemptToGoActive();
if (State.ACTIVE == state)
{
conductor.listRecordingSubscriptions(
correlationId,
pseudoIndex,
subscriptionCount,
applyStreamId,
streamId,
channelFragment,
this);
}
}
void onReplicate(
final long correlationId,
final long srcRecordingId,
final long dstRecordingId,
final int srcControlStreamId,
final String srcControlChannel,
final String liveDestination)
{
attemptToGoActive();
if (State.ACTIVE == state)
{
conductor.replicate(
correlationId,
srcRecordingId,
dstRecordingId,
Aeron.NULL_VALUE,
Aeron.NULL_VALUE,
srcControlStreamId,
srcControlChannel,
liveDestination,
this);
}
}
void onStopReplication(final long correlationId, final long replicationId)
{
attemptToGoActive();
if (State.ACTIVE == state)
{
conductor.stopReplication(correlationId, replicationId, this);
}
}
void onGetStartPosition(final long correlationId, final long recordingId)
{
attemptToGoActive();
if (State.ACTIVE == state)
{
conductor.getStartPosition(correlationId, recordingId, this);
}
}
void onDetachSegments(final long correlationId, final long recordingId, final long newStartPosition)
{
attemptToGoActive();
if (State.ACTIVE == state)
{
conductor.detachSegments(correlationId, recordingId, newStartPosition, this);
}
}
void onDeleteDetachedSegments(final long correlationId, final long recordingId)
{
attemptToGoActive();
if (State.ACTIVE == state)
{
conductor.deleteDetachedSegments(correlationId, recordingId, this);
}
}
void onPurgeSegments(final long correlationId, final long recordingId, final long newStartPosition)
{
attemptToGoActive();
if (State.ACTIVE == state)
{
conductor.purgeSegments(correlationId, recordingId, newStartPosition, this);
}
}
void onAttachSegments(final long correlationId, final long recordingId)
{
attemptToGoActive();
if (State.ACTIVE == state)
{
conductor.attachSegments(correlationId, recordingId, this);
}
}
void onMigrateSegments(final long correlationId, final long srcRecordingId, final long dstRecordingId)
{
attemptToGoActive();
if (State.ACTIVE == state)
{
conductor.migrateSegments(correlationId, srcRecordingId, dstRecordingId, this);
}
}
void onReplicateTagged(
final long correlationId,
final long srcRecordingId,
final long dstRecordingId,
final long channelTagId,
final long subscriptionTagId,
final int srcControlStreamId,
final String srcControlChannel,
final String liveDestination)
{
attemptToGoActive();
if (State.ACTIVE == state)
{
conductor.replicate(
correlationId,
srcRecordingId,
dstRecordingId,
channelTagId,
subscriptionTagId,
srcControlStreamId,
srcControlChannel,
liveDestination,
this);
}
}
void sendOkResponse(final long correlationId, final ControlResponseProxy proxy)
{
sendResponse(correlationId, 0L, OK, null, proxy);
}
void sendOkResponse(final long correlationId, final long relevantId, final ControlResponseProxy proxy)
{
sendResponse(correlationId, relevantId, OK, null, proxy);
}
void sendErrorResponse(final long correlationId, final String errorMessage, final ControlResponseProxy proxy)
{
sendResponse(correlationId, 0L, ERROR, errorMessage, proxy);
}
void sendErrorResponse(
final long correlationId, final long relevantId, final String errorMessage, final ControlResponseProxy proxy)
{
sendResponse(correlationId, relevantId, ERROR, errorMessage, proxy);
}
void sendRecordingUnknown(final long correlationId, final long recordingId, final ControlResponseProxy proxy)
{
sendResponse(correlationId, recordingId, RECORDING_UNKNOWN, null, proxy);
}
void sendSubscriptionUnknown(final long correlationId, final ControlResponseProxy proxy)
{
sendResponse(correlationId, 0L, SUBSCRIPTION_UNKNOWN, null, proxy);
}
void sendResponse(
final long correlationId,
final long relevantId,
final ControlResponseCode code,
final String errorMessage,
final ControlResponseProxy proxy)
{
if (!proxy.sendResponse(controlSessionId, correlationId, relevantId, code, errorMessage, this))
{
queueResponse(correlationId, relevantId, code, errorMessage);
}
}
void attemptErrorResponse(final long correlationId, final String errorMessage, final ControlResponseProxy proxy)
{
proxy.sendResponse(controlSessionId, correlationId, GENERIC, ERROR, errorMessage, this);
}
void attemptErrorResponse(
final long correlationId, final long relevantId, final String errorMessage, final ControlResponseProxy proxy)
{
proxy.sendResponse(controlSessionId, correlationId, relevantId, ERROR, errorMessage, this);
}
int sendDescriptor(final long correlationId, final UnsafeBuffer descriptorBuffer, final ControlResponseProxy proxy)
{
return proxy.sendDescriptor(controlSessionId, correlationId, descriptorBuffer, this);
}
boolean sendSubscriptionDescriptor(
final long correlationId, final Subscription subscription, final ControlResponseProxy proxy)
{
return proxy.sendSubscriptionDescriptor(controlSessionId, correlationId, subscription, this);
}
void attemptSignal(
final long correlationId,
final long recordingId,
final long subscriptionId,
final long position,
final RecordingSignal recordingSignal)
{
controlResponseProxy.attemptSendSignal(
controlSessionId,
correlationId,
recordingId,
subscriptionId,
position,
recordingSignal,
controlPublication);
}
int maxPayloadLength()
{
return controlPublication.maxPayloadLength();
}
void challenged()
{
state(State.CHALLENGED);
}
@SuppressWarnings("unused")
void authenticate(final byte[] encodedPrincipal)
{
activityDeadlineMs = Aeron.NULL_VALUE;
state(State.AUTHENTICATED);
}
void reject()
{
state(State.REJECTED);
}
State state()
{
return state;
}
private void queueResponse(
final long correlationId, final long relevantId, final ControlResponseCode code, final String message)
{
queuedResponses.offer(() -> controlResponseProxy.sendResponse(
controlSessionId,
correlationId,
relevantId,
code,
message,
this));
}
private int waitForConnection(final long nowMs)
{
int workCount = 0;
if (controlPublication.isConnected())
{
state(State.CONNECTED);
workCount += 1;
}
else if (hasNoActivity(nowMs))
{
state(State.INACTIVE);
workCount += 1;
}
return workCount;
}
private int sendConnectResponse(final long nowMs)
{
int workCount = 0;
if (hasNoActivity(nowMs))
{
state(State.INACTIVE);
workCount += 1;
}
else if (nowMs > resendDeadlineMs)
{
resendDeadlineMs = nowMs + RESEND_INTERVAL_MS;
if (null != invalidVersionMessage)
{
controlResponseProxy.sendResponse(
controlSessionId,
correlationId,
controlSessionId,
ERROR,
invalidVersionMessage,
this);
}
else
{
authenticator.onConnectedSession(controlSessionProxy.controlSession(this), nowMs);
}
workCount += 1;
}
return workCount;
}
private int waitForChallengeResponse(final long nowMs)
{
int workCount = 0;
if (hasNoActivity(nowMs))
{
state(State.INACTIVE);
workCount += 1;
}
else
{
authenticator.onChallengedSession(controlSessionProxy.controlSession(this), nowMs);
workCount += 1;
}
return workCount;
}
private int waitForRequest(final long nowMs)
{
int workCount = 0;
if (hasNoActivity(nowMs))
{
state(State.INACTIVE);
workCount += 1;
}
else if (nowMs > resendDeadlineMs)
{
resendDeadlineMs = nowMs + RESEND_INTERVAL_MS;
if (controlResponseProxy.sendResponse(
controlSessionId,
correlationId,
controlSessionId,
OK,
null,
this))
{
activityDeadlineMs = Aeron.NULL_VALUE;
workCount += 1;
}
}
return workCount;
}
private int sendQueuedResponses(final long nowMs)
{
int workCount = 0;
if (!controlPublication.isConnected())
{
state(State.INACTIVE);
}
else
{
if (!queuedResponses.isEmpty())
{
if (queuedResponses.peekFirst().getAsBoolean())
{
queuedResponses.pollFirst();
activityDeadlineMs = Aeron.NULL_VALUE;
workCount++;
}
else if (activityDeadlineMs == Aeron.NULL_VALUE)
{
activityDeadlineMs = nowMs + connectTimeoutMs;
}
else if (hasNoActivity(nowMs))
{
state(State.INACTIVE);
}
}
}
return workCount;
}
private int sendReject(final long nowMs)
{
int workCount = 0;
if (hasNoActivity(nowMs))
{
state(State.INACTIVE);
workCount += 1;
}
else if (nowMs > resendDeadlineMs)
{
resendDeadlineMs = nowMs + RESEND_INTERVAL_MS;
controlResponseProxy.sendResponse(
controlSessionId,
correlationId,
AUTHENTICATION_REJECTED,
ERROR,
SESSION_REJECTED_MSG,
this);
workCount += 1;
}
return workCount;
}
private boolean hasNoActivity(final long nowMs)
{
return Aeron.NULL_VALUE != activityDeadlineMs & nowMs > activityDeadlineMs;
}
private void attemptToGoActive()
{
if (State.AUTHENTICATED == state && null == invalidVersionMessage)
{
state(State.ACTIVE);
}
}
private void state(final State state)
{
//System.out.println(controlSessionId + ": " + this.state + " -> " + state);
this.state = state;
}
public String toString()
{
return "ControlSession{" +
"controlSessionId=" + controlSessionId +
", correlationId=" + correlationId +
", state=" + state +
", controlPublication=" + controlPublication +
'}';
}
}
| [Java] Clean up code to avoid confusion over paths in waitForChallengeResponse.
| aeron-archive/src/main/java/io/aeron/archive/ControlSession.java | [Java] Clean up code to avoid confusion over paths in waitForChallengeResponse. | <ide><path>eron-archive/src/main/java/io/aeron/archive/ControlSession.java
<ide>
<ide> private int waitForChallengeResponse(final long nowMs)
<ide> {
<del> int workCount = 0;
<del>
<ide> if (hasNoActivity(nowMs))
<ide> {
<ide> state(State.INACTIVE);
<del> workCount += 1;
<ide> }
<ide> else
<ide> {
<ide> authenticator.onChallengedSession(controlSessionProxy.controlSession(this), nowMs);
<del> workCount += 1;
<del> }
<del>
<del> return workCount;
<add> }
<add>
<add> return 1;
<ide> }
<ide>
<ide> private int waitForRequest(final long nowMs) |
|
Java | apache-2.0 | 7001dbb3289165c50693269933d2c73ec73d8dc1 | 0 | Br3nda/plow,chadmv/plow,chadmv/plow,chadmv/plow,chadmv/plow,chadmv/plow,chadmv/plow,chadmv/plow,Br3nda/plow,Br3nda/plow,Br3nda/plow,Br3nda/plow | package com.breakersoft.plow.dao.pgsql;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.stereotype.Repository;
import com.breakersoft.plow.Folder;
import com.breakersoft.plow.Job;
import com.breakersoft.plow.JobE;
import com.breakersoft.plow.Project;
import com.breakersoft.plow.dao.AbstractDao;
import com.breakersoft.plow.dao.JobDao;
import com.breakersoft.plow.exceptions.InvalidBlueprintException;
import com.breakersoft.plow.thrift.JobSpecT;
import com.breakersoft.plow.thrift.JobState;
import com.breakersoft.plow.thrift.TaskState;
import com.breakersoft.plow.util.JdbcUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
@Repository
public final class JobDaoImpl extends AbstractDao implements JobDao {
public static final RowMapper<Job> MAPPER = new RowMapper<Job>() {
@Override
public Job mapRow(ResultSet rs, int rowNum)
throws SQLException {
JobE job = new JobE();
job.setJobId((UUID) rs.getObject(1));
job.setProjectId((UUID) rs.getObject(2));
job.setFolderId((UUID) rs.getObject(3));
return job;
}
};
private static final String GET =
"SELECT " +
"pk_job,"+
"pk_project, " +
"pk_folder " +
"FROM " +
"plow.job ";
@Override
public Job get(String name, JobState state) {
return jdbc.queryForObject(
GET + "WHERE str_name=? AND int_state=?",
MAPPER, name, state.ordinal());
}
@Override
public Job getActive(String name) {
return jdbc.queryForObject(
GET + "WHERE str_active_name=?", MAPPER, name);
}
@Override
public Job getActive(UUID id) {
return jdbc.queryForObject(
GET + "WHERE pk_job=? AND int_state!=?", MAPPER,
id, JobState.FINISHED.ordinal());
}
@Override
public Job getByActiveNameOrId(String identifer) {
try {
return getActive(UUID.fromString(identifer));
} catch (IllegalArgumentException e) {
return getActive(identifer);
}
}
@Override
public Job get(UUID id) {
return jdbc.queryForObject(
GET + "WHERE pk_job=?",
MAPPER, id);
}
@Override
public void setPaused(Job job, boolean value) {
jdbc.update("UPDATE plow.job SET bool_paused=? WHERE pk_job=?",
value, job.getJobId());
}
private static final String INSERT[] = {
JdbcUtils.Insert("plow.job",
"pk_job", "pk_project", "str_name", "str_active_name",
"str_username", "int_uid", "int_state", "bool_paused",
"str_log_path", "attrs")
};
@Override
public Job create(final Project project, final JobSpecT spec) {
final UUID jobId = UUID.randomUUID();
jdbc.update(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(final Connection conn) throws SQLException {
final PreparedStatement ret = conn.prepareStatement(INSERT[0]);
ret.setObject(1, jobId);
ret.setObject(2, project.getProjectId());
ret.setString(3, spec.getName());
ret.setString(4, spec.getName());
ret.setString(5, spec.username);
ret.setInt(6, spec.getUid());
ret.setInt(7, JobState.INITIALIZE.ordinal());
ret.setBoolean(8, spec.isPaused());
ret.setString(9, String.format("%s/%s", spec.logPath, spec.name));
ret.setObject(10, spec.attrs);
return ret;
}
});
jdbc.update("INSERT INTO plow.job_count (pk_job) VALUES (?)", jobId);
jdbc.update("INSERT INTO plow.job_dsp (pk_job) VALUES (?)", jobId);
jdbc.update("INSERT INTO plow.job_ping (pk_job) VALUES (?)", jobId);
final JobE job = new JobE();
job.setJobId(jobId);
job.setProjectId(project.getProjectId());
job.setFolderId(null); // Don't know folder yet
return job;
}
private static final String UPDATE_ATTRS =
"UPDATE " +
"plow.job " +
"SET " +
"attrs = ? " +
"WHERE " +
"pk_job=?";
@Override
public void setAttrs(final Job job, final Map<String,String> attrs) {
jdbc.update(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(final Connection conn) throws SQLException {
final PreparedStatement ret = conn.prepareStatement(UPDATE_ATTRS);
ret.setObject(1, attrs);
ret.setObject(2, job.getJobId());
return ret;
}
});
}
@Override
public Map<String,String> getAttrs(final Job job) {
return jdbc.queryForObject(
"SELECT attrs FROM plow.job WHERE job.pk_job=?",
new RowMapper<Map<String,String>>() {
@Override
public Map<String, String> mapRow(ResultSet rs, int rowNum)
throws SQLException {
@SuppressWarnings("unchecked")
Map<String,String> result = (Map<String, String>) rs.getObject("attrs");
return result;
}
}, job.getJobId());
}
@Override
public void updateFolder(Job job, Folder folder) {
jdbc.update("UPDATE plow.job SET pk_folder=? WHERE pk_job=?",
folder.getFolderId(), job.getJobId());
}
@Override
public boolean setJobState(Job job, JobState state) {
return jdbc.update("UPDATE plow.job SET int_state=? WHERE pk_job=?",
state.ordinal(), job.getJobId()) == 1;
}
@Override
public boolean shutdown(Job job) {
return jdbc.update("UPDATE plow.job SET int_state=?, " +
"str_active_name=NULL, time_stopped=plow.txTimeMillis() WHERE pk_job=? AND int_state=?",
JobState.FINISHED.ordinal(), job.getJobId(), JobState.RUNNING.ordinal()) == 1;
}
@Override
public void updateFrameStatesForLaunch(Job job) {
jdbc.update("UPDATE plow.task SET int_state=? WHERE pk_layer " +
"IN (SELECT pk_layer FROM plow.layer WHERE pk_job=?)",
TaskState.WAITING.ordinal(), job.getJobId());
}
private static final String GET_FRAME_STATUS_COUNTS =
"SELECT " +
"COUNT(1) AS c, " +
"task.int_state, " +
"task.pk_layer " +
"FROM " +
"plow.task," +
"plow.layer " +
"WHERE " +
"task.pk_layer = layer.pk_layer " +
"AND "+
"layer.pk_job=? " +
"GROUP BY " +
"task.int_state,"+
"task.pk_layer";
@Override
public void updateFrameCountsForLaunch(Job job) {
Map<Integer, Integer> jobRollup = Maps.newHashMap();
Map<String, List<Integer>> layerRollup = Maps.newHashMap();
List<Map<String, Object>> taskCounts = jdbc.queryForList(
GET_FRAME_STATUS_COUNTS, job.getJobId());
if (taskCounts.isEmpty()) {
throw new InvalidBlueprintException("The job contains no tasks.");
}
for (Map<String, Object> entry: taskCounts) {
String layerId = entry.get("pk_layer").toString();
int state = (Integer) entry.get("int_state");
int count = ((Long)entry.get("c")).intValue();
// Rollup counts for job.
Integer stateCount = jobRollup.get(state);
if (stateCount == null) {
jobRollup.put(state, count);
}
else {
jobRollup.put(state, count + stateCount);
}
// Rollup stats for layers.
List<Integer> layerCounts = layerRollup.get(layerId);
if (layerCounts == null) {
layerRollup.put(layerId, Lists.newArrayList(state, count));
}
else {
layerRollup.get(layerId).add(state);
layerRollup.get(layerId).add(count);
}
}
final StringBuilder sb = new StringBuilder(512);
final List<Object> values = Lists.newArrayList();
// Apply layer counts
for (Map.Entry<String, List<Integer>> entry: layerRollup.entrySet()) {
List<Integer> d = entry.getValue();
values.clear();
int total = 0;
sb.setLength(0);
sb.append("UPDATE plow.layer_count SET");
for (int i=0; i < entry.getValue().size(); i=i+2) {
sb.append(" int_");
sb.append(TaskState.findByValue(d.get(i)).toString().toLowerCase());
sb.append("=?,");
values.add(d.get(i+1));
total=total + d.get(i+1);
}
sb.deleteCharAt(sb.length() - 1);
sb.append(" WHERE pk_layer=?");
values.add(UUID.fromString(entry.getKey()));
jdbc.update(sb.toString(), values.toArray());
jdbc.update("UPDATE plow.layer_count SET int_total=? WHERE pk_layer=?",
total, UUID.fromString(entry.getKey()));
}
int total = 0;
values.clear();
sb.setLength(0);
sb.append("UPDATE plow.job_count SET ");
for (Map.Entry<Integer,Integer> entry: jobRollup.entrySet()) {
sb.append("int_");
sb.append(TaskState.findByValue(entry.getKey()).toString().toLowerCase());
sb.append("=?,");
values.add(entry.getValue());
total=total + entry.getValue();
}
sb.deleteCharAt(sb.length() - 1);
sb.append(" WHERE pk_job=?");
values.add(job.getJobId());
jdbc.update(sb.toString(), values.toArray());
jdbc.update("UPDATE plow.job_count SET int_total=? WHERE pk_job=?",
total, job.getJobId());
}
@Override
public boolean isPaused(Job job) {
return jdbc.queryForObject("SELECT bool_paused FROM plow.job WHERE pk_job=?",
Boolean.class, job.getJobId());
}
@Override
public boolean hasWaitingFrames(Job job) {
return jdbc.queryForInt("SELECT job_count.int_waiting FROM plow.job_count WHERE pk_job=?",
job.getJobId()) > 0;
}
@Override
public boolean updateMaxRssMb(UUID jobId, int value) {
return jdbc.update("UPDATE plow.job_ping SET int_max_rss=? " +
"WHERE pk_job=? AND int_max_rss < ?",
value, jobId, value) == 1;
}
private static final String HAS_PENDING_FRAMES =
"SELECT " +
"job_count.int_total - (job_count.int_eaten + job_count.int_succeeded) AS pending, " +
"job.int_state " +
"FROM " +
"plow.job " +
"INNER JOIN " +
"plow.job_count " +
"ON " +
"job.pk_job = job_count.pk_job " +
"WHERE " +
"job.pk_job=?";
@Override
public boolean isFinished(Job job) {
SqlRowSet row = jdbc.queryForRowSet(HAS_PENDING_FRAMES, job.getJobId());
if (!row.first()) {
return true;
}
if (row.getInt("int_state") == JobState.FINISHED.ordinal()) {
return true;
}
if (row.getInt("pending") == 0) {
return true;
}
return false;
}
@Override
public void setMaxCores(Job job, int value) {
jdbc.update("UPDATE plow.job_dsp SET int_max_cores=? WHERE pk_job=?",
value, job.getJobId());
}
@Override
public void setMinCores(Job job, int value) {
jdbc.update("UPDATE plow.job_dsp SET int_min_cores=? WHERE pk_job=?",
value, job.getJobId());
}
}
| server/src/main/java/com/breakersoft/plow/dao/pgsql/JobDaoImpl.java | package com.breakersoft.plow.dao.pgsql;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.stereotype.Repository;
import com.breakersoft.plow.Folder;
import com.breakersoft.plow.Job;
import com.breakersoft.plow.JobE;
import com.breakersoft.plow.Project;
import com.breakersoft.plow.dao.AbstractDao;
import com.breakersoft.plow.dao.JobDao;
import com.breakersoft.plow.exceptions.InvalidBlueprintException;
import com.breakersoft.plow.thrift.JobSpecT;
import com.breakersoft.plow.thrift.JobState;
import com.breakersoft.plow.thrift.TaskState;
import com.breakersoft.plow.util.JdbcUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
@Repository
public final class JobDaoImpl extends AbstractDao implements JobDao {
public static final RowMapper<Job> MAPPER = new RowMapper<Job>() {
@Override
public Job mapRow(ResultSet rs, int rowNum)
throws SQLException {
JobE job = new JobE();
job.setJobId((UUID) rs.getObject(1));
job.setProjectId((UUID) rs.getObject(2));
job.setFolderId((UUID) rs.getObject(3));
return job;
}
};
private static final String GET =
"SELECT " +
"pk_job,"+
"pk_project, " +
"pk_folder " +
"FROM " +
"plow.job ";
@Override
public Job get(String name, JobState state) {
return jdbc.queryForObject(
GET + "WHERE str_name=? AND int_state=?",
MAPPER, name, state.ordinal());
}
@Override
public Job getActive(String name) {
return jdbc.queryForObject(
GET + "WHERE str_active_name=?", MAPPER, name);
}
@Override
public Job getActive(UUID id) {
return jdbc.queryForObject(
GET + "WHERE pk_job=? AND int_state!=?", MAPPER,
id, JobState.FINISHED.ordinal());
}
@Override
public Job getByActiveNameOrId(String identifer) {
try {
return getActive(UUID.fromString(identifer));
} catch (IllegalArgumentException e) {
return getActive(identifer);
}
}
@Override
public Job get(UUID id) {
return jdbc.queryForObject(
GET + "WHERE pk_job=?",
MAPPER, id);
}
@Override
public void setPaused(Job job, boolean value) {
jdbc.update("UPDATE plow.job SET bool_paused=? WHERE pk_job=?",
value, job.getJobId());
}
private static final String INSERT[] = {
JdbcUtils.Insert("plow.job",
"pk_job", "pk_project", "str_name", "str_active_name",
"str_username", "int_uid", "int_state", "bool_paused",
"str_log_path", "attrs")
};
@Override
public Job create(final Project project, final JobSpecT spec) {
final UUID jobId = UUID.randomUUID();
jdbc.update(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(final Connection conn) throws SQLException {
final PreparedStatement ret = conn.prepareStatement(INSERT[0]);
ret.setObject(1, jobId);
ret.setObject(2, project.getProjectId());
ret.setString(3, spec.getName());
ret.setString(4, spec.getName());
ret.setString(5, spec.username);
ret.setInt(6, spec.getUid());
ret.setInt(7, JobState.INITIALIZE.ordinal());
ret.setBoolean(8, spec.isPaused());
ret.setString(9, String.format("%s/%s", spec.logPath, spec.name));
ret.setObject(10, spec.attrs);
return ret;
}
});
jdbc.update("INSERT INTO plow.job_count (pk_job) VALUES (?)", jobId);
jdbc.update("INSERT INTO plow.job_dsp (pk_job) VALUES (?)", jobId);
jdbc.update("INSERT INTO plow.job_ping (pk_job) VALUES (?)", jobId);
final JobE job = new JobE();
job.setJobId(jobId);
job.setProjectId(project.getProjectId());
job.setFolderId(null); // Don't know folder yet
return job;
}
private static final String UPDATE_ATTRS =
"UPDATE " +
"plow.job " +
"SET " +
"attrs = ? " +
"WHERE " +
"pk_job=?";
@Override
public void setAttrs(final Job job, final Map<String,String> attrs) {
jdbc.update(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(final Connection conn) throws SQLException {
final PreparedStatement ret = conn.prepareStatement(UPDATE_ATTRS);
ret.setObject(1, attrs);
ret.setObject(2, job.getJobId());
return ret;
}
});
}
@Override
public Map<String,String> getAttrs(final Job job) {
return jdbc.queryForObject(
"SELECT attrs FROM plow.job WHERE job.pk_job=?",
new RowMapper<Map<String,String>>() {
@Override
public Map<String, String> mapRow(ResultSet rs, int rowNum)
throws SQLException {
Map<String,String> result = (Map<String, String>) rs.getObject("attrs");
return result;
}
}, job.getJobId());
}
@Override
public void updateFolder(Job job, Folder folder) {
jdbc.update("UPDATE plow.job SET pk_folder=? WHERE pk_job=?",
folder.getFolderId(), job.getJobId());
}
@Override
public boolean setJobState(Job job, JobState state) {
return jdbc.update("UPDATE plow.job SET int_state=? WHERE pk_job=?",
state.ordinal(), job.getJobId()) == 1;
}
@Override
public boolean shutdown(Job job) {
return jdbc.update("UPDATE plow.job SET int_state=?, " +
"str_active_name=NULL, time_stopped=plow.txTimeMillis() WHERE pk_job=? AND int_state=?",
JobState.FINISHED.ordinal(), job.getJobId(), JobState.RUNNING.ordinal()) == 1;
}
@Override
public void updateFrameStatesForLaunch(Job job) {
jdbc.update("UPDATE plow.task SET int_state=? WHERE pk_layer " +
"IN (SELECT pk_layer FROM plow.layer WHERE pk_job=?)",
TaskState.WAITING.ordinal(), job.getJobId());
}
private static final String GET_FRAME_STATUS_COUNTS =
"SELECT " +
"COUNT(1) AS c, " +
"task.int_state, " +
"task.pk_layer " +
"FROM " +
"plow.task," +
"plow.layer " +
"WHERE " +
"task.pk_layer = layer.pk_layer " +
"AND "+
"layer.pk_job=? " +
"GROUP BY " +
"task.int_state,"+
"task.pk_layer";
@Override
public void updateFrameCountsForLaunch(Job job) {
Map<Integer, Integer> jobRollup = Maps.newHashMap();
Map<String, List<Integer>> layerRollup = Maps.newHashMap();
List<Map<String, Object>> taskCounts = jdbc.queryForList(
GET_FRAME_STATUS_COUNTS, job.getJobId());
if (taskCounts.isEmpty()) {
throw new InvalidBlueprintException("The job contains no tasks.");
}
for (Map<String, Object> entry: taskCounts) {
String layerId = entry.get("pk_layer").toString();
int state = (Integer) entry.get("int_state");
int count = ((Long)entry.get("c")).intValue();
// Rollup counts for job.
Integer stateCount = jobRollup.get(state);
if (stateCount == null) {
jobRollup.put(state, count);
}
else {
jobRollup.put(state, count + stateCount);
}
// Rollup stats for layers.
List<Integer> layerCounts = layerRollup.get(layerId);
if (layerCounts == null) {
layerRollup.put(layerId, Lists.newArrayList(state, count));
}
else {
layerRollup.get(layerId).add(state);
layerRollup.get(layerId).add(count);
}
}
final StringBuilder sb = new StringBuilder(512);
final List<Object> values = Lists.newArrayList();
// Apply layer counts
for (Map.Entry<String, List<Integer>> entry: layerRollup.entrySet()) {
List<Integer> d = entry.getValue();
values.clear();
int total = 0;
sb.setLength(0);
sb.append("UPDATE plow.layer_count SET");
for (int i=0; i < entry.getValue().size(); i=i+2) {
sb.append(" int_");
sb.append(TaskState.findByValue(d.get(i)).toString().toLowerCase());
sb.append("=?,");
values.add(d.get(i+1));
total=total + d.get(i+1);
}
sb.deleteCharAt(sb.length() - 1);
sb.append(" WHERE pk_layer=?");
values.add(UUID.fromString(entry.getKey()));
jdbc.update(sb.toString(), values.toArray());
jdbc.update("UPDATE plow.layer_count SET int_total=? WHERE pk_layer=?",
total, UUID.fromString(entry.getKey()));
}
int total = 0;
values.clear();
sb.setLength(0);
sb.append("UPDATE plow.job_count SET ");
for (Map.Entry<Integer,Integer> entry: jobRollup.entrySet()) {
sb.append("int_");
sb.append(TaskState.findByValue(entry.getKey()).toString().toLowerCase());
sb.append("=?,");
values.add(entry.getValue());
total=total + entry.getValue();
}
sb.deleteCharAt(sb.length() - 1);
sb.append(" WHERE pk_job=?");
values.add(job.getJobId());
jdbc.update(sb.toString(), values.toArray());
jdbc.update("UPDATE plow.job_count SET int_total=? WHERE pk_job=?",
total, job.getJobId());
}
@Override
public boolean isPaused(Job job) {
return jdbc.queryForObject("SELECT bool_paused FROM plow.job WHERE pk_job=?",
Boolean.class, job.getJobId());
}
@Override
public boolean hasWaitingFrames(Job job) {
return jdbc.queryForInt("SELECT job_count.int_waiting FROM plow.job_count WHERE pk_job=?",
job.getJobId()) > 0;
}
@Override
public boolean updateMaxRssMb(UUID jobId, int value) {
return jdbc.update("UPDATE plow.job_ping SET int_max_rss=? " +
"WHERE pk_job=? AND int_max_rss < ?",
value, jobId, value) == 1;
}
private static final String HAS_PENDING_FRAMES =
"SELECT " +
"job_count.int_total - (job_count.int_eaten + job_count.int_succeeded) AS pending, " +
"job.int_state " +
"FROM " +
"plow.job " +
"INNER JOIN " +
"plow.job_count " +
"ON " +
"job.pk_job = job_count.pk_job " +
"WHERE " +
"job.pk_job=?";
@Override
public boolean isFinished(Job job) {
SqlRowSet row = jdbc.queryForRowSet(HAS_PENDING_FRAMES, job.getJobId());
if (!row.first()) {
return true;
}
if (row.getInt("int_state") == JobState.FINISHED.ordinal()) {
return true;
}
if (row.getInt("pending") == 0) {
return true;
}
return false;
}
@Override
public void setMaxCores(Job job, int value) {
jdbc.update("UPDATE plow.job_dsp SET int_max_cores=? WHERE pk_job=?",
value, job.getJobId());
}
@Override
public void setMinCores(Job job, int value) {
jdbc.update("UPDATE plow.job_dsp SET int_min_cores=? WHERE pk_job=?",
value, job.getJobId());
}
}
| suppress warnings for an unsafe cast coming from postgres driver.
| server/src/main/java/com/breakersoft/plow/dao/pgsql/JobDaoImpl.java | suppress warnings for an unsafe cast coming from postgres driver. | <ide><path>erver/src/main/java/com/breakersoft/plow/dao/pgsql/JobDaoImpl.java
<ide> @Override
<ide> public Map<String, String> mapRow(ResultSet rs, int rowNum)
<ide> throws SQLException {
<add> @SuppressWarnings("unchecked")
<ide> Map<String,String> result = (Map<String, String>) rs.getObject("attrs");
<ide> return result;
<ide> } |
|
Java | apache-2.0 | c84637a0012d41e823b6d6af298afbfcf268c6b7 | 0 | xdyixia/coolweather | package com.coolweather.android;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.coolweather.android.gson.Forecast;
import com.coolweather.android.gson.Weather;
//import com.coolweather.android.service.AutoUpdateService;
import com.coolweather.android.util.HttpUtil;
import com.coolweather.android.util.Utility;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
public class WeatherActivity extends AppCompatActivity {
public DrawerLayout drawerLayout;
public SwipeRefreshLayout swipeRefresh;
private ScrollView weatherLayout;
private Button navButton;
private TextView titleCity;
private TextView titleUpdateTime;
private TextView degreeText;
private TextView weatherInfoText;
private LinearLayout forecastLayout;
private TextView aqiText;
private TextView pm25Text;
private TextView comfortText;
private TextView carWashText;
private TextView sportText;
private ImageView bingPicImg;
private String mWeatherId;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >= 21) {
View decorView = getWindow().getDecorView();
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
getWindow().setStatusBarColor(Color.TRANSPARENT);
}
setContentView(R.layout.activity_weather);
// 初始化各控件
bingPicImg = (ImageView) findViewById(R.id.bing_pic_img);
weatherLayout = (ScrollView) findViewById(R.id.weather_layout);
titleCity = (TextView) findViewById(R.id.title_city);
titleUpdateTime = (TextView) findViewById(R.id.title_update_time);
degreeText = (TextView) findViewById(R.id.degree_text);
weatherInfoText = (TextView) findViewById(R.id.weather_info_text);
forecastLayout = (LinearLayout) findViewById(R.id.forecast_layout);
aqiText = (TextView) findViewById(R.id.aqi_text);
pm25Text = (TextView) findViewById(R.id.pm25_text);
comfortText = (TextView) findViewById(R.id.comfort_text);
carWashText = (TextView) findViewById(R.id.car_wash_text);
sportText = (TextView) findViewById(R.id.sport_text);
swipeRefresh = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh);
swipeRefresh.setColorSchemeResources(R.color.colorPrimary);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
navButton = (Button) findViewById(R.id.nav_button);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String weatherString = prefs.getString("weather", null);
//final String weatherId;
if (weatherString != null) {
// 有缓存时直接解析天气数据
Weather weather = Utility.handleWeatherResponse(weatherString);
mWeatherId = weather.basic.weatherId;
showWeatherInfo(weather);
} else {
// 无缓存时去服务器查询天气
mWeatherId = getIntent().getStringExtra("weather_id");
weatherLayout.setVisibility(View.INVISIBLE);
requestWeather(mWeatherId);
}
swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
requestWeather(mWeatherId);
}
});
navButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
drawerLayout.openDrawer(GravityCompat.START);
}
});
String bingPic = prefs.getString("bing_pic", null);
if (bingPic != null) {
Glide.with(this).load(bingPic).into(bingPicImg);
} else {
loadBingPic();
}
}
/**
* 根据天气id请求城市天气信息。
*/
public void requestWeather(final String weatherId) {
String weatherUrl = "https://api.heweather.com/x3/weather?cityid=" + weatherId + "&key=bc0418b57b2d4918819d3974ac1285d9";
HttpUtil.sendOkHttpRequest(weatherUrl, new Callback() {
@Override
public void onResponse(Call call, Response response) throws IOException {
final String responseText = response.body().string();
final Weather weather = Utility.handleWeatherResponse(responseText);
runOnUiThread(new Runnable() {
@Override
public void run() {
if (weather != null && "ok".equals(weather.status)) {
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this).edit();
editor.putString("weather", responseText);
editor.apply();
mWeatherId=weather.basic.weatherId;
showWeatherInfo(weather);
} else {
Toast.makeText(WeatherActivity.this, "获取天气信息失败", Toast.LENGTH_SHORT).show();
}
swipeRefresh.setRefreshing(false);
}
});
}
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(WeatherActivity.this, "获取天气信息失败", Toast.LENGTH_SHORT).show();
swipeRefresh.setRefreshing(false);
}
});
}
});
loadBingPic();
}
/**
* 加载必应每日一图
*/
private void loadBingPic() {
String requestBingPic = "http://guolin.tech/api/bing_pic";
HttpUtil.sendOkHttpRequest(requestBingPic, new Callback() {
@Override
public void onResponse(Call call, Response response) throws IOException {
final String bingPic = response.body().string();
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this).edit();
editor.putString("bing_pic", bingPic);
editor.apply();
runOnUiThread(new Runnable() {
@Override
public void run() {
Glide.with(WeatherActivity.this).load(bingPic).into(bingPicImg);
}
});
}
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
});
}
/**
* 处理并展示Weather实体类中的数据。
*/
private void showWeatherInfo(Weather weather) {
String cityName = weather.basic.cityName;
String updateTime = weather.basic.update.updateTime.split(" ")[1];
String degree = weather.now.temperature + "℃";
String weatherInfo = weather.now.more.info;
titleCity.setText(cityName);
titleUpdateTime.setText(updateTime);
degreeText.setText(degree);
weatherInfoText.setText(weatherInfo);
forecastLayout.removeAllViews();
for (Forecast forecast : weather.forecastList) {
View view = LayoutInflater.from(this).inflate(R.layout.forecast_item, forecastLayout, false);
TextView dateText = (TextView) view.findViewById(R.id.date_text);
TextView infoText = (TextView) view.findViewById(R.id.info_text);
TextView maxText = (TextView) view.findViewById(R.id.max_text);
TextView minText = (TextView) view.findViewById(R.id.min_text);
dateText.setText(forecast.date);
infoText.setText(forecast.more.info);
maxText.setText(forecast.temperature.max);
minText.setText(forecast.temperature.min);
forecastLayout.addView(view);
}
if (weather.aqi != null) {
aqiText.setText(weather.aqi.city.aqi);
pm25Text.setText(weather.aqi.city.pm25);
}
String comfort = "舒适度:" + weather.suggestion.comfort.info;
String carWash = "洗车指数:" + weather.suggestion.carWash.info;
String sport = "运行建议:" + weather.suggestion.sport.info;
comfortText.setText(comfort);
carWashText.setText(carWash);
sportText.setText(sport);
weatherLayout.setVisibility(View.VISIBLE);
// Intent intent = new Intent(this, AutoUpdateService.class);
//startService(intent);
}
}
| app/src/main/java/com/coolweather/android/WeatherActivity.java | package com.coolweather.android;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.coolweather.android.gson.Forecast;
import com.coolweather.android.gson.Weather;
//import com.coolweather.android.service.AutoUpdateService;
import com.coolweather.android.util.HttpUtil;
import com.coolweather.android.util.Utility;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
public class WeatherActivity extends AppCompatActivity {
public DrawerLayout drawerLayout;
public SwipeRefreshLayout swipeRefresh;
private ScrollView weatherLayout;
private Button navButton;
private TextView titleCity;
private TextView titleUpdateTime;
private TextView degreeText;
private TextView weatherInfoText;
private LinearLayout forecastLayout;
private TextView aqiText;
private TextView pm25Text;
private TextView comfortText;
private TextView carWashText;
private TextView sportText;
private ImageView bingPicImg;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >= 21) {
View decorView = getWindow().getDecorView();
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
getWindow().setStatusBarColor(Color.TRANSPARENT);
}
setContentView(R.layout.activity_weather);
// 初始化各控件
bingPicImg = (ImageView) findViewById(R.id.bing_pic_img);
weatherLayout = (ScrollView) findViewById(R.id.weather_layout);
titleCity = (TextView) findViewById(R.id.title_city);
titleUpdateTime = (TextView) findViewById(R.id.title_update_time);
degreeText = (TextView) findViewById(R.id.degree_text);
weatherInfoText = (TextView) findViewById(R.id.weather_info_text);
forecastLayout = (LinearLayout) findViewById(R.id.forecast_layout);
aqiText = (TextView) findViewById(R.id.aqi_text);
pm25Text = (TextView) findViewById(R.id.pm25_text);
comfortText = (TextView) findViewById(R.id.comfort_text);
carWashText = (TextView) findViewById(R.id.car_wash_text);
sportText = (TextView) findViewById(R.id.sport_text);
swipeRefresh = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh);
swipeRefresh.setColorSchemeResources(R.color.colorPrimary);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
navButton = (Button) findViewById(R.id.nav_button);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String weatherString = prefs.getString("weather", null);
final String weatherId;
if (weatherString != null) {
// 有缓存时直接解析天气数据
Weather weather = Utility.handleWeatherResponse(weatherString);
weatherId = weather.basic.weatherId;
showWeatherInfo(weather);
} else {
// 无缓存时去服务器查询天气
weatherId = getIntent().getStringExtra("weather_id");
weatherLayout.setVisibility(View.INVISIBLE);
requestWeather(weatherId);
}
swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
requestWeather(weatherId);
}
});
navButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
drawerLayout.openDrawer(GravityCompat.START);
}
});
String bingPic = prefs.getString("bing_pic", null);
if (bingPic != null) {
Glide.with(this).load(bingPic).into(bingPicImg);
} else {
loadBingPic();
}
}
/**
* 根据天气id请求城市天气信息。
*/
public void requestWeather(final String weatherId) {
String weatherUrl = "https://api.heweather.com/x3/weather?cityid=" + weatherId + "&key=bc0418b57b2d4918819d3974ac1285d9";
HttpUtil.sendOkHttpRequest(weatherUrl, new Callback() {
@Override
public void onResponse(Call call, Response response) throws IOException {
final String responseText = response.body().string();
final Weather weather = Utility.handleWeatherResponse(responseText);
runOnUiThread(new Runnable() {
@Override
public void run() {
if (weather != null && "ok".equals(weather.status)) {
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this).edit();
editor.putString("weather", responseText);
editor.apply();
showWeatherInfo(weather);
} else {
Toast.makeText(WeatherActivity.this, "获取天气信息失败", Toast.LENGTH_SHORT).show();
}
swipeRefresh.setRefreshing(false);
}
});
}
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(WeatherActivity.this, "获取天气信息失败", Toast.LENGTH_SHORT).show();
swipeRefresh.setRefreshing(false);
}
});
}
});
loadBingPic();
}
/**
* 加载必应每日一图
*/
private void loadBingPic() {
String requestBingPic = "http://guolin.tech/api/bing_pic";
HttpUtil.sendOkHttpRequest(requestBingPic, new Callback() {
@Override
public void onResponse(Call call, Response response) throws IOException {
final String bingPic = response.body().string();
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this).edit();
editor.putString("bing_pic", bingPic);
editor.apply();
runOnUiThread(new Runnable() {
@Override
public void run() {
Glide.with(WeatherActivity.this).load(bingPic).into(bingPicImg);
}
});
}
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
});
}
/**
* 处理并展示Weather实体类中的数据。
*/
private void showWeatherInfo(Weather weather) {
String cityName = weather.basic.cityName;
String updateTime = weather.basic.update.updateTime.split(" ")[1];
String degree = weather.now.temperature + "℃";
String weatherInfo = weather.now.more.info;
titleCity.setText(cityName);
titleUpdateTime.setText(updateTime);
degreeText.setText(degree);
weatherInfoText.setText(weatherInfo);
forecastLayout.removeAllViews();
for (Forecast forecast : weather.forecastList) {
View view = LayoutInflater.from(this).inflate(R.layout.forecast_item, forecastLayout, false);
TextView dateText = (TextView) view.findViewById(R.id.date_text);
TextView infoText = (TextView) view.findViewById(R.id.info_text);
TextView maxText = (TextView) view.findViewById(R.id.max_text);
TextView minText = (TextView) view.findViewById(R.id.min_text);
dateText.setText(forecast.date);
infoText.setText(forecast.more.info);
maxText.setText(forecast.temperature.max);
minText.setText(forecast.temperature.min);
forecastLayout.addView(view);
}
if (weather.aqi != null) {
aqiText.setText(weather.aqi.city.aqi);
pm25Text.setText(weather.aqi.city.pm25);
}
String comfort = "舒适度:" + weather.suggestion.comfort.info;
String carWash = "洗车指数:" + weather.suggestion.carWash.info;
String sport = "运行建议:" + weather.suggestion.sport.info;
comfortText.setText(comfort);
carWashText.setText(carWash);
sportText.setText(sport);
weatherLayout.setVisibility(View.VISIBLE);
// Intent intent = new Intent(this, AutoUpdateService.class);
// startService(intent);
}
}
| 新增切换城市和手动更新天气的功能。
| app/src/main/java/com/coolweather/android/WeatherActivity.java | 新增切换城市和手动更新天气的功能。 | <ide><path>pp/src/main/java/com/coolweather/android/WeatherActivity.java
<ide> private TextView sportText;
<ide>
<ide> private ImageView bingPicImg;
<add>
<add> private String mWeatherId;
<ide>
<ide> @Override
<ide> protected void onCreate(Bundle savedInstanceState) {
<ide> navButton = (Button) findViewById(R.id.nav_button);
<ide> SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
<ide> String weatherString = prefs.getString("weather", null);
<del> final String weatherId;
<add> //final String weatherId;
<ide> if (weatherString != null) {
<ide> // 有缓存时直接解析天气数据
<ide> Weather weather = Utility.handleWeatherResponse(weatherString);
<del> weatherId = weather.basic.weatherId;
<add> mWeatherId = weather.basic.weatherId;
<ide> showWeatherInfo(weather);
<ide> } else {
<ide> // 无缓存时去服务器查询天气
<del> weatherId = getIntent().getStringExtra("weather_id");
<add> mWeatherId = getIntent().getStringExtra("weather_id");
<ide> weatherLayout.setVisibility(View.INVISIBLE);
<del> requestWeather(weatherId);
<add> requestWeather(mWeatherId);
<ide> }
<ide> swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
<ide> @Override
<ide> public void onRefresh() {
<del> requestWeather(weatherId);
<add> requestWeather(mWeatherId);
<ide> }
<ide> });
<ide> navButton.setOnClickListener(new View.OnClickListener() {
<ide> SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this).edit();
<ide> editor.putString("weather", responseText);
<ide> editor.apply();
<add> mWeatherId=weather.basic.weatherId;
<ide> showWeatherInfo(weather);
<ide> } else {
<ide> Toast.makeText(WeatherActivity.this, "获取天气信息失败", Toast.LENGTH_SHORT).show();
<ide> carWashText.setText(carWash);
<ide> sportText.setText(sport);
<ide> weatherLayout.setVisibility(View.VISIBLE);
<del>// Intent intent = new Intent(this, AutoUpdateService.class);
<del> // startService(intent);
<add> // Intent intent = new Intent(this, AutoUpdateService.class);
<add> //startService(intent);
<ide> }
<ide>
<ide> } |
|
JavaScript | mit | 6a948a1a2021dca92b7097b3e5f76bbe866da770 | 0 | inventree/InvenTree,SchrodingersGat/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree | {% load i18n %}
{% load inventree_extras %}
/* globals
Chart,
constructForm,
global_settings,
imageHoverIcon,
inventreeGet,
inventreePut,
launchModalForm,
linkButtonsToSelection,
loadTableFilters,
makeIconBadge,
makeIconButton,
printPartLabels,
renderLink,
setFormGroupVisibility,
setupFilterList,
yesNoLabel,
*/
/* exported
duplicatePart,
editCategory,
editPart,
initPriceBreakSet,
loadBomChart,
loadParametricPartTable,
loadPartCategoryTable,
loadPartParameterTable,
loadPartTable,
loadPartTestTemplateTable,
loadPartVariantTable,
loadRelatedPartsTable,
loadSellPricingChart,
loadSimplePartTable,
loadStockPricingChart,
partStockLabel,
toggleStar,
*/
/* Part API functions
* Requires api.js to be loaded first
*/
function partGroups() {
return {
attributes: {
title: '{% trans "Part Attributes" %}',
collapsible: true,
},
create: {
title: '{% trans "Part Creation Options" %}',
collapsible: true,
},
duplicate: {
title: '{% trans "Part Duplication Options" %}',
collapsible: true,
},
supplier: {
title: '{% trans "Supplier Options" %}',
collapsible: true,
hidden: !global_settings.PART_PURCHASEABLE,
}
};
}
// Construct fieldset for part forms
function partFields(options={}) {
var fields = {
category: {
secondary: {
title: '{% trans "Add Part Category" %}',
fields: function() {
var fields = categoryFields();
return fields;
}
}
},
name: {},
IPN: {},
revision: {},
description: {},
variant_of: {},
keywords: {
icon: 'fa-key',
},
units: {},
link: {
icon: 'fa-link',
},
default_location: {
},
default_supplier: {
filters: {
part_detail: true,
supplier_detail: true,
}
},
default_expiry: {
icon: 'fa-calendar-alt',
},
minimum_stock: {
icon: 'fa-boxes',
},
component: {
default: global_settings.PART_COMPONENT,
group: 'attributes',
},
assembly: {
default: global_settings.PART_ASSEMBLY,
group: 'attributes',
},
is_template: {
default: global_settings.PART_TEMPLATE,
group: 'attributes',
},
trackable: {
default: global_settings.PART_TRACKABLE,
group: 'attributes',
},
purchaseable: {
default: global_settings.PART_PURCHASEABLE,
group: 'attributes',
onEdit: function(value, name, field, options) {
setFormGroupVisibility('supplier', value, options);
}
},
salable: {
default: global_settings.PART_SALABLE,
group: 'attributes',
},
virtual: {
default: global_settings.PART_VIRTUAL,
group: 'attributes',
},
};
// If editing a part, we can set the "active" status
if (options.edit) {
fields.active = {
group: 'attributes'
};
}
// Pop expiry field
if (!global_settings.STOCK_ENABLE_EXPIRY) {
delete fields['default_expiry'];
}
// Additional fields when "creating" a new part
if (options.create) {
// No supplier parts available yet
delete fields['default_supplier'];
if (global_settings.PART_CREATE_INITIAL) {
fields.initial_stock = {
type: 'boolean',
label: '{% trans "Create Initial Stock" %}',
help_text: '{% trans "Create an initial stock item for this part" %}',
group: 'create',
};
fields.initial_stock_quantity = {
type: 'decimal',
value: 1,
label: '{% trans "Initial Stock Quantity" %}',
help_text: '{% trans "Specify initial stock quantity for this part" %}',
group: 'create',
};
// TODO - Allow initial location of stock to be specified
fields.initial_stock_location = {
label: '{% trans "Location" %}',
help_text: '{% trans "Select destination stock location" %}',
type: 'related field',
required: true,
api_url: `/api/stock/location/`,
model: 'stocklocation',
group: 'create',
};
}
fields.copy_category_parameters = {
type: 'boolean',
label: '{% trans "Copy Category Parameters" %}',
help_text: '{% trans "Copy parameter templates from selected part category" %}',
value: global_settings.PART_CATEGORY_PARAMETERS,
group: 'create',
};
// Supplier options
fields.add_supplier_info = {
type: 'boolean',
label: '{% trans "Add Supplier Data" %}',
help_text: '{% trans "Create initial supplier data for this part" %}',
group: 'supplier',
};
fields.supplier = {
type: 'related field',
model: 'company',
label: '{% trans "Supplier" %}',
help_text: '{% trans "Select supplier" %}',
filters: {
'is_supplier': true,
},
api_url: '{% url "api-company-list" %}',
group: 'supplier',
};
fields.SKU = {
type: 'string',
label: '{% trans "SKU" %}',
help_text: '{% trans "Supplier stock keeping unit" %}',
group: 'supplier',
};
fields.manufacturer = {
type: 'related field',
model: 'company',
label: '{% trans "Manufacturer" %}',
help_text: '{% trans "Select manufacturer" %}',
filters: {
'is_manufacturer': true,
},
api_url: '{% url "api-company-list" %}',
group: 'supplier',
};
fields.MPN = {
type: 'string',
label: '{% trans "MPN" %}',
help_text: '{% trans "Manufacturer Part Number" %}',
group: 'supplier',
};
}
// Additional fields when "duplicating" a part
if (options.duplicate) {
fields.copy_from = {
type: 'integer',
hidden: true,
value: options.duplicate,
group: 'duplicate',
},
fields.copy_image = {
type: 'boolean',
label: '{% trans "Copy Image" %}',
help_text: '{% trans "Copy image from original part" %}',
value: true,
group: 'duplicate',
},
fields.copy_bom = {
type: 'boolean',
label: '{% trans "Copy BOM" %}',
help_text: '{% trans "Copy bill of materials from original part" %}',
value: global_settings.PART_COPY_BOM,
group: 'duplicate',
};
fields.copy_parameters = {
type: 'boolean',
label: '{% trans "Copy Parameters" %}',
help_text: '{% trans "Copy parameter data from original part" %}',
value: global_settings.PART_COPY_PARAMETERS,
group: 'duplicate',
};
}
return fields;
}
function categoryFields() {
return {
parent: {
help_text: '{% trans "Parent part category" %}',
},
name: {},
description: {},
default_location: {},
default_keywords: {
icon: 'fa-key',
}
};
}
// Edit a PartCategory via the API
function editCategory(pk) {
var url = `/api/part/category/${pk}/`;
var fields = categoryFields();
constructForm(url, {
fields: fields,
title: '{% trans "Edit Part Category" %}',
reload: true,
});
}
function editPart(pk) {
var url = `/api/part/${pk}/`;
var fields = partFields({
edit: true
});
// Filter supplied parts by the Part ID
fields.default_supplier.filters.part = pk;
var groups = partGroups({});
constructForm(url, {
fields: fields,
groups: groups,
title: '{% trans "Edit Part" %}',
reload: true,
successMessage: '{% trans "Part edited" %}',
});
}
// Launch form to duplicate a part
function duplicatePart(pk, options={}) {
// First we need all the part information
inventreeGet(`/api/part/${pk}/`, {}, {
success: function(data) {
var fields = partFields({
duplicate: pk,
});
// Remove "default_supplier" field
delete fields['default_supplier'];
// If we are making a "variant" part
if (options.variant) {
// Override the "variant_of" field
data.variant_of = pk;
}
constructForm('{% url "api-part-list" %}', {
method: 'POST',
fields: fields,
groups: partGroups(),
title: '{% trans "Duplicate Part" %}',
data: data,
onSuccess: function(data) {
// Follow the new part
location.href = `/part/${data.pk}/`;
}
});
}
});
}
/* Toggle the 'starred' status of a part.
* Performs AJAX queries and updates the display on the button.
*
* options:
* - button: ID of the button (default = '#part-star-icon')
* - URL: API url of the object
* - user: pk of the user
*/
function toggleStar(options) {
inventreeGet(options.url, {}, {
success: function(response) {
var starred = response.starred;
inventreePut(
options.url,
{
starred: !starred,
},
{
method: 'PATCH',
success: function(response) {
if (response.starred) {
$(options.button).removeClass('fa fa-bell-slash').addClass('fas fa-bell icon-green');
$(options.button).attr('title', '{% trans "You are subscribed to notifications for this item" %}');
showMessage('{% trans "You have subscribed to notifications for this item" %}', {
style: 'success',
});
} else {
$(options.button).removeClass('fas fa-bell icon-green').addClass('fa fa-bell-slash');
$(options.button).attr('title', '{% trans "Subscribe to notifications for this item" %}');
showMessage('{% trans "You have unsubscribed to notifications for this item" %}', {
style: 'warning',
});
}
}
}
);
}
});
}
function partStockLabel(part, options={}) {
if (part.in_stock) {
return `<span class='badge rounded-pill bg-success ${options.classes}'>{% trans "Stock" %}: ${part.in_stock}</span>`;
} else {
return `<span class='badge rounded-pill bg-danger ${options.classes}'>{% trans "No Stock" %}</span>`;
}
}
function makePartIcons(part) {
/* Render a set of icons for the given part.
*/
var html = '';
if (part.trackable) {
html += makeIconBadge('fa-directions', '{% trans "Trackable part" %}');
}
if (part.virtual) {
html += makeIconBadge('fa-ghost', '{% trans "Virtual part" %}');
}
if (part.is_template) {
html += makeIconBadge('fa-clone', '{% trans "Template part" %}');
}
if (part.assembly) {
html += makeIconBadge('fa-tools', '{% trans "Assembled part" %}');
}
if (part.starred) {
html += makeIconBadge('fa-bell icon-green', '{% trans "Subscribed part" %}');
}
if (part.salable) {
html += makeIconBadge('fa-dollar-sign', '{% trans "Salable part" %}');
}
if (!part.active) {
html += `<span class='badge badge-right rounded-pill bg-warning'>{% trans "Inactive" %}</span> `;
}
return html;
}
function loadPartVariantTable(table, partId, options={}) {
/* Load part variant table
*/
var params = options.params || {};
params.ancestor = partId;
// Load filters
var filters = loadTableFilters('variants');
for (var key in params) {
filters[key] = params[key];
}
setupFilterList('variants', $(table));
var cols = [
{
field: 'pk',
title: 'ID',
visible: false,
switchable: false,
},
{
field: 'name',
title: '{% trans "Name" %}',
switchable: false,
formatter: function(value, row) {
var html = '';
var name = '';
if (row.IPN) {
name += row.IPN;
name += ' | ';
}
name += value;
if (row.revision) {
name += ' | ';
name += row.revision;
}
if (row.is_template) {
name = '<i>' + name + '</i>';
}
html += imageHoverIcon(row.thumbnail);
html += renderLink(name, `/part/${row.pk}/`);
if (row.trackable) {
html += makeIconBadge('fa-directions', '{% trans "Trackable part" %}');
}
if (row.virtual) {
html += makeIconBadge('fa-ghost', '{% trans "Virtual part" %}');
}
if (row.is_template) {
html += makeIconBadge('fa-clone', '{% trans "Template part" %}');
}
if (row.assembly) {
html += makeIconBadge('fa-tools', '{% trans "Assembled part" %}');
}
if (!row.active) {
html += `<span class='badge badge-right rounded-pill bg-warning'>{% trans "Inactive" %}</span>`;
}
return html;
},
},
{
field: 'IPN',
title: '{% trans "IPN" %}',
},
{
field: 'revision',
title: '{% trans "Revision" %}',
},
{
field: 'description',
title: '{% trans "Description" %}',
},
{
field: 'in_stock',
title: '{% trans "Stock" %}',
formatter: function(value, row) {
return renderLink(value, `/part/${row.pk}/?display=part-stock`);
}
}
];
table.inventreeTable({
url: '{% url "api-part-list" %}',
name: 'partvariants',
showColumns: true,
original: params,
queryParams: filters,
formatNoMatches: function() {
return '{% trans "No variants found" %}';
},
columns: cols,
treeEnable: true,
rootParentId: partId,
parentIdField: 'variant_of',
idField: 'pk',
uniqueId: 'pk',
treeShowField: 'name',
sortable: true,
search: true,
onPostBody: function() {
table.treegrid({
treeColumn: 0,
});
table.treegrid('collapseAll');
}
});
}
function loadSimplePartTable(table, url, options={}) {
options.disableFilters = true;
loadPartTable(table, url, options);
}
function loadPartParameterTable(table, url, options) {
var params = options.params || {};
// Load filters
var filters = loadTableFilters('part-parameters');
for (var key in params) {
filters[key] = params[key];
}
// setupFilterList("#part-parameters", $(table));
$(table).inventreeTable({
url: url,
original: params,
queryParams: filters,
name: 'partparameters',
groupBy: false,
formatNoMatches: function() {
return '{% trans "No parameters found" %}';
},
columns: [
{
checkbox: true,
switchable: false,
visible: true,
},
{
field: 'name',
title: '{% trans "Name" %}',
switchable: false,
sortable: true,
formatter: function(value, row) {
return row.template_detail.name;
}
},
{
field: 'data',
title: '{% trans "Value" %}',
switchable: false,
sortable: true,
},
{
field: 'units',
title: '{% trans "Units" %}',
switchable: true,
sortable: true,
formatter: function(value, row) {
return row.template_detail.units;
}
},
{
field: 'actions',
title: '',
switchable: false,
sortable: false,
formatter: function(value, row) {
var pk = row.pk;
var html = `<div class='btn-group float-right' role='group'>`;
html += makeIconButton('fa-edit icon-blue', 'button-parameter-edit', pk, '{% trans "Edit parameter" %}');
html += makeIconButton('fa-trash-alt icon-red', 'button-parameter-delete', pk, '{% trans "Delete parameter" %}');
html += `</div>`;
return html;
}
}
],
onPostBody: function() {
// Setup button callbacks
$(table).find('.button-parameter-edit').click(function() {
var pk = $(this).attr('pk');
constructForm(`/api/part/parameter/${pk}/`, {
fields: {
data: {},
},
title: '{% trans "Edit Parameter" %}',
onSuccess: function() {
$(table).bootstrapTable('refresh');
}
});
});
$(table).find('.button-parameter-delete').click(function() {
var pk = $(this).attr('pk');
constructForm(`/api/part/parameter/${pk}/`, {
method: 'DELETE',
title: '{% trans "Delete Parameter" %}',
onSuccess: function() {
$(table).bootstrapTable('refresh');
}
});
});
}
});
}
function loadRelatedPartsTable(table, part_id, options={}) {
/*
* Load table of "related" parts
*/
options.params = options.params || {};
options.params.part = part_id;
var filters = {};
for (var key in options.params) {
filters[key] = options.params[key];
}
setupFilterList('related', $(table), options.filterTarget);
function getPart(row) {
if (row.part_1 == part_id) {
return row.part_2_detail;
} else {
return row.part_1_detail;
}
}
var columns = [
{
field: 'name',
title: '{% trans "Part" %}',
switchable: false,
formatter: function(value, row) {
var part = getPart(row);
var html = imageHoverIcon(part.thumbnail) + renderLink(part.full_name, `/part/${part.pk}/`);
html += makePartIcons(part);
return html;
}
},
{
field: 'description',
title: '{% trans "Description" %}',
formatter: function(value, row) {
return getPart(row).description;
}
},
{
field: 'actions',
title: '',
switchable: false,
formatter: function(value, row) {
var html = `<div class='btn-group float-right' role='group'>`;
html += makeIconButton('fa-trash-alt icon-red', 'button-related-delete', row.pk, '{% trans "Delete part relationship" %}');
html += '</div>';
return html;
}
}
];
$(table).inventreeTable({
url: '{% url "api-part-related-list" %}',
groupBy: false,
name: 'related',
original: options.params,
queryParams: filters,
columns: columns,
showColumns: false,
search: true,
onPostBody: function() {
$(table).find('.button-related-delete').click(function() {
var pk = $(this).attr('pk');
constructForm(`/api/part/related/${pk}/`, {
method: 'DELETE',
title: '{% trans "Delete Part Relationship" %}',
onSuccess: function() {
$(table).bootstrapTable('refresh');
}
});
});
},
});
}
function loadParametricPartTable(table, options={}) {
/* Load parametric table for part parameters
*
* Args:
* - table: HTML reference to the table
* - table_headers: Unique parameters found in category
* - table_data: Parameters data
*/
var table_headers = options.headers;
var table_data = options.data;
var columns = [];
for (var header of table_headers) {
if (header === 'part') {
columns.push({
field: header,
title: '{% trans "Part" %}',
sortable: true,
sortName: 'name',
formatter: function(value, row) {
var name = '';
if (row.IPN) {
name += row.IPN + ' | ' + row.name;
} else {
name += row.name;
}
return renderLink(name, '/part/' + row.pk + '/');
}
});
} else if (header === 'description') {
columns.push({
field: header,
title: '{% trans "Description" %}',
sortable: true,
});
} else {
columns.push({
field: header,
title: header,
sortable: true,
filterControl: 'input',
});
}
}
$(table).inventreeTable({
sortName: 'part',
queryParams: table_headers,
groupBy: false,
name: options.name || 'parametric',
formatNoMatches: function() {
return '{% trans "No parts found" %}';
},
columns: columns,
showColumns: true,
data: table_data,
filterControl: true,
});
}
function partGridTile(part) {
// Generate a "grid tile" view for a particular part
// Rows for table view
var rows = '';
var stock = `${part.in_stock}`;
if (!part.in_stock) {
stock = `<span class='badge rounded-pill bg-danger'>{% trans "No Stock" %}</span>`;
}
rows += `<tr><td><b>{% trans "Stock" %}</b></td><td>${stock}</td></tr>`;
if (part.on_order) {
rows += `<tr><td><b>{$ trans "On Order" %}</b></td><td>${part.on_order}</td></tr>`;
}
if (part.building) {
rows += `<tr><td><b>{% trans "Building" %}</b></td><td>${part.building}</td></tr>`;
}
var html = `
<div class='card product-card borderless'>
<div class='panel product-card-panel'>
<div class='panel-heading'>
<a href='/part/${part.pk}/'>
<b>${part.full_name}</b>
</a>
${makePartIcons(part)}
<br>
<i>${part.description}</i>
</div>
<div class='panel-content'>
<div class='row'>
<div class='col-sm-6'>
<img src='${part.thumbnail}' class='card-thumb' onclick='showModalImage("${part.image}")'>
</div>
<div class='col-sm-6'>
<table class='table table-striped table-condensed'>
${rows}
</table>
</div>
</div>
</div>
</div>
</div>
`;
return html;
}
function loadPartTable(table, url, options={}) {
/* Load part listing data into specified table.
*
* Args:
* - table: HTML reference to the table
* - url: Base URL for API query
* - options: object containing following (optional) fields
* checkbox: Show the checkbox column
* query: extra query params for API request
* buttons: If provided, link buttons to selection status of this table
* disableFilters: If true, disable custom filters
* actions: Provide a callback function to construct an "actions" column
*/
// Ensure category detail is included
options.params['category_detail'] = true;
var params = options.params || {};
var filters = {};
var col = null;
if (!options.disableFilters) {
filters = loadTableFilters('parts');
}
for (var key in params) {
filters[key] = params[key];
}
setupFilterList('parts', $(table), options.filterTarget || null);
var columns = [
{
field: 'pk',
title: 'ID',
visible: false,
switchable: false,
searchable: false,
}
];
if (options.checkbox) {
columns.push({
checkbox: true,
title: '{% trans "Select" %}',
searchable: false,
switchable: false,
});
}
col = {
field: 'IPN',
title: '{% trans "IPN" %}',
};
if (!options.params.ordering) {
col['sortable'] = true;
}
columns.push(col);
col = {
field: 'name',
title: '{% trans "Part" %}',
switchable: false,
formatter: function(value, row) {
var name = row.full_name;
var display = imageHoverIcon(row.thumbnail) + renderLink(name, `/part/${row.pk}/`);
display += makePartIcons(row);
return display;
}
};
if (!options.params.ordering) {
col['sortable'] = true;
}
columns.push(col);
columns.push({
field: 'description',
title: '{% trans "Description" %}',
formatter: function(value, row) {
if (row.is_template) {
value = `<i>${value}</i>`;
}
return value;
}
});
col = {
sortName: 'category',
field: 'category_detail',
title: '{% trans "Category" %}',
formatter: function(value, row) {
if (row.category) {
return renderLink(value.pathstring, `/part/category/${row.category}/`);
} else {
return '{% trans "No category" %}';
}
}
};
if (!options.params.ordering) {
col['sortable'] = true;
}
columns.push(col);
col = {
field: 'in_stock',
title: '{% trans "Stock" %}',
searchable: false,
formatter: function(value, row) {
var link = '?display=part-stock';
if (value) {
// There IS stock available for this part
// Is stock "low" (below the 'minimum_stock' quantity)?
if (row.minimum_stock && row.minimum_stock > value) {
value += `<span class='badge badge-right rounded-pill bg-warning'>{% trans "Low stock" %}</span>`;
}
} else if (row.on_order) {
// There is no stock available, but stock is on order
value = `0<span class='badge badge-right rounded-pill bg-info'>{% trans "On Order" %}: ${row.on_order}</span>`;
link = '?display=purchase-orders';
} else if (row.building) {
// There is no stock available, but stock is being built
value = `0<span class='badge badge-right rounded-pill bg-info'>{% trans "Building" %}: ${row.building}</span>`;
link = '?display=build-orders';
} else {
// There is no stock available
value = `0<span class='badge badge-right rounded-pill bg-danger'>{% trans "No Stock" %}</span>`;
}
return renderLink(value, `/part/${row.pk}/${link}`);
}
};
if (!options.params.ordering) {
col['sortable'] = true;
}
columns.push(col);
columns.push({
field: 'link',
title: '{% trans "Link" %}',
formatter: function(value) {
return renderLink(
value, value,
{
max_length: 32,
remove_http: true,
}
);
}
});
// Push an "actions" column
if (options.actions) {
columns.push({
field: 'actions',
title: '',
switchable: false,
visible: true,
searchable: false,
sortable: false,
formatter: function(value, row) {
return options.actions(value, row);
}
});
}
var grid_view = options.gridView && inventreeLoad('part-grid-view') == 1;
$(table).inventreeTable({
url: url,
method: 'get',
queryParams: filters,
groupBy: false,
name: options.name || 'part',
original: params,
sidePagination: 'server',
pagination: 'true',
formatNoMatches: function() {
return '{% trans "No parts found" %}';
},
columns: columns,
showColumns: true,
showCustomView: grid_view,
showCustomViewButton: false,
onPostBody: function() {
grid_view = inventreeLoad('part-grid-view') == 1;
if (grid_view) {
$('#view-part-list').removeClass('btn-secondary').addClass('btn-outline-secondary');
$('#view-part-grid').removeClass('btn-outline-secondary').addClass('btn-secondary');
} else {
$('#view-part-grid').removeClass('btn-secondary').addClass('btn-outline-secondary');
$('#view-part-list').removeClass('btn-outline-secondary').addClass('btn-secondary');
}
if (options.onPostBody) {
options.onPostBody();
}
},
buttons: options.gridView ? [
{
icon: 'fas fa-bars',
attributes: {
title: '{% trans "Display as list" %}',
id: 'view-part-list',
},
event: () => {
inventreeSave('part-grid-view', 0);
$(table).bootstrapTable(
'refreshOptions',
{
showCustomView: false,
}
);
}
},
{
icon: 'fas fa-th',
attributes: {
title: '{% trans "Display as grid" %}',
id: 'view-part-grid',
},
event: () => {
inventreeSave('part-grid-view', 1);
$(table).bootstrapTable(
'refreshOptions',
{
showCustomView: true,
}
);
}
}
] : [],
customView: function(data) {
var html = '';
html = `<div class='row full-height'>`;
data.forEach(function(row, index) {
// Force a new row every 5 columns
if ((index > 0) && (index % 5 == 0) && (index < data.length)) {
html += `</div><div class='row full-height'>`;
}
html += partGridTile(row);
});
html += `</div>`;
return html;
}
});
if (options.buttons) {
linkButtonsToSelection($(table), options.buttons);
}
/* Button callbacks for part table buttons */
$('#multi-part-order').click(function() {
var selections = $(table).bootstrapTable('getSelections');
var parts = [];
selections.forEach(function(item) {
parts.push(item.pk);
});
launchModalForm('/order/purchase-order/order-parts/', {
data: {
parts: parts,
},
});
});
$('#multi-part-category').click(function() {
var selections = $(table).bootstrapTable('getSelections');
var parts = [];
selections.forEach(function(item) {
parts.push(item.pk);
});
launchModalForm('/part/set-category/', {
data: {
parts: parts,
},
reload: true,
});
});
$('#multi-part-print-label').click(function() {
var selections = $(table).bootstrapTable('getSelections');
var items = [];
selections.forEach(function(item) {
items.push(item.pk);
});
printPartLabels(items);
});
$('#multi-part-export').click(function() {
var selections = $(table).bootstrapTable('getSelections');
var parts = '';
selections.forEach(function(item) {
parts += item.pk;
parts += ',';
});
location.href = '/part/export/?parts=' + parts;
});
}
/*
* Display a table of part categories
*/
function loadPartCategoryTable(table, options) {
var params = options.params || {};
var filterListElement = options.filterList || '#filter-list-category';
var filters = {};
var filterKey = options.filterKey || options.name || 'category';
if (!options.disableFilters) {
filters = loadTableFilters(filterKey);
}
var tree_view = options.allowTreeView && inventreeLoad('category-tree-view') == 1;
if (tree_view) {
params.cascade = true;
}
var original = {};
for (var key in params) {
original[key] = params[key];
filters[key] = params[key];
}
setupFilterList(filterKey, table, filterListElement);
table.inventreeTable({
treeEnable: tree_view,
rootParentId: tree_view ? options.params.parent : null,
uniqueId: 'pk',
idField: 'pk',
treeShowField: 'name',
parentIdField: tree_view ? 'parent' : null,
method: 'get',
url: options.url || '{% url "api-part-category-list" %}',
queryParams: filters,
disablePagination: tree_view,
sidePagination: tree_view ? 'client' : 'server',
serverSort: !tree_view,
search: !tree_view,
name: 'category',
original: original,
showColumns: true,
buttons: options.allowTreeView ? [
{
icon: 'fas fa-bars',
attributes: {
title: '{% trans "Display as list" %}',
id: 'view-category-list',
},
event: () => {
inventreeSave('category-tree-view', 0);
table.bootstrapTable(
'refreshOptions',
{
treeEnable: false,
serverSort: true,
search: true,
pagination: true,
}
);
}
},
{
icon: 'fas fa-sitemap',
attributes: {
title: '{% trans "Display as tree" %}',
id: 'view-category-tree',
},
event: () => {
inventreeSave('category-tree-view', 1);
table.bootstrapTable(
'refreshOptions',
{
treeEnable: true,
serverSort: false,
search: false,
pagination: false,
}
);
}
}
] : [],
onPostBody: function() {
if (options.allowTreeView) {
tree_view = inventreeLoad('category-tree-view') == 1;
if (tree_view) {
$('#view-category-list').removeClass('btn-secondary').addClass('btn-outline-secondary');
$('#view-category-tree').removeClass('btn-outline-secondary').addClass('btn-secondary');
table.treegrid({
treeColumn: 0,
onChange: function() {
table.bootstrapTable('resetView');
},
onExpand: function() {
}
});
} else {
$('#view-category-tree').removeClass('btn-secondary').addClass('btn-outline-secondary');
$('#view-category-list').removeClass('btn-outline-secondary').addClass('btn-secondary');
}
}
},
columns: [
{
checkbox: true,
title: '{% trans "Select" %}',
searchable: false,
switchable: false,
visible: false,
},
{
field: 'name',
title: '{% trans "Name" %}',
switchable: true,
sortable: true,
formatter: function(value, row) {
var html = renderLink(
value,
`/part/category/${row.pk}/`
);
if (row.starred) {
html += makeIconBadge('fa-bell icon-green', '{% trans "Subscribed category" %}');
}
return html;
}
},
{
field: 'description',
title: '{% trans "Description" %}',
switchable: true,
sortable: false,
},
{
field: 'pathstring',
title: '{% trans "Path" %}',
switchable: !tree_view,
visible: !tree_view,
sortable: false,
},
{
field: 'parts',
title: '{% trans "Parts" %}',
switchable: true,
sortable: false,
}
]
});
}
function loadPartTestTemplateTable(table, options) {
/*
* Load PartTestTemplate table.
*/
var params = options.params || {};
var part = options.part || null;
var filterListElement = options.filterList || '#filter-list-parttests';
var filters = loadTableFilters('parttests');
var original = {};
for (var k in params) {
original[k] = params[k];
}
setupFilterList('parttests', table, filterListElement);
// Override the default values, or add new ones
for (var key in params) {
filters[key] = params[key];
}
table.inventreeTable({
method: 'get',
formatNoMatches: function() {
return '{% trans "No test templates matching query" %}';
},
url: '{% url "api-part-test-template-list" %}',
queryParams: filters,
name: 'testtemplate',
original: original,
columns: [
{
field: 'pk',
title: 'ID',
visible: false,
},
{
field: 'test_name',
title: '{% trans "Test Name" %}',
sortable: true,
},
{
field: 'description',
title: '{% trans "Description" %}',
},
{
field: 'required',
title: '{% trans "Required" %}',
sortable: true,
formatter: function(value) {
return yesNoLabel(value);
}
},
{
field: 'requires_value',
title: '{% trans "Requires Value" %}',
formatter: function(value) {
return yesNoLabel(value);
}
},
{
field: 'requires_attachment',
title: '{% trans "Requires Attachment" %}',
formatter: function(value) {
return yesNoLabel(value);
}
},
{
field: 'buttons',
formatter: function(value, row) {
var pk = row.pk;
if (row.part == part) {
var html = `<div class='btn-group float-right' role='group'>`;
html += makeIconButton('fa-edit icon-blue', 'button-test-edit', pk, '{% trans "Edit test result" %}');
html += makeIconButton('fa-trash-alt icon-red', 'button-test-delete', pk, '{% trans "Delete test result" %}');
html += `</div>`;
return html;
} else {
var text = '{% trans "This test is defined for a parent part" %}';
return renderLink(text, `/part/${row.part}/tests/`);
}
}
}
],
onPostBody: function() {
table.find('.button-test-edit').click(function() {
var pk = $(this).attr('pk');
var url = `/api/part/test-template/${pk}/`;
constructForm(url, {
fields: {
test_name: {},
description: {},
required: {},
requires_value: {},
requires_attachment: {},
},
title: '{% trans "Edit Test Result Template" %}',
onSuccess: function() {
table.bootstrapTable('refresh');
},
});
});
table.find('.button-test-delete').click(function() {
var pk = $(this).attr('pk');
var url = `/api/part/test-template/${pk}/`;
constructForm(url, {
method: 'DELETE',
title: '{% trans "Delete Test Result Template" %}',
onSuccess: function() {
table.bootstrapTable('refresh');
},
});
});
}
});
}
function loadPriceBreakTable(table, options) {
/*
* Load PriceBreak table.
*/
var name = options.name || 'pricebreak';
var human_name = options.human_name || 'price break';
var linkedGraph = options.linkedGraph || null;
var chart = null;
table.inventreeTable({
name: name,
method: 'get',
formatNoMatches: function() {
return `{% trans "No ${human_name} information found" %}`;
},
queryParams: {part: options.part},
url: options.url,
onLoadSuccess: function(tableData) {
if (linkedGraph) {
// sort array
tableData = tableData.sort((a, b) => (a.quantity - b.quantity));
// split up for graph definition
var graphLabels = Array.from(tableData, (x) => (x.quantity));
var graphData = Array.from(tableData, (x) => (x.price));
// destroy chart if exists
if (chart) {
chart.destroy();
}
chart = loadLineChart(linkedGraph,
{
labels: graphLabels,
datasets: [
{
label: '{% trans "Unit Price" %}',
data: graphData,
backgroundColor: 'rgba(255, 206, 86, 0.2)',
borderColor: 'rgb(255, 206, 86)',
stepped: true,
fill: true,
},
],
}
);
}
},
columns: [
{
field: 'pk',
title: 'ID',
visible: false,
switchable: false,
},
{
field: 'quantity',
title: '{% trans "Quantity" %}',
sortable: true,
},
{
field: 'price',
title: '{% trans "Price" %}',
sortable: true,
formatter: function(value, row) {
var html = value;
html += `<div class='btn-group float-right' role='group'>`;
html += makeIconButton('fa-edit icon-blue', `button-${name}-edit`, row.pk, `{% trans "Edit ${human_name}" %}`);
html += makeIconButton('fa-trash-alt icon-red', `button-${name}-delete`, row.pk, `{% trans "Delete ${human_name}" %}`);
html += `</div>`;
return html;
}
},
]
});
}
function loadLineChart(context, data) {
return new Chart(context, {
type: 'line',
data: data,
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {position: 'bottom'},
}
}
});
}
function initPriceBreakSet(table, options) {
var part_id = options.part_id;
var pb_human_name = options.pb_human_name;
var pb_url_slug = options.pb_url_slug;
var pb_url = options.pb_url;
var pb_new_btn = options.pb_new_btn;
var pb_new_url = options.pb_new_url;
var linkedGraph = options.linkedGraph || null;
loadPriceBreakTable(
table,
{
name: pb_url_slug,
human_name: pb_human_name,
url: pb_url,
linkedGraph: linkedGraph,
part: part_id,
}
);
function reloadPriceBreakTable() {
table.bootstrapTable('refresh');
}
pb_new_btn.click(function() {
launchModalForm(pb_new_url,
{
success: reloadPriceBreakTable,
data: {
part: part_id,
}
}
);
});
table.on('click', `.button-${pb_url_slug}-delete`, function() {
var pk = $(this).attr('pk');
launchModalForm(
`/part/${pb_url_slug}/${pk}/delete/`,
{
success: reloadPriceBreakTable
}
);
});
table.on('click', `.button-${pb_url_slug}-edit`, function() {
var pk = $(this).attr('pk');
launchModalForm(
`/part/${pb_url_slug}/${pk}/edit/`,
{
success: reloadPriceBreakTable
}
);
});
}
function loadStockPricingChart(context, data) {
return new Chart(context, {
type: 'bar',
data: data,
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {legend: {position: 'bottom'}},
scales: {
y: {
type: 'linear',
position: 'left',
grid: {display: false},
title: {
display: true,
text: '{% trans "Single Price" %}'
}
},
y1: {
type: 'linear',
position: 'right',
grid: {display: false},
titel: {
display: true,
text: '{% trans "Quantity" %}',
position: 'right'
}
},
y2: {
type: 'linear',
position: 'left',
grid: {display: false},
title: {
display: true,
text: '{% trans "Single Price Difference" %}'
}
}
},
}
});
}
function loadBomChart(context, data) {
return new Chart(context, {
type: 'doughnut',
data: data,
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
position: 'bottom',
},
scales: {
xAxes: [
{
beginAtZero: true,
ticks: {
autoSkip: false,
}
}
]
}
}
}
});
}
function loadSellPricingChart(context, data) {
return new Chart(context, {
type: 'line',
data: data,
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
position: 'bottom'
}
},
scales: {
y: {
type: 'linear',
position: 'left',
grid: {
display: false
},
title: {
display: true,
text: '{% trans "Unit Price" %}',
}
},
y1: {
type: 'linear',
position: 'right',
grid: {
display: false
},
titel: {
display: true,
text: '{% trans "Quantity" %}',
position: 'right'
}
},
},
}
});
}
| InvenTree/templates/js/translated/part.js | {% load i18n %}
{% load inventree_extras %}
/* globals
Chart,
constructForm,
global_settings,
imageHoverIcon,
inventreeGet,
inventreePut,
launchModalForm,
linkButtonsToSelection,
loadTableFilters,
makeIconBadge,
makeIconButton,
printPartLabels,
renderLink,
setFormGroupVisibility,
setupFilterList,
yesNoLabel,
*/
/* exported
duplicatePart,
editCategory,
editPart,
initPriceBreakSet,
loadBomChart,
loadParametricPartTable,
loadPartCategoryTable,
loadPartParameterTable,
loadPartTable,
loadPartTestTemplateTable,
loadPartVariantTable,
loadSellPricingChart,
loadSimplePartTable,
loadStockPricingChart,
partStockLabel,
toggleStar,
*/
/* Part API functions
* Requires api.js to be loaded first
*/
function partGroups() {
return {
attributes: {
title: '{% trans "Part Attributes" %}',
collapsible: true,
},
create: {
title: '{% trans "Part Creation Options" %}',
collapsible: true,
},
duplicate: {
title: '{% trans "Part Duplication Options" %}',
collapsible: true,
},
supplier: {
title: '{% trans "Supplier Options" %}',
collapsible: true,
hidden: !global_settings.PART_PURCHASEABLE,
}
};
}
// Construct fieldset for part forms
function partFields(options={}) {
var fields = {
category: {
secondary: {
title: '{% trans "Add Part Category" %}',
fields: function() {
var fields = categoryFields();
return fields;
}
}
},
name: {},
IPN: {},
revision: {},
description: {},
variant_of: {},
keywords: {
icon: 'fa-key',
},
units: {},
link: {
icon: 'fa-link',
},
default_location: {
},
default_supplier: {
filters: {
part_detail: true,
supplier_detail: true,
}
},
default_expiry: {
icon: 'fa-calendar-alt',
},
minimum_stock: {
icon: 'fa-boxes',
},
component: {
default: global_settings.PART_COMPONENT,
group: 'attributes',
},
assembly: {
default: global_settings.PART_ASSEMBLY,
group: 'attributes',
},
is_template: {
default: global_settings.PART_TEMPLATE,
group: 'attributes',
},
trackable: {
default: global_settings.PART_TRACKABLE,
group: 'attributes',
},
purchaseable: {
default: global_settings.PART_PURCHASEABLE,
group: 'attributes',
onEdit: function(value, name, field, options) {
setFormGroupVisibility('supplier', value, options);
}
},
salable: {
default: global_settings.PART_SALABLE,
group: 'attributes',
},
virtual: {
default: global_settings.PART_VIRTUAL,
group: 'attributes',
},
};
// If editing a part, we can set the "active" status
if (options.edit) {
fields.active = {
group: 'attributes'
};
}
// Pop expiry field
if (!global_settings.STOCK_ENABLE_EXPIRY) {
delete fields['default_expiry'];
}
// Additional fields when "creating" a new part
if (options.create) {
// No supplier parts available yet
delete fields['default_supplier'];
if (global_settings.PART_CREATE_INITIAL) {
fields.initial_stock = {
type: 'boolean',
label: '{% trans "Create Initial Stock" %}',
help_text: '{% trans "Create an initial stock item for this part" %}',
group: 'create',
};
fields.initial_stock_quantity = {
type: 'decimal',
value: 1,
label: '{% trans "Initial Stock Quantity" %}',
help_text: '{% trans "Specify initial stock quantity for this part" %}',
group: 'create',
};
// TODO - Allow initial location of stock to be specified
fields.initial_stock_location = {
label: '{% trans "Location" %}',
help_text: '{% trans "Select destination stock location" %}',
type: 'related field',
required: true,
api_url: `/api/stock/location/`,
model: 'stocklocation',
group: 'create',
};
}
fields.copy_category_parameters = {
type: 'boolean',
label: '{% trans "Copy Category Parameters" %}',
help_text: '{% trans "Copy parameter templates from selected part category" %}',
value: global_settings.PART_CATEGORY_PARAMETERS,
group: 'create',
};
// Supplier options
fields.add_supplier_info = {
type: 'boolean',
label: '{% trans "Add Supplier Data" %}',
help_text: '{% trans "Create initial supplier data for this part" %}',
group: 'supplier',
};
fields.supplier = {
type: 'related field',
model: 'company',
label: '{% trans "Supplier" %}',
help_text: '{% trans "Select supplier" %}',
filters: {
'is_supplier': true,
},
api_url: '{% url "api-company-list" %}',
group: 'supplier',
};
fields.SKU = {
type: 'string',
label: '{% trans "SKU" %}',
help_text: '{% trans "Supplier stock keeping unit" %}',
group: 'supplier',
};
fields.manufacturer = {
type: 'related field',
model: 'company',
label: '{% trans "Manufacturer" %}',
help_text: '{% trans "Select manufacturer" %}',
filters: {
'is_manufacturer': true,
},
api_url: '{% url "api-company-list" %}',
group: 'supplier',
};
fields.MPN = {
type: 'string',
label: '{% trans "MPN" %}',
help_text: '{% trans "Manufacturer Part Number" %}',
group: 'supplier',
};
}
// Additional fields when "duplicating" a part
if (options.duplicate) {
fields.copy_from = {
type: 'integer',
hidden: true,
value: options.duplicate,
group: 'duplicate',
},
fields.copy_image = {
type: 'boolean',
label: '{% trans "Copy Image" %}',
help_text: '{% trans "Copy image from original part" %}',
value: true,
group: 'duplicate',
},
fields.copy_bom = {
type: 'boolean',
label: '{% trans "Copy BOM" %}',
help_text: '{% trans "Copy bill of materials from original part" %}',
value: global_settings.PART_COPY_BOM,
group: 'duplicate',
};
fields.copy_parameters = {
type: 'boolean',
label: '{% trans "Copy Parameters" %}',
help_text: '{% trans "Copy parameter data from original part" %}',
value: global_settings.PART_COPY_PARAMETERS,
group: 'duplicate',
};
}
return fields;
}
function categoryFields() {
return {
parent: {
help_text: '{% trans "Parent part category" %}',
},
name: {},
description: {},
default_location: {},
default_keywords: {
icon: 'fa-key',
}
};
}
// Edit a PartCategory via the API
function editCategory(pk) {
var url = `/api/part/category/${pk}/`;
var fields = categoryFields();
constructForm(url, {
fields: fields,
title: '{% trans "Edit Part Category" %}',
reload: true,
});
}
function editPart(pk) {
var url = `/api/part/${pk}/`;
var fields = partFields({
edit: true
});
// Filter supplied parts by the Part ID
fields.default_supplier.filters.part = pk;
var groups = partGroups({});
constructForm(url, {
fields: fields,
groups: groups,
title: '{% trans "Edit Part" %}',
reload: true,
successMessage: '{% trans "Part edited" %}',
});
}
// Launch form to duplicate a part
function duplicatePart(pk, options={}) {
// First we need all the part information
inventreeGet(`/api/part/${pk}/`, {}, {
success: function(data) {
var fields = partFields({
duplicate: pk,
});
// Remove "default_supplier" field
delete fields['default_supplier'];
// If we are making a "variant" part
if (options.variant) {
// Override the "variant_of" field
data.variant_of = pk;
}
constructForm('{% url "api-part-list" %}', {
method: 'POST',
fields: fields,
groups: partGroups(),
title: '{% trans "Duplicate Part" %}',
data: data,
onSuccess: function(data) {
// Follow the new part
location.href = `/part/${data.pk}/`;
}
});
}
});
}
/* Toggle the 'starred' status of a part.
* Performs AJAX queries and updates the display on the button.
*
* options:
* - button: ID of the button (default = '#part-star-icon')
* - URL: API url of the object
* - user: pk of the user
*/
function toggleStar(options) {
inventreeGet(options.url, {}, {
success: function(response) {
var starred = response.starred;
inventreePut(
options.url,
{
starred: !starred,
},
{
method: 'PATCH',
success: function(response) {
if (response.starred) {
$(options.button).removeClass('fa fa-bell-slash').addClass('fas fa-bell icon-green');
$(options.button).attr('title', '{% trans "You are subscribed to notifications for this item" %}');
showMessage('{% trans "You have subscribed to notifications for this item" %}', {
style: 'success',
});
} else {
$(options.button).removeClass('fas fa-bell icon-green').addClass('fa fa-bell-slash');
$(options.button).attr('title', '{% trans "Subscribe to notifications for this item" %}');
showMessage('{% trans "You have unsubscribed to notifications for this item" %}', {
style: 'warning',
});
}
}
}
);
}
});
}
function partStockLabel(part, options={}) {
if (part.in_stock) {
return `<span class='badge rounded-pill bg-success ${options.classes}'>{% trans "Stock" %}: ${part.in_stock}</span>`;
} else {
return `<span class='badge rounded-pill bg-danger ${options.classes}'>{% trans "No Stock" %}</span>`;
}
}
function makePartIcons(part) {
/* Render a set of icons for the given part.
*/
var html = '';
if (part.trackable) {
html += makeIconBadge('fa-directions', '{% trans "Trackable part" %}');
}
if (part.virtual) {
html += makeIconBadge('fa-ghost', '{% trans "Virtual part" %}');
}
if (part.is_template) {
html += makeIconBadge('fa-clone', '{% trans "Template part" %}');
}
if (part.assembly) {
html += makeIconBadge('fa-tools', '{% trans "Assembled part" %}');
}
if (part.starred) {
html += makeIconBadge('fa-bell icon-green', '{% trans "Subscribed part" %}');
}
if (part.salable) {
html += makeIconBadge('fa-dollar-sign', '{% trans "Salable part" %}');
}
if (!part.active) {
html += `<span class='badge badge-right rounded-pill bg-warning'>{% trans "Inactive" %}</span> `;
}
return html;
}
function loadPartVariantTable(table, partId, options={}) {
/* Load part variant table
*/
var params = options.params || {};
params.ancestor = partId;
// Load filters
var filters = loadTableFilters('variants');
for (var key in params) {
filters[key] = params[key];
}
setupFilterList('variants', $(table));
var cols = [
{
field: 'pk',
title: 'ID',
visible: false,
switchable: false,
},
{
field: 'name',
title: '{% trans "Name" %}',
switchable: false,
formatter: function(value, row) {
var html = '';
var name = '';
if (row.IPN) {
name += row.IPN;
name += ' | ';
}
name += value;
if (row.revision) {
name += ' | ';
name += row.revision;
}
if (row.is_template) {
name = '<i>' + name + '</i>';
}
html += imageHoverIcon(row.thumbnail);
html += renderLink(name, `/part/${row.pk}/`);
if (row.trackable) {
html += makeIconBadge('fa-directions', '{% trans "Trackable part" %}');
}
if (row.virtual) {
html += makeIconBadge('fa-ghost', '{% trans "Virtual part" %}');
}
if (row.is_template) {
html += makeIconBadge('fa-clone', '{% trans "Template part" %}');
}
if (row.assembly) {
html += makeIconBadge('fa-tools', '{% trans "Assembled part" %}');
}
if (!row.active) {
html += `<span class='badge badge-right rounded-pill bg-warning'>{% trans "Inactive" %}</span>`;
}
return html;
},
},
{
field: 'IPN',
title: '{% trans "IPN" %}',
},
{
field: 'revision',
title: '{% trans "Revision" %}',
},
{
field: 'description',
title: '{% trans "Description" %}',
},
{
field: 'in_stock',
title: '{% trans "Stock" %}',
formatter: function(value, row) {
return renderLink(value, `/part/${row.pk}/?display=part-stock`);
}
}
];
table.inventreeTable({
url: '{% url "api-part-list" %}',
name: 'partvariants',
showColumns: true,
original: params,
queryParams: filters,
formatNoMatches: function() {
return '{% trans "No variants found" %}';
},
columns: cols,
treeEnable: true,
rootParentId: partId,
parentIdField: 'variant_of',
idField: 'pk',
uniqueId: 'pk',
treeShowField: 'name',
sortable: true,
search: true,
onPostBody: function() {
table.treegrid({
treeColumn: 0,
});
table.treegrid('collapseAll');
}
});
}
function loadSimplePartTable(table, url, options={}) {
options.disableFilters = true;
loadPartTable(table, url, options);
}
function loadPartParameterTable(table, url, options) {
var params = options.params || {};
// Load filters
var filters = loadTableFilters('part-parameters');
for (var key in params) {
filters[key] = params[key];
}
// setupFilterList("#part-parameters", $(table));
$(table).inventreeTable({
url: url,
original: params,
queryParams: filters,
name: 'partparameters',
groupBy: false,
formatNoMatches: function() {
return '{% trans "No parameters found" %}';
},
columns: [
{
checkbox: true,
switchable: false,
visible: true,
},
{
field: 'name',
title: '{% trans "Name" %}',
switchable: false,
sortable: true,
formatter: function(value, row) {
return row.template_detail.name;
}
},
{
field: 'data',
title: '{% trans "Value" %}',
switchable: false,
sortable: true,
},
{
field: 'units',
title: '{% trans "Units" %}',
switchable: true,
sortable: true,
formatter: function(value, row) {
return row.template_detail.units;
}
},
{
field: 'actions',
title: '',
switchable: false,
sortable: false,
formatter: function(value, row) {
var pk = row.pk;
var html = `<div class='btn-group float-right' role='group'>`;
html += makeIconButton('fa-edit icon-blue', 'button-parameter-edit', pk, '{% trans "Edit parameter" %}');
html += makeIconButton('fa-trash-alt icon-red', 'button-parameter-delete', pk, '{% trans "Delete parameter" %}');
html += `</div>`;
return html;
}
}
],
onPostBody: function() {
// Setup button callbacks
$(table).find('.button-parameter-edit').click(function() {
var pk = $(this).attr('pk');
constructForm(`/api/part/parameter/${pk}/`, {
fields: {
data: {},
},
title: '{% trans "Edit Parameter" %}',
onSuccess: function() {
$(table).bootstrapTable('refresh');
}
});
});
$(table).find('.button-parameter-delete').click(function() {
var pk = $(this).attr('pk');
constructForm(`/api/part/parameter/${pk}/`, {
method: 'DELETE',
title: '{% trans "Delete Parameter" %}',
onSuccess: function() {
$(table).bootstrapTable('refresh');
}
});
});
}
});
}
function loadRelatedPartsTable(table, part_id, options={}) {
/*
* Load table of "related" parts
*/
options.params = options.params || {};
options.params.part = part_id;
var filters = {};
for (var key in options.params) {
filters[key] = options.params[key];
}
setupFilterList('related', $(table), options.filterTarget);
function getPart(row) {
if (row.part_1 == part_id) {
return row.part_2_detail;
} else {
return row.part_1_detail;
}
}
var columns = [
{
field: 'name',
title: '{% trans "Part" %}',
switchable: false,
formatter: function(value, row) {
var part = getPart(row);
var html = imageHoverIcon(part.thumbnail) + renderLink(part.full_name, `/part/${part.pk}/`)
html += makePartIcons(part);
return html;
}
},
{
field: 'description',
title: '{% trans "Description" %}',
formatter: function(value, row) {
return getPart(row).description;
}
},
{
field: 'actions',
title: '',
switchable: false,
formatter: function(value, row) {
var html = `<div class='btn-group float-right' role='group'>`;
html += makeIconButton('fa-trash-alt icon-red', 'button-related-delete', row.pk, '{% trans "Delete part relationship" %}');
html += '</div>';
return html;
}
}
];
$(table).inventreeTable({
url: '{% url "api-part-related-list" %}',
groupBy: false,
name: 'related',
original: options.params,
queryParams: filters,
columns: columns,
showColumns: false,
search: true,
onPostBody: function() {
$(table).find('.button-related-delete').click(function() {
var pk = $(this).attr('pk');
constructForm(`/api/part/related/${pk}/`, {
method: 'DELETE',
title: '{% trans "Delete Part Relationship" %}',
onSuccess: function() {
$(table).bootstrapTable('refresh');
}
});
});
},
});
}
function loadParametricPartTable(table, options={}) {
/* Load parametric table for part parameters
*
* Args:
* - table: HTML reference to the table
* - table_headers: Unique parameters found in category
* - table_data: Parameters data
*/
var table_headers = options.headers;
var table_data = options.data;
var columns = [];
for (var header of table_headers) {
if (header === 'part') {
columns.push({
field: header,
title: '{% trans "Part" %}',
sortable: true,
sortName: 'name',
formatter: function(value, row) {
var name = '';
if (row.IPN) {
name += row.IPN + ' | ' + row.name;
} else {
name += row.name;
}
return renderLink(name, '/part/' + row.pk + '/');
}
});
} else if (header === 'description') {
columns.push({
field: header,
title: '{% trans "Description" %}',
sortable: true,
});
} else {
columns.push({
field: header,
title: header,
sortable: true,
filterControl: 'input',
});
}
}
$(table).inventreeTable({
sortName: 'part',
queryParams: table_headers,
groupBy: false,
name: options.name || 'parametric',
formatNoMatches: function() {
return '{% trans "No parts found" %}';
},
columns: columns,
showColumns: true,
data: table_data,
filterControl: true,
});
}
function partGridTile(part) {
// Generate a "grid tile" view for a particular part
// Rows for table view
var rows = '';
var stock = `${part.in_stock}`;
if (!part.in_stock) {
stock = `<span class='badge rounded-pill bg-danger'>{% trans "No Stock" %}</span>`;
}
rows += `<tr><td><b>{% trans "Stock" %}</b></td><td>${stock}</td></tr>`;
if (part.on_order) {
rows += `<tr><td><b>{$ trans "On Order" %}</b></td><td>${part.on_order}</td></tr>`;
}
if (part.building) {
rows += `<tr><td><b>{% trans "Building" %}</b></td><td>${part.building}</td></tr>`;
}
var html = `
<div class='card product-card borderless'>
<div class='panel product-card-panel'>
<div class='panel-heading'>
<a href='/part/${part.pk}/'>
<b>${part.full_name}</b>
</a>
${makePartIcons(part)}
<br>
<i>${part.description}</i>
</div>
<div class='panel-content'>
<div class='row'>
<div class='col-sm-6'>
<img src='${part.thumbnail}' class='card-thumb' onclick='showModalImage("${part.image}")'>
</div>
<div class='col-sm-6'>
<table class='table table-striped table-condensed'>
${rows}
</table>
</div>
</div>
</div>
</div>
</div>
`;
return html;
}
function loadPartTable(table, url, options={}) {
/* Load part listing data into specified table.
*
* Args:
* - table: HTML reference to the table
* - url: Base URL for API query
* - options: object containing following (optional) fields
* checkbox: Show the checkbox column
* query: extra query params for API request
* buttons: If provided, link buttons to selection status of this table
* disableFilters: If true, disable custom filters
* actions: Provide a callback function to construct an "actions" column
*/
// Ensure category detail is included
options.params['category_detail'] = true;
var params = options.params || {};
var filters = {};
var col = null;
if (!options.disableFilters) {
filters = loadTableFilters('parts');
}
for (var key in params) {
filters[key] = params[key];
}
setupFilterList('parts', $(table), options.filterTarget || null);
var columns = [
{
field: 'pk',
title: 'ID',
visible: false,
switchable: false,
searchable: false,
}
];
if (options.checkbox) {
columns.push({
checkbox: true,
title: '{% trans "Select" %}',
searchable: false,
switchable: false,
});
}
col = {
field: 'IPN',
title: '{% trans "IPN" %}',
};
if (!options.params.ordering) {
col['sortable'] = true;
}
columns.push(col);
col = {
field: 'name',
title: '{% trans "Part" %}',
switchable: false,
formatter: function(value, row) {
var name = row.full_name;
var display = imageHoverIcon(row.thumbnail) + renderLink(name, `/part/${row.pk}/`);
display += makePartIcons(row);
return display;
}
};
if (!options.params.ordering) {
col['sortable'] = true;
}
columns.push(col);
columns.push({
field: 'description',
title: '{% trans "Description" %}',
formatter: function(value, row) {
if (row.is_template) {
value = `<i>${value}</i>`;
}
return value;
}
});
col = {
sortName: 'category',
field: 'category_detail',
title: '{% trans "Category" %}',
formatter: function(value, row) {
if (row.category) {
return renderLink(value.pathstring, `/part/category/${row.category}/`);
} else {
return '{% trans "No category" %}';
}
}
};
if (!options.params.ordering) {
col['sortable'] = true;
}
columns.push(col);
col = {
field: 'in_stock',
title: '{% trans "Stock" %}',
searchable: false,
formatter: function(value, row) {
var link = '?display=part-stock';
if (value) {
// There IS stock available for this part
// Is stock "low" (below the 'minimum_stock' quantity)?
if (row.minimum_stock && row.minimum_stock > value) {
value += `<span class='badge badge-right rounded-pill bg-warning'>{% trans "Low stock" %}</span>`;
}
} else if (row.on_order) {
// There is no stock available, but stock is on order
value = `0<span class='badge badge-right rounded-pill bg-info'>{% trans "On Order" %}: ${row.on_order}</span>`;
link = '?display=purchase-orders';
} else if (row.building) {
// There is no stock available, but stock is being built
value = `0<span class='badge badge-right rounded-pill bg-info'>{% trans "Building" %}: ${row.building}</span>`;
link = '?display=build-orders';
} else {
// There is no stock available
value = `0<span class='badge badge-right rounded-pill bg-danger'>{% trans "No Stock" %}</span>`;
}
return renderLink(value, `/part/${row.pk}/${link}`);
}
};
if (!options.params.ordering) {
col['sortable'] = true;
}
columns.push(col);
columns.push({
field: 'link',
title: '{% trans "Link" %}',
formatter: function(value) {
return renderLink(
value, value,
{
max_length: 32,
remove_http: true,
}
);
}
});
// Push an "actions" column
if (options.actions) {
columns.push({
field: 'actions',
title: '',
switchable: false,
visible: true,
searchable: false,
sortable: false,
formatter: function(value, row) {
return options.actions(value, row);
}
});
}
var grid_view = options.gridView && inventreeLoad('part-grid-view') == 1;
$(table).inventreeTable({
url: url,
method: 'get',
queryParams: filters,
groupBy: false,
name: options.name || 'part',
original: params,
sidePagination: 'server',
pagination: 'true',
formatNoMatches: function() {
return '{% trans "No parts found" %}';
},
columns: columns,
showColumns: true,
showCustomView: grid_view,
showCustomViewButton: false,
onPostBody: function() {
grid_view = inventreeLoad('part-grid-view') == 1;
if (grid_view) {
$('#view-part-list').removeClass('btn-secondary').addClass('btn-outline-secondary');
$('#view-part-grid').removeClass('btn-outline-secondary').addClass('btn-secondary');
} else {
$('#view-part-grid').removeClass('btn-secondary').addClass('btn-outline-secondary');
$('#view-part-list').removeClass('btn-outline-secondary').addClass('btn-secondary');
}
if (options.onPostBody) {
options.onPostBody();
}
},
buttons: options.gridView ? [
{
icon: 'fas fa-bars',
attributes: {
title: '{% trans "Display as list" %}',
id: 'view-part-list',
},
event: () => {
inventreeSave('part-grid-view', 0);
$(table).bootstrapTable(
'refreshOptions',
{
showCustomView: false,
}
);
}
},
{
icon: 'fas fa-th',
attributes: {
title: '{% trans "Display as grid" %}',
id: 'view-part-grid',
},
event: () => {
inventreeSave('part-grid-view', 1);
$(table).bootstrapTable(
'refreshOptions',
{
showCustomView: true,
}
);
}
}
] : [],
customView: function(data) {
var html = '';
html = `<div class='row full-height'>`;
data.forEach(function(row, index) {
// Force a new row every 5 columns
if ((index > 0) && (index % 5 == 0) && (index < data.length)) {
html += `</div><div class='row full-height'>`;
}
html += partGridTile(row);
});
html += `</div>`;
return html;
}
});
if (options.buttons) {
linkButtonsToSelection($(table), options.buttons);
}
/* Button callbacks for part table buttons */
$('#multi-part-order').click(function() {
var selections = $(table).bootstrapTable('getSelections');
var parts = [];
selections.forEach(function(item) {
parts.push(item.pk);
});
launchModalForm('/order/purchase-order/order-parts/', {
data: {
parts: parts,
},
});
});
$('#multi-part-category').click(function() {
var selections = $(table).bootstrapTable('getSelections');
var parts = [];
selections.forEach(function(item) {
parts.push(item.pk);
});
launchModalForm('/part/set-category/', {
data: {
parts: parts,
},
reload: true,
});
});
$('#multi-part-print-label').click(function() {
var selections = $(table).bootstrapTable('getSelections');
var items = [];
selections.forEach(function(item) {
items.push(item.pk);
});
printPartLabels(items);
});
$('#multi-part-export').click(function() {
var selections = $(table).bootstrapTable('getSelections');
var parts = '';
selections.forEach(function(item) {
parts += item.pk;
parts += ',';
});
location.href = '/part/export/?parts=' + parts;
});
}
/*
* Display a table of part categories
*/
function loadPartCategoryTable(table, options) {
var params = options.params || {};
var filterListElement = options.filterList || '#filter-list-category';
var filters = {};
var filterKey = options.filterKey || options.name || 'category';
if (!options.disableFilters) {
filters = loadTableFilters(filterKey);
}
var tree_view = options.allowTreeView && inventreeLoad('category-tree-view') == 1;
if (tree_view) {
params.cascade = true;
}
var original = {};
for (var key in params) {
original[key] = params[key];
filters[key] = params[key];
}
setupFilterList(filterKey, table, filterListElement);
table.inventreeTable({
treeEnable: tree_view,
rootParentId: tree_view ? options.params.parent : null,
uniqueId: 'pk',
idField: 'pk',
treeShowField: 'name',
parentIdField: tree_view ? 'parent' : null,
method: 'get',
url: options.url || '{% url "api-part-category-list" %}',
queryParams: filters,
disablePagination: tree_view,
sidePagination: tree_view ? 'client' : 'server',
serverSort: !tree_view,
search: !tree_view,
name: 'category',
original: original,
showColumns: true,
buttons: options.allowTreeView ? [
{
icon: 'fas fa-bars',
attributes: {
title: '{% trans "Display as list" %}',
id: 'view-category-list',
},
event: () => {
inventreeSave('category-tree-view', 0);
table.bootstrapTable(
'refreshOptions',
{
treeEnable: false,
serverSort: true,
search: true,
pagination: true,
}
);
}
},
{
icon: 'fas fa-sitemap',
attributes: {
title: '{% trans "Display as tree" %}',
id: 'view-category-tree',
},
event: () => {
inventreeSave('category-tree-view', 1);
table.bootstrapTable(
'refreshOptions',
{
treeEnable: true,
serverSort: false,
search: false,
pagination: false,
}
);
}
}
] : [],
onPostBody: function() {
if (options.allowTreeView) {
tree_view = inventreeLoad('category-tree-view') == 1;
if (tree_view) {
$('#view-category-list').removeClass('btn-secondary').addClass('btn-outline-secondary');
$('#view-category-tree').removeClass('btn-outline-secondary').addClass('btn-secondary');
table.treegrid({
treeColumn: 0,
onChange: function() {
table.bootstrapTable('resetView');
},
onExpand: function() {
}
});
} else {
$('#view-category-tree').removeClass('btn-secondary').addClass('btn-outline-secondary');
$('#view-category-list').removeClass('btn-outline-secondary').addClass('btn-secondary');
}
}
},
columns: [
{
checkbox: true,
title: '{% trans "Select" %}',
searchable: false,
switchable: false,
visible: false,
},
{
field: 'name',
title: '{% trans "Name" %}',
switchable: true,
sortable: true,
formatter: function(value, row) {
var html = renderLink(
value,
`/part/category/${row.pk}/`
);
if (row.starred) {
html += makeIconBadge('fa-bell icon-green', '{% trans "Subscribed category" %}');
}
return html;
}
},
{
field: 'description',
title: '{% trans "Description" %}',
switchable: true,
sortable: false,
},
{
field: 'pathstring',
title: '{% trans "Path" %}',
switchable: !tree_view,
visible: !tree_view,
sortable: false,
},
{
field: 'parts',
title: '{% trans "Parts" %}',
switchable: true,
sortable: false,
}
]
});
}
function loadPartTestTemplateTable(table, options) {
/*
* Load PartTestTemplate table.
*/
var params = options.params || {};
var part = options.part || null;
var filterListElement = options.filterList || '#filter-list-parttests';
var filters = loadTableFilters('parttests');
var original = {};
for (var k in params) {
original[k] = params[k];
}
setupFilterList('parttests', table, filterListElement);
// Override the default values, or add new ones
for (var key in params) {
filters[key] = params[key];
}
table.inventreeTable({
method: 'get',
formatNoMatches: function() {
return '{% trans "No test templates matching query" %}';
},
url: '{% url "api-part-test-template-list" %}',
queryParams: filters,
name: 'testtemplate',
original: original,
columns: [
{
field: 'pk',
title: 'ID',
visible: false,
},
{
field: 'test_name',
title: '{% trans "Test Name" %}',
sortable: true,
},
{
field: 'description',
title: '{% trans "Description" %}',
},
{
field: 'required',
title: '{% trans "Required" %}',
sortable: true,
formatter: function(value) {
return yesNoLabel(value);
}
},
{
field: 'requires_value',
title: '{% trans "Requires Value" %}',
formatter: function(value) {
return yesNoLabel(value);
}
},
{
field: 'requires_attachment',
title: '{% trans "Requires Attachment" %}',
formatter: function(value) {
return yesNoLabel(value);
}
},
{
field: 'buttons',
formatter: function(value, row) {
var pk = row.pk;
if (row.part == part) {
var html = `<div class='btn-group float-right' role='group'>`;
html += makeIconButton('fa-edit icon-blue', 'button-test-edit', pk, '{% trans "Edit test result" %}');
html += makeIconButton('fa-trash-alt icon-red', 'button-test-delete', pk, '{% trans "Delete test result" %}');
html += `</div>`;
return html;
} else {
var text = '{% trans "This test is defined for a parent part" %}';
return renderLink(text, `/part/${row.part}/tests/`);
}
}
}
],
onPostBody: function() {
table.find('.button-test-edit').click(function() {
var pk = $(this).attr('pk');
var url = `/api/part/test-template/${pk}/`;
constructForm(url, {
fields: {
test_name: {},
description: {},
required: {},
requires_value: {},
requires_attachment: {},
},
title: '{% trans "Edit Test Result Template" %}',
onSuccess: function() {
table.bootstrapTable('refresh');
},
});
});
table.find('.button-test-delete').click(function() {
var pk = $(this).attr('pk');
var url = `/api/part/test-template/${pk}/`;
constructForm(url, {
method: 'DELETE',
title: '{% trans "Delete Test Result Template" %}',
onSuccess: function() {
table.bootstrapTable('refresh');
},
});
});
}
});
}
function loadPriceBreakTable(table, options) {
/*
* Load PriceBreak table.
*/
var name = options.name || 'pricebreak';
var human_name = options.human_name || 'price break';
var linkedGraph = options.linkedGraph || null;
var chart = null;
table.inventreeTable({
name: name,
method: 'get',
formatNoMatches: function() {
return `{% trans "No ${human_name} information found" %}`;
},
queryParams: {part: options.part},
url: options.url,
onLoadSuccess: function(tableData) {
if (linkedGraph) {
// sort array
tableData = tableData.sort((a, b) => (a.quantity - b.quantity));
// split up for graph definition
var graphLabels = Array.from(tableData, (x) => (x.quantity));
var graphData = Array.from(tableData, (x) => (x.price));
// destroy chart if exists
if (chart) {
chart.destroy();
}
chart = loadLineChart(linkedGraph,
{
labels: graphLabels,
datasets: [
{
label: '{% trans "Unit Price" %}',
data: graphData,
backgroundColor: 'rgba(255, 206, 86, 0.2)',
borderColor: 'rgb(255, 206, 86)',
stepped: true,
fill: true,
},
],
}
);
}
},
columns: [
{
field: 'pk',
title: 'ID',
visible: false,
switchable: false,
},
{
field: 'quantity',
title: '{% trans "Quantity" %}',
sortable: true,
},
{
field: 'price',
title: '{% trans "Price" %}',
sortable: true,
formatter: function(value, row) {
var html = value;
html += `<div class='btn-group float-right' role='group'>`;
html += makeIconButton('fa-edit icon-blue', `button-${name}-edit`, row.pk, `{% trans "Edit ${human_name}" %}`);
html += makeIconButton('fa-trash-alt icon-red', `button-${name}-delete`, row.pk, `{% trans "Delete ${human_name}" %}`);
html += `</div>`;
return html;
}
},
]
});
}
function loadLineChart(context, data) {
return new Chart(context, {
type: 'line',
data: data,
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {position: 'bottom'},
}
}
});
}
function initPriceBreakSet(table, options) {
var part_id = options.part_id;
var pb_human_name = options.pb_human_name;
var pb_url_slug = options.pb_url_slug;
var pb_url = options.pb_url;
var pb_new_btn = options.pb_new_btn;
var pb_new_url = options.pb_new_url;
var linkedGraph = options.linkedGraph || null;
loadPriceBreakTable(
table,
{
name: pb_url_slug,
human_name: pb_human_name,
url: pb_url,
linkedGraph: linkedGraph,
part: part_id,
}
);
function reloadPriceBreakTable() {
table.bootstrapTable('refresh');
}
pb_new_btn.click(function() {
launchModalForm(pb_new_url,
{
success: reloadPriceBreakTable,
data: {
part: part_id,
}
}
);
});
table.on('click', `.button-${pb_url_slug}-delete`, function() {
var pk = $(this).attr('pk');
launchModalForm(
`/part/${pb_url_slug}/${pk}/delete/`,
{
success: reloadPriceBreakTable
}
);
});
table.on('click', `.button-${pb_url_slug}-edit`, function() {
var pk = $(this).attr('pk');
launchModalForm(
`/part/${pb_url_slug}/${pk}/edit/`,
{
success: reloadPriceBreakTable
}
);
});
}
function loadStockPricingChart(context, data) {
return new Chart(context, {
type: 'bar',
data: data,
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {legend: {position: 'bottom'}},
scales: {
y: {
type: 'linear',
position: 'left',
grid: {display: false},
title: {
display: true,
text: '{% trans "Single Price" %}'
}
},
y1: {
type: 'linear',
position: 'right',
grid: {display: false},
titel: {
display: true,
text: '{% trans "Quantity" %}',
position: 'right'
}
},
y2: {
type: 'linear',
position: 'left',
grid: {display: false},
title: {
display: true,
text: '{% trans "Single Price Difference" %}'
}
}
},
}
});
}
function loadBomChart(context, data) {
return new Chart(context, {
type: 'doughnut',
data: data,
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
position: 'bottom',
},
scales: {
xAxes: [
{
beginAtZero: true,
ticks: {
autoSkip: false,
}
}
]
}
}
}
});
}
function loadSellPricingChart(context, data) {
return new Chart(context, {
type: 'line',
data: data,
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
position: 'bottom'
}
},
scales: {
y: {
type: 'linear',
position: 'left',
grid: {
display: false
},
title: {
display: true,
text: '{% trans "Unit Price" %}',
}
},
y1: {
type: 'linear',
position: 'right',
grid: {
display: false
},
titel: {
display: true,
text: '{% trans "Quantity" %}',
position: 'right'
}
},
},
}
});
}
| javascript linting
| InvenTree/templates/js/translated/part.js | javascript linting | <ide><path>nvenTree/templates/js/translated/part.js
<ide> loadPartTable,
<ide> loadPartTestTemplateTable,
<ide> loadPartVariantTable,
<add> loadRelatedPartsTable,
<ide> loadSellPricingChart,
<ide> loadSimplePartTable,
<ide> loadStockPricingChart,
<ide>
<ide> var part = getPart(row);
<ide>
<del> var html = imageHoverIcon(part.thumbnail) + renderLink(part.full_name, `/part/${part.pk}/`)
<add> var html = imageHoverIcon(part.thumbnail) + renderLink(part.full_name, `/part/${part.pk}/`);
<ide>
<ide> html += makePartIcons(part);
<ide> |
|
Java | apache-2.0 | 373d7f724d67d04990ef583e3647a3c4d357ad21 | 0 | mrkcsc/android-spanner,mrkcsc/android-spanner | package com.miguelgaeta.spanner;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.CharacterStyle;
import android.util.Log;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
/**
* Created by Miguel Gaeta on 4/20/16.
*
* A powerful spannable string builder that supports arbitrary substitutions.
*/
public class Spanner {
private String sourceString = "";
private final List<MatchStrategy> matchStrategies = new ArrayList<>();
private final List<Replacement> replacements = new ArrayList<>();
public Spanner(final String sourceString) {
this.sourceString = sourceString;
}
@SuppressWarnings("unused")
public Spanner addReplacementStrategy(final OnMatchListener onMatchListener, final String start) {
return addReplacementStrategy(onMatchListener, start, null);
}
public Spanner addReplacementStrategy(final OnMatchListener onMatchListener, final String start, final String end) {
return addReplacementStrategy(onMatchListener, start, end, true);
}
public Spanner addReplacementStrategy(final OnMatchListener onMatchListener, final String start, final String end, boolean endRequired) {
return addReplacementStrategy(onMatchListener, start, end, endRequired, false);
}
public Spanner addReplacementStrategy(final OnMatchListener onMatchListener, final String start, final String end, final boolean endRequired, final boolean endWithWhitespaceOrEOL) {
matchStrategies.add(new MatchStrategy(onMatchListener, start, end, endRequired, endWithWhitespaceOrEOL));
return this;
}
@SuppressWarnings("unused")
public Spanner addMarkdownStrategy() {
addMarkdownBoldStrategy();
addReplacementStrategy(new OnMatchListener() {
@Override
public Replacement call(String match) {
return new Replacement(match, SpanHelpers.createItalicSpan());
}
}, "*", "*");
addReplacementStrategy(new OnMatchListener() {
@Override
public Replacement call(String match) {
return new Replacement(match, SpanHelpers.createStrikethroughSpan());
}
}, "~~", "~~");
addReplacementStrategy(new OnMatchListener() {
@Override
public Replacement call(String match) {
return new Replacement(match, SpanHelpers.createUnderlineSpan());
}
}, "__", "__");
addReplacementStrategy(new OnMatchListener() {
@Override
public Replacement call(String match) {
return new Replacement(match, SpanHelpers.createItalicSpan());
}
}, "_", "_", true, true);
return this;
}
public Spanner addMarkdownBoldStrategy() {
addReplacementStrategy(new OnMatchListener() {
@Override
public Replacement call(String match) {
return new Replacement(match, SpanHelpers.createBoldItalicSpan());
}
}, "***", "***");
addReplacementStrategy(new OnMatchListener() {
@Override
public Replacement call(String match) {
return new Replacement(match, SpanHelpers.createBoldSpan());
}
}, "**", "**");
return this;
}
public SpannableString toSpannableString() {
for (final MatchStrategy matchStrategy : matchStrategies) {
int startIndex = 0;
do {
startIndex = sourceString.indexOf(matchStrategy.start, startIndex);
if (startIndex != -1) {
final int startIndexOffset = matchStrategy.start.length();
if (matchStrategy.end == null) {
int endIndex = startIndex + startIndexOffset;
final Replacement replacement = matchStrategy.onMatchListener.call(matchStrategy.start);
startIndex = computeStartIndexWithSpans(startIndex, startIndexOffset, endIndex, replacement);
} else {
int endIndex = sourceString.indexOf(matchStrategy.end, startIndex + startIndexOffset);
final boolean isEOLMatch = endIndex == -1 && !matchStrategy.endRequired;
if (isEOLMatch) {
endIndex = sourceString.length();
}
if (matchStrategy.endWithWhitespaceOrEOL && endIndex != -1) {
if (endIndex != (sourceString.length() - 1) && !Character.isWhitespace(sourceString.charAt(endIndex + 1))) {
endIndex = -1;
}
}
if (endIndex != -1) {
final String match = sourceString.substring(startIndex + startIndexOffset, endIndex);
final Replacement replacement = matchStrategy.onMatchListener.call(match);
if (!isEOLMatch) {
endIndex += matchStrategy.end.length();
}
startIndex = computeStartIndexWithSpans(startIndex, startIndexOffset, endIndex, replacement);
} else {
startIndex = -1;
}
}
}
} while (startIndex != -1);
}
return buildSpannableString(sourceString, replacements);
}
private int computeStartIndexWithSpans(final int startIndex, final int startIndexOffset, final int endIndex, final Replacement replacement) {
// Replace match with user provided replacement.
sourceString = new StringBuilder(sourceString).replace(startIndex, endIndex, replacement.replacementString).toString();
// Update the new end index location.
final int endIndexUpdated = startIndex + replacement.replacementString.length();
final int offset = (endIndex - startIndex) - (endIndexUpdated - startIndex);
if (offset != 0) {
for (final Replacement existingReplacement : replacements) {
if (existingReplacement.start > startIndex) {
existingReplacement.start -= startIndexOffset;
if (existingReplacement.start > endIndexUpdated) {
existingReplacement.start -= offset - startIndexOffset;
}
}
if (existingReplacement.end > startIndex) {
existingReplacement.end -= startIndexOffset;
if (existingReplacement.end > endIndexUpdated) {
existingReplacement.end -= offset - startIndexOffset;
}
}
}
}
replacement.start = startIndex;
replacement.end = endIndexUpdated;
replacements.add(replacement);
return endIndexUpdated;
}
/**
* Given a source string and a corresponding list of replacement objects,
* transform into a spannable string spans applied from each replacement.
*
* Assumes the source string has been formatted with string replacements
* during the computation step.
*
* @param sourceString Source string with replacements.
* @param replacements Replacement objects with desired spans to apply at start and end indices.
*
* @return Source string with spans applied.
*/
private static SpannableString buildSpannableString(final String sourceString, final Collection<Replacement> replacements) {
final SpannableString spannableString = new SpannableString(sourceString);
try {
for (final Replacement replacement : replacements) {
for (final CharacterStyle characterStyle : replacement.replacementSpans) {
spannableString.setSpan(characterStyle, replacement.start, replacement.end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
} catch (IndexOutOfBoundsException e) {
Log.i("Spanner", "Span cannot be applied, index out of bounds.", e);
}
return spannableString;
}
@SuppressWarnings("unused")
public interface OnMatchListener {
Replacement call(final String match);
}
/**
* Represents a desired match strategy with a callback
* to allow the user to return a replacement string
* along with desired spans to apply to it.
*
* TODO: This could be made simpler by being represented as a regex.
*/
private static class MatchStrategy {
final OnMatchListener onMatchListener;
final String start;
final String end;
final boolean endRequired;
final boolean endWithWhitespaceOrEOL;
private MatchStrategy(final OnMatchListener onMatchListener, final String start, final String end, final boolean endRequired, final boolean endWithWhitespaceOrEOL) {
this.onMatchListener = onMatchListener;
this.start = start;
this.end = end;
this.endRequired = endRequired;
this.endWithWhitespaceOrEOL = endWithWhitespaceOrEOL;
}
}
@SuppressWarnings("unused")
public static class Replacement {
final String replacementString;
final List<CharacterStyle> replacementSpans;
int start;
int end;
public Replacement(final String replacementString, final List<CharacterStyle> replacementSpans) {
this.replacementString = replacementString;
this.replacementSpans = replacementSpans;
}
public Replacement(final String replacementString, CharacterStyle... spanStyles) {
this(replacementString, Arrays.asList(spanStyles));
}
public Replacement(final String replacementString) {
this(replacementString, Collections.<CharacterStyle>emptyList());
}
}
}
| spanner/src/main/java/com/miguelgaeta/spanner/Spanner.java | package com.miguelgaeta.spanner;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.CharacterStyle;
import android.util.Log;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
/**
* Created by Miguel Gaeta on 4/20/16.
*
* A powerful spannable string builder that supports arbitrary substitutions.
*/
public class Spanner {
private String sourceString = "";
private final List<MatchStrategy> matchStrategies = new ArrayList<>();
private final List<Replacement> replacements = new ArrayList<>();
public Spanner(final String sourceString) {
this.sourceString = sourceString;
}
@SuppressWarnings("unused")
public Spanner addReplacementStrategy(final OnMatchListener onMatchListener, final String start) {
return addReplacementStrategy(onMatchListener, start, null);
}
public Spanner addReplacementStrategy(final OnMatchListener onMatchListener, final String start, final String end) {
return addReplacementStrategy(onMatchListener, start, end, true);
}
public Spanner addReplacementStrategy(final OnMatchListener onMatchListener, final String start, final String end, boolean endRequired) {
return addReplacementStrategy(onMatchListener, start, end, endRequired, false);
}
public Spanner addReplacementStrategy(final OnMatchListener onMatchListener, final String start, final String end, final boolean endRequired, final boolean endWithWhitespaceOrEOL) {
matchStrategies.add(new MatchStrategy(onMatchListener, start, end, endRequired, endWithWhitespaceOrEOL));
return this;
}
@SuppressWarnings("unused")
public Spanner addMarkdownStrategy() {
addReplacementStrategy(new OnMatchListener() {
@Override
public Replacement call(String match) {
return new Replacement(match, SpanHelpers.createBoldItalicSpan());
}
}, "***", "***");
addReplacementStrategy(new OnMatchListener() {
@Override
public Replacement call(String match) {
return new Replacement(match, SpanHelpers.createBoldSpan());
}
}, "**", "**");
addReplacementStrategy(new OnMatchListener() {
@Override
public Replacement call(String match) {
return new Replacement(match, SpanHelpers.createItalicSpan());
}
}, "*", "*");
addReplacementStrategy(new OnMatchListener() {
@Override
public Replacement call(String match) {
return new Replacement(match, SpanHelpers.createStrikethroughSpan());
}
}, "~~", "~~");
addReplacementStrategy(new OnMatchListener() {
@Override
public Replacement call(String match) {
return new Replacement(match, SpanHelpers.createUnderlineSpan());
}
}, "__", "__");
addReplacementStrategy(new OnMatchListener() {
@Override
public Replacement call(String match) {
return new Replacement(match, SpanHelpers.createItalicSpan());
}
}, "_", "_", true, true);
return this;
}
public SpannableString toSpannableString() {
for (final MatchStrategy matchStrategy : matchStrategies) {
int startIndex = 0;
do {
startIndex = sourceString.indexOf(matchStrategy.start, startIndex);
if (startIndex != -1) {
final int startIndexOffset = matchStrategy.start.length();
if (matchStrategy.end == null) {
int endIndex = startIndex + startIndexOffset;
final Replacement replacement = matchStrategy.onMatchListener.call(matchStrategy.start);
startIndex = computeStartIndexWithSpans(startIndex, startIndexOffset, endIndex, replacement);
} else {
int endIndex = sourceString.indexOf(matchStrategy.end, startIndex + startIndexOffset);
final boolean isEOLMatch = endIndex == -1 && !matchStrategy.endRequired;
if (isEOLMatch) {
endIndex = sourceString.length();
}
if (matchStrategy.endWithWhitespaceOrEOL && endIndex != -1) {
if (endIndex != (sourceString.length() - 1) && !Character.isWhitespace(sourceString.charAt(endIndex + 1))) {
endIndex = -1;
}
}
if (endIndex != -1) {
final String match = sourceString.substring(startIndex + startIndexOffset, endIndex);
final Replacement replacement = matchStrategy.onMatchListener.call(match);
if (!isEOLMatch) {
endIndex += matchStrategy.end.length();
}
startIndex = computeStartIndexWithSpans(startIndex, startIndexOffset, endIndex, replacement);
} else {
startIndex = -1;
}
}
}
} while (startIndex != -1);
}
return buildSpannableString(sourceString, replacements);
}
private int computeStartIndexWithSpans(final int startIndex, final int startIndexOffset, final int endIndex, final Replacement replacement) {
// Replace match with user provided replacement.
sourceString = new StringBuilder(sourceString).replace(startIndex, endIndex, replacement.replacementString).toString();
// Update the new end index location.
final int endIndexUpdated = startIndex + replacement.replacementString.length();
final int offset = (endIndex - startIndex) - (endIndexUpdated - startIndex);
if (offset != 0) {
for (final Replacement existingReplacement : replacements) {
if (existingReplacement.start > startIndex) {
existingReplacement.start -= startIndexOffset;
if (existingReplacement.start > endIndexUpdated) {
existingReplacement.start -= offset - startIndexOffset;
}
}
if (existingReplacement.end > startIndex) {
existingReplacement.end -= startIndexOffset;
if (existingReplacement.end > endIndexUpdated) {
existingReplacement.end -= offset - startIndexOffset;
}
}
}
}
replacement.start = startIndex;
replacement.end = endIndexUpdated;
replacements.add(replacement);
return endIndexUpdated;
}
/**
* Given a source string and a corresponding list of replacement objects,
* transform into a spannable string spans applied from each replacement.
*
* Assumes the source string has been formatted with string replacements
* during the computation step.
*
* @param sourceString Source string with replacements.
* @param replacements Replacement objects with desired spans to apply at start and end indices.
*
* @return Source string with spans applied.
*/
private static SpannableString buildSpannableString(final String sourceString, final Collection<Replacement> replacements) {
final SpannableString spannableString = new SpannableString(sourceString);
try {
for (final Replacement replacement : replacements) {
for (final CharacterStyle characterStyle : replacement.replacementSpans) {
spannableString.setSpan(characterStyle, replacement.start, replacement.end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
} catch (IndexOutOfBoundsException e) {
Log.i("Spanner", "Span cannot be applied, index out of bounds.", e);
}
return spannableString;
}
@SuppressWarnings("unused")
public interface OnMatchListener {
Replacement call(final String match);
}
/**
* Represents a desired match strategy with a callback
* to allow the user to return a replacement string
* along with desired spans to apply to it.
*
* TODO: This could be made simpler by being represented as a regex.
*/
private static class MatchStrategy {
final OnMatchListener onMatchListener;
final String start;
final String end;
final boolean endRequired;
final boolean endWithWhitespaceOrEOL;
private MatchStrategy(final OnMatchListener onMatchListener, final String start, final String end, final boolean endRequired, final boolean endWithWhitespaceOrEOL) {
this.onMatchListener = onMatchListener;
this.start = start;
this.end = end;
this.endRequired = endRequired;
this.endWithWhitespaceOrEOL = endWithWhitespaceOrEOL;
}
}
@SuppressWarnings("unused")
public static class Replacement {
final String replacementString;
final List<CharacterStyle> replacementSpans;
int start;
int end;
public Replacement(final String replacementString, final List<CharacterStyle> replacementSpans) {
this.replacementString = replacementString;
this.replacementSpans = replacementSpans;
}
public Replacement(final String replacementString, CharacterStyle... spanStyles) {
this(replacementString, Arrays.asList(spanStyles));
}
public Replacement(final String replacementString) {
this(replacementString, Collections.<CharacterStyle>emptyList());
}
}
}
| Add bold shorthand.
| spanner/src/main/java/com/miguelgaeta/spanner/Spanner.java | Add bold shorthand. | <ide><path>panner/src/main/java/com/miguelgaeta/spanner/Spanner.java
<ide>
<ide> @SuppressWarnings("unused")
<ide> public Spanner addMarkdownStrategy() {
<add> addMarkdownBoldStrategy();
<add>
<add> addReplacementStrategy(new OnMatchListener() {
<add> @Override
<add> public Replacement call(String match) {
<add> return new Replacement(match, SpanHelpers.createItalicSpan());
<add> }
<add> }, "*", "*");
<add>
<add> addReplacementStrategy(new OnMatchListener() {
<add> @Override
<add> public Replacement call(String match) {
<add> return new Replacement(match, SpanHelpers.createStrikethroughSpan());
<add> }
<add> }, "~~", "~~");
<add>
<add> addReplacementStrategy(new OnMatchListener() {
<add> @Override
<add> public Replacement call(String match) {
<add> return new Replacement(match, SpanHelpers.createUnderlineSpan());
<add> }
<add> }, "__", "__");
<add>
<add> addReplacementStrategy(new OnMatchListener() {
<add> @Override
<add> public Replacement call(String match) {
<add> return new Replacement(match, SpanHelpers.createItalicSpan());
<add> }
<add> }, "_", "_", true, true);
<add>
<add> return this;
<add> }
<add>
<add> public Spanner addMarkdownBoldStrategy() {
<ide> addReplacementStrategy(new OnMatchListener() {
<ide> @Override
<ide> public Replacement call(String match) {
<ide> return new Replacement(match, SpanHelpers.createBoldSpan());
<ide> }
<ide> }, "**", "**");
<del>
<del> addReplacementStrategy(new OnMatchListener() {
<del> @Override
<del> public Replacement call(String match) {
<del> return new Replacement(match, SpanHelpers.createItalicSpan());
<del> }
<del> }, "*", "*");
<del>
<del> addReplacementStrategy(new OnMatchListener() {
<del> @Override
<del> public Replacement call(String match) {
<del> return new Replacement(match, SpanHelpers.createStrikethroughSpan());
<del> }
<del> }, "~~", "~~");
<del>
<del> addReplacementStrategy(new OnMatchListener() {
<del> @Override
<del> public Replacement call(String match) {
<del> return new Replacement(match, SpanHelpers.createUnderlineSpan());
<del> }
<del> }, "__", "__");
<del>
<del> addReplacementStrategy(new OnMatchListener() {
<del> @Override
<del> public Replacement call(String match) {
<del> return new Replacement(match, SpanHelpers.createItalicSpan());
<del> }
<del> }, "_", "_", true, true);
<ide>
<ide> return this;
<ide> } |
|
Java | apache-2.0 | b957c0ffb6f5e96ebe7c6ee16442bbeac8ba5b92 | 0 | ekux44/LampShade,ekux44/HueMore | package com.kuxhausen.huemore;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import com.kuxhausen.huemore.billing.IabHelper;
import com.kuxhausen.huemore.billing.IabResult;
import com.kuxhausen.huemore.billing.Inventory;
import com.kuxhausen.huemore.billing.Purchase;
import com.kuxhausen.huemore.database.DatabaseDefinitions;
import com.kuxhausen.huemore.database.DatabaseDefinitions.PlayItems;
import com.kuxhausen.huemore.database.DatabaseHelper;
import com.kuxhausen.huemore.database.DatabaseDefinitions.GroupColumns;
import com.kuxhausen.huemore.database.DatabaseDefinitions.MoodColumns;
import com.kuxhausen.huemore.database.DatabaseDefinitions.PreferencesKeys;
import com.kuxhausen.huemore.network.GetBulbList;
import com.kuxhausen.huemore.network.TransmitGroupMood;
import com.kuxhausen.huemore.ui.registration.RegisterWithHubDialogFragment;
/**
* @author Eric Kuxhausen
*
*/
public class MainActivity extends FragmentActivity implements
GroupBulbPagingFragment.OnBulbGroupSelectedListener,
MoodsFragment.OnMoodSelectedListener {
DatabaseHelper databaseHelper = new DatabaseHelper(this);
Integer[] bulbS;
String mood;
IabHelper mPlayHelper;
MainActivity m;
Inventory lastQuerriedInventory;
public GetBulbList.OnBulbListReturnedListener bulbListenerFragment;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("asdf", "onCreate");
setContentView(R.layout.hue_more);
m = this;
// Check whether the activity is using the layout version with
// the fragment_container FrameLayout. If so, we must add the first
// fragment
if (findViewById(R.id.fragment_container) != null) {
// However, if we're being restored from a previous state,
// then we don't need to do anything and should return or else
// we could end up with overlapping fragments.
if (savedInstanceState != null) {
// return;
}else{
// Create an instance of ExampleFragment
GroupBulbPagingFragment firstFragment = new GroupBulbPagingFragment();
// GroupsFragment firstFragment = new GroupsFragment();
// In case this activity was started with special instructions from
// an Intent,
// pass the Intent's extras to the fragment as arguments
firstFragment.setArguments(getIntent().getExtras());
// Add the fragment to the 'fragment_container' FrameLayout
getSupportFragmentManager()
.beginTransaction()
.add(R.id.fragment_container, firstFragment,
GroupBulbPagingFragment.class.getName()).commit();
}
}
// (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) ?
// this.getActionBar().setDisplayHomeAsUpEnabled(true)
// : System.out.println("wtf");
SharedPreferences settings = PreferenceManager
.getDefaultSharedPreferences(this);
if (!settings.contains(PreferencesKeys.THIRD_UPDATE)) {
databaseHelper.updatedPopulate();
// Mark no longer first update in preferences cache
Editor edit = settings.edit();
edit.putBoolean(PreferencesKeys.THIRD_UPDATE, false);
edit.commit();
}
if (!settings.contains(PreferencesKeys.FIRST_RUN)) {
databaseHelper.initialPopulate();// initialize database
// Mark no longer first run in preferences cache
Editor edit = settings.edit();
edit.putBoolean(PreferencesKeys.FIRST_RUN, false);
edit.putInt(PreferencesKeys.BULBS_UNLOCKED,
PreferencesKeys.ALWAYS_FREE_BULBS);// TODO load from
// google store
edit.commit();
}
if (!settings.contains(PreferencesKeys.DEFAULT_TO_GROUPS)) {
Editor edit = settings.edit();
edit.putBoolean(PreferencesKeys.DEFAULT_TO_GROUPS, false);
edit.commit();
}
if (!settings.contains(PreferencesKeys.DEFAULT_TO_MOODS)) {
Editor edit = settings.edit();
edit.putBoolean(PreferencesKeys.DEFAULT_TO_MOODS, true);
edit.commit();
}
// check to see if the bridge IP address is setup yet
if (!settings.contains(PreferencesKeys.BRIDGE_IP_ADDRESS)) {
RegisterWithHubDialogFragment rwhdf = new RegisterWithHubDialogFragment();
rwhdf.show(this.getSupportFragmentManager(), "dialog");
}
String firstChunk = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAgPUhHgGEdnpyPMAWgP3Xw/jHkReU1O0n6d4rtcULxOrVl/hcZlOsVyByMIZY5wMD84gmMXjbz8pFb4RymFTP7Yp8LSEGiw6DOXc7ydNd0lbZ4WtKyDEwwaio1wRbRPxdU7/4JBpMCh9L6geYx6nYLt0ExZEFxULV3dZJpIlEkEYaNGk/64gc0l34yybccYfORrWzu8u+";
String secondChunk = "5YxJ5k1ikIJJ2I7/2Rp5AXkj2dWybmT+AGx83zh8+iMGGawEQerGtso9NUqpyZWU08EO9DcF8r2KnFwjmyWvqJ2JzbqCMNt0A08IGQNOrd16/C/65GE6J/EtsggkNIgQti6jD7zd3b2NAQIDAQAB";
String base64EncodedPublicKey = firstChunk + secondChunk;
// compute your public key and store it in base64EncodedPublicKey
mPlayHelper = new IabHelper(this, base64EncodedPublicKey);
Log.d("asdf", "mPlayHelperCreated" + (mPlayHelper !=null));
mPlayHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
public void onIabSetupFinished(IabResult result) {
if (!result.isSuccess()) {
// Oh noes, there was a problem.
// Log.d("asdf", "Problem setting up In-app Billing: "+
// result);
} else {
// Hooray, IAB is fully set up!
mPlayHelper.queryInventoryAsync(mGotInventoryListener);
if (m.bulbListenerFragment != null) {
GetBulbList pushGroupMood = new GetBulbList();
pushGroupMood.execute(m, m.bulbListenerFragment);
}
}
}
});
}
// Listener that's called when we finish querying the items and
// subscriptions we own
IabHelper.QueryInventoryFinishedListener mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener() {
public void onQueryInventoryFinished(IabResult result,
Inventory inventory) {
// Log.d("asdf", "Query inventory finished.");
if (result.isFailure()) {
// handle error
return;
} else {
// Log.d("asdf", "Query inventory was successful.");
lastQuerriedInventory = inventory;
int numUnlocked = PreferencesKeys.ALWAYS_FREE_BULBS;
if (inventory.hasPurchase(PlayItems.FIVE_BULB_UNLOCK_1))
numUnlocked += 5;
if (inventory.hasPurchase(PlayItems.FIVE_BULB_UNLOCK_2))
numUnlocked += 5;
if (inventory.hasPurchase(PlayItems.FIVE_BULB_UNLOCK_3))
numUnlocked += 5;
if (inventory.hasPurchase(PlayItems.FIVE_BULB_UNLOCK_4))
numUnlocked += 5;
if (inventory.hasPurchase(PlayItems.FIVE_BULB_UNLOCK_5))
numUnlocked += 5;
if (inventory.hasPurchase(PlayItems.FIVE_BULB_UNLOCK_6))
numUnlocked += 5;
if (inventory.hasPurchase(PlayItems.FIVE_BULB_UNLOCK_7))
numUnlocked += 5;
if (inventory.hasPurchase(PlayItems.FIVE_BULB_UNLOCK_8))
numUnlocked += 5;
if (inventory.hasPurchase(PlayItems.BUY_ME_A_BULB_DONATION_1))
numUnlocked = Math.max(50, numUnlocked);
// update UI accordingly
// Get preferences cache
SharedPreferences settings = PreferenceManager
.getDefaultSharedPreferences(m);
int previousMax = settings.getInt(
PreferencesKeys.BULBS_UNLOCKED,
PreferencesKeys.ALWAYS_FREE_BULBS);
if (numUnlocked > previousMax) {
// Update the number held in settings
Editor edit = settings.edit();
edit.putInt(PreferencesKeys.BULBS_UNLOCKED, numUnlocked);
edit.commit();
databaseHelper.addBulbs(previousMax, numUnlocked);// initialize
// database
}
}
/*
* Check for items we own. Notice that for each purchase, we check
* the developer payload to see if it's correct! See
* verifyDeveloperPayload().
*/
/*
* // Do we have the premium upgrade? Purchase premiumPurchase =
* inventory.getPurchase(SKU_PREMIUM); mIsPremium = (premiumPurchase
* != null && verifyDeveloperPayload(premiumPurchase)); Log.d(TAG,
* "User is " + (mIsPremium ? "PREMIUM" : "NOT PREMIUM"));
*
*
* updateUi(); setWaitScreen(false); Log.d(TAG,
* "Initial inventory query finished; enabling main UI.");
*/
}
};
IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
public void onIabPurchaseFinished(IabResult result, Purchase purchase) {
mPlayHelper.queryInventoryAsync(mGotInventoryListener);
}
};
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void initializeActionBar(Boolean value) {
try {
this.getActionBar().setDisplayHomeAsUpEnabled(value);
} catch (Error e) {
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Log.d(TAG, "onActivityResult(" + requestCode + "," + resultCode + ","
// + data);
// Pass on the activity result to the helper for handling
if (!mPlayHelper.handleActivityResult(requestCode, resultCode, data)) {
// not handled, so handle it ourselves (here's where you'd
// perform any handling of activity results not related to in-app
// billing...
super.onActivityResult(requestCode, resultCode, data);
} else {
// Log.d(TAG, "onActivityResult handled by IABUtil.");
}
}
/** Verifies the developer payload of a purchase. */
boolean verifyDeveloperPayload(Purchase p) {
String payload = p.getDeveloperPayload();
/*
* TODO: verify that the developer payload of the purchase is correct.
* It will be the same one that you sent when initiating the purchase.
*
* WARNING: Locally generating a random string when starting a purchase
* and verifying it here might seem like a good approach, but this will
* fail in the case where the user purchases an item on one device and
* then uses your app on a different device, because on the other device
* you will not have access to the random string you originally
* generated.
*
* So a good developer payload has these characteristics:
*
* 1. If two different users purchase an item, the payload is different
* between them, so that one user's purchase can't be replayed to
* another user.
*
* 2. The payload must be such that you can verify it even when the app
* wasn't the one who initiated the purchase flow (so that items
* purchased by the user on one device work on other devices owned by
* the user).
*
* Using your own server to store and verify developer payloads across
* app installations is recommended.
*/
return true;
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d("asdf", "onDestroy");
if (mPlayHelper != null)
mPlayHelper.dispose();
mPlayHelper = null;
Log.d("asdf", "mPlayHelperDestroyed" + (mPlayHelper ==null));
}
@Override
public void onGroupBulbSelected(Integer[] bulb) {
bulbS = bulb;
// Capture the article fragment from the activity layout
MoodManualPagingFragment moodFrag = (MoodManualPagingFragment) getSupportFragmentManager()
.findFragmentById(R.id.moods_fragment);
if (moodFrag != null) {
// If article frag is available, we're in two-pane layout...
// Call a method in the ArticleFragment to update its content
moodFrag.reset();
} else {
// If the frag is not available, we're in the one-pane layout and
// must swap frags...
// Create fragment and give it an argument for the selected article
MoodManualPagingFragment newFragment = new MoodManualPagingFragment();
FragmentTransaction transaction = getSupportFragmentManager()
.beginTransaction();
transaction
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
// Replace whatever is in the fragment_container view with this
// fragment,
// and add the transaction to the back stack so the user can
// navigate back
transaction.replace(R.id.fragment_container, newFragment,
MoodManualPagingFragment.class.getName());
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
transaction
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
initializeActionBar(true);
}
}
}
@Override
public void onBackPressed() {
super.onBackPressed();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
initializeActionBar(false);
}
}
private void moveToGroupBulb() {
MoodManualPagingFragment moodFrag = (MoodManualPagingFragment) getSupportFragmentManager()
.findFragmentById(R.id.moods_fragment);
if (moodFrag == null || !moodFrag.isVisible()) {
this.onBackPressed();
}
}
@Override
public void onMoodSelected(String moodParam) {
mood = moodParam;
pushMoodGroup();
}
public void onBrightnessChanged(String brightnessState[]) {
TransmitGroupMood pushGroupMood = new TransmitGroupMood();
pushGroupMood.execute(this, bulbS, brightnessState);
}
/*
* test mood by applying to json states array to these bulbs
*
* @param states
*/
/*
* public void testMood(Integer[] bulbs, String[] states) {
* TransmitGroupMood pushGroupMood = new TransmitGroupMood();
* pushGroupMood.execute(this, bulbs, states); }
*/
/**
* test mood by applying to json states array to previously selected moods
*
* @param states
*/
public void testMood(String[] states) {
TransmitGroupMood pushGroupMood = new TransmitGroupMood();
pushGroupMood.execute(this, bulbS, states);
}
private void pushMoodGroup() {
if (bulbS == null || mood == null)
return;
String[] moodColumns = { MoodColumns.STATE };
String[] mWereClause = { mood };
Cursor cursor = getContentResolver().query(
DatabaseDefinitions.MoodColumns.MOODSTATES_URI, // Use the
// default
// content URI
// for the
// provider.
moodColumns, // Return the note ID and title for each note.
MoodColumns.MOOD + "=?", // selection clause
mWereClause, // election clause args
null // Use the default sort order.
);
ArrayList<String> moodStates = new ArrayList<String>();
while (cursor.moveToNext()) {
moodStates.add(cursor.getString(0));
}
String[] moodS = moodStates.toArray(new String[moodStates.size()]);
TransmitGroupMood pushGroupMood = new TransmitGroupMood();
pushGroupMood.execute(this, bulbS, moodS);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case android.R.id.home:
moveToGroupBulb();
return true;
case R.id.action_register_with_hub:
RegisterWithHubDialogFragment rwhdf = new RegisterWithHubDialogFragment();
rwhdf.show(getSupportFragmentManager(), "dialog");
return true;
case R.id.action_settings:
Settings settings = new Settings();
settings.show(getSupportFragmentManager(), "dialog");
return true;
case R.id.action_unlock_more_bulbs:
if (lastQuerriedInventory == null)
mPlayHelper.queryInventoryAsync(mGotInventoryListener);
else {
if (!lastQuerriedInventory
.hasPurchase(PlayItems.FIVE_BULB_UNLOCK_1))
mPlayHelper.launchPurchaseFlow(this,
PlayItems.FIVE_BULB_UNLOCK_1, 10001,
mPurchaseFinishedListener, "");
else if (!lastQuerriedInventory
.hasPurchase(PlayItems.FIVE_BULB_UNLOCK_2))
mPlayHelper.launchPurchaseFlow(this,
PlayItems.FIVE_BULB_UNLOCK_2, 10002,
mPurchaseFinishedListener, "");
else if (!lastQuerriedInventory
.hasPurchase(PlayItems.FIVE_BULB_UNLOCK_3))
mPlayHelper.launchPurchaseFlow(this,
PlayItems.FIVE_BULB_UNLOCK_3, 10003,
mPurchaseFinishedListener, "");
else if (!lastQuerriedInventory
.hasPurchase(PlayItems.FIVE_BULB_UNLOCK_4))
mPlayHelper.launchPurchaseFlow(this,
PlayItems.FIVE_BULB_UNLOCK_4, 10004,
mPurchaseFinishedListener, "");
else if (!lastQuerriedInventory
.hasPurchase(PlayItems.FIVE_BULB_UNLOCK_5))
mPlayHelper.launchPurchaseFlow(this,
PlayItems.FIVE_BULB_UNLOCK_5, 10005,
mPurchaseFinishedListener, "");
else if (!lastQuerriedInventory
.hasPurchase(PlayItems.FIVE_BULB_UNLOCK_6))
mPlayHelper.launchPurchaseFlow(this,
PlayItems.FIVE_BULB_UNLOCK_6, 10006,
mPurchaseFinishedListener, "");
else if (!lastQuerriedInventory
.hasPurchase(PlayItems.FIVE_BULB_UNLOCK_7))
mPlayHelper.launchPurchaseFlow(this,
PlayItems.FIVE_BULB_UNLOCK_7, 10007,
mPurchaseFinishedListener, "");
else if (!lastQuerriedInventory
.hasPurchase(PlayItems.FIVE_BULB_UNLOCK_8))
mPlayHelper.launchPurchaseFlow(this,
PlayItems.FIVE_BULB_UNLOCK_8, 10008,
mPurchaseFinishedListener, "");
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
| app/src/com/kuxhausen/huemore/MainActivity.java | package com.kuxhausen.huemore;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import com.kuxhausen.huemore.billing.IabHelper;
import com.kuxhausen.huemore.billing.IabResult;
import com.kuxhausen.huemore.billing.Inventory;
import com.kuxhausen.huemore.billing.Purchase;
import com.kuxhausen.huemore.database.DatabaseDefinitions;
import com.kuxhausen.huemore.database.DatabaseDefinitions.PlayItems;
import com.kuxhausen.huemore.database.DatabaseHelper;
import com.kuxhausen.huemore.database.DatabaseDefinitions.GroupColumns;
import com.kuxhausen.huemore.database.DatabaseDefinitions.MoodColumns;
import com.kuxhausen.huemore.database.DatabaseDefinitions.PreferencesKeys;
import com.kuxhausen.huemore.network.GetBulbList;
import com.kuxhausen.huemore.network.TransmitGroupMood;
import com.kuxhausen.huemore.ui.registration.RegisterWithHubDialogFragment;
/**
* @author Eric Kuxhausen
*
*/
public class MainActivity extends FragmentActivity implements
GroupBulbPagingFragment.OnBulbGroupSelectedListener,
MoodsFragment.OnMoodSelectedListener {
DatabaseHelper databaseHelper = new DatabaseHelper(this);
Integer[] bulbS;
String mood;
IabHelper mPlayHelper;
MainActivity m;
Inventory lastQuerriedInventory;
public GetBulbList.OnBulbListReturnedListener bulbListenerFragment;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hue_more);
m = this;
// Check whether the activity is using the layout version with
// the fragment_container FrameLayout. If so, we must add the first
// fragment
if (findViewById(R.id.fragment_container) != null) {
// However, if we're being restored from a previous state,
// then we don't need to do anything and should return or else
// we could end up with overlapping fragments.
if (savedInstanceState != null) {
return;
}
// Create an instance of ExampleFragment
GroupBulbPagingFragment firstFragment = new GroupBulbPagingFragment();
// GroupsFragment firstFragment = new GroupsFragment();
// In case this activity was started with special instructions from
// an Intent,
// pass the Intent's extras to the fragment as arguments
firstFragment.setArguments(getIntent().getExtras());
// Add the fragment to the 'fragment_container' FrameLayout
getSupportFragmentManager()
.beginTransaction()
.add(R.id.fragment_container, firstFragment,
GroupBulbPagingFragment.class.getName()).commit();
}
// (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) ?
// this.getActionBar().setDisplayHomeAsUpEnabled(true)
// : System.out.println("wtf");
SharedPreferences settings = PreferenceManager
.getDefaultSharedPreferences(this);
if (!settings.contains(PreferencesKeys.THIRD_UPDATE)) {
databaseHelper.updatedPopulate();
// Mark no longer first update in preferences cache
Editor edit = settings.edit();
edit.putBoolean(PreferencesKeys.THIRD_UPDATE, false);
edit.commit();
}
if (!settings.contains(PreferencesKeys.FIRST_RUN)) {
databaseHelper.initialPopulate();// initialize database
// Mark no longer first run in preferences cache
Editor edit = settings.edit();
edit.putBoolean(PreferencesKeys.FIRST_RUN, false);
edit.putInt(PreferencesKeys.BULBS_UNLOCKED,
PreferencesKeys.ALWAYS_FREE_BULBS);// TODO load from
// google store
edit.commit();
}
if (!settings.contains(PreferencesKeys.DEFAULT_TO_GROUPS)) {
Editor edit = settings.edit();
edit.putBoolean(PreferencesKeys.DEFAULT_TO_GROUPS, false);
edit.commit();
}
if (!settings.contains(PreferencesKeys.DEFAULT_TO_MOODS)) {
Editor edit = settings.edit();
edit.putBoolean(PreferencesKeys.DEFAULT_TO_MOODS, true);
edit.commit();
}
// check to see if the bridge IP address is setup yet
if (!settings.contains(PreferencesKeys.BRIDGE_IP_ADDRESS)) {
RegisterWithHubDialogFragment rwhdf = new RegisterWithHubDialogFragment();
rwhdf.show(this.getSupportFragmentManager(), "dialog");
}
String firstChunk = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAgPUhHgGEdnpyPMAWgP3Xw/jHkReU1O0n6d4rtcULxOrVl/hcZlOsVyByMIZY5wMD84gmMXjbz8pFb4RymFTP7Yp8LSEGiw6DOXc7ydNd0lbZ4WtKyDEwwaio1wRbRPxdU7/4JBpMCh9L6geYx6nYLt0ExZEFxULV3dZJpIlEkEYaNGk/64gc0l34yybccYfORrWzu8u+";
String secondChunk = "5YxJ5k1ikIJJ2I7/2Rp5AXkj2dWybmT+AGx83zh8+iMGGawEQerGtso9NUqpyZWU08EO9DcF8r2KnFwjmyWvqJ2JzbqCMNt0A08IGQNOrd16/C/65GE6J/EtsggkNIgQti6jD7zd3b2NAQIDAQAB";
String base64EncodedPublicKey = firstChunk + secondChunk;
// compute your public key and store it in base64EncodedPublicKey
mPlayHelper = new IabHelper(this, base64EncodedPublicKey);
mPlayHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
public void onIabSetupFinished(IabResult result) {
if (!result.isSuccess()) {
// Oh noes, there was a problem.
// Log.d("asdf", "Problem setting up In-app Billing: "+
// result);
} else {
// Hooray, IAB is fully set up!
mPlayHelper.queryInventoryAsync(mGotInventoryListener);
if (m.bulbListenerFragment != null) {
GetBulbList pushGroupMood = new GetBulbList();
pushGroupMood.execute(m, m.bulbListenerFragment);
}
}
}
});
}
// Listener that's called when we finish querying the items and
// subscriptions we own
IabHelper.QueryInventoryFinishedListener mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener() {
public void onQueryInventoryFinished(IabResult result,
Inventory inventory) {
// Log.d("asdf", "Query inventory finished.");
if (result.isFailure()) {
// handle error
return;
} else {
// Log.d("asdf", "Query inventory was successful.");
lastQuerriedInventory = inventory;
int numUnlocked = PreferencesKeys.ALWAYS_FREE_BULBS;
if (inventory.hasPurchase(PlayItems.FIVE_BULB_UNLOCK_1))
numUnlocked += 5;
if (inventory.hasPurchase(PlayItems.FIVE_BULB_UNLOCK_2))
numUnlocked += 5;
if (inventory.hasPurchase(PlayItems.FIVE_BULB_UNLOCK_3))
numUnlocked += 5;
if (inventory.hasPurchase(PlayItems.FIVE_BULB_UNLOCK_4))
numUnlocked += 5;
if (inventory.hasPurchase(PlayItems.FIVE_BULB_UNLOCK_5))
numUnlocked += 5;
if (inventory.hasPurchase(PlayItems.FIVE_BULB_UNLOCK_6))
numUnlocked += 5;
if (inventory.hasPurchase(PlayItems.FIVE_BULB_UNLOCK_7))
numUnlocked += 5;
if (inventory.hasPurchase(PlayItems.FIVE_BULB_UNLOCK_8))
numUnlocked += 5;
if (inventory.hasPurchase(PlayItems.BUY_ME_A_BULB_DONATION_1))
numUnlocked = Math.max(50, numUnlocked);
// update UI accordingly
// Get preferences cache
SharedPreferences settings = PreferenceManager
.getDefaultSharedPreferences(m);
int previousMax = settings.getInt(
PreferencesKeys.BULBS_UNLOCKED,
PreferencesKeys.ALWAYS_FREE_BULBS);
if (numUnlocked > previousMax) {
// Update the number held in settings
Editor edit = settings.edit();
edit.putInt(PreferencesKeys.BULBS_UNLOCKED, numUnlocked);
edit.commit();
databaseHelper.addBulbs(previousMax, numUnlocked);// initialize
// database
}
}
/*
* Check for items we own. Notice that for each purchase, we check
* the developer payload to see if it's correct! See
* verifyDeveloperPayload().
*/
/*
* // Do we have the premium upgrade? Purchase premiumPurchase =
* inventory.getPurchase(SKU_PREMIUM); mIsPremium = (premiumPurchase
* != null && verifyDeveloperPayload(premiumPurchase)); Log.d(TAG,
* "User is " + (mIsPremium ? "PREMIUM" : "NOT PREMIUM"));
*
*
* updateUi(); setWaitScreen(false); Log.d(TAG,
* "Initial inventory query finished; enabling main UI.");
*/
}
};
IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
public void onIabPurchaseFinished(IabResult result, Purchase purchase) {
mPlayHelper.queryInventoryAsync(mGotInventoryListener);
}
};
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void initializeActionBar(Boolean value) {
try {
this.getActionBar().setDisplayHomeAsUpEnabled(value);
} catch (Error e) {
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Log.d(TAG, "onActivityResult(" + requestCode + "," + resultCode + ","
// + data);
// Pass on the activity result to the helper for handling
if (!mPlayHelper.handleActivityResult(requestCode, resultCode, data)) {
// not handled, so handle it ourselves (here's where you'd
// perform any handling of activity results not related to in-app
// billing...
super.onActivityResult(requestCode, resultCode, data);
} else {
// Log.d(TAG, "onActivityResult handled by IABUtil.");
}
}
/** Verifies the developer payload of a purchase. */
boolean verifyDeveloperPayload(Purchase p) {
String payload = p.getDeveloperPayload();
/*
* TODO: verify that the developer payload of the purchase is correct.
* It will be the same one that you sent when initiating the purchase.
*
* WARNING: Locally generating a random string when starting a purchase
* and verifying it here might seem like a good approach, but this will
* fail in the case where the user purchases an item on one device and
* then uses your app on a different device, because on the other device
* you will not have access to the random string you originally
* generated.
*
* So a good developer payload has these characteristics:
*
* 1. If two different users purchase an item, the payload is different
* between them, so that one user's purchase can't be replayed to
* another user.
*
* 2. The payload must be such that you can verify it even when the app
* wasn't the one who initiated the purchase flow (so that items
* purchased by the user on one device work on other devices owned by
* the user).
*
* Using your own server to store and verify developer payloads across
* app installations is recommended.
*/
return true;
}
@Override
public void onDestroy() {
super.onDestroy();
if (mPlayHelper != null)
mPlayHelper.dispose();
mPlayHelper = null;
}
@Override
public void onGroupBulbSelected(Integer[] bulb) {
bulbS = bulb;
// Capture the article fragment from the activity layout
MoodManualPagingFragment moodFrag = (MoodManualPagingFragment) getSupportFragmentManager()
.findFragmentById(R.id.moods_fragment);
if (moodFrag != null) {
// If article frag is available, we're in two-pane layout...
// Call a method in the ArticleFragment to update its content
moodFrag.reset();
} else {
// If the frag is not available, we're in the one-pane layout and
// must swap frags...
// Create fragment and give it an argument for the selected article
MoodManualPagingFragment newFragment = new MoodManualPagingFragment();
FragmentTransaction transaction = getSupportFragmentManager()
.beginTransaction();
transaction
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
// Replace whatever is in the fragment_container view with this
// fragment,
// and add the transaction to the back stack so the user can
// navigate back
transaction.replace(R.id.fragment_container, newFragment,
MoodManualPagingFragment.class.getName());
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
transaction
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
initializeActionBar(true);
}
}
}
@Override
public void onBackPressed() {
super.onBackPressed();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
initializeActionBar(false);
}
}
private void moveToGroupBulb() {
MoodManualPagingFragment moodFrag = (MoodManualPagingFragment) getSupportFragmentManager()
.findFragmentById(R.id.moods_fragment);
if (moodFrag == null || !moodFrag.isVisible()) {
this.onBackPressed();
}
}
@Override
public void onMoodSelected(String moodParam) {
mood = moodParam;
pushMoodGroup();
}
public void onBrightnessChanged(String brightnessState[]) {
TransmitGroupMood pushGroupMood = new TransmitGroupMood();
pushGroupMood.execute(this, bulbS, brightnessState);
}
/*
* test mood by applying to json states array to these bulbs
*
* @param states
*/
/*
* public void testMood(Integer[] bulbs, String[] states) {
* TransmitGroupMood pushGroupMood = new TransmitGroupMood();
* pushGroupMood.execute(this, bulbs, states); }
*/
/**
* test mood by applying to json states array to previously selected moods
*
* @param states
*/
public void testMood(String[] states) {
TransmitGroupMood pushGroupMood = new TransmitGroupMood();
pushGroupMood.execute(this, bulbS, states);
}
private void pushMoodGroup() {
if (bulbS == null || mood == null)
return;
String[] moodColumns = { MoodColumns.STATE };
String[] mWereClause = { mood };
Cursor cursor = getContentResolver().query(
DatabaseDefinitions.MoodColumns.MOODSTATES_URI, // Use the
// default
// content URI
// for the
// provider.
moodColumns, // Return the note ID and title for each note.
MoodColumns.MOOD + "=?", // selection clause
mWereClause, // election clause args
null // Use the default sort order.
);
ArrayList<String> moodStates = new ArrayList<String>();
while (cursor.moveToNext()) {
moodStates.add(cursor.getString(0));
}
String[] moodS = moodStates.toArray(new String[moodStates.size()]);
TransmitGroupMood pushGroupMood = new TransmitGroupMood();
pushGroupMood.execute(this, bulbS, moodS);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case android.R.id.home:
moveToGroupBulb();
return true;
case R.id.action_register_with_hub:
RegisterWithHubDialogFragment rwhdf = new RegisterWithHubDialogFragment();
rwhdf.show(getSupportFragmentManager(), "dialog");
return true;
case R.id.action_settings:
Settings settings = new Settings();
settings.show(getSupportFragmentManager(), "dialog");
return true;
case R.id.action_unlock_more_bulbs:
if (lastQuerriedInventory == null)
mPlayHelper.queryInventoryAsync(mGotInventoryListener);
else {
if (!lastQuerriedInventory
.hasPurchase(PlayItems.FIVE_BULB_UNLOCK_1))
mPlayHelper.launchPurchaseFlow(this,
PlayItems.FIVE_BULB_UNLOCK_1, 10001,
mPurchaseFinishedListener, "");
else if (!lastQuerriedInventory
.hasPurchase(PlayItems.FIVE_BULB_UNLOCK_2))
mPlayHelper.launchPurchaseFlow(this,
PlayItems.FIVE_BULB_UNLOCK_2, 10002,
mPurchaseFinishedListener, "");
else if (!lastQuerriedInventory
.hasPurchase(PlayItems.FIVE_BULB_UNLOCK_3))
mPlayHelper.launchPurchaseFlow(this,
PlayItems.FIVE_BULB_UNLOCK_3, 10003,
mPurchaseFinishedListener, "");
else if (!lastQuerriedInventory
.hasPurchase(PlayItems.FIVE_BULB_UNLOCK_4))
mPlayHelper.launchPurchaseFlow(this,
PlayItems.FIVE_BULB_UNLOCK_4, 10004,
mPurchaseFinishedListener, "");
else if (!lastQuerriedInventory
.hasPurchase(PlayItems.FIVE_BULB_UNLOCK_5))
mPlayHelper.launchPurchaseFlow(this,
PlayItems.FIVE_BULB_UNLOCK_5, 10005,
mPurchaseFinishedListener, "");
else if (!lastQuerriedInventory
.hasPurchase(PlayItems.FIVE_BULB_UNLOCK_6))
mPlayHelper.launchPurchaseFlow(this,
PlayItems.FIVE_BULB_UNLOCK_6, 10006,
mPurchaseFinishedListener, "");
else if (!lastQuerriedInventory
.hasPurchase(PlayItems.FIVE_BULB_UNLOCK_7))
mPlayHelper.launchPurchaseFlow(this,
PlayItems.FIVE_BULB_UNLOCK_7, 10007,
mPurchaseFinishedListener, "");
else if (!lastQuerriedInventory
.hasPurchase(PlayItems.FIVE_BULB_UNLOCK_8))
mPlayHelper.launchPurchaseFlow(this,
PlayItems.FIVE_BULB_UNLOCK_8, 10008,
mPurchaseFinishedListener, "");
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
| Fixed activity recreation issue found in testing
| app/src/com/kuxhausen/huemore/MainActivity.java | Fixed activity recreation issue found in testing | <ide><path>pp/src/com/kuxhausen/huemore/MainActivity.java
<ide> import android.preference.PreferenceManager;
<ide> import android.support.v4.app.FragmentActivity;
<ide> import android.support.v4.app.FragmentTransaction;
<add>import android.util.Log;
<ide> import android.view.Menu;
<ide> import android.view.MenuInflater;
<ide> import android.view.MenuItem;
<ide> @Override
<ide> public void onCreate(Bundle savedInstanceState) {
<ide> super.onCreate(savedInstanceState);
<add> Log.d("asdf", "onCreate");
<add>
<ide> setContentView(R.layout.hue_more);
<ide> m = this;
<ide>
<ide> // then we don't need to do anything and should return or else
<ide> // we could end up with overlapping fragments.
<ide> if (savedInstanceState != null) {
<del> return;
<del> }
<add> // return;
<add> }else{
<ide>
<ide> // Create an instance of ExampleFragment
<ide> GroupBulbPagingFragment firstFragment = new GroupBulbPagingFragment();
<ide> .beginTransaction()
<ide> .add(R.id.fragment_container, firstFragment,
<ide> GroupBulbPagingFragment.class.getName()).commit();
<add> }
<ide>
<ide> }
<ide>
<ide> String base64EncodedPublicKey = firstChunk + secondChunk;
<ide> // compute your public key and store it in base64EncodedPublicKey
<ide> mPlayHelper = new IabHelper(this, base64EncodedPublicKey);
<add> Log.d("asdf", "mPlayHelperCreated" + (mPlayHelper !=null));
<ide> mPlayHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
<ide> public void onIabSetupFinished(IabResult result) {
<ide> if (!result.isSuccess()) {
<ide> @Override
<ide> public void onDestroy() {
<ide> super.onDestroy();
<add> Log.d("asdf", "onDestroy");
<ide> if (mPlayHelper != null)
<ide> mPlayHelper.dispose();
<ide> mPlayHelper = null;
<add> Log.d("asdf", "mPlayHelperDestroyed" + (mPlayHelper ==null));
<ide> }
<ide>
<ide> @Override |
|
Java | apache-2.0 | ee28034a8a155406b111813602cb5f4fb3fb1f4d | 0 | zrccxyb62/hadoop,zrccxyb62/hadoop,zrccxyb62/hadoop,zrccxyb62/hadoop,zrccxyb62/hadoop,zrccxyb62/hadoop,zrccxyb62/hadoop | /**
* 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.hadoop.hdfs;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintStream;
import java.io.RandomAccessFile;
import java.io.StringReader;
import java.net.URI;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.EnumSet;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import com.google.common.collect.Lists;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.crypto.CipherSuite;
import org.apache.hadoop.crypto.CryptoProtocolVersion;
import org.apache.hadoop.crypto.key.JavaKeyStoreProvider;
import org.apache.hadoop.crypto.key.KeyProvider;
import org.apache.hadoop.crypto.key.KeyProviderFactory;
import org.apache.hadoop.fs.CommonConfigurationKeysPublic;
import org.apache.hadoop.fs.CreateFlag;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FSTestWrapper;
import org.apache.hadoop.fs.FileContext;
import org.apache.hadoop.fs.FileContextTestWrapper;
import org.apache.hadoop.fs.FileEncryptionInfo;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FileSystemTestHelper;
import org.apache.hadoop.fs.FileSystemTestWrapper;
import org.apache.hadoop.fs.FsShell;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.RemoteIterator;
import org.apache.hadoop.fs.permission.FsAction;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.hdfs.client.CreateEncryptionZoneFlag;
import org.apache.hadoop.hdfs.client.HdfsAdmin;
import org.apache.hadoop.hdfs.protocol.ClientProtocol;
import org.apache.hadoop.hdfs.protocol.EncryptionZone;
import org.apache.hadoop.hdfs.protocol.HdfsFileStatus;
import org.apache.hadoop.hdfs.protocol.LocatedBlocks;
import org.apache.hadoop.hdfs.protocol.HdfsConstants.SafeModeAction;
import org.apache.hadoop.hdfs.server.namenode.EncryptionFaultInjector;
import org.apache.hadoop.hdfs.server.namenode.EncryptionZoneManager;
import org.apache.hadoop.hdfs.server.namenode.FSImageTestUtil;
import org.apache.hadoop.hdfs.server.namenode.NamenodeFsck;
import org.apache.hadoop.hdfs.tools.CryptoAdmin;
import org.apache.hadoop.hdfs.tools.DFSck;
import org.apache.hadoop.hdfs.tools.offlineImageViewer.PBImageXmlWriter;
import org.apache.hadoop.hdfs.web.WebHdfsConstants;
import org.apache.hadoop.hdfs.web.WebHdfsTestUtil;
import org.apache.hadoop.io.EnumSetWritable;
import org.apache.hadoop.security.AccessControlException;
import org.apache.hadoop.security.Credentials;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.security.token.Token;
import org.apache.hadoop.util.ToolRunner;
import org.apache.hadoop.crypto.key.KeyProviderDelegationTokenExtension.DelegationTokenExtension;
import org.apache.hadoop.crypto.key.KeyProviderCryptoExtension.CryptoExtension;
import org.apache.hadoop.io.Text;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.anyObject;
import static org.mockito.Matchers.anyShort;
import static org.mockito.Mockito.withSettings;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.anyString;
import static org.apache.hadoop.fs.CommonConfigurationKeysPublic.FS_TRASH_INTERVAL_KEY;
import static org.apache.hadoop.hdfs.DFSTestUtil.verifyFilesEqual;
import static org.apache.hadoop.test.GenericTestUtils.assertExceptionContains;
import static org.apache.hadoop.test.MetricsAsserts.assertGauge;
import static org.apache.hadoop.test.MetricsAsserts.getMetrics;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.xml.sax.InputSource;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
public class TestEncryptionZones {
protected Configuration conf;
private FileSystemTestHelper fsHelper;
protected MiniDFSCluster cluster;
protected HdfsAdmin dfsAdmin;
protected DistributedFileSystem fs;
private File testRootDir;
protected final String TEST_KEY = "test_key";
private static final String NS_METRICS = "FSNamesystem";
protected FileSystemTestWrapper fsWrapper;
protected FileContextTestWrapper fcWrapper;
protected static final EnumSet< CreateEncryptionZoneFlag > NO_TRASH =
EnumSet.of(CreateEncryptionZoneFlag.NO_TRASH);
protected String getKeyProviderURI() {
return JavaKeyStoreProvider.SCHEME_NAME + "://file" +
new Path(testRootDir.toString(), "test.jks").toUri();
}
@Before
public void setup() throws Exception {
conf = new HdfsConfiguration();
fsHelper = new FileSystemTestHelper();
// Set up java key store
String testRoot = fsHelper.getTestRootDir();
testRootDir = new File(testRoot).getAbsoluteFile();
conf.set(DFSConfigKeys.DFS_ENCRYPTION_KEY_PROVIDER_URI, getKeyProviderURI());
conf.setBoolean(DFSConfigKeys.DFS_NAMENODE_DELEGATION_TOKEN_ALWAYS_USE_KEY, true);
// Lower the batch size for testing
conf.setInt(DFSConfigKeys.DFS_NAMENODE_LIST_ENCRYPTION_ZONES_NUM_RESPONSES,
2);
cluster = new MiniDFSCluster.Builder(conf).numDataNodes(1).build();
Logger.getLogger(EncryptionZoneManager.class).setLevel(Level.TRACE);
fs = cluster.getFileSystem();
fsWrapper = new FileSystemTestWrapper(fs);
fcWrapper = new FileContextTestWrapper(
FileContext.getFileContext(cluster.getURI(), conf));
dfsAdmin = new HdfsAdmin(cluster.getURI(), conf);
setProvider();
// Create a test key
DFSTestUtil.createKey(TEST_KEY, cluster, conf);
}
protected void setProvider() {
// Need to set the client's KeyProvider to the NN's for JKS,
// else the updates do not get flushed properly
fs.getClient().setKeyProvider(cluster.getNameNode().getNamesystem()
.getProvider());
}
@After
public void teardown() {
if (cluster != null) {
cluster.shutdown();
cluster = null;
}
EncryptionFaultInjector.instance = new EncryptionFaultInjector();
}
public void assertNumZones(final int numZones) throws IOException {
RemoteIterator<EncryptionZone> it = dfsAdmin.listEncryptionZones();
int count = 0;
while (it.hasNext()) {
count++;
it.next();
}
assertEquals("Unexpected number of encryption zones!", numZones, count);
}
/**
* Checks that an encryption zone with the specified keyName and path (if not
* null) is present.
*
* @throws IOException if a matching zone could not be found
*/
public void assertZonePresent(String keyName, String path) throws IOException {
final RemoteIterator<EncryptionZone> it = dfsAdmin.listEncryptionZones();
boolean match = false;
while (it.hasNext()) {
EncryptionZone zone = it.next();
boolean matchKey = (keyName == null);
boolean matchPath = (path == null);
if (keyName != null && zone.getKeyName().equals(keyName)) {
matchKey = true;
}
if (path != null && zone.getPath().equals(path)) {
matchPath = true;
}
if (matchKey && matchPath) {
match = true;
break;
}
}
assertTrue("Did not find expected encryption zone with keyName " + keyName +
" path " + path, match
);
}
/**
* Make sure hdfs crypto -createZone command creates a trash directory
* with sticky bits.
* @throws Exception
*/
@Test(timeout = 60000)
public void testTrashStickyBit() throws Exception {
// create an EZ /zones/zone1, make it world writable.
final Path zoneParent = new Path("/zones");
final Path zone1 = new Path(zoneParent, "zone1");
CryptoAdmin cryptoAdmin = new CryptoAdmin(conf);
fsWrapper.mkdir(zone1, FsPermission.getDirDefault(), true);
fsWrapper.setPermission(zone1,
new FsPermission(FsAction.ALL, FsAction.ALL, FsAction.ALL));
String[] cryptoArgv = new String[]{"-createZone", "-keyName", TEST_KEY,
"-path", zone1.toUri().getPath()};
cryptoAdmin.run(cryptoArgv);
// create a file in EZ
final Path ezfile1 = new Path(zone1, "file1");
// Create the encrypted file in zone1
final int len = 8192;
DFSTestUtil.createFile(fs, ezfile1, len, (short) 1, 0xFEED);
// enable trash, delete /zones/zone1/file1,
// which moves the file to
// /zones/zone1/.Trash/$SUPERUSER/Current/zones/zone1/file1
Configuration clientConf = new Configuration(conf);
clientConf.setLong(FS_TRASH_INTERVAL_KEY, 1);
final FsShell shell = new FsShell(clientConf);
String[] argv = new String[]{"-rm", ezfile1.toString()};
int res = ToolRunner.run(shell, argv);
assertEquals("Can't remove a file in EZ as superuser", 0, res);
final Path trashDir = new Path(zone1, FileSystem.TRASH_PREFIX);
assertTrue(fsWrapper.exists(trashDir));
FileStatus trashFileStatus = fsWrapper.getFileStatus(trashDir);
assertTrue(trashFileStatus.getPermission().getStickyBit());
// create a non-privileged user
final UserGroupInformation user = UserGroupInformation.
createUserForTesting("user", new String[] { "mygroup" });
user.doAs(new PrivilegedExceptionAction<Object>() {
@Override
public Object run() throws Exception {
final Path ezfile2 = new Path(zone1, "file2");
final int len = 8192;
// create a file /zones/zone1/file2 in EZ
// this file is owned by user:mygroup
FileSystem fs2 = FileSystem.get(cluster.getConfiguration(0));
DFSTestUtil.createFile(fs2, ezfile2, len, (short) 1, 0xFEED);
// delete /zones/zone1/file2,
// which moves the file to
// /zones/zone1/.Trash/user/Current/zones/zone1/file2
String[] argv = new String[]{"-rm", ezfile2.toString()};
int res = ToolRunner.run(shell, argv);
assertEquals("Can't remove a file in EZ as user:mygroup", 0, res);
return null;
}
});
}
/**
* Make sure hdfs crypto -provisionTrash command creates a trash directory
* with sticky bits.
* @throws Exception
*/
@Test(timeout = 60000)
public void testProvisionTrash() throws Exception {
// create an EZ /zones/zone1
final Path zoneParent = new Path("/zones");
final Path zone1 = new Path(zoneParent, "zone1");
CryptoAdmin cryptoAdmin = new CryptoAdmin(conf);
fsWrapper.mkdir(zone1, FsPermission.getDirDefault(), true);
String[] cryptoArgv = new String[]{"-createZone", "-keyName", TEST_KEY,
"-path", zone1.toUri().getPath()};
cryptoAdmin.run(cryptoArgv);
// remove the trash directory
Configuration clientConf = new Configuration(conf);
clientConf.setLong(FS_TRASH_INTERVAL_KEY, 1);
final FsShell shell = new FsShell(clientConf);
final Path trashDir = new Path(zone1, FileSystem.TRASH_PREFIX);
String[] argv = new String[]{"-rmdir", trashDir.toUri().getPath()};
int res = ToolRunner.run(shell, argv);
assertEquals("Unable to delete trash directory.", 0, res);
assertFalse(fsWrapper.exists(trashDir));
// execute -provisionTrash command option and make sure the trash
// directory has sticky bit.
String[] provisionTrashArgv = new String[]{"-provisionTrash", "-path",
zone1.toUri().getPath()};
cryptoAdmin.run(provisionTrashArgv);
assertTrue(fsWrapper.exists(trashDir));
FileStatus trashFileStatus = fsWrapper.getFileStatus(trashDir);
assertTrue(trashFileStatus.getPermission().getStickyBit());
}
@Test(timeout = 60000)
public void testBasicOperations() throws Exception {
int numZones = 0;
/* Number of EZs should be 0 if no EZ is created */
assertEquals("Unexpected number of encryption zones!", numZones,
cluster.getNamesystem().getNumEncryptionZones());
/* Test failure of create EZ on a directory that doesn't exist. */
final Path zoneParent = new Path("/zones");
final Path zone1 = new Path(zoneParent, "zone1");
try {
dfsAdmin.createEncryptionZone(zone1, TEST_KEY, NO_TRASH);
fail("expected /test doesn't exist");
} catch (IOException e) {
assertExceptionContains("cannot find", e);
}
/* Normal creation of an EZ */
fsWrapper.mkdir(zone1, FsPermission.getDirDefault(), true);
dfsAdmin.createEncryptionZone(zone1, TEST_KEY, NO_TRASH);
assertNumZones(++numZones);
assertZonePresent(null, zone1.toString());
/* Test failure of create EZ on a directory which is already an EZ. */
try {
dfsAdmin.createEncryptionZone(zone1, TEST_KEY, NO_TRASH);
} catch (IOException e) {
assertExceptionContains("is already an encryption zone", e);
}
/* create EZ on parent of an EZ should fail */
try {
dfsAdmin.createEncryptionZone(zoneParent, TEST_KEY, NO_TRASH);
fail("EZ over an EZ");
} catch (IOException e) {
assertExceptionContains("encryption zone for a non-empty directory", e);
}
/* create EZ on a folder with a folder fails */
final Path notEmpty = new Path("/notEmpty");
final Path notEmptyChild = new Path(notEmpty, "child");
fsWrapper.mkdir(notEmptyChild, FsPermission.getDirDefault(), true);
try {
dfsAdmin.createEncryptionZone(notEmpty, TEST_KEY, NO_TRASH);
fail("Created EZ on an non-empty directory with folder");
} catch (IOException e) {
assertExceptionContains("create an encryption zone", e);
}
fsWrapper.delete(notEmptyChild, false);
/* create EZ on a folder with a file fails */
fsWrapper.createFile(notEmptyChild);
try {
dfsAdmin.createEncryptionZone(notEmpty, TEST_KEY, NO_TRASH);
fail("Created EZ on an non-empty directory with file");
} catch (IOException e) {
assertExceptionContains("create an encryption zone", e);
}
/* Test failure of create EZ on a file. */
try {
dfsAdmin.createEncryptionZone(notEmptyChild, TEST_KEY, NO_TRASH);
fail("Created EZ on a file");
} catch (IOException e) {
assertExceptionContains("create an encryption zone for a file.", e);
}
/* Test failure of creating an EZ passing a key that doesn't exist. */
final Path zone2 = new Path("/zone2");
fsWrapper.mkdir(zone2, FsPermission.getDirDefault(), false);
final String myKeyName = "mykeyname";
try {
dfsAdmin.createEncryptionZone(zone2, myKeyName, NO_TRASH);
fail("expected key doesn't exist");
} catch (IOException e) {
assertExceptionContains("doesn't exist.", e);
}
/* Test failure of empty and null key name */
try {
dfsAdmin.createEncryptionZone(zone2, "", NO_TRASH);
fail("created a zone with empty key name");
} catch (IOException e) {
assertExceptionContains("Must specify a key name when creating", e);
}
try {
dfsAdmin.createEncryptionZone(zone2, null, NO_TRASH);
fail("created a zone with null key name");
} catch (IOException e) {
assertExceptionContains("Must specify a key name when creating", e);
}
assertNumZones(1);
/* Test success of creating an EZ when they key exists. */
DFSTestUtil.createKey(myKeyName, cluster, conf);
dfsAdmin.createEncryptionZone(zone2, myKeyName, NO_TRASH);
assertNumZones(++numZones);
assertZonePresent(myKeyName, zone2.toString());
/* Test failure of create encryption zones as a non super user. */
final UserGroupInformation user = UserGroupInformation.
createUserForTesting("user", new String[] { "mygroup" });
final Path nonSuper = new Path("/nonSuper");
fsWrapper.mkdir(nonSuper, FsPermission.getDirDefault(), false);
user.doAs(new PrivilegedExceptionAction<Object>() {
@Override
public Object run() throws Exception {
final HdfsAdmin userAdmin =
new HdfsAdmin(FileSystem.getDefaultUri(conf), conf);
try {
userAdmin.createEncryptionZone(nonSuper, TEST_KEY, NO_TRASH);
fail("createEncryptionZone is superuser-only operation");
} catch (AccessControlException e) {
assertExceptionContains("Superuser privilege is required", e);
}
return null;
}
});
// Test success of creating an encryption zone a few levels down.
Path deepZone = new Path("/d/e/e/p/zone");
fsWrapper.mkdir(deepZone, FsPermission.getDirDefault(), true);
dfsAdmin.createEncryptionZone(deepZone, TEST_KEY, NO_TRASH);
assertNumZones(++numZones);
assertZonePresent(null, deepZone.toString());
// Create and list some zones to test batching of listEZ
for (int i=1; i<6; i++) {
final Path zonePath = new Path("/listZone" + i);
fsWrapper.mkdir(zonePath, FsPermission.getDirDefault(), false);
dfsAdmin.createEncryptionZone(zonePath, TEST_KEY, NO_TRASH);
numZones++;
assertNumZones(numZones);
assertZonePresent(null, zonePath.toString());
}
fs.setSafeMode(SafeModeAction.SAFEMODE_ENTER);
fs.saveNamespace();
fs.setSafeMode(SafeModeAction.SAFEMODE_LEAVE);
cluster.restartNameNode(true);
assertNumZones(numZones);
assertEquals("Unexpected number of encryption zones!", numZones, cluster
.getNamesystem().getNumEncryptionZones());
assertGauge("NumEncryptionZones", numZones, getMetrics(NS_METRICS));
assertZonePresent(null, zone1.toString());
// Verify newly added ez is present after restarting the NameNode
// without persisting the namespace.
Path nonpersistZone = new Path("/nonpersistZone");
fsWrapper.mkdir(nonpersistZone, FsPermission.getDirDefault(), false);
dfsAdmin.createEncryptionZone(nonpersistZone, TEST_KEY, NO_TRASH);
numZones++;
cluster.restartNameNode(true);
assertNumZones(numZones);
assertZonePresent(null, nonpersistZone.toString());
}
@Test(timeout = 60000)
public void testBasicOperationsRootDir() throws Exception {
int numZones = 0;
final Path rootDir = new Path("/");
final Path zone1 = new Path(rootDir, "zone1");
/* Normal creation of an EZ on rootDir */
dfsAdmin.createEncryptionZone(rootDir, TEST_KEY, NO_TRASH);
assertNumZones(++numZones);
assertZonePresent(null, rootDir.toString());
// Verify rootDir ez is present after restarting the NameNode
// and saving/loading from fsimage.
fs.setSafeMode(SafeModeAction.SAFEMODE_ENTER);
fs.saveNamespace();
fs.setSafeMode(SafeModeAction.SAFEMODE_LEAVE);
cluster.restartNameNode(true);
assertNumZones(numZones);
assertZonePresent(null, rootDir.toString());
}
/**
* Test listing encryption zones as a non super user.
*/
@Test(timeout = 60000)
public void testListEncryptionZonesAsNonSuperUser() throws Exception {
final UserGroupInformation user = UserGroupInformation.
createUserForTesting("user", new String[] { "mygroup" });
final Path testRoot = new Path("/tmp/TestEncryptionZones");
final Path superPath = new Path(testRoot, "superuseronly");
final Path allPath = new Path(testRoot, "accessall");
fsWrapper.mkdir(superPath, new FsPermission((short) 0700), true);
dfsAdmin.createEncryptionZone(superPath, TEST_KEY, NO_TRASH);
fsWrapper.mkdir(allPath, new FsPermission((short) 0707), true);
dfsAdmin.createEncryptionZone(allPath, TEST_KEY, NO_TRASH);
user.doAs(new PrivilegedExceptionAction<Object>() {
@Override
public Object run() throws Exception {
final HdfsAdmin userAdmin =
new HdfsAdmin(FileSystem.getDefaultUri(conf), conf);
try {
userAdmin.listEncryptionZones();
} catch (AccessControlException e) {
assertExceptionContains("Superuser privilege is required", e);
}
return null;
}
});
}
/**
* Test getEncryptionZoneForPath as a non super user.
*/
@Test(timeout = 60000)
public void testGetEZAsNonSuperUser() throws Exception {
final UserGroupInformation user = UserGroupInformation.
createUserForTesting("user", new String[] { "mygroup" });
final Path testRoot = new Path("/tmp/TestEncryptionZones");
final Path superPath = new Path(testRoot, "superuseronly");
final Path superPathFile = new Path(superPath, "file1");
final Path allPath = new Path(testRoot, "accessall");
final Path allPathFile = new Path(allPath, "file1");
final Path nonEZDir = new Path(testRoot, "nonEZDir");
final Path nonEZFile = new Path(nonEZDir, "file1");
final Path nonexistent = new Path("/nonexistent");
final int len = 8192;
fsWrapper.mkdir(testRoot, new FsPermission((short) 0777), true);
fsWrapper.mkdir(superPath, new FsPermission((short) 0700), false);
fsWrapper.mkdir(allPath, new FsPermission((short) 0777), false);
fsWrapper.mkdir(nonEZDir, new FsPermission((short) 0777), false);
dfsAdmin.createEncryptionZone(superPath, TEST_KEY, NO_TRASH);
dfsAdmin.createEncryptionZone(allPath, TEST_KEY, NO_TRASH);
dfsAdmin.allowSnapshot(new Path("/"));
final Path newSnap = fs.createSnapshot(new Path("/"));
DFSTestUtil.createFile(fs, superPathFile, len, (short) 1, 0xFEED);
DFSTestUtil.createFile(fs, allPathFile, len, (short) 1, 0xFEED);
DFSTestUtil.createFile(fs, nonEZFile, len, (short) 1, 0xFEED);
user.doAs(new PrivilegedExceptionAction<Object>() {
@Override
public Object run() throws Exception {
final HdfsAdmin userAdmin =
new HdfsAdmin(FileSystem.getDefaultUri(conf), conf);
// Check null arg
try {
userAdmin.getEncryptionZoneForPath(null);
fail("should have thrown NPE");
} catch (NullPointerException e) {
/*
* IWBNI we could use assertExceptionContains, but the NPE that is
* thrown has no message text.
*/
}
// Check operation with accessible paths
assertEquals("expected ez path", allPath.toString(),
userAdmin.getEncryptionZoneForPath(allPath).getPath().
toString());
assertEquals("expected ez path", allPath.toString(),
userAdmin.getEncryptionZoneForPath(allPathFile).getPath().
toString());
// Check operation with inaccessible (lack of permissions) path
try {
userAdmin.getEncryptionZoneForPath(superPathFile);
fail("expected AccessControlException");
} catch (AccessControlException e) {
assertExceptionContains("Permission denied:", e);
}
try {
userAdmin.getEncryptionZoneForPath(nonexistent);
fail("FileNotFoundException should be thrown for a non-existent"
+ " file path");
} catch (FileNotFoundException e) {
assertExceptionContains("Path not found: " + nonexistent, e);
}
// Check operation with non-ez paths
assertNull("expected null for non-ez path",
userAdmin.getEncryptionZoneForPath(nonEZDir));
assertNull("expected null for non-ez path",
userAdmin.getEncryptionZoneForPath(nonEZFile));
// Check operation with snapshots
String snapshottedAllPath = newSnap.toString() + allPath.toString();
assertEquals("expected ez path", allPath.toString(),
userAdmin.getEncryptionZoneForPath(
new Path(snapshottedAllPath)).getPath().toString());
/*
* Delete the file from the non-snapshot and test that it is still ok
* in the ez.
*/
fs.delete(allPathFile, false);
assertEquals("expected ez path", allPath.toString(),
userAdmin.getEncryptionZoneForPath(
new Path(snapshottedAllPath)).getPath().toString());
// Delete the ez and make sure ss's ez is still ok.
fs.delete(allPath, true);
assertEquals("expected ez path", allPath.toString(),
userAdmin.getEncryptionZoneForPath(
new Path(snapshottedAllPath)).getPath().toString());
try {
userAdmin.getEncryptionZoneForPath(allPathFile);
fail("FileNotFoundException should be thrown for a non-existent"
+ " file path");
} catch (FileNotFoundException e) {
assertExceptionContains("Path not found: " + allPathFile, e);
}
try {
userAdmin.getEncryptionZoneForPath(allPath);
fail("FileNotFoundException should be thrown for a non-existent"
+ " file path");
} catch (FileNotFoundException e) {
assertExceptionContains("Path not found: " + allPath, e);
}
return null;
}
});
}
/**
* Test success of Rename EZ on a directory which is already an EZ.
*/
private void doRenameEncryptionZone(FSTestWrapper wrapper) throws Exception {
final Path testRoot = new Path("/tmp/TestEncryptionZones");
final Path pathFoo = new Path(testRoot, "foo");
final Path pathFooBaz = new Path(pathFoo, "baz");
final Path pathFooBazFile = new Path(pathFooBaz, "file");
final Path pathFooBar = new Path(pathFoo, "bar");
final Path pathFooBarFile = new Path(pathFooBar, "file");
final int len = 8192;
wrapper.mkdir(pathFoo, FsPermission.getDirDefault(), true);
dfsAdmin.createEncryptionZone(pathFoo, TEST_KEY, NO_TRASH);
wrapper.mkdir(pathFooBaz, FsPermission.getDirDefault(), true);
DFSTestUtil.createFile(fs, pathFooBazFile, len, (short) 1, 0xFEED);
String contents = DFSTestUtil.readFile(fs, pathFooBazFile);
try {
wrapper.rename(pathFooBaz, testRoot);
} catch (IOException e) {
assertExceptionContains(pathFooBaz.toString() + " can't be moved from" +
" an encryption zone.", e
);
}
// Verify that we can rename dir and files within an encryption zone.
assertTrue(fs.rename(pathFooBaz, pathFooBar));
assertTrue("Rename of dir and file within ez failed",
!wrapper.exists(pathFooBaz) && wrapper.exists(pathFooBar));
assertEquals("Renamed file contents not the same",
contents, DFSTestUtil.readFile(fs, pathFooBarFile));
// Verify that we can rename an EZ root
final Path newFoo = new Path(testRoot, "newfoo");
assertTrue("Rename of EZ root", fs.rename(pathFoo, newFoo));
assertTrue("Rename of EZ root failed",
!wrapper.exists(pathFoo) && wrapper.exists(newFoo));
// Verify that we can't rename an EZ root onto itself
try {
wrapper.rename(newFoo, newFoo);
} catch (IOException e) {
assertExceptionContains("are the same", e);
}
}
@Test(timeout = 60000)
public void testRenameFileSystem() throws Exception {
doRenameEncryptionZone(fsWrapper);
}
@Test(timeout = 60000)
public void testRenameFileContext() throws Exception {
doRenameEncryptionZone(fcWrapper);
}
private FileEncryptionInfo getFileEncryptionInfo(Path path) throws Exception {
LocatedBlocks blocks = fs.getClient().getLocatedBlocks(path.toString(), 0);
return blocks.getFileEncryptionInfo();
}
@Test(timeout = 120000)
public void testReadWrite() throws Exception {
final HdfsAdmin dfsAdmin =
new HdfsAdmin(FileSystem.getDefaultUri(conf), conf);
// Create a base file for comparison
final Path baseFile = new Path("/base");
final int len = 8192;
DFSTestUtil.createFile(fs, baseFile, len, (short) 1, 0xFEED);
// Create the first enc file
final Path zone = new Path("/zone");
fs.mkdirs(zone);
dfsAdmin.createEncryptionZone(zone, TEST_KEY, NO_TRASH);
final Path encFile1 = new Path(zone, "myfile");
DFSTestUtil.createFile(fs, encFile1, len, (short) 1, 0xFEED);
// Read them back in and compare byte-by-byte
verifyFilesEqual(fs, baseFile, encFile1, len);
// Roll the key of the encryption zone
assertNumZones(1);
String keyName = dfsAdmin.listEncryptionZones().next().getKeyName();
cluster.getNamesystem().getProvider().rollNewVersion(keyName);
// Read them back in and compare byte-by-byte
verifyFilesEqual(fs, baseFile, encFile1, len);
// Write a new enc file and validate
final Path encFile2 = new Path(zone, "myfile2");
DFSTestUtil.createFile(fs, encFile2, len, (short) 1, 0xFEED);
// FEInfos should be different
FileEncryptionInfo feInfo1 = getFileEncryptionInfo(encFile1);
FileEncryptionInfo feInfo2 = getFileEncryptionInfo(encFile2);
assertFalse("EDEKs should be different", Arrays
.equals(feInfo1.getEncryptedDataEncryptionKey(),
feInfo2.getEncryptedDataEncryptionKey()));
assertNotEquals("Key was rolled, versions should be different",
feInfo1.getEzKeyVersionName(), feInfo2.getEzKeyVersionName());
// Contents still equal
verifyFilesEqual(fs, encFile1, encFile2, len);
}
@Test(timeout = 120000)
public void testReadWriteUsingWebHdfs() throws Exception {
final HdfsAdmin dfsAdmin =
new HdfsAdmin(FileSystem.getDefaultUri(conf), conf);
final FileSystem webHdfsFs = WebHdfsTestUtil.getWebHdfsFileSystem(conf,
WebHdfsConstants.WEBHDFS_SCHEME);
final Path zone = new Path("/zone");
fs.mkdirs(zone);
dfsAdmin.createEncryptionZone(zone, TEST_KEY, NO_TRASH);
/* Create an unencrypted file for comparison purposes. */
final Path unencFile = new Path("/unenc");
final int len = 8192;
DFSTestUtil.createFile(webHdfsFs, unencFile, len, (short) 1, 0xFEED);
/*
* Create the same file via webhdfs, but this time encrypted. Compare it
* using both webhdfs and DFS.
*/
final Path encFile1 = new Path(zone, "myfile");
DFSTestUtil.createFile(webHdfsFs, encFile1, len, (short) 1, 0xFEED);
verifyFilesEqual(webHdfsFs, unencFile, encFile1, len);
verifyFilesEqual(fs, unencFile, encFile1, len);
/*
* Same thing except this time create the encrypted file using DFS.
*/
final Path encFile2 = new Path(zone, "myfile2");
DFSTestUtil.createFile(fs, encFile2, len, (short) 1, 0xFEED);
verifyFilesEqual(webHdfsFs, unencFile, encFile2, len);
verifyFilesEqual(fs, unencFile, encFile2, len);
/* Verify appending to files works correctly. */
appendOneByte(fs, unencFile);
appendOneByte(webHdfsFs, encFile1);
appendOneByte(fs, encFile2);
verifyFilesEqual(webHdfsFs, unencFile, encFile1, len);
verifyFilesEqual(fs, unencFile, encFile1, len);
verifyFilesEqual(webHdfsFs, unencFile, encFile2, len);
verifyFilesEqual(fs, unencFile, encFile2, len);
}
private void appendOneByte(FileSystem fs, Path p) throws IOException {
final FSDataOutputStream out = fs.append(p);
out.write((byte) 0x123);
out.close();
}
@Test(timeout = 60000)
public void testVersionAndSuiteNegotiation() throws Exception {
final HdfsAdmin dfsAdmin =
new HdfsAdmin(FileSystem.getDefaultUri(conf), conf);
final Path zone = new Path("/zone");
fs.mkdirs(zone);
dfsAdmin.createEncryptionZone(zone, TEST_KEY, NO_TRASH);
// Create a file in an EZ, which should succeed
DFSTestUtil
.createFile(fs, new Path(zone, "success1"), 0, (short) 1, 0xFEED);
// Pass no supported versions, fail
DFSOutputStream.SUPPORTED_CRYPTO_VERSIONS = new CryptoProtocolVersion[] {};
try {
DFSTestUtil.createFile(fs, new Path(zone, "fail"), 0, (short) 1, 0xFEED);
fail("Created a file without specifying a crypto protocol version");
} catch (UnknownCryptoProtocolVersionException e) {
assertExceptionContains("No crypto protocol versions", e);
}
// Pass some unknown versions, fail
DFSOutputStream.SUPPORTED_CRYPTO_VERSIONS = new CryptoProtocolVersion[]
{ CryptoProtocolVersion.UNKNOWN, CryptoProtocolVersion.UNKNOWN };
try {
DFSTestUtil.createFile(fs, new Path(zone, "fail"), 0, (short) 1, 0xFEED);
fail("Created a file without specifying a known crypto protocol version");
} catch (UnknownCryptoProtocolVersionException e) {
assertExceptionContains("No crypto protocol versions", e);
}
// Pass some unknown and a good cipherSuites, success
DFSOutputStream.SUPPORTED_CRYPTO_VERSIONS =
new CryptoProtocolVersion[] {
CryptoProtocolVersion.UNKNOWN,
CryptoProtocolVersion.UNKNOWN,
CryptoProtocolVersion.ENCRYPTION_ZONES };
DFSTestUtil
.createFile(fs, new Path(zone, "success2"), 0, (short) 1, 0xFEED);
DFSOutputStream.SUPPORTED_CRYPTO_VERSIONS =
new CryptoProtocolVersion[] {
CryptoProtocolVersion.ENCRYPTION_ZONES,
CryptoProtocolVersion.UNKNOWN,
CryptoProtocolVersion.UNKNOWN} ;
DFSTestUtil
.createFile(fs, new Path(zone, "success3"), 4096, (short) 1, 0xFEED);
// Check KeyProvider state
// Flushing the KP on the NN, since it caches, and init a test one
cluster.getNamesystem().getProvider().flush();
KeyProvider provider = KeyProviderFactory
.get(new URI(conf.getTrimmed(DFSConfigKeys.DFS_ENCRYPTION_KEY_PROVIDER_URI)),
conf);
List<String> keys = provider.getKeys();
assertEquals("Expected NN to have created one key per zone", 1,
keys.size());
List<KeyProvider.KeyVersion> allVersions = Lists.newArrayList();
for (String key : keys) {
List<KeyProvider.KeyVersion> versions = provider.getKeyVersions(key);
assertEquals("Should only have one key version per key", 1,
versions.size());
allVersions.addAll(versions);
}
// Check that the specified CipherSuite was correctly saved on the NN
for (int i = 2; i <= 3; i++) {
FileEncryptionInfo feInfo =
getFileEncryptionInfo(new Path(zone.toString() +
"/success" + i));
assertEquals(feInfo.getCipherSuite(), CipherSuite.AES_CTR_NOPADDING);
}
DFSClient old = fs.dfs;
try {
testCipherSuiteNegotiation(fs, conf);
} finally {
fs.dfs = old;
}
}
@SuppressWarnings("unchecked")
private static void mockCreate(ClientProtocol mcp,
CipherSuite suite, CryptoProtocolVersion version) throws Exception {
Mockito.doReturn(
new HdfsFileStatus(0, false, 1, 1024, 0, 0, new FsPermission(
(short) 777), "owner", "group", new byte[0], new byte[0],
1010, 0, new FileEncryptionInfo(suite,
version, new byte[suite.getAlgorithmBlockSize()],
new byte[suite.getAlgorithmBlockSize()],
"fakeKey", "fakeVersion"),
(byte) 0))
.when(mcp)
.create(anyString(), (FsPermission) anyObject(), anyString(),
(EnumSetWritable<CreateFlag>) anyObject(), anyBoolean(),
anyShort(), anyLong(), (CryptoProtocolVersion[]) anyObject());
}
// This test only uses mocks. Called from the end of an existing test to
// avoid an extra mini cluster.
private static void testCipherSuiteNegotiation(DistributedFileSystem fs,
Configuration conf) throws Exception {
// Set up mock ClientProtocol to test client-side CipherSuite negotiation
final ClientProtocol mcp = Mockito.mock(ClientProtocol.class);
// Try with an empty conf
final Configuration noCodecConf = new Configuration(conf);
final CipherSuite suite = CipherSuite.AES_CTR_NOPADDING;
final String confKey = CommonConfigurationKeysPublic
.HADOOP_SECURITY_CRYPTO_CODEC_CLASSES_KEY_PREFIX + suite
.getConfigSuffix();
noCodecConf.set(confKey, "");
fs.dfs = new DFSClient(null, mcp, noCodecConf, null);
mockCreate(mcp, suite, CryptoProtocolVersion.ENCRYPTION_ZONES);
try {
fs.create(new Path("/mock"));
fail("Created with no configured codecs!");
} catch (UnknownCipherSuiteException e) {
assertExceptionContains("No configuration found for the cipher", e);
}
// Try create with an UNKNOWN CipherSuite
fs.dfs = new DFSClient(null, mcp, conf, null);
CipherSuite unknown = CipherSuite.UNKNOWN;
unknown.setUnknownValue(989);
mockCreate(mcp, unknown, CryptoProtocolVersion.ENCRYPTION_ZONES);
try {
fs.create(new Path("/mock"));
fail("Created with unknown cipher!");
} catch (IOException e) {
assertExceptionContains("unknown CipherSuite with ID 989", e);
}
}
@Test(timeout = 120000)
public void testCreateEZWithNoProvider() throws Exception {
// Unset the key provider and make sure EZ ops don't work
final Configuration clusterConf = cluster.getConfiguration(0);
clusterConf.unset(DFSConfigKeys.DFS_ENCRYPTION_KEY_PROVIDER_URI);
cluster.restartNameNode(true);
cluster.waitActive();
final Path zone1 = new Path("/zone1");
fsWrapper.mkdir(zone1, FsPermission.getDirDefault(), true);
try {
dfsAdmin.createEncryptionZone(zone1, TEST_KEY, NO_TRASH);
fail("expected exception");
} catch (IOException e) {
assertExceptionContains("since no key provider is available", e);
}
final Path jksPath = new Path(testRootDir.toString(), "test.jks");
clusterConf.set(DFSConfigKeys.DFS_ENCRYPTION_KEY_PROVIDER_URI,
JavaKeyStoreProvider.SCHEME_NAME + "://file" + jksPath.toUri()
);
// Try listing EZs as well
assertNumZones(0);
}
@Test(timeout = 120000)
public void testIsEncryptedMethod() throws Exception {
doTestIsEncryptedMethod(new Path("/"));
doTestIsEncryptedMethod(new Path("/.reserved/raw"));
}
private void doTestIsEncryptedMethod(Path prefix) throws Exception {
try {
dTIEM(prefix);
} finally {
for (FileStatus s : fsWrapper.listStatus(prefix)) {
fsWrapper.delete(s.getPath(), true);
}
}
}
private void dTIEM(Path prefix) throws Exception {
final HdfsAdmin dfsAdmin =
new HdfsAdmin(FileSystem.getDefaultUri(conf), conf);
// Create an unencrypted file to check isEncrypted returns false
final Path baseFile = new Path(prefix, "base");
fsWrapper.createFile(baseFile);
FileStatus stat = fsWrapper.getFileStatus(baseFile);
assertFalse("Expected isEncrypted to return false for " + baseFile,
stat.isEncrypted());
// Create an encrypted file to check isEncrypted returns true
final Path zone = new Path(prefix, "zone");
fsWrapper.mkdir(zone, FsPermission.getDirDefault(), true);
dfsAdmin.createEncryptionZone(zone, TEST_KEY, NO_TRASH);
final Path encFile = new Path(zone, "encfile");
fsWrapper.createFile(encFile);
stat = fsWrapper.getFileStatus(encFile);
assertTrue("Expected isEncrypted to return true for enc file" + encFile,
stat.isEncrypted());
// check that it returns true for an ez root
stat = fsWrapper.getFileStatus(zone);
assertTrue("Expected isEncrypted to return true for ezroot",
stat.isEncrypted());
// check that it returns true for a dir in the ez
final Path zoneSubdir = new Path(zone, "subdir");
fsWrapper.mkdir(zoneSubdir, FsPermission.getDirDefault(), true);
stat = fsWrapper.getFileStatus(zoneSubdir);
assertTrue(
"Expected isEncrypted to return true for ez subdir " + zoneSubdir,
stat.isEncrypted());
// check that it returns false for a non ez dir
final Path nonEzDirPath = new Path(prefix, "nonzone");
fsWrapper.mkdir(nonEzDirPath, FsPermission.getDirDefault(), true);
stat = fsWrapper.getFileStatus(nonEzDirPath);
assertFalse(
"Expected isEncrypted to return false for directory " + nonEzDirPath,
stat.isEncrypted());
// check that it returns true for listings within an ez
FileStatus[] statuses = fsWrapper.listStatus(zone);
for (FileStatus s : statuses) {
assertTrue("Expected isEncrypted to return true for ez stat " + zone,
s.isEncrypted());
}
statuses = fsWrapper.listStatus(encFile);
for (FileStatus s : statuses) {
assertTrue(
"Expected isEncrypted to return true for ez file stat " + encFile,
s.isEncrypted());
}
// check that it returns false for listings outside an ez
statuses = fsWrapper.listStatus(nonEzDirPath);
for (FileStatus s : statuses) {
assertFalse(
"Expected isEncrypted to return false for nonez stat " + nonEzDirPath,
s.isEncrypted());
}
statuses = fsWrapper.listStatus(baseFile);
for (FileStatus s : statuses) {
assertFalse(
"Expected isEncrypted to return false for non ez stat " + baseFile,
s.isEncrypted());
}
}
private class MyInjector extends EncryptionFaultInjector {
int generateCount;
CountDownLatch ready;
CountDownLatch wait;
public MyInjector() {
this.ready = new CountDownLatch(1);
this.wait = new CountDownLatch(1);
}
@Override
public void startFileAfterGenerateKey() throws IOException {
ready.countDown();
try {
wait.await();
} catch (InterruptedException e) {
throw new IOException(e);
}
generateCount++;
}
}
private class CreateFileTask implements Callable<Void> {
private FileSystemTestWrapper fsWrapper;
private Path name;
CreateFileTask(FileSystemTestWrapper fsWrapper, Path name) {
this.fsWrapper = fsWrapper;
this.name = name;
}
@Override
public Void call() throws Exception {
fsWrapper.createFile(name);
return null;
}
}
private class InjectFaultTask implements Callable<Void> {
final Path zone1 = new Path("/zone1");
final Path file = new Path(zone1, "file1");
final ExecutorService executor = Executors.newSingleThreadExecutor();
MyInjector injector;
@Override
public Void call() throws Exception {
// Set up the injector
injector = new MyInjector();
EncryptionFaultInjector.instance = injector;
Future<Void> future =
executor.submit(new CreateFileTask(fsWrapper, file));
injector.ready.await();
// Do the fault
doFault();
// Allow create to proceed
injector.wait.countDown();
future.get();
// Cleanup and postconditions
doCleanup();
return null;
}
public void doFault() throws Exception {}
public void doCleanup() throws Exception {}
}
/**
* Tests the retry logic in startFile. We release the lock while generating
* an EDEK, so tricky things can happen in the intervening time.
*/
@Test(timeout = 120000)
public void testStartFileRetry() throws Exception {
final Path zone1 = new Path("/zone1");
final Path file = new Path(zone1, "file1");
fsWrapper.mkdir(zone1, FsPermission.getDirDefault(), true);
ExecutorService executor = Executors.newSingleThreadExecutor();
// Test when the parent directory becomes an EZ
executor.submit(new InjectFaultTask() {
@Override
public void doFault() throws Exception {
dfsAdmin.createEncryptionZone(zone1, TEST_KEY, NO_TRASH);
}
@Override
public void doCleanup() throws Exception {
assertEquals("Expected a startFile retry", 2, injector.generateCount);
fsWrapper.delete(file, false);
}
}).get();
// Test when the parent directory unbecomes an EZ
executor.submit(new InjectFaultTask() {
@Override
public void doFault() throws Exception {
fsWrapper.delete(zone1, true);
}
@Override
public void doCleanup() throws Exception {
assertEquals("Expected no startFile retries", 1, injector.generateCount);
fsWrapper.delete(file, false);
}
}).get();
// Test when the parent directory becomes a different EZ
fsWrapper.mkdir(zone1, FsPermission.getDirDefault(), true);
final String otherKey = "other_key";
DFSTestUtil.createKey(otherKey, cluster, conf);
dfsAdmin.createEncryptionZone(zone1, TEST_KEY, NO_TRASH);
executor.submit(new InjectFaultTask() {
@Override
public void doFault() throws Exception {
fsWrapper.delete(zone1, true);
fsWrapper.mkdir(zone1, FsPermission.getDirDefault(), true);
dfsAdmin.createEncryptionZone(zone1, otherKey, NO_TRASH);
}
@Override
public void doCleanup() throws Exception {
assertEquals("Expected a startFile retry", 2, injector.generateCount);
fsWrapper.delete(zone1, true);
}
}).get();
// Test that the retry limit leads to an error
fsWrapper.mkdir(zone1, FsPermission.getDirDefault(), true);
final String anotherKey = "another_key";
DFSTestUtil.createKey(anotherKey, cluster, conf);
dfsAdmin.createEncryptionZone(zone1, anotherKey, NO_TRASH);
String keyToUse = otherKey;
MyInjector injector = new MyInjector();
EncryptionFaultInjector.instance = injector;
Future<?> future = executor.submit(new CreateFileTask(fsWrapper, file));
// Flip-flop between two EZs to repeatedly fail
for (int i=0; i<DFSOutputStream.CREATE_RETRY_COUNT+1; i++) {
injector.ready.await();
fsWrapper.delete(zone1, true);
fsWrapper.mkdir(zone1, FsPermission.getDirDefault(), true);
dfsAdmin.createEncryptionZone(zone1, keyToUse, NO_TRASH);
if (keyToUse == otherKey) {
keyToUse = anotherKey;
} else {
keyToUse = otherKey;
}
injector.wait.countDown();
injector = new MyInjector();
EncryptionFaultInjector.instance = injector;
}
try {
future.get();
fail("Expected exception from too many retries");
} catch (ExecutionException e) {
assertExceptionContains(
"Too many retries because of encryption zone operations",
e.getCause());
}
}
/**
* Tests obtaining delegation token from stored key
*/
@Test(timeout = 120000)
public void testDelegationToken() throws Exception {
UserGroupInformation.createRemoteUser("JobTracker");
DistributedFileSystem dfs = cluster.getFileSystem();
KeyProvider keyProvider = Mockito.mock(KeyProvider.class,
withSettings().extraInterfaces(
DelegationTokenExtension.class,
CryptoExtension.class));
Mockito.when(keyProvider.getConf()).thenReturn(conf);
byte[] testIdentifier = "Test identifier for delegation token".getBytes();
Token<?> testToken = new Token(testIdentifier, new byte[0],
new Text(), new Text());
Mockito.when(((DelegationTokenExtension)keyProvider).
addDelegationTokens(anyString(), (Credentials)any())).
thenReturn(new Token<?>[] { testToken });
dfs.getClient().setKeyProvider(keyProvider);
Credentials creds = new Credentials();
final Token<?> tokens[] = dfs.addDelegationTokens("JobTracker", creds);
DistributedFileSystem.LOG.debug("Delegation tokens: " +
Arrays.asList(tokens));
Assert.assertEquals(2, tokens.length);
Assert.assertEquals(tokens[1], testToken);
Assert.assertEquals(1, creds.numberOfTokens());
}
/**
* Test running fsck on a system with encryption zones.
*/
@Test(timeout = 60000)
public void testFsckOnEncryptionZones() throws Exception {
final int len = 8196;
final Path zoneParent = new Path("/zones");
final Path zone1 = new Path(zoneParent, "zone1");
final Path zone1File = new Path(zone1, "file");
fsWrapper.mkdir(zone1, FsPermission.getDirDefault(), true);
dfsAdmin.createEncryptionZone(zone1, TEST_KEY, NO_TRASH);
DFSTestUtil.createFile(fs, zone1File, len, (short) 1, 0xFEED);
ByteArrayOutputStream bStream = new ByteArrayOutputStream();
PrintStream out = new PrintStream(bStream, true);
int errCode = ToolRunner.run(new DFSck(conf, out),
new String[]{ "/" });
assertEquals("Fsck ran with non-zero error code", 0, errCode);
String result = bStream.toString();
assertTrue("Fsck did not return HEALTHY status",
result.contains(NamenodeFsck.HEALTHY_STATUS));
// Run fsck directly on the encryption zone instead of root
errCode = ToolRunner.run(new DFSck(conf, out),
new String[]{ zoneParent.toString() });
assertEquals("Fsck ran with non-zero error code", 0, errCode);
result = bStream.toString();
assertTrue("Fsck did not return HEALTHY status",
result.contains(NamenodeFsck.HEALTHY_STATUS));
}
/**
* Test correctness of successive snapshot creation and deletion
* on a system with encryption zones.
*/
@Test(timeout = 60000)
public void testSnapshotsOnEncryptionZones() throws Exception {
final String TEST_KEY2 = "testkey2";
DFSTestUtil.createKey(TEST_KEY2, cluster, conf);
final int len = 8196;
final Path zoneParent = new Path("/zones");
final Path zone = new Path(zoneParent, "zone");
final Path zoneFile = new Path(zone, "zoneFile");
fsWrapper.mkdir(zone, FsPermission.getDirDefault(), true);
dfsAdmin.allowSnapshot(zoneParent);
dfsAdmin.createEncryptionZone(zone, TEST_KEY, NO_TRASH);
DFSTestUtil.createFile(fs, zoneFile, len, (short) 1, 0xFEED);
String contents = DFSTestUtil.readFile(fs, zoneFile);
final Path snap1 = fs.createSnapshot(zoneParent, "snap1");
final Path snap1Zone = new Path(snap1, zone.getName());
assertEquals("Got unexpected ez path", zone.toString(),
dfsAdmin.getEncryptionZoneForPath(snap1Zone).getPath().toString());
// Now delete the encryption zone, recreate the dir, and take another
// snapshot
fsWrapper.delete(zone, true);
fsWrapper.mkdir(zone, FsPermission.getDirDefault(), true);
final Path snap2 = fs.createSnapshot(zoneParent, "snap2");
final Path snap2Zone = new Path(snap2, zone.getName());
assertNull("Expected null ez path",
dfsAdmin.getEncryptionZoneForPath(snap2Zone));
// Create the encryption zone again
dfsAdmin.createEncryptionZone(zone, TEST_KEY2, NO_TRASH);
final Path snap3 = fs.createSnapshot(zoneParent, "snap3");
final Path snap3Zone = new Path(snap3, zone.getName());
// Check that snap3's EZ has the correct settings
EncryptionZone ezSnap3 = dfsAdmin.getEncryptionZoneForPath(snap3Zone);
assertEquals("Got unexpected ez path", zone.toString(),
ezSnap3.getPath().toString());
assertEquals("Unexpected ez key", TEST_KEY2, ezSnap3.getKeyName());
// Check that older snapshots still have the old EZ settings
EncryptionZone ezSnap1 = dfsAdmin.getEncryptionZoneForPath(snap1Zone);
assertEquals("Got unexpected ez path", zone.toString(),
ezSnap1.getPath().toString());
assertEquals("Unexpected ez key", TEST_KEY, ezSnap1.getKeyName());
// Check that listEZs only shows the current filesystem state
ArrayList<EncryptionZone> listZones = Lists.newArrayList();
RemoteIterator<EncryptionZone> it = dfsAdmin.listEncryptionZones();
while (it.hasNext()) {
listZones.add(it.next());
}
for (EncryptionZone z: listZones) {
System.out.println(z);
}
assertEquals("Did not expect additional encryption zones!", 1,
listZones.size());
EncryptionZone listZone = listZones.get(0);
assertEquals("Got unexpected ez path", zone.toString(),
listZone.getPath().toString());
assertEquals("Unexpected ez key", TEST_KEY2, listZone.getKeyName());
// Verify contents of the snapshotted file
final Path snapshottedZoneFile = new Path(
snap1.toString() + "/" + zone.getName() + "/" + zoneFile.getName());
assertEquals("Contents of snapshotted file have changed unexpectedly",
contents, DFSTestUtil.readFile(fs, snapshottedZoneFile));
// Now delete the snapshots out of order and verify the zones are still
// correct
fs.deleteSnapshot(zoneParent, snap2.getName());
assertEquals("Got unexpected ez path", zone.toString(),
dfsAdmin.getEncryptionZoneForPath(snap1Zone).getPath().toString());
assertEquals("Got unexpected ez path", zone.toString(),
dfsAdmin.getEncryptionZoneForPath(snap3Zone).getPath().toString());
fs.deleteSnapshot(zoneParent, snap1.getName());
assertEquals("Got unexpected ez path", zone.toString(),
dfsAdmin.getEncryptionZoneForPath(snap3Zone).getPath().toString());
}
/**
* Verify symlinks can be created in encryption zones and that
* they function properly when the target is in the same
* or different ez.
*/
@Test(timeout = 60000)
public void testEncryptionZonesWithSymlinks() throws Exception {
// Verify we can create an encryption zone over both link and target
final int len = 8192;
final Path parent = new Path("/parent");
final Path linkParent = new Path(parent, "symdir1");
final Path targetParent = new Path(parent, "symdir2");
final Path link = new Path(linkParent, "link");
final Path target = new Path(targetParent, "target");
fs.mkdirs(parent);
dfsAdmin.createEncryptionZone(parent, TEST_KEY, NO_TRASH);
fs.mkdirs(linkParent);
fs.mkdirs(targetParent);
DFSTestUtil.createFile(fs, target, len, (short)1, 0xFEED);
String content = DFSTestUtil.readFile(fs, target);
fs.createSymlink(target, link, false);
assertEquals("Contents read from link are not the same as target",
content, DFSTestUtil.readFile(fs, link));
fs.delete(parent, true);
// Now let's test when the symlink and target are in different
// encryption zones
fs.mkdirs(linkParent);
fs.mkdirs(targetParent);
dfsAdmin.createEncryptionZone(linkParent, TEST_KEY, NO_TRASH);
dfsAdmin.createEncryptionZone(targetParent, TEST_KEY, NO_TRASH);
DFSTestUtil.createFile(fs, target, len, (short)1, 0xFEED);
content = DFSTestUtil.readFile(fs, target);
fs.createSymlink(target, link, false);
assertEquals("Contents read from link are not the same as target",
content, DFSTestUtil.readFile(fs, link));
fs.delete(link, true);
fs.delete(target, true);
}
@Test(timeout = 60000)
public void testConcatFailsInEncryptionZones() throws Exception {
final int len = 8192;
final Path ez = new Path("/ez");
fs.mkdirs(ez);
dfsAdmin.createEncryptionZone(ez, TEST_KEY, NO_TRASH);
final Path src1 = new Path(ez, "src1");
final Path src2 = new Path(ez, "src2");
final Path target = new Path(ez, "target");
DFSTestUtil.createFile(fs, src1, len, (short)1, 0xFEED);
DFSTestUtil.createFile(fs, src2, len, (short)1, 0xFEED);
DFSTestUtil.createFile(fs, target, len, (short)1, 0xFEED);
try {
fs.concat(target, new Path[] { src1, src2 });
fail("expected concat to throw en exception for files in an ez");
} catch (IOException e) {
assertExceptionContains(
"concat can not be called for files in an encryption zone", e);
}
fs.delete(ez, true);
}
/**
* Test running the OfflineImageViewer on a system with encryption zones.
*/
@Test(timeout = 60000)
public void testOfflineImageViewerOnEncryptionZones() throws Exception {
final int len = 8196;
final Path zoneParent = new Path("/zones");
final Path zone1 = new Path(zoneParent, "zone1");
final Path zone1File = new Path(zone1, "file");
fsWrapper.mkdir(zone1, FsPermission.getDirDefault(), true);
dfsAdmin.createEncryptionZone(zone1, TEST_KEY, NO_TRASH);
DFSTestUtil.createFile(fs, zone1File, len, (short) 1, 0xFEED);
fs.setSafeMode(SafeModeAction.SAFEMODE_ENTER, false);
fs.saveNamespace();
File originalFsimage = FSImageTestUtil.findLatestImageFile(FSImageTestUtil
.getFSImage(cluster.getNameNode()).getStorage().getStorageDir(0));
if (originalFsimage == null) {
throw new RuntimeException("Didn't generate or can't find fsimage");
}
// Run the XML OIV processor
ByteArrayOutputStream output = new ByteArrayOutputStream();
PrintStream pw = new PrintStream(output);
PBImageXmlWriter v = new PBImageXmlWriter(new Configuration(), pw);
v.visit(new RandomAccessFile(originalFsimage, "r"));
final String xml = output.toString();
SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
parser.parse(new InputSource(new StringReader(xml)), new DefaultHandler());
}
/**
* Test creating encryption zone on the root path
*/
@Test(timeout = 60000)
public void testEncryptionZonesOnRootPath() throws Exception {
final int len = 8196;
final Path rootDir = new Path("/");
final Path zoneFile = new Path(rootDir, "file");
final Path rawFile = new Path("/.reserved/raw/file");
dfsAdmin.createEncryptionZone(rootDir, TEST_KEY, NO_TRASH);
DFSTestUtil.createFile(fs, zoneFile, len, (short) 1, 0xFEED);
assertEquals("File can be created on the root encryption zone " +
"with correct length",
len, fs.getFileStatus(zoneFile).getLen());
assertEquals("Root dir is encrypted",
true, fs.getFileStatus(rootDir).isEncrypted());
assertEquals("File is encrypted",
true, fs.getFileStatus(zoneFile).isEncrypted());
DFSTestUtil.verifyFilesNotEqual(fs, zoneFile, rawFile, len);
}
@Test(timeout = 60000)
public void testEncryptionZonesOnRelativePath() throws Exception {
final int len = 8196;
final Path baseDir = new Path("/somewhere/base");
final Path zoneDir = new Path("zone");
final Path zoneFile = new Path("file");
fs.setWorkingDirectory(baseDir);
fs.mkdirs(zoneDir);
dfsAdmin.createEncryptionZone(zoneDir, TEST_KEY, NO_TRASH);
DFSTestUtil.createFile(fs, zoneFile, len, (short) 1, 0xFEED);
assertNumZones(1);
assertZonePresent(TEST_KEY, "/somewhere/base/zone");
assertEquals("Got unexpected ez path", "/somewhere/base/zone", dfsAdmin
.getEncryptionZoneForPath(zoneDir).getPath().toString());
}
@Test(timeout = 60000)
public void testGetEncryptionZoneOnANonExistentZoneFile() throws Exception {
final Path ez = new Path("/ez");
fs.mkdirs(ez);
dfsAdmin.createEncryptionZone(ez, TEST_KEY, NO_TRASH);
Path zoneFile = new Path(ez, "file");
try {
fs.getEZForPath(zoneFile);
fail("FileNotFoundException should be thrown for a non-existent"
+ " file path");
} catch (FileNotFoundException e) {
assertExceptionContains("Path not found: " + zoneFile, e);
}
try {
dfsAdmin.getEncryptionZoneForPath(zoneFile);
fail("FileNotFoundException should be thrown for a non-existent"
+ " file path");
} catch (FileNotFoundException e) {
assertExceptionContains("Path not found: " + zoneFile, e);
}
}
@Test(timeout = 120000)
public void testEncryptionZoneWithTrash() throws Exception {
// Create the encryption zone1
final HdfsAdmin dfsAdmin =
new HdfsAdmin(FileSystem.getDefaultUri(conf), conf);
final Path zone1 = new Path("/zone1");
fs.mkdirs(zone1);
dfsAdmin.createEncryptionZone(zone1, TEST_KEY, NO_TRASH);
// Create the encrypted file in zone1
final Path encFile1 = new Path(zone1, "encFile1");
final int len = 8192;
DFSTestUtil.createFile(fs, encFile1, len, (short) 1, 0xFEED);
Configuration clientConf = new Configuration(conf);
clientConf.setLong(FS_TRASH_INTERVAL_KEY, 1);
FsShell shell = new FsShell(clientConf);
// Delete encrypted file from the shell with trash enabled
// Verify the file is moved to appropriate trash within the zone
verifyShellDeleteWithTrash(shell, encFile1);
// Delete encryption zone from the shell with trash enabled
// Verify the zone is moved to appropriate trash location in user's home dir
verifyShellDeleteWithTrash(shell, zone1);
final Path topEZ = new Path("/topEZ");
fs.mkdirs(topEZ);
dfsAdmin.createEncryptionZone(topEZ, TEST_KEY, NO_TRASH);
final String NESTED_EZ_TEST_KEY = "nested_ez_test_key";
DFSTestUtil.createKey(NESTED_EZ_TEST_KEY, cluster, conf);
final Path nestedEZ = new Path(topEZ, "nestedEZ");
fs.mkdirs(nestedEZ);
dfsAdmin.createEncryptionZone(nestedEZ, NESTED_EZ_TEST_KEY, NO_TRASH);
final Path topEZFile = new Path(topEZ, "file");
final Path nestedEZFile = new Path(nestedEZ, "file");
DFSTestUtil.createFile(fs, topEZFile, len, (short) 1, 0xFEED);
DFSTestUtil.createFile(fs, nestedEZFile, len, (short) 1, 0xFEED);
verifyShellDeleteWithTrash(shell, topEZFile);
verifyShellDeleteWithTrash(shell, nestedEZFile);
verifyShellDeleteWithTrash(shell, nestedEZ);
verifyShellDeleteWithTrash(shell, topEZ);
}
@Test(timeout = 120000)
public void testRootDirEZTrash() throws Exception {
final HdfsAdmin dfsAdmin =
new HdfsAdmin(FileSystem.getDefaultUri(conf), conf);
dfsAdmin.createEncryptionZone(new Path("/"), TEST_KEY, NO_TRASH);
final Path encFile = new Path("/encFile");
final int len = 8192;
DFSTestUtil.createFile(fs, encFile, len, (short) 1, 0xFEED);
Configuration clientConf = new Configuration(conf);
clientConf.setLong(FS_TRASH_INTERVAL_KEY, 1);
FsShell shell = new FsShell(clientConf);
verifyShellDeleteWithTrash(shell, encFile);
}
@Test(timeout = 120000)
public void testGetTrashRoots() throws Exception {
final HdfsAdmin dfsAdmin =
new HdfsAdmin(FileSystem.getDefaultUri(conf), conf);
Path ezRoot1 = new Path("/ez1");
fs.mkdirs(ezRoot1);
dfsAdmin.createEncryptionZone(ezRoot1, TEST_KEY, NO_TRASH);
Path ezRoot2 = new Path("/ez2");
fs.mkdirs(ezRoot2);
dfsAdmin.createEncryptionZone(ezRoot2, TEST_KEY, NO_TRASH);
Path ezRoot3 = new Path("/ez3");
fs.mkdirs(ezRoot3);
dfsAdmin.createEncryptionZone(ezRoot3, TEST_KEY, NO_TRASH);
Collection<FileStatus> trashRootsBegin = fs.getTrashRoots(true);
assertEquals("Unexpected getTrashRoots result", 0, trashRootsBegin.size());
final Path encFile = new Path(ezRoot2, "encFile");
final int len = 8192;
DFSTestUtil.createFile(fs, encFile, len, (short) 1, 0xFEED);
Configuration clientConf = new Configuration(conf);
clientConf.setLong(FS_TRASH_INTERVAL_KEY, 1);
FsShell shell = new FsShell(clientConf);
verifyShellDeleteWithTrash(shell, encFile);
Collection<FileStatus> trashRootsDelete1 = fs.getTrashRoots(true);
assertEquals("Unexpected getTrashRoots result", 1,
trashRootsDelete1.size());
final Path nonEncFile = new Path("/nonEncFile");
DFSTestUtil.createFile(fs, nonEncFile, len, (short) 1, 0xFEED);
verifyShellDeleteWithTrash(shell, nonEncFile);
Collection<FileStatus> trashRootsDelete2 = fs.getTrashRoots(true);
assertEquals("Unexpected getTrashRoots result", 2,
trashRootsDelete2.size());
}
private void verifyShellDeleteWithTrash(FsShell shell, Path path)
throws Exception{
try {
Path trashDir = shell.getCurrentTrashDir(path);
// Verify that trashDir has a path component named ".Trash"
Path checkTrash = trashDir;
while (!checkTrash.isRoot() && !checkTrash.getName().equals(".Trash")) {
checkTrash = checkTrash.getParent();
}
assertEquals("No .Trash component found in trash dir " + trashDir,
".Trash", checkTrash.getName());
final Path trashFile =
new Path(shell.getCurrentTrashDir(path) + "/" + path);
String[] argv = new String[]{"-rm", "-r", path.toString()};
int res = ToolRunner.run(shell, argv);
assertEquals("rm failed", 0, res);
assertTrue("File not in trash : " + trashFile, fs.exists(trashFile));
} catch (IOException ioe) {
fail(ioe.getMessage());
} finally {
if (fs.exists(path)) {
fs.delete(path, true);
}
}
}
}
| hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestEncryptionZones.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.hadoop.hdfs;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintStream;
import java.io.RandomAccessFile;
import java.io.StringReader;
import java.net.URI;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.EnumSet;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import com.google.common.collect.Lists;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.crypto.CipherSuite;
import org.apache.hadoop.crypto.CryptoProtocolVersion;
import org.apache.hadoop.crypto.key.JavaKeyStoreProvider;
import org.apache.hadoop.crypto.key.KeyProvider;
import org.apache.hadoop.crypto.key.KeyProviderFactory;
import org.apache.hadoop.fs.CommonConfigurationKeysPublic;
import org.apache.hadoop.fs.CreateFlag;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FSTestWrapper;
import org.apache.hadoop.fs.FileContext;
import org.apache.hadoop.fs.FileContextTestWrapper;
import org.apache.hadoop.fs.FileEncryptionInfo;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FileSystemTestHelper;
import org.apache.hadoop.fs.FileSystemTestWrapper;
import org.apache.hadoop.fs.FsShell;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.RemoteIterator;
import org.apache.hadoop.fs.permission.FsAction;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.hdfs.client.CreateEncryptionZoneFlag;
import org.apache.hadoop.hdfs.client.HdfsAdmin;
import org.apache.hadoop.hdfs.protocol.ClientProtocol;
import org.apache.hadoop.hdfs.protocol.EncryptionZone;
import org.apache.hadoop.hdfs.protocol.HdfsFileStatus;
import org.apache.hadoop.hdfs.protocol.LocatedBlocks;
import org.apache.hadoop.hdfs.protocol.HdfsConstants.SafeModeAction;
import org.apache.hadoop.hdfs.server.namenode.EncryptionFaultInjector;
import org.apache.hadoop.hdfs.server.namenode.EncryptionZoneManager;
import org.apache.hadoop.hdfs.server.namenode.FSImageTestUtil;
import org.apache.hadoop.hdfs.server.namenode.NamenodeFsck;
import org.apache.hadoop.hdfs.tools.CryptoAdmin;
import org.apache.hadoop.hdfs.tools.DFSck;
import org.apache.hadoop.hdfs.tools.offlineImageViewer.PBImageXmlWriter;
import org.apache.hadoop.hdfs.web.WebHdfsConstants;
import org.apache.hadoop.hdfs.web.WebHdfsTestUtil;
import org.apache.hadoop.io.EnumSetWritable;
import org.apache.hadoop.security.AccessControlException;
import org.apache.hadoop.security.Credentials;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.security.token.Token;
import org.apache.hadoop.util.ToolRunner;
import org.apache.hadoop.crypto.key.KeyProviderDelegationTokenExtension.DelegationTokenExtension;
import org.apache.hadoop.crypto.key.KeyProviderCryptoExtension.CryptoExtension;
import org.apache.hadoop.io.Text;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.anyObject;
import static org.mockito.Matchers.anyShort;
import static org.mockito.Mockito.withSettings;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.anyString;
import static org.apache.hadoop.fs.CommonConfigurationKeysPublic.FS_TRASH_INTERVAL_KEY;
import static org.apache.hadoop.hdfs.DFSTestUtil.verifyFilesEqual;
import static org.apache.hadoop.test.GenericTestUtils.assertExceptionContains;
import static org.apache.hadoop.test.MetricsAsserts.assertGauge;
import static org.apache.hadoop.test.MetricsAsserts.getMetrics;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.xml.sax.InputSource;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
public class TestEncryptionZones {
protected Configuration conf;
private FileSystemTestHelper fsHelper;
protected MiniDFSCluster cluster;
protected HdfsAdmin dfsAdmin;
protected DistributedFileSystem fs;
private File testRootDir;
protected final String TEST_KEY = "test_key";
private static final String NS_METRICS = "FSNamesystem";
protected FileSystemTestWrapper fsWrapper;
protected FileContextTestWrapper fcWrapper;
protected static final EnumSet< CreateEncryptionZoneFlag > NO_TRASH =
EnumSet.of(CreateEncryptionZoneFlag.NO_TRASH);
protected String getKeyProviderURI() {
return JavaKeyStoreProvider.SCHEME_NAME + "://file" +
new Path(testRootDir.toString(), "test.jks").toUri();
}
@Before
public void setup() throws Exception {
conf = new HdfsConfiguration();
fsHelper = new FileSystemTestHelper();
// Set up java key store
String testRoot = fsHelper.getTestRootDir();
testRootDir = new File(testRoot).getAbsoluteFile();
conf.set(DFSConfigKeys.DFS_ENCRYPTION_KEY_PROVIDER_URI, getKeyProviderURI());
conf.setBoolean(DFSConfigKeys.DFS_NAMENODE_DELEGATION_TOKEN_ALWAYS_USE_KEY, true);
// Lower the batch size for testing
conf.setInt(DFSConfigKeys.DFS_NAMENODE_LIST_ENCRYPTION_ZONES_NUM_RESPONSES,
2);
cluster = new MiniDFSCluster.Builder(conf).numDataNodes(1).build();
Logger.getLogger(EncryptionZoneManager.class).setLevel(Level.TRACE);
fs = cluster.getFileSystem();
fsWrapper = new FileSystemTestWrapper(fs);
fcWrapper = new FileContextTestWrapper(
FileContext.getFileContext(cluster.getURI(), conf));
dfsAdmin = new HdfsAdmin(cluster.getURI(), conf);
setProvider();
// Create a test key
DFSTestUtil.createKey(TEST_KEY, cluster, conf);
}
protected void setProvider() {
// Need to set the client's KeyProvider to the NN's for JKS,
// else the updates do not get flushed properly
fs.getClient().setKeyProvider(cluster.getNameNode().getNamesystem()
.getProvider());
}
@After
public void teardown() {
if (cluster != null) {
cluster.shutdown();
cluster = null;
}
EncryptionFaultInjector.instance = new EncryptionFaultInjector();
}
public void assertNumZones(final int numZones) throws IOException {
RemoteIterator<EncryptionZone> it = dfsAdmin.listEncryptionZones();
int count = 0;
while (it.hasNext()) {
count++;
it.next();
}
assertEquals("Unexpected number of encryption zones!", numZones, count);
}
/**
* Checks that an encryption zone with the specified keyName and path (if not
* null) is present.
*
* @throws IOException if a matching zone could not be found
*/
public void assertZonePresent(String keyName, String path) throws IOException {
final RemoteIterator<EncryptionZone> it = dfsAdmin.listEncryptionZones();
boolean match = false;
while (it.hasNext()) {
EncryptionZone zone = it.next();
boolean matchKey = (keyName == null);
boolean matchPath = (path == null);
if (keyName != null && zone.getKeyName().equals(keyName)) {
matchKey = true;
}
if (path != null && zone.getPath().equals(path)) {
matchPath = true;
}
if (matchKey && matchPath) {
match = true;
break;
}
}
assertTrue("Did not find expected encryption zone with keyName " + keyName +
" path " + path, match
);
}
/**
* Make sure hdfs crypto -createZone command creates a trash directory
* with sticky bits.
* @throws Exception
*/
@Test(timeout = 60000)
public void testTrashStickyBit() throws Exception {
// create an EZ /zones/zone1, make it world writable.
final Path zoneParent = new Path("/zones");
final Path zone1 = new Path(zoneParent, "zone1");
CryptoAdmin cryptoAdmin = new CryptoAdmin(conf);
fsWrapper.mkdir(zone1, FsPermission.getDirDefault(), true);
fsWrapper.setPermission(zone1,
new FsPermission(FsAction.ALL, FsAction.ALL, FsAction.ALL));
String[] cryptoArgv = new String[]{"-createZone", "-keyName", TEST_KEY,
"-path", zone1.toUri().getPath()};
cryptoAdmin.run(cryptoArgv);
// create a file in EZ
final Path ezfile1 = new Path(zone1, "file1");
// Create the encrypted file in zone1
final int len = 8192;
DFSTestUtil.createFile(fs, ezfile1, len, (short) 1, 0xFEED);
// enable trash, delete /zones/zone1/file1,
// which moves the file to
// /zones/zone1/.Trash/$SUPERUSER/Current/zones/zone1/file1
Configuration clientConf = new Configuration(conf);
clientConf.setLong(FS_TRASH_INTERVAL_KEY, 1);
final FsShell shell = new FsShell(clientConf);
String[] argv = new String[]{"-rm", ezfile1.toString()};
int res = ToolRunner.run(shell, argv);
assertEquals("Can't remove a file in EZ as superuser", 0, res);
final Path trashDir = new Path(zone1, FileSystem.TRASH_PREFIX);
assertTrue(fsWrapper.exists(trashDir));
FileStatus trashFileStatus = fsWrapper.getFileStatus(trashDir);
assertTrue(trashFileStatus.getPermission().getStickyBit());
// create a non-privileged user
final UserGroupInformation user = UserGroupInformation.
createUserForTesting("user", new String[] { "mygroup" });
user.doAs(new PrivilegedExceptionAction<Object>() {
@Override
public Object run() throws Exception {
final Path ezfile2 = new Path(zone1, "file2");
final int len = 8192;
// create a file /zones/zone1/file2 in EZ
// this file is owned by user:mygroup
FileSystem fs2 = FileSystem.get(cluster.getConfiguration(0));
DFSTestUtil.createFile(fs2, ezfile2, len, (short) 1, 0xFEED);
// delete /zones/zone1/file2,
// which moves the file to
// /zones/zone1/.Trash/user/Current/zones/zone1/file2
String[] argv = new String[]{"-rm", ezfile2.toString()};
int res = ToolRunner.run(shell, argv);
assertEquals("Can't remove a file in EZ as user:mygroup", 0, res);
return null;
}
});
}
/**
* Make sure hdfs crypto -provisionTrash command creates a trash directory
* with sticky bits.
* @throws Exception
*/
@Test(timeout = 60000)
public void testProvisionTrash() throws Exception {
// create an EZ /zones/zone1
final Path zoneParent = new Path("/zones");
final Path zone1 = new Path(zoneParent, "zone1");
CryptoAdmin cryptoAdmin = new CryptoAdmin(conf);
fsWrapper.mkdir(zone1, FsPermission.getDirDefault(), true);
String[] cryptoArgv = new String[]{"-createZone", "-keyName", TEST_KEY,
"-path", zone1.toUri().getPath()};
cryptoAdmin.run(cryptoArgv);
// remove the trash directory
Configuration clientConf = new Configuration(conf);
clientConf.setLong(FS_TRASH_INTERVAL_KEY, 1);
final FsShell shell = new FsShell(clientConf);
final Path trashDir = new Path(zone1, FileSystem.TRASH_PREFIX);
String[] argv = new String[]{"-rmdir", trashDir.toUri().getPath()};
int res = ToolRunner.run(shell, argv);
assertEquals("Unable to delete trash directory.", 0, res);
assertFalse(fsWrapper.exists(trashDir));
// execute -provisionTrash command option and make sure the trash
// directory has sticky bit.
String[] provisionTrashArgv = new String[]{"-provisionTrash", "-path",
zone1.toUri().getPath()};
cryptoAdmin.run(provisionTrashArgv);
assertTrue(fsWrapper.exists(trashDir));
FileStatus trashFileStatus = fsWrapper.getFileStatus(trashDir);
assertTrue(trashFileStatus.getPermission().getStickyBit());
}
@Test(timeout = 60000)
public void testBasicOperations() throws Exception {
int numZones = 0;
/* Test failure of create EZ on a directory that doesn't exist. */
final Path zoneParent = new Path("/zones");
final Path zone1 = new Path(zoneParent, "zone1");
try {
dfsAdmin.createEncryptionZone(zone1, TEST_KEY, NO_TRASH);
fail("expected /test doesn't exist");
} catch (IOException e) {
assertExceptionContains("cannot find", e);
}
/* Normal creation of an EZ */
fsWrapper.mkdir(zone1, FsPermission.getDirDefault(), true);
dfsAdmin.createEncryptionZone(zone1, TEST_KEY, NO_TRASH);
assertNumZones(++numZones);
assertZonePresent(null, zone1.toString());
/* Test failure of create EZ on a directory which is already an EZ. */
try {
dfsAdmin.createEncryptionZone(zone1, TEST_KEY, NO_TRASH);
} catch (IOException e) {
assertExceptionContains("is already an encryption zone", e);
}
/* create EZ on parent of an EZ should fail */
try {
dfsAdmin.createEncryptionZone(zoneParent, TEST_KEY, NO_TRASH);
fail("EZ over an EZ");
} catch (IOException e) {
assertExceptionContains("encryption zone for a non-empty directory", e);
}
/* create EZ on a folder with a folder fails */
final Path notEmpty = new Path("/notEmpty");
final Path notEmptyChild = new Path(notEmpty, "child");
fsWrapper.mkdir(notEmptyChild, FsPermission.getDirDefault(), true);
try {
dfsAdmin.createEncryptionZone(notEmpty, TEST_KEY, NO_TRASH);
fail("Created EZ on an non-empty directory with folder");
} catch (IOException e) {
assertExceptionContains("create an encryption zone", e);
}
fsWrapper.delete(notEmptyChild, false);
/* create EZ on a folder with a file fails */
fsWrapper.createFile(notEmptyChild);
try {
dfsAdmin.createEncryptionZone(notEmpty, TEST_KEY, NO_TRASH);
fail("Created EZ on an non-empty directory with file");
} catch (IOException e) {
assertExceptionContains("create an encryption zone", e);
}
/* Test failure of create EZ on a file. */
try {
dfsAdmin.createEncryptionZone(notEmptyChild, TEST_KEY, NO_TRASH);
fail("Created EZ on a file");
} catch (IOException e) {
assertExceptionContains("create an encryption zone for a file.", e);
}
/* Test failure of creating an EZ passing a key that doesn't exist. */
final Path zone2 = new Path("/zone2");
fsWrapper.mkdir(zone2, FsPermission.getDirDefault(), false);
final String myKeyName = "mykeyname";
try {
dfsAdmin.createEncryptionZone(zone2, myKeyName, NO_TRASH);
fail("expected key doesn't exist");
} catch (IOException e) {
assertExceptionContains("doesn't exist.", e);
}
/* Test failure of empty and null key name */
try {
dfsAdmin.createEncryptionZone(zone2, "", NO_TRASH);
fail("created a zone with empty key name");
} catch (IOException e) {
assertExceptionContains("Must specify a key name when creating", e);
}
try {
dfsAdmin.createEncryptionZone(zone2, null, NO_TRASH);
fail("created a zone with null key name");
} catch (IOException e) {
assertExceptionContains("Must specify a key name when creating", e);
}
assertNumZones(1);
/* Test success of creating an EZ when they key exists. */
DFSTestUtil.createKey(myKeyName, cluster, conf);
dfsAdmin.createEncryptionZone(zone2, myKeyName, NO_TRASH);
assertNumZones(++numZones);
assertZonePresent(myKeyName, zone2.toString());
/* Test failure of create encryption zones as a non super user. */
final UserGroupInformation user = UserGroupInformation.
createUserForTesting("user", new String[] { "mygroup" });
final Path nonSuper = new Path("/nonSuper");
fsWrapper.mkdir(nonSuper, FsPermission.getDirDefault(), false);
user.doAs(new PrivilegedExceptionAction<Object>() {
@Override
public Object run() throws Exception {
final HdfsAdmin userAdmin =
new HdfsAdmin(FileSystem.getDefaultUri(conf), conf);
try {
userAdmin.createEncryptionZone(nonSuper, TEST_KEY, NO_TRASH);
fail("createEncryptionZone is superuser-only operation");
} catch (AccessControlException e) {
assertExceptionContains("Superuser privilege is required", e);
}
return null;
}
});
// Test success of creating an encryption zone a few levels down.
Path deepZone = new Path("/d/e/e/p/zone");
fsWrapper.mkdir(deepZone, FsPermission.getDirDefault(), true);
dfsAdmin.createEncryptionZone(deepZone, TEST_KEY, NO_TRASH);
assertNumZones(++numZones);
assertZonePresent(null, deepZone.toString());
// Create and list some zones to test batching of listEZ
for (int i=1; i<6; i++) {
final Path zonePath = new Path("/listZone" + i);
fsWrapper.mkdir(zonePath, FsPermission.getDirDefault(), false);
dfsAdmin.createEncryptionZone(zonePath, TEST_KEY, NO_TRASH);
numZones++;
assertNumZones(numZones);
assertZonePresent(null, zonePath.toString());
}
fs.setSafeMode(SafeModeAction.SAFEMODE_ENTER);
fs.saveNamespace();
fs.setSafeMode(SafeModeAction.SAFEMODE_LEAVE);
cluster.restartNameNode(true);
assertNumZones(numZones);
assertEquals("Unexpected number of encryption zones!", numZones, cluster
.getNamesystem().getNumEncryptionZones());
assertGauge("NumEncryptionZones", numZones, getMetrics(NS_METRICS));
assertZonePresent(null, zone1.toString());
// Verify newly added ez is present after restarting the NameNode
// without persisting the namespace.
Path nonpersistZone = new Path("/nonpersistZone");
fsWrapper.mkdir(nonpersistZone, FsPermission.getDirDefault(), false);
dfsAdmin.createEncryptionZone(nonpersistZone, TEST_KEY, NO_TRASH);
numZones++;
cluster.restartNameNode(true);
assertNumZones(numZones);
assertZonePresent(null, nonpersistZone.toString());
}
@Test(timeout = 60000)
public void testBasicOperationsRootDir() throws Exception {
int numZones = 0;
final Path rootDir = new Path("/");
final Path zone1 = new Path(rootDir, "zone1");
/* Normal creation of an EZ on rootDir */
dfsAdmin.createEncryptionZone(rootDir, TEST_KEY, NO_TRASH);
assertNumZones(++numZones);
assertZonePresent(null, rootDir.toString());
// Verify rootDir ez is present after restarting the NameNode
// and saving/loading from fsimage.
fs.setSafeMode(SafeModeAction.SAFEMODE_ENTER);
fs.saveNamespace();
fs.setSafeMode(SafeModeAction.SAFEMODE_LEAVE);
cluster.restartNameNode(true);
assertNumZones(numZones);
assertZonePresent(null, rootDir.toString());
}
/**
* Test listing encryption zones as a non super user.
*/
@Test(timeout = 60000)
public void testListEncryptionZonesAsNonSuperUser() throws Exception {
final UserGroupInformation user = UserGroupInformation.
createUserForTesting("user", new String[] { "mygroup" });
final Path testRoot = new Path("/tmp/TestEncryptionZones");
final Path superPath = new Path(testRoot, "superuseronly");
final Path allPath = new Path(testRoot, "accessall");
fsWrapper.mkdir(superPath, new FsPermission((short) 0700), true);
dfsAdmin.createEncryptionZone(superPath, TEST_KEY, NO_TRASH);
fsWrapper.mkdir(allPath, new FsPermission((short) 0707), true);
dfsAdmin.createEncryptionZone(allPath, TEST_KEY, NO_TRASH);
user.doAs(new PrivilegedExceptionAction<Object>() {
@Override
public Object run() throws Exception {
final HdfsAdmin userAdmin =
new HdfsAdmin(FileSystem.getDefaultUri(conf), conf);
try {
userAdmin.listEncryptionZones();
} catch (AccessControlException e) {
assertExceptionContains("Superuser privilege is required", e);
}
return null;
}
});
}
/**
* Test getEncryptionZoneForPath as a non super user.
*/
@Test(timeout = 60000)
public void testGetEZAsNonSuperUser() throws Exception {
final UserGroupInformation user = UserGroupInformation.
createUserForTesting("user", new String[] { "mygroup" });
final Path testRoot = new Path("/tmp/TestEncryptionZones");
final Path superPath = new Path(testRoot, "superuseronly");
final Path superPathFile = new Path(superPath, "file1");
final Path allPath = new Path(testRoot, "accessall");
final Path allPathFile = new Path(allPath, "file1");
final Path nonEZDir = new Path(testRoot, "nonEZDir");
final Path nonEZFile = new Path(nonEZDir, "file1");
final Path nonexistent = new Path("/nonexistent");
final int len = 8192;
fsWrapper.mkdir(testRoot, new FsPermission((short) 0777), true);
fsWrapper.mkdir(superPath, new FsPermission((short) 0700), false);
fsWrapper.mkdir(allPath, new FsPermission((short) 0777), false);
fsWrapper.mkdir(nonEZDir, new FsPermission((short) 0777), false);
dfsAdmin.createEncryptionZone(superPath, TEST_KEY, NO_TRASH);
dfsAdmin.createEncryptionZone(allPath, TEST_KEY, NO_TRASH);
dfsAdmin.allowSnapshot(new Path("/"));
final Path newSnap = fs.createSnapshot(new Path("/"));
DFSTestUtil.createFile(fs, superPathFile, len, (short) 1, 0xFEED);
DFSTestUtil.createFile(fs, allPathFile, len, (short) 1, 0xFEED);
DFSTestUtil.createFile(fs, nonEZFile, len, (short) 1, 0xFEED);
user.doAs(new PrivilegedExceptionAction<Object>() {
@Override
public Object run() throws Exception {
final HdfsAdmin userAdmin =
new HdfsAdmin(FileSystem.getDefaultUri(conf), conf);
// Check null arg
try {
userAdmin.getEncryptionZoneForPath(null);
fail("should have thrown NPE");
} catch (NullPointerException e) {
/*
* IWBNI we could use assertExceptionContains, but the NPE that is
* thrown has no message text.
*/
}
// Check operation with accessible paths
assertEquals("expected ez path", allPath.toString(),
userAdmin.getEncryptionZoneForPath(allPath).getPath().
toString());
assertEquals("expected ez path", allPath.toString(),
userAdmin.getEncryptionZoneForPath(allPathFile).getPath().
toString());
// Check operation with inaccessible (lack of permissions) path
try {
userAdmin.getEncryptionZoneForPath(superPathFile);
fail("expected AccessControlException");
} catch (AccessControlException e) {
assertExceptionContains("Permission denied:", e);
}
try {
userAdmin.getEncryptionZoneForPath(nonexistent);
fail("FileNotFoundException should be thrown for a non-existent"
+ " file path");
} catch (FileNotFoundException e) {
assertExceptionContains("Path not found: " + nonexistent, e);
}
// Check operation with non-ez paths
assertNull("expected null for non-ez path",
userAdmin.getEncryptionZoneForPath(nonEZDir));
assertNull("expected null for non-ez path",
userAdmin.getEncryptionZoneForPath(nonEZFile));
// Check operation with snapshots
String snapshottedAllPath = newSnap.toString() + allPath.toString();
assertEquals("expected ez path", allPath.toString(),
userAdmin.getEncryptionZoneForPath(
new Path(snapshottedAllPath)).getPath().toString());
/*
* Delete the file from the non-snapshot and test that it is still ok
* in the ez.
*/
fs.delete(allPathFile, false);
assertEquals("expected ez path", allPath.toString(),
userAdmin.getEncryptionZoneForPath(
new Path(snapshottedAllPath)).getPath().toString());
// Delete the ez and make sure ss's ez is still ok.
fs.delete(allPath, true);
assertEquals("expected ez path", allPath.toString(),
userAdmin.getEncryptionZoneForPath(
new Path(snapshottedAllPath)).getPath().toString());
try {
userAdmin.getEncryptionZoneForPath(allPathFile);
fail("FileNotFoundException should be thrown for a non-existent"
+ " file path");
} catch (FileNotFoundException e) {
assertExceptionContains("Path not found: " + allPathFile, e);
}
try {
userAdmin.getEncryptionZoneForPath(allPath);
fail("FileNotFoundException should be thrown for a non-existent"
+ " file path");
} catch (FileNotFoundException e) {
assertExceptionContains("Path not found: " + allPath, e);
}
return null;
}
});
}
/**
* Test success of Rename EZ on a directory which is already an EZ.
*/
private void doRenameEncryptionZone(FSTestWrapper wrapper) throws Exception {
final Path testRoot = new Path("/tmp/TestEncryptionZones");
final Path pathFoo = new Path(testRoot, "foo");
final Path pathFooBaz = new Path(pathFoo, "baz");
final Path pathFooBazFile = new Path(pathFooBaz, "file");
final Path pathFooBar = new Path(pathFoo, "bar");
final Path pathFooBarFile = new Path(pathFooBar, "file");
final int len = 8192;
wrapper.mkdir(pathFoo, FsPermission.getDirDefault(), true);
dfsAdmin.createEncryptionZone(pathFoo, TEST_KEY, NO_TRASH);
wrapper.mkdir(pathFooBaz, FsPermission.getDirDefault(), true);
DFSTestUtil.createFile(fs, pathFooBazFile, len, (short) 1, 0xFEED);
String contents = DFSTestUtil.readFile(fs, pathFooBazFile);
try {
wrapper.rename(pathFooBaz, testRoot);
} catch (IOException e) {
assertExceptionContains(pathFooBaz.toString() + " can't be moved from" +
" an encryption zone.", e
);
}
// Verify that we can rename dir and files within an encryption zone.
assertTrue(fs.rename(pathFooBaz, pathFooBar));
assertTrue("Rename of dir and file within ez failed",
!wrapper.exists(pathFooBaz) && wrapper.exists(pathFooBar));
assertEquals("Renamed file contents not the same",
contents, DFSTestUtil.readFile(fs, pathFooBarFile));
// Verify that we can rename an EZ root
final Path newFoo = new Path(testRoot, "newfoo");
assertTrue("Rename of EZ root", fs.rename(pathFoo, newFoo));
assertTrue("Rename of EZ root failed",
!wrapper.exists(pathFoo) && wrapper.exists(newFoo));
// Verify that we can't rename an EZ root onto itself
try {
wrapper.rename(newFoo, newFoo);
} catch (IOException e) {
assertExceptionContains("are the same", e);
}
}
@Test(timeout = 60000)
public void testRenameFileSystem() throws Exception {
doRenameEncryptionZone(fsWrapper);
}
@Test(timeout = 60000)
public void testRenameFileContext() throws Exception {
doRenameEncryptionZone(fcWrapper);
}
private FileEncryptionInfo getFileEncryptionInfo(Path path) throws Exception {
LocatedBlocks blocks = fs.getClient().getLocatedBlocks(path.toString(), 0);
return blocks.getFileEncryptionInfo();
}
@Test(timeout = 120000)
public void testReadWrite() throws Exception {
final HdfsAdmin dfsAdmin =
new HdfsAdmin(FileSystem.getDefaultUri(conf), conf);
// Create a base file for comparison
final Path baseFile = new Path("/base");
final int len = 8192;
DFSTestUtil.createFile(fs, baseFile, len, (short) 1, 0xFEED);
// Create the first enc file
final Path zone = new Path("/zone");
fs.mkdirs(zone);
dfsAdmin.createEncryptionZone(zone, TEST_KEY, NO_TRASH);
final Path encFile1 = new Path(zone, "myfile");
DFSTestUtil.createFile(fs, encFile1, len, (short) 1, 0xFEED);
// Read them back in and compare byte-by-byte
verifyFilesEqual(fs, baseFile, encFile1, len);
// Roll the key of the encryption zone
assertNumZones(1);
String keyName = dfsAdmin.listEncryptionZones().next().getKeyName();
cluster.getNamesystem().getProvider().rollNewVersion(keyName);
// Read them back in and compare byte-by-byte
verifyFilesEqual(fs, baseFile, encFile1, len);
// Write a new enc file and validate
final Path encFile2 = new Path(zone, "myfile2");
DFSTestUtil.createFile(fs, encFile2, len, (short) 1, 0xFEED);
// FEInfos should be different
FileEncryptionInfo feInfo1 = getFileEncryptionInfo(encFile1);
FileEncryptionInfo feInfo2 = getFileEncryptionInfo(encFile2);
assertFalse("EDEKs should be different", Arrays
.equals(feInfo1.getEncryptedDataEncryptionKey(),
feInfo2.getEncryptedDataEncryptionKey()));
assertNotEquals("Key was rolled, versions should be different",
feInfo1.getEzKeyVersionName(), feInfo2.getEzKeyVersionName());
// Contents still equal
verifyFilesEqual(fs, encFile1, encFile2, len);
}
@Test(timeout = 120000)
public void testReadWriteUsingWebHdfs() throws Exception {
final HdfsAdmin dfsAdmin =
new HdfsAdmin(FileSystem.getDefaultUri(conf), conf);
final FileSystem webHdfsFs = WebHdfsTestUtil.getWebHdfsFileSystem(conf,
WebHdfsConstants.WEBHDFS_SCHEME);
final Path zone = new Path("/zone");
fs.mkdirs(zone);
dfsAdmin.createEncryptionZone(zone, TEST_KEY, NO_TRASH);
/* Create an unencrypted file for comparison purposes. */
final Path unencFile = new Path("/unenc");
final int len = 8192;
DFSTestUtil.createFile(webHdfsFs, unencFile, len, (short) 1, 0xFEED);
/*
* Create the same file via webhdfs, but this time encrypted. Compare it
* using both webhdfs and DFS.
*/
final Path encFile1 = new Path(zone, "myfile");
DFSTestUtil.createFile(webHdfsFs, encFile1, len, (short) 1, 0xFEED);
verifyFilesEqual(webHdfsFs, unencFile, encFile1, len);
verifyFilesEqual(fs, unencFile, encFile1, len);
/*
* Same thing except this time create the encrypted file using DFS.
*/
final Path encFile2 = new Path(zone, "myfile2");
DFSTestUtil.createFile(fs, encFile2, len, (short) 1, 0xFEED);
verifyFilesEqual(webHdfsFs, unencFile, encFile2, len);
verifyFilesEqual(fs, unencFile, encFile2, len);
/* Verify appending to files works correctly. */
appendOneByte(fs, unencFile);
appendOneByte(webHdfsFs, encFile1);
appendOneByte(fs, encFile2);
verifyFilesEqual(webHdfsFs, unencFile, encFile1, len);
verifyFilesEqual(fs, unencFile, encFile1, len);
verifyFilesEqual(webHdfsFs, unencFile, encFile2, len);
verifyFilesEqual(fs, unencFile, encFile2, len);
}
private void appendOneByte(FileSystem fs, Path p) throws IOException {
final FSDataOutputStream out = fs.append(p);
out.write((byte) 0x123);
out.close();
}
@Test(timeout = 60000)
public void testVersionAndSuiteNegotiation() throws Exception {
final HdfsAdmin dfsAdmin =
new HdfsAdmin(FileSystem.getDefaultUri(conf), conf);
final Path zone = new Path("/zone");
fs.mkdirs(zone);
dfsAdmin.createEncryptionZone(zone, TEST_KEY, NO_TRASH);
// Create a file in an EZ, which should succeed
DFSTestUtil
.createFile(fs, new Path(zone, "success1"), 0, (short) 1, 0xFEED);
// Pass no supported versions, fail
DFSOutputStream.SUPPORTED_CRYPTO_VERSIONS = new CryptoProtocolVersion[] {};
try {
DFSTestUtil.createFile(fs, new Path(zone, "fail"), 0, (short) 1, 0xFEED);
fail("Created a file without specifying a crypto protocol version");
} catch (UnknownCryptoProtocolVersionException e) {
assertExceptionContains("No crypto protocol versions", e);
}
// Pass some unknown versions, fail
DFSOutputStream.SUPPORTED_CRYPTO_VERSIONS = new CryptoProtocolVersion[]
{ CryptoProtocolVersion.UNKNOWN, CryptoProtocolVersion.UNKNOWN };
try {
DFSTestUtil.createFile(fs, new Path(zone, "fail"), 0, (short) 1, 0xFEED);
fail("Created a file without specifying a known crypto protocol version");
} catch (UnknownCryptoProtocolVersionException e) {
assertExceptionContains("No crypto protocol versions", e);
}
// Pass some unknown and a good cipherSuites, success
DFSOutputStream.SUPPORTED_CRYPTO_VERSIONS =
new CryptoProtocolVersion[] {
CryptoProtocolVersion.UNKNOWN,
CryptoProtocolVersion.UNKNOWN,
CryptoProtocolVersion.ENCRYPTION_ZONES };
DFSTestUtil
.createFile(fs, new Path(zone, "success2"), 0, (short) 1, 0xFEED);
DFSOutputStream.SUPPORTED_CRYPTO_VERSIONS =
new CryptoProtocolVersion[] {
CryptoProtocolVersion.ENCRYPTION_ZONES,
CryptoProtocolVersion.UNKNOWN,
CryptoProtocolVersion.UNKNOWN} ;
DFSTestUtil
.createFile(fs, new Path(zone, "success3"), 4096, (short) 1, 0xFEED);
// Check KeyProvider state
// Flushing the KP on the NN, since it caches, and init a test one
cluster.getNamesystem().getProvider().flush();
KeyProvider provider = KeyProviderFactory
.get(new URI(conf.getTrimmed(DFSConfigKeys.DFS_ENCRYPTION_KEY_PROVIDER_URI)),
conf);
List<String> keys = provider.getKeys();
assertEquals("Expected NN to have created one key per zone", 1,
keys.size());
List<KeyProvider.KeyVersion> allVersions = Lists.newArrayList();
for (String key : keys) {
List<KeyProvider.KeyVersion> versions = provider.getKeyVersions(key);
assertEquals("Should only have one key version per key", 1,
versions.size());
allVersions.addAll(versions);
}
// Check that the specified CipherSuite was correctly saved on the NN
for (int i = 2; i <= 3; i++) {
FileEncryptionInfo feInfo =
getFileEncryptionInfo(new Path(zone.toString() +
"/success" + i));
assertEquals(feInfo.getCipherSuite(), CipherSuite.AES_CTR_NOPADDING);
}
DFSClient old = fs.dfs;
try {
testCipherSuiteNegotiation(fs, conf);
} finally {
fs.dfs = old;
}
}
@SuppressWarnings("unchecked")
private static void mockCreate(ClientProtocol mcp,
CipherSuite suite, CryptoProtocolVersion version) throws Exception {
Mockito.doReturn(
new HdfsFileStatus(0, false, 1, 1024, 0, 0, new FsPermission(
(short) 777), "owner", "group", new byte[0], new byte[0],
1010, 0, new FileEncryptionInfo(suite,
version, new byte[suite.getAlgorithmBlockSize()],
new byte[suite.getAlgorithmBlockSize()],
"fakeKey", "fakeVersion"),
(byte) 0))
.when(mcp)
.create(anyString(), (FsPermission) anyObject(), anyString(),
(EnumSetWritable<CreateFlag>) anyObject(), anyBoolean(),
anyShort(), anyLong(), (CryptoProtocolVersion[]) anyObject());
}
// This test only uses mocks. Called from the end of an existing test to
// avoid an extra mini cluster.
private static void testCipherSuiteNegotiation(DistributedFileSystem fs,
Configuration conf) throws Exception {
// Set up mock ClientProtocol to test client-side CipherSuite negotiation
final ClientProtocol mcp = Mockito.mock(ClientProtocol.class);
// Try with an empty conf
final Configuration noCodecConf = new Configuration(conf);
final CipherSuite suite = CipherSuite.AES_CTR_NOPADDING;
final String confKey = CommonConfigurationKeysPublic
.HADOOP_SECURITY_CRYPTO_CODEC_CLASSES_KEY_PREFIX + suite
.getConfigSuffix();
noCodecConf.set(confKey, "");
fs.dfs = new DFSClient(null, mcp, noCodecConf, null);
mockCreate(mcp, suite, CryptoProtocolVersion.ENCRYPTION_ZONES);
try {
fs.create(new Path("/mock"));
fail("Created with no configured codecs!");
} catch (UnknownCipherSuiteException e) {
assertExceptionContains("No configuration found for the cipher", e);
}
// Try create with an UNKNOWN CipherSuite
fs.dfs = new DFSClient(null, mcp, conf, null);
CipherSuite unknown = CipherSuite.UNKNOWN;
unknown.setUnknownValue(989);
mockCreate(mcp, unknown, CryptoProtocolVersion.ENCRYPTION_ZONES);
try {
fs.create(new Path("/mock"));
fail("Created with unknown cipher!");
} catch (IOException e) {
assertExceptionContains("unknown CipherSuite with ID 989", e);
}
}
@Test(timeout = 120000)
public void testCreateEZWithNoProvider() throws Exception {
// Unset the key provider and make sure EZ ops don't work
final Configuration clusterConf = cluster.getConfiguration(0);
clusterConf.unset(DFSConfigKeys.DFS_ENCRYPTION_KEY_PROVIDER_URI);
cluster.restartNameNode(true);
cluster.waitActive();
final Path zone1 = new Path("/zone1");
fsWrapper.mkdir(zone1, FsPermission.getDirDefault(), true);
try {
dfsAdmin.createEncryptionZone(zone1, TEST_KEY, NO_TRASH);
fail("expected exception");
} catch (IOException e) {
assertExceptionContains("since no key provider is available", e);
}
final Path jksPath = new Path(testRootDir.toString(), "test.jks");
clusterConf.set(DFSConfigKeys.DFS_ENCRYPTION_KEY_PROVIDER_URI,
JavaKeyStoreProvider.SCHEME_NAME + "://file" + jksPath.toUri()
);
// Try listing EZs as well
assertNumZones(0);
}
@Test(timeout = 120000)
public void testIsEncryptedMethod() throws Exception {
doTestIsEncryptedMethod(new Path("/"));
doTestIsEncryptedMethod(new Path("/.reserved/raw"));
}
private void doTestIsEncryptedMethod(Path prefix) throws Exception {
try {
dTIEM(prefix);
} finally {
for (FileStatus s : fsWrapper.listStatus(prefix)) {
fsWrapper.delete(s.getPath(), true);
}
}
}
private void dTIEM(Path prefix) throws Exception {
final HdfsAdmin dfsAdmin =
new HdfsAdmin(FileSystem.getDefaultUri(conf), conf);
// Create an unencrypted file to check isEncrypted returns false
final Path baseFile = new Path(prefix, "base");
fsWrapper.createFile(baseFile);
FileStatus stat = fsWrapper.getFileStatus(baseFile);
assertFalse("Expected isEncrypted to return false for " + baseFile,
stat.isEncrypted());
// Create an encrypted file to check isEncrypted returns true
final Path zone = new Path(prefix, "zone");
fsWrapper.mkdir(zone, FsPermission.getDirDefault(), true);
dfsAdmin.createEncryptionZone(zone, TEST_KEY, NO_TRASH);
final Path encFile = new Path(zone, "encfile");
fsWrapper.createFile(encFile);
stat = fsWrapper.getFileStatus(encFile);
assertTrue("Expected isEncrypted to return true for enc file" + encFile,
stat.isEncrypted());
// check that it returns true for an ez root
stat = fsWrapper.getFileStatus(zone);
assertTrue("Expected isEncrypted to return true for ezroot",
stat.isEncrypted());
// check that it returns true for a dir in the ez
final Path zoneSubdir = new Path(zone, "subdir");
fsWrapper.mkdir(zoneSubdir, FsPermission.getDirDefault(), true);
stat = fsWrapper.getFileStatus(zoneSubdir);
assertTrue(
"Expected isEncrypted to return true for ez subdir " + zoneSubdir,
stat.isEncrypted());
// check that it returns false for a non ez dir
final Path nonEzDirPath = new Path(prefix, "nonzone");
fsWrapper.mkdir(nonEzDirPath, FsPermission.getDirDefault(), true);
stat = fsWrapper.getFileStatus(nonEzDirPath);
assertFalse(
"Expected isEncrypted to return false for directory " + nonEzDirPath,
stat.isEncrypted());
// check that it returns true for listings within an ez
FileStatus[] statuses = fsWrapper.listStatus(zone);
for (FileStatus s : statuses) {
assertTrue("Expected isEncrypted to return true for ez stat " + zone,
s.isEncrypted());
}
statuses = fsWrapper.listStatus(encFile);
for (FileStatus s : statuses) {
assertTrue(
"Expected isEncrypted to return true for ez file stat " + encFile,
s.isEncrypted());
}
// check that it returns false for listings outside an ez
statuses = fsWrapper.listStatus(nonEzDirPath);
for (FileStatus s : statuses) {
assertFalse(
"Expected isEncrypted to return false for nonez stat " + nonEzDirPath,
s.isEncrypted());
}
statuses = fsWrapper.listStatus(baseFile);
for (FileStatus s : statuses) {
assertFalse(
"Expected isEncrypted to return false for non ez stat " + baseFile,
s.isEncrypted());
}
}
private class MyInjector extends EncryptionFaultInjector {
int generateCount;
CountDownLatch ready;
CountDownLatch wait;
public MyInjector() {
this.ready = new CountDownLatch(1);
this.wait = new CountDownLatch(1);
}
@Override
public void startFileAfterGenerateKey() throws IOException {
ready.countDown();
try {
wait.await();
} catch (InterruptedException e) {
throw new IOException(e);
}
generateCount++;
}
}
private class CreateFileTask implements Callable<Void> {
private FileSystemTestWrapper fsWrapper;
private Path name;
CreateFileTask(FileSystemTestWrapper fsWrapper, Path name) {
this.fsWrapper = fsWrapper;
this.name = name;
}
@Override
public Void call() throws Exception {
fsWrapper.createFile(name);
return null;
}
}
private class InjectFaultTask implements Callable<Void> {
final Path zone1 = new Path("/zone1");
final Path file = new Path(zone1, "file1");
final ExecutorService executor = Executors.newSingleThreadExecutor();
MyInjector injector;
@Override
public Void call() throws Exception {
// Set up the injector
injector = new MyInjector();
EncryptionFaultInjector.instance = injector;
Future<Void> future =
executor.submit(new CreateFileTask(fsWrapper, file));
injector.ready.await();
// Do the fault
doFault();
// Allow create to proceed
injector.wait.countDown();
future.get();
// Cleanup and postconditions
doCleanup();
return null;
}
public void doFault() throws Exception {}
public void doCleanup() throws Exception {}
}
/**
* Tests the retry logic in startFile. We release the lock while generating
* an EDEK, so tricky things can happen in the intervening time.
*/
@Test(timeout = 120000)
public void testStartFileRetry() throws Exception {
final Path zone1 = new Path("/zone1");
final Path file = new Path(zone1, "file1");
fsWrapper.mkdir(zone1, FsPermission.getDirDefault(), true);
ExecutorService executor = Executors.newSingleThreadExecutor();
// Test when the parent directory becomes an EZ
executor.submit(new InjectFaultTask() {
@Override
public void doFault() throws Exception {
dfsAdmin.createEncryptionZone(zone1, TEST_KEY, NO_TRASH);
}
@Override
public void doCleanup() throws Exception {
assertEquals("Expected a startFile retry", 2, injector.generateCount);
fsWrapper.delete(file, false);
}
}).get();
// Test when the parent directory unbecomes an EZ
executor.submit(new InjectFaultTask() {
@Override
public void doFault() throws Exception {
fsWrapper.delete(zone1, true);
}
@Override
public void doCleanup() throws Exception {
assertEquals("Expected no startFile retries", 1, injector.generateCount);
fsWrapper.delete(file, false);
}
}).get();
// Test when the parent directory becomes a different EZ
fsWrapper.mkdir(zone1, FsPermission.getDirDefault(), true);
final String otherKey = "other_key";
DFSTestUtil.createKey(otherKey, cluster, conf);
dfsAdmin.createEncryptionZone(zone1, TEST_KEY, NO_TRASH);
executor.submit(new InjectFaultTask() {
@Override
public void doFault() throws Exception {
fsWrapper.delete(zone1, true);
fsWrapper.mkdir(zone1, FsPermission.getDirDefault(), true);
dfsAdmin.createEncryptionZone(zone1, otherKey, NO_TRASH);
}
@Override
public void doCleanup() throws Exception {
assertEquals("Expected a startFile retry", 2, injector.generateCount);
fsWrapper.delete(zone1, true);
}
}).get();
// Test that the retry limit leads to an error
fsWrapper.mkdir(zone1, FsPermission.getDirDefault(), true);
final String anotherKey = "another_key";
DFSTestUtil.createKey(anotherKey, cluster, conf);
dfsAdmin.createEncryptionZone(zone1, anotherKey, NO_TRASH);
String keyToUse = otherKey;
MyInjector injector = new MyInjector();
EncryptionFaultInjector.instance = injector;
Future<?> future = executor.submit(new CreateFileTask(fsWrapper, file));
// Flip-flop between two EZs to repeatedly fail
for (int i=0; i<DFSOutputStream.CREATE_RETRY_COUNT+1; i++) {
injector.ready.await();
fsWrapper.delete(zone1, true);
fsWrapper.mkdir(zone1, FsPermission.getDirDefault(), true);
dfsAdmin.createEncryptionZone(zone1, keyToUse, NO_TRASH);
if (keyToUse == otherKey) {
keyToUse = anotherKey;
} else {
keyToUse = otherKey;
}
injector.wait.countDown();
injector = new MyInjector();
EncryptionFaultInjector.instance = injector;
}
try {
future.get();
fail("Expected exception from too many retries");
} catch (ExecutionException e) {
assertExceptionContains(
"Too many retries because of encryption zone operations",
e.getCause());
}
}
/**
* Tests obtaining delegation token from stored key
*/
@Test(timeout = 120000)
public void testDelegationToken() throws Exception {
UserGroupInformation.createRemoteUser("JobTracker");
DistributedFileSystem dfs = cluster.getFileSystem();
KeyProvider keyProvider = Mockito.mock(KeyProvider.class,
withSettings().extraInterfaces(
DelegationTokenExtension.class,
CryptoExtension.class));
Mockito.when(keyProvider.getConf()).thenReturn(conf);
byte[] testIdentifier = "Test identifier for delegation token".getBytes();
Token<?> testToken = new Token(testIdentifier, new byte[0],
new Text(), new Text());
Mockito.when(((DelegationTokenExtension)keyProvider).
addDelegationTokens(anyString(), (Credentials)any())).
thenReturn(new Token<?>[] { testToken });
dfs.getClient().setKeyProvider(keyProvider);
Credentials creds = new Credentials();
final Token<?> tokens[] = dfs.addDelegationTokens("JobTracker", creds);
DistributedFileSystem.LOG.debug("Delegation tokens: " +
Arrays.asList(tokens));
Assert.assertEquals(2, tokens.length);
Assert.assertEquals(tokens[1], testToken);
Assert.assertEquals(1, creds.numberOfTokens());
}
/**
* Test running fsck on a system with encryption zones.
*/
@Test(timeout = 60000)
public void testFsckOnEncryptionZones() throws Exception {
final int len = 8196;
final Path zoneParent = new Path("/zones");
final Path zone1 = new Path(zoneParent, "zone1");
final Path zone1File = new Path(zone1, "file");
fsWrapper.mkdir(zone1, FsPermission.getDirDefault(), true);
dfsAdmin.createEncryptionZone(zone1, TEST_KEY, NO_TRASH);
DFSTestUtil.createFile(fs, zone1File, len, (short) 1, 0xFEED);
ByteArrayOutputStream bStream = new ByteArrayOutputStream();
PrintStream out = new PrintStream(bStream, true);
int errCode = ToolRunner.run(new DFSck(conf, out),
new String[]{ "/" });
assertEquals("Fsck ran with non-zero error code", 0, errCode);
String result = bStream.toString();
assertTrue("Fsck did not return HEALTHY status",
result.contains(NamenodeFsck.HEALTHY_STATUS));
// Run fsck directly on the encryption zone instead of root
errCode = ToolRunner.run(new DFSck(conf, out),
new String[]{ zoneParent.toString() });
assertEquals("Fsck ran with non-zero error code", 0, errCode);
result = bStream.toString();
assertTrue("Fsck did not return HEALTHY status",
result.contains(NamenodeFsck.HEALTHY_STATUS));
}
/**
* Test correctness of successive snapshot creation and deletion
* on a system with encryption zones.
*/
@Test(timeout = 60000)
public void testSnapshotsOnEncryptionZones() throws Exception {
final String TEST_KEY2 = "testkey2";
DFSTestUtil.createKey(TEST_KEY2, cluster, conf);
final int len = 8196;
final Path zoneParent = new Path("/zones");
final Path zone = new Path(zoneParent, "zone");
final Path zoneFile = new Path(zone, "zoneFile");
fsWrapper.mkdir(zone, FsPermission.getDirDefault(), true);
dfsAdmin.allowSnapshot(zoneParent);
dfsAdmin.createEncryptionZone(zone, TEST_KEY, NO_TRASH);
DFSTestUtil.createFile(fs, zoneFile, len, (short) 1, 0xFEED);
String contents = DFSTestUtil.readFile(fs, zoneFile);
final Path snap1 = fs.createSnapshot(zoneParent, "snap1");
final Path snap1Zone = new Path(snap1, zone.getName());
assertEquals("Got unexpected ez path", zone.toString(),
dfsAdmin.getEncryptionZoneForPath(snap1Zone).getPath().toString());
// Now delete the encryption zone, recreate the dir, and take another
// snapshot
fsWrapper.delete(zone, true);
fsWrapper.mkdir(zone, FsPermission.getDirDefault(), true);
final Path snap2 = fs.createSnapshot(zoneParent, "snap2");
final Path snap2Zone = new Path(snap2, zone.getName());
assertNull("Expected null ez path",
dfsAdmin.getEncryptionZoneForPath(snap2Zone));
// Create the encryption zone again
dfsAdmin.createEncryptionZone(zone, TEST_KEY2, NO_TRASH);
final Path snap3 = fs.createSnapshot(zoneParent, "snap3");
final Path snap3Zone = new Path(snap3, zone.getName());
// Check that snap3's EZ has the correct settings
EncryptionZone ezSnap3 = dfsAdmin.getEncryptionZoneForPath(snap3Zone);
assertEquals("Got unexpected ez path", zone.toString(),
ezSnap3.getPath().toString());
assertEquals("Unexpected ez key", TEST_KEY2, ezSnap3.getKeyName());
// Check that older snapshots still have the old EZ settings
EncryptionZone ezSnap1 = dfsAdmin.getEncryptionZoneForPath(snap1Zone);
assertEquals("Got unexpected ez path", zone.toString(),
ezSnap1.getPath().toString());
assertEquals("Unexpected ez key", TEST_KEY, ezSnap1.getKeyName());
// Check that listEZs only shows the current filesystem state
ArrayList<EncryptionZone> listZones = Lists.newArrayList();
RemoteIterator<EncryptionZone> it = dfsAdmin.listEncryptionZones();
while (it.hasNext()) {
listZones.add(it.next());
}
for (EncryptionZone z: listZones) {
System.out.println(z);
}
assertEquals("Did not expect additional encryption zones!", 1,
listZones.size());
EncryptionZone listZone = listZones.get(0);
assertEquals("Got unexpected ez path", zone.toString(),
listZone.getPath().toString());
assertEquals("Unexpected ez key", TEST_KEY2, listZone.getKeyName());
// Verify contents of the snapshotted file
final Path snapshottedZoneFile = new Path(
snap1.toString() + "/" + zone.getName() + "/" + zoneFile.getName());
assertEquals("Contents of snapshotted file have changed unexpectedly",
contents, DFSTestUtil.readFile(fs, snapshottedZoneFile));
// Now delete the snapshots out of order and verify the zones are still
// correct
fs.deleteSnapshot(zoneParent, snap2.getName());
assertEquals("Got unexpected ez path", zone.toString(),
dfsAdmin.getEncryptionZoneForPath(snap1Zone).getPath().toString());
assertEquals("Got unexpected ez path", zone.toString(),
dfsAdmin.getEncryptionZoneForPath(snap3Zone).getPath().toString());
fs.deleteSnapshot(zoneParent, snap1.getName());
assertEquals("Got unexpected ez path", zone.toString(),
dfsAdmin.getEncryptionZoneForPath(snap3Zone).getPath().toString());
}
/**
* Verify symlinks can be created in encryption zones and that
* they function properly when the target is in the same
* or different ez.
*/
@Test(timeout = 60000)
public void testEncryptionZonesWithSymlinks() throws Exception {
// Verify we can create an encryption zone over both link and target
final int len = 8192;
final Path parent = new Path("/parent");
final Path linkParent = new Path(parent, "symdir1");
final Path targetParent = new Path(parent, "symdir2");
final Path link = new Path(linkParent, "link");
final Path target = new Path(targetParent, "target");
fs.mkdirs(parent);
dfsAdmin.createEncryptionZone(parent, TEST_KEY, NO_TRASH);
fs.mkdirs(linkParent);
fs.mkdirs(targetParent);
DFSTestUtil.createFile(fs, target, len, (short)1, 0xFEED);
String content = DFSTestUtil.readFile(fs, target);
fs.createSymlink(target, link, false);
assertEquals("Contents read from link are not the same as target",
content, DFSTestUtil.readFile(fs, link));
fs.delete(parent, true);
// Now let's test when the symlink and target are in different
// encryption zones
fs.mkdirs(linkParent);
fs.mkdirs(targetParent);
dfsAdmin.createEncryptionZone(linkParent, TEST_KEY, NO_TRASH);
dfsAdmin.createEncryptionZone(targetParent, TEST_KEY, NO_TRASH);
DFSTestUtil.createFile(fs, target, len, (short)1, 0xFEED);
content = DFSTestUtil.readFile(fs, target);
fs.createSymlink(target, link, false);
assertEquals("Contents read from link are not the same as target",
content, DFSTestUtil.readFile(fs, link));
fs.delete(link, true);
fs.delete(target, true);
}
@Test(timeout = 60000)
public void testConcatFailsInEncryptionZones() throws Exception {
final int len = 8192;
final Path ez = new Path("/ez");
fs.mkdirs(ez);
dfsAdmin.createEncryptionZone(ez, TEST_KEY, NO_TRASH);
final Path src1 = new Path(ez, "src1");
final Path src2 = new Path(ez, "src2");
final Path target = new Path(ez, "target");
DFSTestUtil.createFile(fs, src1, len, (short)1, 0xFEED);
DFSTestUtil.createFile(fs, src2, len, (short)1, 0xFEED);
DFSTestUtil.createFile(fs, target, len, (short)1, 0xFEED);
try {
fs.concat(target, new Path[] { src1, src2 });
fail("expected concat to throw en exception for files in an ez");
} catch (IOException e) {
assertExceptionContains(
"concat can not be called for files in an encryption zone", e);
}
fs.delete(ez, true);
}
/**
* Test running the OfflineImageViewer on a system with encryption zones.
*/
@Test(timeout = 60000)
public void testOfflineImageViewerOnEncryptionZones() throws Exception {
final int len = 8196;
final Path zoneParent = new Path("/zones");
final Path zone1 = new Path(zoneParent, "zone1");
final Path zone1File = new Path(zone1, "file");
fsWrapper.mkdir(zone1, FsPermission.getDirDefault(), true);
dfsAdmin.createEncryptionZone(zone1, TEST_KEY, NO_TRASH);
DFSTestUtil.createFile(fs, zone1File, len, (short) 1, 0xFEED);
fs.setSafeMode(SafeModeAction.SAFEMODE_ENTER, false);
fs.saveNamespace();
File originalFsimage = FSImageTestUtil.findLatestImageFile(FSImageTestUtil
.getFSImage(cluster.getNameNode()).getStorage().getStorageDir(0));
if (originalFsimage == null) {
throw new RuntimeException("Didn't generate or can't find fsimage");
}
// Run the XML OIV processor
ByteArrayOutputStream output = new ByteArrayOutputStream();
PrintStream pw = new PrintStream(output);
PBImageXmlWriter v = new PBImageXmlWriter(new Configuration(), pw);
v.visit(new RandomAccessFile(originalFsimage, "r"));
final String xml = output.toString();
SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
parser.parse(new InputSource(new StringReader(xml)), new DefaultHandler());
}
/**
* Test creating encryption zone on the root path
*/
@Test(timeout = 60000)
public void testEncryptionZonesOnRootPath() throws Exception {
final int len = 8196;
final Path rootDir = new Path("/");
final Path zoneFile = new Path(rootDir, "file");
final Path rawFile = new Path("/.reserved/raw/file");
dfsAdmin.createEncryptionZone(rootDir, TEST_KEY, NO_TRASH);
DFSTestUtil.createFile(fs, zoneFile, len, (short) 1, 0xFEED);
assertEquals("File can be created on the root encryption zone " +
"with correct length",
len, fs.getFileStatus(zoneFile).getLen());
assertEquals("Root dir is encrypted",
true, fs.getFileStatus(rootDir).isEncrypted());
assertEquals("File is encrypted",
true, fs.getFileStatus(zoneFile).isEncrypted());
DFSTestUtil.verifyFilesNotEqual(fs, zoneFile, rawFile, len);
}
@Test(timeout = 60000)
public void testEncryptionZonesOnRelativePath() throws Exception {
final int len = 8196;
final Path baseDir = new Path("/somewhere/base");
final Path zoneDir = new Path("zone");
final Path zoneFile = new Path("file");
fs.setWorkingDirectory(baseDir);
fs.mkdirs(zoneDir);
dfsAdmin.createEncryptionZone(zoneDir, TEST_KEY, NO_TRASH);
DFSTestUtil.createFile(fs, zoneFile, len, (short) 1, 0xFEED);
assertNumZones(1);
assertZonePresent(TEST_KEY, "/somewhere/base/zone");
assertEquals("Got unexpected ez path", "/somewhere/base/zone", dfsAdmin
.getEncryptionZoneForPath(zoneDir).getPath().toString());
}
@Test(timeout = 60000)
public void testGetEncryptionZoneOnANonExistentZoneFile() throws Exception {
final Path ez = new Path("/ez");
fs.mkdirs(ez);
dfsAdmin.createEncryptionZone(ez, TEST_KEY, NO_TRASH);
Path zoneFile = new Path(ez, "file");
try {
fs.getEZForPath(zoneFile);
fail("FileNotFoundException should be thrown for a non-existent"
+ " file path");
} catch (FileNotFoundException e) {
assertExceptionContains("Path not found: " + zoneFile, e);
}
try {
dfsAdmin.getEncryptionZoneForPath(zoneFile);
fail("FileNotFoundException should be thrown for a non-existent"
+ " file path");
} catch (FileNotFoundException e) {
assertExceptionContains("Path not found: " + zoneFile, e);
}
}
@Test(timeout = 120000)
public void testEncryptionZoneWithTrash() throws Exception {
// Create the encryption zone1
final HdfsAdmin dfsAdmin =
new HdfsAdmin(FileSystem.getDefaultUri(conf), conf);
final Path zone1 = new Path("/zone1");
fs.mkdirs(zone1);
dfsAdmin.createEncryptionZone(zone1, TEST_KEY, NO_TRASH);
// Create the encrypted file in zone1
final Path encFile1 = new Path(zone1, "encFile1");
final int len = 8192;
DFSTestUtil.createFile(fs, encFile1, len, (short) 1, 0xFEED);
Configuration clientConf = new Configuration(conf);
clientConf.setLong(FS_TRASH_INTERVAL_KEY, 1);
FsShell shell = new FsShell(clientConf);
// Delete encrypted file from the shell with trash enabled
// Verify the file is moved to appropriate trash within the zone
verifyShellDeleteWithTrash(shell, encFile1);
// Delete encryption zone from the shell with trash enabled
// Verify the zone is moved to appropriate trash location in user's home dir
verifyShellDeleteWithTrash(shell, zone1);
final Path topEZ = new Path("/topEZ");
fs.mkdirs(topEZ);
dfsAdmin.createEncryptionZone(topEZ, TEST_KEY, NO_TRASH);
final String NESTED_EZ_TEST_KEY = "nested_ez_test_key";
DFSTestUtil.createKey(NESTED_EZ_TEST_KEY, cluster, conf);
final Path nestedEZ = new Path(topEZ, "nestedEZ");
fs.mkdirs(nestedEZ);
dfsAdmin.createEncryptionZone(nestedEZ, NESTED_EZ_TEST_KEY, NO_TRASH);
final Path topEZFile = new Path(topEZ, "file");
final Path nestedEZFile = new Path(nestedEZ, "file");
DFSTestUtil.createFile(fs, topEZFile, len, (short) 1, 0xFEED);
DFSTestUtil.createFile(fs, nestedEZFile, len, (short) 1, 0xFEED);
verifyShellDeleteWithTrash(shell, topEZFile);
verifyShellDeleteWithTrash(shell, nestedEZFile);
verifyShellDeleteWithTrash(shell, nestedEZ);
verifyShellDeleteWithTrash(shell, topEZ);
}
@Test(timeout = 120000)
public void testRootDirEZTrash() throws Exception {
final HdfsAdmin dfsAdmin =
new HdfsAdmin(FileSystem.getDefaultUri(conf), conf);
dfsAdmin.createEncryptionZone(new Path("/"), TEST_KEY, NO_TRASH);
final Path encFile = new Path("/encFile");
final int len = 8192;
DFSTestUtil.createFile(fs, encFile, len, (short) 1, 0xFEED);
Configuration clientConf = new Configuration(conf);
clientConf.setLong(FS_TRASH_INTERVAL_KEY, 1);
FsShell shell = new FsShell(clientConf);
verifyShellDeleteWithTrash(shell, encFile);
}
@Test(timeout = 120000)
public void testGetTrashRoots() throws Exception {
final HdfsAdmin dfsAdmin =
new HdfsAdmin(FileSystem.getDefaultUri(conf), conf);
Path ezRoot1 = new Path("/ez1");
fs.mkdirs(ezRoot1);
dfsAdmin.createEncryptionZone(ezRoot1, TEST_KEY, NO_TRASH);
Path ezRoot2 = new Path("/ez2");
fs.mkdirs(ezRoot2);
dfsAdmin.createEncryptionZone(ezRoot2, TEST_KEY, NO_TRASH);
Path ezRoot3 = new Path("/ez3");
fs.mkdirs(ezRoot3);
dfsAdmin.createEncryptionZone(ezRoot3, TEST_KEY, NO_TRASH);
Collection<FileStatus> trashRootsBegin = fs.getTrashRoots(true);
assertEquals("Unexpected getTrashRoots result", 0, trashRootsBegin.size());
final Path encFile = new Path(ezRoot2, "encFile");
final int len = 8192;
DFSTestUtil.createFile(fs, encFile, len, (short) 1, 0xFEED);
Configuration clientConf = new Configuration(conf);
clientConf.setLong(FS_TRASH_INTERVAL_KEY, 1);
FsShell shell = new FsShell(clientConf);
verifyShellDeleteWithTrash(shell, encFile);
Collection<FileStatus> trashRootsDelete1 = fs.getTrashRoots(true);
assertEquals("Unexpected getTrashRoots result", 1,
trashRootsDelete1.size());
final Path nonEncFile = new Path("/nonEncFile");
DFSTestUtil.createFile(fs, nonEncFile, len, (short) 1, 0xFEED);
verifyShellDeleteWithTrash(shell, nonEncFile);
Collection<FileStatus> trashRootsDelete2 = fs.getTrashRoots(true);
assertEquals("Unexpected getTrashRoots result", 2,
trashRootsDelete2.size());
}
private void verifyShellDeleteWithTrash(FsShell shell, Path path)
throws Exception{
try {
Path trashDir = shell.getCurrentTrashDir(path);
// Verify that trashDir has a path component named ".Trash"
Path checkTrash = trashDir;
while (!checkTrash.isRoot() && !checkTrash.getName().equals(".Trash")) {
checkTrash = checkTrash.getParent();
}
assertEquals("No .Trash component found in trash dir " + trashDir,
".Trash", checkTrash.getName());
final Path trashFile =
new Path(shell.getCurrentTrashDir(path) + "/" + path);
String[] argv = new String[]{"-rm", "-r", path.toString()};
int res = ToolRunner.run(shell, argv);
assertEquals("rm failed", 0, res);
assertTrue("File not in trash : " + trashFile, fs.exists(trashFile));
} catch (IOException ioe) {
fail(ioe.getMessage());
} finally {
if (fs.exists(path)) {
fs.delete(path, true);
}
}
}
}
| HDFS-10814. Add assertion for getNumEncryptionZones when no EZ is created. Contributed by Vinitha Reddy Gankidi.
(cherry picked from commit 4bd45f54eedd449a98a90540698c6ceb47454fec)
| hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestEncryptionZones.java | HDFS-10814. Add assertion for getNumEncryptionZones when no EZ is created. Contributed by Vinitha Reddy Gankidi. | <ide><path>adoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestEncryptionZones.java
<ide> public void testBasicOperations() throws Exception {
<ide>
<ide> int numZones = 0;
<del>
<add> /* Number of EZs should be 0 if no EZ is created */
<add> assertEquals("Unexpected number of encryption zones!", numZones,
<add> cluster.getNamesystem().getNumEncryptionZones());
<ide> /* Test failure of create EZ on a directory that doesn't exist. */
<ide> final Path zoneParent = new Path("/zones");
<ide> final Path zone1 = new Path(zoneParent, "zone1"); |
|
Java | apache-2.0 | 36d280522f56f1dfa99760d0292d60cc8aee9709 | 0 | selckin/wicket,AlienQueen/wicket,dashorst/wicket,klopfdreh/wicket,apache/wicket,topicusonderwijs/wicket,aldaris/wicket,apache/wicket,apache/wicket,mosoft521/wicket,freiheit-com/wicket,selckin/wicket,freiheit-com/wicket,mosoft521/wicket,mosoft521/wicket,mafulafunk/wicket,klopfdreh/wicket,astrapi69/wicket,mafulafunk/wicket,astrapi69/wicket,aldaris/wicket,AlienQueen/wicket,dashorst/wicket,freiheit-com/wicket,mafulafunk/wicket,dashorst/wicket,AlienQueen/wicket,mosoft521/wicket,dashorst/wicket,klopfdreh/wicket,selckin/wicket,bitstorm/wicket,topicusonderwijs/wicket,bitstorm/wicket,aldaris/wicket,dashorst/wicket,selckin/wicket,klopfdreh/wicket,zwsong/wicket,selckin/wicket,aldaris/wicket,AlienQueen/wicket,zwsong/wicket,freiheit-com/wicket,astrapi69/wicket,bitstorm/wicket,freiheit-com/wicket,topicusonderwijs/wicket,aldaris/wicket,zwsong/wicket,AlienQueen/wicket,topicusonderwijs/wicket,topicusonderwijs/wicket,apache/wicket,mosoft521/wicket,apache/wicket,bitstorm/wicket,zwsong/wicket,astrapi69/wicket,klopfdreh/wicket,bitstorm/wicket | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.wicket.markup.head;
import org.apache.wicket.core.util.string.JavaScriptUtils;
import org.apache.wicket.request.Response;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.request.resource.ResourceReference;
import org.apache.wicket.util.lang.Args;
import org.apache.wicket.util.string.Strings;
/**
* Base class for all {@link HeaderItem}s that represent javascripts. This class mainly contains
* factory methods.
*
* @author papegaaij
*/
public abstract class JavaScriptHeaderItem extends HeaderItem
{
/**
* The condition to use for Internet Explorer conditional comments. E.g. "IE 7".
* {@code null} or empty string for no condition.
*/
private final String condition;
protected JavaScriptHeaderItem(String condition)
{
this.condition = condition;
}
/**
* @return the condition to use for Internet Explorer conditional comments. E.g. "IE 7".
*/
public String getCondition()
{
return condition;
}
/**
* Creates a {@link JavaScriptReferenceHeaderItem} for the given reference.
*
* @param reference
* resource reference pointing to the javascript resource
* @return A newly created {@link JavaScriptReferenceHeaderItem} for the given reference.
*/
public static JavaScriptReferenceHeaderItem forReference(ResourceReference reference)
{
return forReference(reference, null);
}
/**
* Creates a {@link JavaScriptReferenceHeaderItem} for the given reference.
*
* @param reference
* resource reference pointing to the javascript resource
* @param id
* id that will be used to filter duplicate reference (it's still filtered by URL
* too)
* @return A newly created {@link JavaScriptReferenceHeaderItem} for the given reference.
*/
public static JavaScriptReferenceHeaderItem forReference(ResourceReference reference, String id)
{
return forReference(reference, null, id);
}
/**
* Creates a {@link JavaScriptReferenceHeaderItem} for the given reference.
*
* @param reference
* resource reference pointing to the javascript resource
* @param pageParameters
* the parameters for this Javascript resource reference
* @param id
* id that will be used to filter duplicate reference (it's still filtered by URL
* too)
* @return A newly created {@link JavaScriptReferenceHeaderItem} for the given reference.
*/
public static JavaScriptReferenceHeaderItem forReference(ResourceReference reference,
PageParameters pageParameters, String id)
{
return forReference(reference, pageParameters, id, false);
}
/**
* Creates a {@link JavaScriptReferenceHeaderItem} for the given reference.
*
* @param reference
* resource reference pointing to the javascript resource
* @param pageParameters
* the parameters for this Javascript resource reference
* @param id
* id that will be used to filter duplicate reference (it's still filtered by URL
* too)
* @param defer
* specifies that the execution of a script should be deferred (delayed) until after
* the page has been loaded.
* @return A newly created {@link JavaScriptReferenceHeaderItem} for the given reference.
*/
public static JavaScriptReferenceHeaderItem forReference(ResourceReference reference,
PageParameters pageParameters, String id, boolean defer)
{
return forReference(reference, pageParameters, id, defer, null);
}
/**
* Creates a {@link JavaScriptReferenceHeaderItem} for the given reference.
*
* @param reference
* resource reference pointing to the JavaScript resource
* @param id
* id that will be used to filter duplicate reference (it's still filtered by URL
* too)
* @param defer
* specifies that the execution of a script should be deferred (delayed) until after
* the page has been loaded.
* @return A newly created {@link JavaScriptReferenceHeaderItem} for the given reference.
*/
public static JavaScriptReferenceHeaderItem forReference(ResourceReference reference,
String id, boolean defer)
{
return forReference(reference, null, id, defer, null);
}
/**
* Creates a {@link JavaScriptReferenceHeaderItem} for the given reference.
*
* @param reference
* resource reference pointing to the JavaScript resource
* @param defer
* specifies that the execution of a script should be deferred (delayed) until after
* the page has been loaded.
* @return A newly created {@link JavaScriptReferenceHeaderItem} for the given reference.
*/
public static JavaScriptReferenceHeaderItem forReference(ResourceReference reference,
boolean defer)
{
return forReference(reference, null, null, defer, null);
}
/**
* Creates a {@link JavaScriptReferenceHeaderItem} for the given reference.
*
* @param reference
* resource reference pointing to the javascript resource
* @param pageParameters
* the parameters for this Javascript resource reference
* @param id
* id that will be used to filter duplicate reference (it's still filtered by URL
* too)
* @param defer
* specifies that the execution of a script should be deferred (delayed) until after
* the page has been loaded.
* @param charset
* a non null value specifies the charset attribute of the script tag
* @return A newly created {@link JavaScriptReferenceHeaderItem} for the given reference.
*/
public static JavaScriptReferenceHeaderItem forReference(ResourceReference reference,
PageParameters pageParameters, String id, boolean defer, String charset)
{
return new JavaScriptReferenceHeaderItem(reference, pageParameters, id, defer, charset, null);
}
/**
* Creates a {@link JavaScriptReferenceHeaderItem} for the given reference.
*
* @param reference
* resource reference pointing to the javascript resource
* @param pageParameters
* the parameters for this Javascript resource reference
* @param id
* id that will be used to filter duplicate reference (it's still filtered by URL
* too)
* @param defer
* specifies that the execution of a script should be deferred (delayed) until after
* the page has been loaded.
* @param charset
* a non null value specifies the charset attribute of the script tag
* @param condition
* the condition to use for Internet Explorer conditional comments. E.g. "IE 7".
* @return A newly created {@link JavaScriptReferenceHeaderItem} for the given reference.
*/
public static JavaScriptReferenceHeaderItem forReference(ResourceReference reference,
PageParameters pageParameters, String id, boolean defer, String charset, String condition)
{
return new JavaScriptReferenceHeaderItem(reference, pageParameters, id, defer, charset, condition);
}
/**
* Creates a {@link JavaScriptContentHeaderItem} for the given content.
*
* @param javascript
* javascript content to be rendered.
* @param id
* unique id for the javascript element. This can be null, however in that case the
* ajax header contribution can't detect duplicate script fragments.
* @return A newly created {@link JavaScriptContentHeaderItem} for the given content.
*/
public static JavaScriptContentHeaderItem forScript(CharSequence javascript, String id)
{
return forScript(javascript, id, null);
}
/**
* Creates a {@link JavaScriptContentHeaderItem} for the given content.
*
* @param javascript
* javascript content to be rendered.
* @param id
* unique id for the javascript element. This can be null, however in that case the
* ajax header contribution can't detect duplicate script fragments.
* @param condition
* the condition to use for Internet Explorer conditional comments. E.g. "IE 7".
* @return A newly created {@link JavaScriptContentHeaderItem} for the given content.
*/
public static JavaScriptContentHeaderItem forScript(CharSequence javascript, String id, String condition)
{
return new JavaScriptContentHeaderItem(javascript, id, condition);
}
/**
* Creates a {@link JavaScriptUrlReferenceHeaderItem} for the given url.
*
* @param url
* context-relative url of the the javascript resource
* @return A newly created {@link JavaScriptUrlReferenceHeaderItem} for the given url.
*/
public static JavaScriptUrlReferenceHeaderItem forUrl(String url)
{
return forUrl(url, null);
}
/**
* Creates a {@link JavaScriptUrlReferenceHeaderItem} for the given url.
*
* @param url
* context-relative url of the the javascript resource
* @param id
* id that will be used to filter duplicate reference (it's still filtered by URL
* too)
* @return A newly created {@link JavaScriptUrlReferenceHeaderItem} for the given url.
*/
public static JavaScriptUrlReferenceHeaderItem forUrl(String url, String id)
{
return forUrl(url, id, false);
}
/**
* Creates a {@link JavaScriptUrlReferenceHeaderItem} for the given url.
*
* @param url
* context-relative url of the the javascript resource
* @param id
* id that will be used to filter duplicate reference (it's still filtered by URL
* too)
* @param defer
* specifies that the execution of a script should be deferred (delayed) until after
* the page has been loaded.
* @return A newly created {@link JavaScriptUrlReferenceHeaderItem} for the given url.
*/
public static JavaScriptUrlReferenceHeaderItem forUrl(String url, String id, boolean defer)
{
return forUrl(url, id, defer, null);
}
/**
* Creates a {@link JavaScriptUrlReferenceHeaderItem} for the given url.
*
* @param url
* context-relative url of the the javascript resource
* @param id
* id that will be used to filter duplicate reference (it's still filtered by URL
* too)
* @param defer
* specifies that the execution of a script should be deferred (delayed) until after
* the page has been loaded.
* @param charset
* a non null value specifies the charset attribute of the script tag
* @return A newly created {@link JavaScriptUrlReferenceHeaderItem} for the given url.
*/
public static JavaScriptUrlReferenceHeaderItem forUrl(String url, String id, boolean defer,
String charset)
{
return forUrl(url, id, defer, charset, null);
}
/**
* Creates a {@link JavaScriptUrlReferenceHeaderItem} for the given url.
*
* @param url
* context-relative url of the the javascript resource
* @param id
* id that will be used to filter duplicate reference (it's still filtered by URL
* too)
* @param defer
* specifies that the execution of a script should be deferred (delayed) until after
* the page has been loaded.
* @param charset
* a non null value specifies the charset attribute of the script tag
* @return A newly created {@link JavaScriptUrlReferenceHeaderItem} for the given url.
*/
public static JavaScriptUrlReferenceHeaderItem forUrl(String url, String id, boolean defer,
String charset, String condition)
{
return new JavaScriptUrlReferenceHeaderItem(url, id, defer, charset, condition);
}
protected final void internalRenderJavaScriptReference(Response response, String url,
String id, boolean defer, String charset, String condition)
{
Args.notEmpty(url, "url");
boolean hasCondition = Strings.isEmpty(condition) == false;
if (hasCondition)
{
response.write("<!--[if ");
response.write(condition);
response.write("]>");
}
JavaScriptUtils.writeJavaScriptUrl(response, url, id, defer, charset);
if (hasCondition)
{
response.write("<![endif]-->\n");
}
}
}
| wicket-core/src/main/java/org/apache/wicket/markup/head/JavaScriptHeaderItem.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.wicket.markup.head;
import org.apache.wicket.request.Response;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.request.resource.ResourceReference;
import org.apache.wicket.util.lang.Args;
import org.apache.wicket.core.util.string.JavaScriptUtils;
import org.apache.wicket.util.string.Strings;
/**
* Base class for all {@link HeaderItem}s that represent javascripts. This class mainly contains
* factory methods.
*
* @author papegaaij
*/
public abstract class JavaScriptHeaderItem extends HeaderItem
{
/**
* The condition to use for Internet Explorer conditional comments. E.g. "IE 7".
* {@code null} or empty string for no condition.
*/
private final String condition;
protected JavaScriptHeaderItem(String condition)
{
this.condition = condition;
}
/**
* @return the condition to use for Internet Explorer conditional comments. E.g. "IE 7".
*/
public String getCondition()
{
return condition;
}
/**
* Creates a {@link JavaScriptReferenceHeaderItem} for the given reference.
*
* @param reference
* resource reference pointing to the javascript resource
* @return A newly created {@link JavaScriptReferenceHeaderItem} for the given reference.
*/
public static JavaScriptReferenceHeaderItem forReference(ResourceReference reference)
{
return forReference(reference, null);
}
/**
* Creates a {@link JavaScriptReferenceHeaderItem} for the given reference.
*
* @param reference
* resource reference pointing to the javascript resource
* @param id
* id that will be used to filter duplicate reference (it's still filtered by URL
* too)
* @return A newly created {@link JavaScriptReferenceHeaderItem} for the given reference.
*/
public static JavaScriptReferenceHeaderItem forReference(ResourceReference reference, String id)
{
return forReference(reference, null, id);
}
/**
* Creates a {@link JavaScriptReferenceHeaderItem} for the given reference.
*
* @param reference
* resource reference pointing to the javascript resource
* @param pageParameters
* the parameters for this Javascript resource reference
* @param id
* id that will be used to filter duplicate reference (it's still filtered by URL
* too)
* @return A newly created {@link JavaScriptReferenceHeaderItem} for the given reference.
*/
public static JavaScriptReferenceHeaderItem forReference(ResourceReference reference,
PageParameters pageParameters, String id)
{
return forReference(reference, pageParameters, id, false);
}
/**
* Creates a {@link JavaScriptReferenceHeaderItem} for the given reference.
*
* @param reference
* resource reference pointing to the javascript resource
* @param pageParameters
* the parameters for this Javascript resource reference
* @param id
* id that will be used to filter duplicate reference (it's still filtered by URL
* too)
* @param defer
* specifies that the execution of a script should be deferred (delayed) until after
* the page has been loaded.
* @return A newly created {@link JavaScriptReferenceHeaderItem} for the given reference.
*/
public static JavaScriptReferenceHeaderItem forReference(ResourceReference reference,
PageParameters pageParameters, String id, boolean defer)
{
return forReference(reference, pageParameters, id, defer, null);
}
/**
* Creates a {@link JavaScriptReferenceHeaderItem} for the given reference.
*
* @param reference
* resource reference pointing to the javascript resource
* @param pageParameters
* the parameters for this Javascript resource reference
* @param id
* id that will be used to filter duplicate reference (it's still filtered by URL
* too)
* @param defer
* specifies that the execution of a script should be deferred (delayed) until after
* the page has been loaded.
* @param charset
* a non null value specifies the charset attribute of the script tag
* @return A newly created {@link JavaScriptReferenceHeaderItem} for the given reference.
*/
public static JavaScriptReferenceHeaderItem forReference(ResourceReference reference,
PageParameters pageParameters, String id, boolean defer, String charset)
{
return new JavaScriptReferenceHeaderItem(reference, pageParameters, id, defer, charset, null);
}
/**
* Creates a {@link JavaScriptReferenceHeaderItem} for the given reference.
*
* @param reference
* resource reference pointing to the javascript resource
* @param pageParameters
* the parameters for this Javascript resource reference
* @param id
* id that will be used to filter duplicate reference (it's still filtered by URL
* too)
* @param defer
* specifies that the execution of a script should be deferred (delayed) until after
* the page has been loaded.
* @param charset
* a non null value specifies the charset attribute of the script tag
* @param condition
* the condition to use for Internet Explorer conditional comments. E.g. "IE 7".
* @return A newly created {@link JavaScriptReferenceHeaderItem} for the given reference.
*/
public static JavaScriptReferenceHeaderItem forReference(ResourceReference reference,
PageParameters pageParameters, String id, boolean defer, String charset, String condition)
{
return new JavaScriptReferenceHeaderItem(reference, pageParameters, id, defer, charset, condition);
}
/**
* Creates a {@link JavaScriptContentHeaderItem} for the given content.
*
* @param javascript
* javascript content to be rendered.
* @param id
* unique id for the javascript element. This can be null, however in that case the
* ajax header contribution can't detect duplicate script fragments.
* @return A newly created {@link JavaScriptContentHeaderItem} for the given content.
*/
public static JavaScriptContentHeaderItem forScript(CharSequence javascript, String id)
{
return forScript(javascript, id, null);
}
/**
* Creates a {@link JavaScriptContentHeaderItem} for the given content.
*
* @param javascript
* javascript content to be rendered.
* @param id
* unique id for the javascript element. This can be null, however in that case the
* ajax header contribution can't detect duplicate script fragments.
* @param condition
* the condition to use for Internet Explorer conditional comments. E.g. "IE 7".
* @return A newly created {@link JavaScriptContentHeaderItem} for the given content.
*/
public static JavaScriptContentHeaderItem forScript(CharSequence javascript, String id, String condition)
{
return new JavaScriptContentHeaderItem(javascript, id, condition);
}
/**
* Creates a {@link JavaScriptUrlReferenceHeaderItem} for the given url.
*
* @param url
* context-relative url of the the javascript resource
* @return A newly created {@link JavaScriptUrlReferenceHeaderItem} for the given url.
*/
public static JavaScriptUrlReferenceHeaderItem forUrl(String url)
{
return forUrl(url, null);
}
/**
* Creates a {@link JavaScriptUrlReferenceHeaderItem} for the given url.
*
* @param url
* context-relative url of the the javascript resource
* @param id
* id that will be used to filter duplicate reference (it's still filtered by URL
* too)
* @return A newly created {@link JavaScriptUrlReferenceHeaderItem} for the given url.
*/
public static JavaScriptUrlReferenceHeaderItem forUrl(String url, String id)
{
return forUrl(url, id, false);
}
/**
* Creates a {@link JavaScriptUrlReferenceHeaderItem} for the given url.
*
* @param url
* context-relative url of the the javascript resource
* @param id
* id that will be used to filter duplicate reference (it's still filtered by URL
* too)
* @param defer
* specifies that the execution of a script should be deferred (delayed) until after
* the page has been loaded.
* @return A newly created {@link JavaScriptUrlReferenceHeaderItem} for the given url.
*/
public static JavaScriptUrlReferenceHeaderItem forUrl(String url, String id, boolean defer)
{
return forUrl(url, id, defer, null);
}
/**
* Creates a {@link JavaScriptUrlReferenceHeaderItem} for the given url.
*
* @param url
* context-relative url of the the javascript resource
* @param id
* id that will be used to filter duplicate reference (it's still filtered by URL
* too)
* @param defer
* specifies that the execution of a script should be deferred (delayed) until after
* the page has been loaded.
* @param charset
* a non null value specifies the charset attribute of the script tag
* @return A newly created {@link JavaScriptUrlReferenceHeaderItem} for the given url.
*/
public static JavaScriptUrlReferenceHeaderItem forUrl(String url, String id, boolean defer,
String charset)
{
return forUrl(url, id, defer, charset, null);
}
/**
* Creates a {@link JavaScriptUrlReferenceHeaderItem} for the given url.
*
* @param url
* context-relative url of the the javascript resource
* @param id
* id that will be used to filter duplicate reference (it's still filtered by URL
* too)
* @param defer
* specifies that the execution of a script should be deferred (delayed) until after
* the page has been loaded.
* @param charset
* a non null value specifies the charset attribute of the script tag
* @return A newly created {@link JavaScriptUrlReferenceHeaderItem} for the given url.
*/
public static JavaScriptUrlReferenceHeaderItem forUrl(String url, String id, boolean defer,
String charset, String condition)
{
return new JavaScriptUrlReferenceHeaderItem(url, id, defer, charset, condition);
}
protected final void internalRenderJavaScriptReference(Response response, String url,
String id, boolean defer, String charset, String condition)
{
Args.notEmpty(url, "url");
boolean hasCondition = Strings.isEmpty(condition) == false;
if (hasCondition)
{
response.write("<!--[if ");
response.write(condition);
response.write("]>");
}
JavaScriptUtils.writeJavaScriptUrl(response, url, id, defer, charset);
if (hasCondition)
{
response.write("<![endif]-->\n");
}
}
}
| WICKET-4778 Add factory methods to JavaScriptHeaderItem to create a deferred JavaScript header item.
| wicket-core/src/main/java/org/apache/wicket/markup/head/JavaScriptHeaderItem.java | WICKET-4778 Add factory methods to JavaScriptHeaderItem to create a deferred JavaScript header item. | <ide><path>icket-core/src/main/java/org/apache/wicket/markup/head/JavaScriptHeaderItem.java
<ide> */
<ide> package org.apache.wicket.markup.head;
<ide>
<add>import org.apache.wicket.core.util.string.JavaScriptUtils;
<ide> import org.apache.wicket.request.Response;
<ide> import org.apache.wicket.request.mapper.parameter.PageParameters;
<ide> import org.apache.wicket.request.resource.ResourceReference;
<ide> import org.apache.wicket.util.lang.Args;
<del>import org.apache.wicket.core.util.string.JavaScriptUtils;
<ide> import org.apache.wicket.util.string.Strings;
<ide>
<ide> /**
<ide> * {@code null} or empty string for no condition.
<ide> */
<ide> private final String condition;
<del>
<add>
<ide> protected JavaScriptHeaderItem(String condition)
<ide> {
<ide> this.condition = condition;
<ide> /**
<ide> * Creates a {@link JavaScriptReferenceHeaderItem} for the given reference.
<ide> *
<add> * @param reference
<add> * resource reference pointing to the JavaScript resource
<add> * @param id
<add> * id that will be used to filter duplicate reference (it's still filtered by URL
<add> * too)
<add> * @param defer
<add> * specifies that the execution of a script should be deferred (delayed) until after
<add> * the page has been loaded.
<add> * @return A newly created {@link JavaScriptReferenceHeaderItem} for the given reference.
<add> */
<add> public static JavaScriptReferenceHeaderItem forReference(ResourceReference reference,
<add> String id, boolean defer)
<add> {
<add> return forReference(reference, null, id, defer, null);
<add> }
<add>
<add> /**
<add> * Creates a {@link JavaScriptReferenceHeaderItem} for the given reference.
<add> *
<add> * @param reference
<add> * resource reference pointing to the JavaScript resource
<add> * @param defer
<add> * specifies that the execution of a script should be deferred (delayed) until after
<add> * the page has been loaded.
<add> * @return A newly created {@link JavaScriptReferenceHeaderItem} for the given reference.
<add> */
<add> public static JavaScriptReferenceHeaderItem forReference(ResourceReference reference,
<add> boolean defer)
<add> {
<add> return forReference(reference, null, null, defer, null);
<add> }
<add>
<add> /**
<add> * Creates a {@link JavaScriptReferenceHeaderItem} for the given reference.
<add> *
<ide> * @param reference
<ide> * resource reference pointing to the javascript resource
<ide> * @param pageParameters
<ide> String id, boolean defer, String charset, String condition)
<ide> {
<ide> Args.notEmpty(url, "url");
<del>
<del> boolean hasCondition = Strings.isEmpty(condition) == false;
<add>
<add> boolean hasCondition = Strings.isEmpty(condition) == false;
<ide> if (hasCondition)
<ide> {
<ide> response.write("<!--[if ");
<ide> response.write(condition);
<ide> response.write("]>");
<ide> }
<del>
<add>
<ide> JavaScriptUtils.writeJavaScriptUrl(response, url, id, defer, charset);
<del>
<add>
<ide> if (hasCondition)
<ide> {
<ide> response.write("<![endif]-->\n"); |
|
Java | mit | ff371f804739ff6bf8c5bd9a0865fd0f65bac0cc | 0 | UMM-CSci-3601-S17/digital-display-garden-iteration-3-dorfner,UMM-CSci-3601-S17/digital-display-garden-iteration-3-dorfner,UMM-CSci-3601-S17/digital-display-garden-iteration-3-dorfner,UMM-CSci-3601-S17/digital-display-garden-iteration-3-dorfner,UMM-CSci-3601-S17/digital-display-garden-iteration-4-dorfner-v2,UMM-CSci-3601-S17/digital-display-garden-iteration-4-dorfner-v2,UMM-CSci-3601-S17/digital-display-garden-iteration-4-dorfner-v2,UMM-CSci-3601-S17/digital-display-garden-iteration-4-dorfner-v2,UMM-CSci-3601-S17/digital-display-garden-iteration-4-dorfner-v2 | package umm3601.digitalDisplayGarden;
import com.google.gson.Gson;
import com.mongodb.MongoClient;
import com.mongodb.client.*;
import com.mongodb.client.model.Accumulators;
import com.mongodb.client.model.Aggregates;
import com.mongodb.client.model.Sorts;
import com.mongodb.util.JSON;
import org.bson.BsonInvalidOperationException;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.bson.conversions.Bson;
import org.joda.time.DateTime;
import java.io.OutputStream;
import java.util.Iterator;
import static com.mongodb.client.model.Filters.eq;
import static com.mongodb.client.model.Filters.and;
import static com.mongodb.client.model.Filters.exists;
import static com.mongodb.client.model.Projections.include;
import static com.mongodb.client.model.Updates.*;
import static com.mongodb.client.model.Projections.fields;
import java.io.IOException;
import java.util.*;
import static com.mongodb.client.model.Updates.push;
public class PlantController {
private final MongoCollection<Document> plantCollection;
private final MongoCollection<Document> commentCollection;
private final MongoCollection<Document> configCollection;
public PlantController(String databaseName) throws IOException {
// Set up our server address
// (Default host: 'localhost', default port: 27017)
// ServerAddress testAddress = new ServerAddress();
// Try connecting to the server
//MongoClient mongoClient = new MongoClient(testAddress, credentials);
MongoClient mongoClient = new MongoClient(); // Defaults!
// Try connecting to a database
MongoDatabase db = mongoClient.getDatabase(databaseName);
plantCollection = db.getCollection("plants");
commentCollection = db.getCollection("comments");
configCollection = db.getCollection("config");
}
public String getLiveUploadId() {
try
{
FindIterable<Document> findIterable = configCollection.find(exists("liveUploadId"));
Iterator<Document> iterator = findIterable.iterator();
Document doc = iterator.next();
return doc.getString("liveUploadId");
}
catch(Exception e)
{
e.printStackTrace();
System.err.println(" [hint] Database might be empty? Couldn't getLiveUploadId");
throw e;
}
}
// List plants
public String listPlants(Map<String, String[]> queryParams, String uploadId) {
Document filterDoc = new Document();
filterDoc.append("uploadId", uploadId);
if (queryParams.containsKey("gardenLocation")) {
String location =(queryParams.get("gardenLocation")[0]);
filterDoc = filterDoc.append("gardenLocation", location);
}
if (queryParams.containsKey("commonName")) {
String commonName =(queryParams.get("commonName")[0]);
filterDoc = filterDoc.append("commonName", commonName);
}
FindIterable<Document> matchingPlants = plantCollection.find(filterDoc);
return JSON.serialize(matchingPlants);
}
/**
* Takes a String representing an ID number of a plant
* and when the ID is found in the database returns a JSON document
* as a String of the following form
*
* <code>
* {
* "plantID" : String,
* "commonName" : String,
* "cultivar" : String
* }
* </code>
*
* If the ID is invalid or not found, the following JSON value is
* returned
*
* <code>
* null
* </code>
*
* @param plantID an ID number of a plant in the DB
* @param uploadID Dataset to find the plant
* @return a string representation of a JSON value
*/
public String getPlantByPlantID(String plantID, String uploadID) {
FindIterable<Document> jsonPlant;
String returnVal;
try {
jsonPlant = plantCollection.find(and(eq("id", plantID),
eq("uploadId", uploadID)))
.projection(fields(include("commonName", "cultivar")));
Iterator<Document> iterator = jsonPlant.iterator();
if (iterator.hasNext()) {
incrementMetadata(plantID, "pageViews");
addVisit(plantID);
returnVal = iterator.next().toJson();
} else {
returnVal = "null";
}
} catch (IllegalArgumentException e) {
returnVal = "null";
}
return returnVal;
}
/**
*
* @param plantID The plant to get feedback of
* @param uploadID Dataset to find the plant
*
* @return JSON for the number of interactions of a plant (likes + dislikes + comments)
* Of the form:
* {
* interactionCount: number
* }
*/
public String getFeedbackForPlantByPlantID(String plantID, String uploadID) {
Document out = new Document();
Document filter = new Document();
filter.put("commentOnPlant", plantID);
filter.put("uploadId", uploadID);
long comments = commentCollection.count(filter);
long likes = 0;
long dislikes = 0;
long interactions = 0;
//Get a plant by plantID
FindIterable doc = plantCollection.find(new Document().append("id", plantID).append("uploadId", uploadID));
Iterator iterator = doc.iterator();
if(iterator.hasNext()) {
Document result = (Document) iterator.next();
//Get metadata.rating array
List<Document> ratings = (List<Document>) ((Document) result.get("metadata")).get("ratings");
//Loop through all of the entries within the array, counting like=true(like) and like=false(dislike)
for(Document rating : ratings)
{
if(rating.get("like").equals(true))
likes++;
else if(rating.get("like").equals(false))
dislikes++;
}
}
interactions = likes + dislikes + comments;
out.put("interactionCount", interactions);
return JSON.serialize(out);
}
public String getGardenLocationsAsJson(String uploadID){
AggregateIterable<Document> documents
= plantCollection.aggregate(
Arrays.asList(
Aggregates.match(eq("uploadId", uploadID)), //!! Order is important here
Aggregates.group("$gardenLocation"),
Aggregates.sort(Sorts.ascending("_id"))
));
return JSON.serialize(documents);
}
public String[] getGardenLocations(String uploadID){
Document filter = new Document();
filter.append("uploadId", uploadID);
DistinctIterable<String> bedIterator = plantCollection.distinct("gardenLocation", filter, String.class);
List<String> beds = new ArrayList<String>();
for(String s : bedIterator)
{
beds.add(s);
}
return beds.toArray(new String[beds.size()]);
}
/**
* Accepts string representation of JSON object containing
* at least the following.
* <code>
* {
* plantId: String,
* comment: String
* }
* </code>
* If either of the keys are missing or the types of the values are
* wrong, false is returned.
* @param json string representation of JSON object
* @param uploadID Dataset to find the plant
* @return true iff the comment was successfully submitted
*/
public boolean storePlantComment(String json, String uploadID) {
try {
Document toInsert = new Document();
Document parsedDocument = Document.parse(json);
if (parsedDocument.containsKey("plantId") && parsedDocument.get("plantId") instanceof String) {
FindIterable<Document> jsonPlant = plantCollection.find(eq("_id",
new ObjectId(parsedDocument.getString("plantId"))));
Iterator<Document> iterator = jsonPlant.iterator();
if(iterator.hasNext()){
toInsert.put("commentOnPlant", iterator.next().getString("id"));
} else {
return false;
}
} else {
return false;
}
if (parsedDocument.containsKey("comment") && parsedDocument.get("comment") instanceof String) {
toInsert.put("comment", parsedDocument.getString("comment"));
} else {
return false;
}
toInsert.append("uploadId", uploadID);
commentCollection.insertOne(toInsert);
} catch (BsonInvalidOperationException e){
e.printStackTrace();
return false;
} catch (org.bson.json.JsonParseException e){
return false;
} catch (IllegalArgumentException e){
return false;
}
return true;
}
public void writeComments(OutputStream outputStream, String uploadId) throws IOException{
FindIterable iter = commentCollection.find(
and(
exists("commentOnPlant"),
eq("uploadId", uploadId)
));
Iterator iterator = iter.iterator();
CommentWriter commentWriter = new CommentWriter(outputStream);
while (iterator.hasNext()) {
Document comment = (Document) iterator.next();
commentWriter.writeComment(comment.getString("commentOnPlant"),
comment.getString("comment"),
((ObjectId) comment.get("_id")).getDate());
}
commentWriter.complete();
}
/**
* Adds a like or dislike to the specified plant.
*
* @param id a hexstring specifiying the oid
* @param like true if this is a like, false if this is a dislike
* @param uploadID Dataset to find the plant
* @return true iff the operation succeeded.
*/
public boolean addFlowerRating(String id, boolean like, String uploadID) {
Document filterDoc = new Document();
ObjectId objectId;
try {
objectId = new ObjectId(id);
} catch (IllegalArgumentException e) {
return false;
}
filterDoc.append("_id", new ObjectId(id));
filterDoc.append("uploadId", uploadID);
Document rating = new Document();
rating.append("like", like);
rating.append("ratingOnObjectOfId", objectId);
return null != plantCollection.findOneAndUpdate(filterDoc, push("metadata.ratings", rating));
}
/**
* Accepts string representation of JSON object containing
* at least the following:
* <code>
* {
* id: String,
* like: boolean
* }
* </code>
*
* @param json string representation of a JSON object
* @param uploadID Dataset to find the plant
* @return true iff the operation succeeded.
*/
public boolean addFlowerRating(String json, String uploadID){
boolean like;
String id;
try {
Document parsedDocument = Document.parse(json);
if(parsedDocument.containsKey("id") && parsedDocument.get("id") instanceof String){
id = parsedDocument.getString("id");
} else {
return false;
}
if(parsedDocument.containsKey("like") && parsedDocument.get("like") instanceof Boolean){
like = parsedDocument.getBoolean("like");
} else {
return false;
}
} catch (BsonInvalidOperationException e){
e.printStackTrace();
return false;
} catch (org.bson.json.JsonParseException e){
return false;
}
return addFlowerRating(id, like, uploadID);
}
/**
*
* @return a sorted JSON array of all the distinct uploadIds in the DB
*/
public String listUploadIds() {
AggregateIterable<Document> documents
= plantCollection.aggregate(
Arrays.asList(
Aggregates.group("$uploadId"),
Aggregates.sort(Sorts.ascending("_id"))
));
List<String> lst = new LinkedList<>();
for(Document d: documents) {
lst.add(d.getString("_id"));
}
return JSON.serialize(lst);
// return JSON.serialize(plantCollection.distinct("uploadId","".getClass()));
}
/**
* Finds a plant and atomically increments the specified field
* in its metadata object. This method returns true if the plant was
* found successfully (false otherwise), but there is no indication of
* whether the field was found.
*
* @param plantID a ID number of a plant in the DB
* @param field a field to be incremented in the metadata object of the plant
* @return true if a plant was found
* @throws com.mongodb.MongoCommandException when the id is valid and the field is empty
*/
public boolean incrementMetadata(String plantID, String field) {
Document searchDocument = new Document();
searchDocument.append("id", plantID);
Bson updateDocument = inc("metadata." + field, 1);
return null != plantCollection.findOneAndUpdate(searchDocument, updateDocument);
}
public boolean addVisit(String plantID) {
Document filterDoc = new Document();
filterDoc.append("id", plantID);
Document visit = new Document();
visit.append("visit", new ObjectId());
return null != plantCollection.findOneAndUpdate(filterDoc, push("metadata.visits", visit));
}
} | server/src/main/java/umm3601/digitalDisplayGarden/PlantController.java | package umm3601.digitalDisplayGarden;
import com.google.gson.Gson;
import com.mongodb.MongoClient;
import com.mongodb.client.*;
import com.mongodb.client.model.Accumulators;
import com.mongodb.client.model.Aggregates;
import com.mongodb.client.model.Sorts;
import com.mongodb.util.JSON;
import org.bson.BsonInvalidOperationException;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.bson.conversions.Bson;
import org.joda.time.DateTime;
import java.io.OutputStream;
import java.util.Iterator;
import static com.mongodb.client.model.Filters.eq;
import static com.mongodb.client.model.Filters.and;
import static com.mongodb.client.model.Filters.exists;
import static com.mongodb.client.model.Projections.include;
import static com.mongodb.client.model.Updates.*;
import static com.mongodb.client.model.Projections.fields;
import java.io.IOException;
import java.util.*;
import static com.mongodb.client.model.Updates.push;
public class PlantController {
private final MongoCollection<Document> plantCollection;
private final MongoCollection<Document> commentCollection;
private final MongoCollection<Document> configCollection;
public PlantController(String databaseName) throws IOException {
// Set up our server address
// (Default host: 'localhost', default port: 27017)
// ServerAddress testAddress = new ServerAddress();
// Try connecting to the server
//MongoClient mongoClient = new MongoClient(testAddress, credentials);
MongoClient mongoClient = new MongoClient(); // Defaults!
// Try connecting to a database
MongoDatabase db = mongoClient.getDatabase(databaseName);
plantCollection = db.getCollection("plants");
commentCollection = db.getCollection("comments");
configCollection = db.getCollection("config");
}
public String getLiveUploadId() {
try
{
FindIterable<Document> findIterable = configCollection.find(exists("liveUploadId"));
Iterator<Document> iterator = findIterable.iterator();
Document doc = iterator.next();
return doc.getString("liveUploadId");
}
catch(Exception e)
{
e.printStackTrace();
System.err.println(" [hint] Database might be empty? Couldn't getLiveUploadId");
throw e;
}
}
// List plants
public String listPlants(Map<String, String[]> queryParams, String uploadId) {
Document filterDoc = new Document();
filterDoc.append("uploadId", uploadId);
if (queryParams.containsKey("gardenLocation")) {
String location =(queryParams.get("gardenLocation")[0]);
filterDoc = filterDoc.append("gardenLocation", location);
}
if (queryParams.containsKey("commonName")) {
String commonName =(queryParams.get("commonName")[0]);
filterDoc = filterDoc.append("commonName", commonName);
}
FindIterable<Document> matchingPlants = plantCollection.find(filterDoc);
return JSON.serialize(matchingPlants);
}
/**
* Takes a String representing an ID number of a plant
* and when the ID is found in the database returns a JSON document
* as a String of the following form
*
* <code>
* {
* "plantID" : String,
* "commonName" : String,
* "cultivar" : String
* }
* </code>
*
* If the ID is invalid or not found, the following JSON value is
* returned
*
* <code>
* null
* </code>
*
* @param plantID an ID number of a plant in the DB
* @param uploadID Dataset to find the plant
* @return a string representation of a JSON value
*/
public String getPlantByPlantID(String plantID, String uploadID) {
FindIterable<Document> jsonPlant;
String returnVal;
try {
jsonPlant = plantCollection.find(and(eq("id", plantID),
eq("uploadId", uploadID)))
.projection(fields(include("commonName", "cultivar")));
Iterator<Document> iterator = jsonPlant.iterator();
if (iterator.hasNext()) {
incrementMetadata(plantID, "pageViews");
addVisit(plantID);
returnVal = iterator.next().toJson();
} else {
returnVal = "null";
}
} catch (IllegalArgumentException e) {
returnVal = "null";
}
return returnVal;
}
/**
*
* @param plantID The plant to get feedback of
* @param uploadID Dataset to find the plant
*
* @return JSON for the number of comments, likes, and dislikes
* Of the form:
* {
* commentCount: number
* likeCount: number
* dislikeCount: number
* }
*/
public String getFeedbackForPlantByPlantID(String plantID, String uploadID) {
Document out = new Document();
Document filter = new Document();
filter.put("commentOnPlant", plantID);
filter.put("uploadId", uploadID);
long comments = commentCollection.count(filter);
long likes = 0;
long dislikes = 0;
long interactions = 0;
//Get a plant by plantID
FindIterable doc = plantCollection.find(new Document().append("id", plantID).append("uploadId", uploadID));
Iterator iterator = doc.iterator();
if(iterator.hasNext()) {
Document result = (Document) iterator.next();
//Get metadata.rating array
List<Document> ratings = (List<Document>) ((Document) result.get("metadata")).get("ratings");
//Loop through all of the entries within the array, counting like=true(like) and like=false(dislike)
for(Document rating : ratings)
{
if(rating.get("like").equals(true))
likes++;
else if(rating.get("like").equals(false))
dislikes++;
}
}
interactions = likes + dislikes + comments;
out.put("interactionCount", interactions);
return JSON.serialize(out);
}
public String getGardenLocationsAsJson(String uploadID){
AggregateIterable<Document> documents
= plantCollection.aggregate(
Arrays.asList(
Aggregates.match(eq("uploadId", uploadID)), //!! Order is important here
Aggregates.group("$gardenLocation"),
Aggregates.sort(Sorts.ascending("_id"))
));
return JSON.serialize(documents);
}
public String[] getGardenLocations(String uploadID){
Document filter = new Document();
filter.append("uploadId", uploadID);
DistinctIterable<String> bedIterator = plantCollection.distinct("gardenLocation", filter, String.class);
List<String> beds = new ArrayList<String>();
for(String s : bedIterator)
{
beds.add(s);
}
return beds.toArray(new String[beds.size()]);
}
/**
* Accepts string representation of JSON object containing
* at least the following.
* <code>
* {
* plantId: String,
* comment: String
* }
* </code>
* If either of the keys are missing or the types of the values are
* wrong, false is returned.
* @param json string representation of JSON object
* @param uploadID Dataset to find the plant
* @return true iff the comment was successfully submitted
*/
public boolean storePlantComment(String json, String uploadID) {
try {
Document toInsert = new Document();
Document parsedDocument = Document.parse(json);
if (parsedDocument.containsKey("plantId") && parsedDocument.get("plantId") instanceof String) {
FindIterable<Document> jsonPlant = plantCollection.find(eq("_id",
new ObjectId(parsedDocument.getString("plantId"))));
Iterator<Document> iterator = jsonPlant.iterator();
if(iterator.hasNext()){
toInsert.put("commentOnPlant", iterator.next().getString("id"));
} else {
return false;
}
} else {
return false;
}
if (parsedDocument.containsKey("comment") && parsedDocument.get("comment") instanceof String) {
toInsert.put("comment", parsedDocument.getString("comment"));
} else {
return false;
}
toInsert.append("uploadId", uploadID);
commentCollection.insertOne(toInsert);
} catch (BsonInvalidOperationException e){
e.printStackTrace();
return false;
} catch (org.bson.json.JsonParseException e){
return false;
} catch (IllegalArgumentException e){
return false;
}
return true;
}
public void writeComments(OutputStream outputStream, String uploadId) throws IOException{
FindIterable iter = commentCollection.find(
and(
exists("commentOnPlant"),
eq("uploadId", uploadId)
));
Iterator iterator = iter.iterator();
CommentWriter commentWriter = new CommentWriter(outputStream);
while (iterator.hasNext()) {
Document comment = (Document) iterator.next();
commentWriter.writeComment(comment.getString("commentOnPlant"),
comment.getString("comment"),
((ObjectId) comment.get("_id")).getDate());
}
commentWriter.complete();
}
/**
* Adds a like or dislike to the specified plant.
*
* @param id a hexstring specifiying the oid
* @param like true if this is a like, false if this is a dislike
* @param uploadID Dataset to find the plant
* @return true iff the operation succeeded.
*/
public boolean addFlowerRating(String id, boolean like, String uploadID) {
Document filterDoc = new Document();
ObjectId objectId;
try {
objectId = new ObjectId(id);
} catch (IllegalArgumentException e) {
return false;
}
filterDoc.append("_id", new ObjectId(id));
filterDoc.append("uploadId", uploadID);
Document rating = new Document();
rating.append("like", like);
rating.append("ratingOnObjectOfId", objectId);
return null != plantCollection.findOneAndUpdate(filterDoc, push("metadata.ratings", rating));
}
/**
* Accepts string representation of JSON object containing
* at least the following:
* <code>
* {
* id: String,
* like: boolean
* }
* </code>
*
* @param json string representation of a JSON object
* @param uploadID Dataset to find the plant
* @return true iff the operation succeeded.
*/
public boolean addFlowerRating(String json, String uploadID){
boolean like;
String id;
try {
Document parsedDocument = Document.parse(json);
if(parsedDocument.containsKey("id") && parsedDocument.get("id") instanceof String){
id = parsedDocument.getString("id");
} else {
return false;
}
if(parsedDocument.containsKey("like") && parsedDocument.get("like") instanceof Boolean){
like = parsedDocument.getBoolean("like");
} else {
return false;
}
} catch (BsonInvalidOperationException e){
e.printStackTrace();
return false;
} catch (org.bson.json.JsonParseException e){
return false;
}
return addFlowerRating(id, like, uploadID);
}
/**
*
* @return a sorted JSON array of all the distinct uploadIds in the DB
*/
public String listUploadIds() {
AggregateIterable<Document> documents
= plantCollection.aggregate(
Arrays.asList(
Aggregates.group("$uploadId"),
Aggregates.sort(Sorts.ascending("_id"))
));
List<String> lst = new LinkedList<>();
for(Document d: documents) {
lst.add(d.getString("_id"));
}
return JSON.serialize(lst);
// return JSON.serialize(plantCollection.distinct("uploadId","".getClass()));
}
/**
* Finds a plant and atomically increments the specified field
* in its metadata object. This method returns true if the plant was
* found successfully (false otherwise), but there is no indication of
* whether the field was found.
*
* @param plantID a ID number of a plant in the DB
* @param field a field to be incremented in the metadata object of the plant
* @return true if a plant was found
* @throws com.mongodb.MongoCommandException when the id is valid and the field is empty
*/
public boolean incrementMetadata(String plantID, String field) {
Document searchDocument = new Document();
searchDocument.append("id", plantID);
Bson updateDocument = inc("metadata." + field, 1);
return null != plantCollection.findOneAndUpdate(searchDocument, updateDocument);
}
public boolean addVisit(String plantID) {
Document filterDoc = new Document();
filterDoc.append("id", plantID);
Document visit = new Document();
visit.append("visit", new ObjectId());
return null != plantCollection.findOneAndUpdate(filterDoc, push("metadata.visits", visit));
}
} | Changed comment on Feedback method
Issue #5
| server/src/main/java/umm3601/digitalDisplayGarden/PlantController.java | Changed comment on Feedback method Issue #5 | <ide><path>erver/src/main/java/umm3601/digitalDisplayGarden/PlantController.java
<ide> * @param plantID The plant to get feedback of
<ide> * @param uploadID Dataset to find the plant
<ide> *
<del> * @return JSON for the number of comments, likes, and dislikes
<add> * @return JSON for the number of interactions of a plant (likes + dislikes + comments)
<ide> * Of the form:
<ide> * {
<del> * commentCount: number
<del> * likeCount: number
<del> * dislikeCount: number
<add> * interactionCount: number
<ide> * }
<ide> */
<ide> |
|
JavaScript | apache-2.0 | 17efa2814f1c7fdb0f6454ae8578d8fba1f18e34 | 0 | Esri/geotrigger-editor,Esri/geotrigger-editor | GeotriggerEditor.module('Editor', function(Editor, App, Backbone, Marionette, $, _) {
// Editor Router
// ---------------
//
// Handle routes to show the active vs complete todo items
var Router = Marionette.AppRouter.extend({
appRoutes: {
'': 'index',
'list': 'list',
'list/:term': 'list',
'new': 'create',
'edit/:id': 'edit',
'*notfound': 'notFound'
}
});
// Editor Controller (Mediator)
// ------------------------------
//
// Control the workflow and logic that exists at the application
// level, above the implementation detail of views and models
var Controller = function() {};
_.extend(Controller.prototype, {
// initialization
start: function() {
this.setup();
App.vent.trigger('notify', 'Fetching application data..');
if (window.location.hash.match('edit')) {
App._zoomToLayer = true;
}
App.collections.triggers.fetch({
fetch: true,
reset: true,
success: function (model, response, options) {
App.vent.trigger('notify:clear');
// don't start history until triggers have been fetched
Backbone.history.start();
if (response && response.length === 0) {
App.router.navigate('list', { trigger: true });
}
else if (App.config.fitOnLoad && !Backbone.history.fragment.match('edit')) {
App.execute('map:fit');
}
}
});
App.vent.on('draw:new', function(options){
if (Backbone.history.fragment === 'new' ||
Backbone.history.fragment.match('edit')) {
} else {
App.router.navigate('new', { trigger: true });
}
}, this);
App.vent.on('trigger:create', this.createTrigger, this);
App.vent.on('trigger:update', this.updateTrigger, this);
App.vent.on('trigger:destroy', this.deleteTrigger, this);
},
// setup
setup: function() {
this.setupMap();
this.setupDrawer();
this.setupControls();
this.setupNotifications();
},
setupMap: function() {
var view = new App.Views.Map({ collection: App.collections.triggers });
App.regions.map.show(view);
},
setupDrawer: function() {
var drawer = App.regions.drawer;
var content = App.mainRegion.$el.find('#gt-content');
drawer.on('show', function(){
content.addClass('gt-active');
});
drawer.on('close', function(){
content.removeClass('gt-active');
});
},
setupControls: function() {
var view = new App.Views.Controls();
App.regions.controls.show(view);
},
setupNotifications: function() {
var view = new App.Views.NotificationList({
collection: App.collections.notifications
});
App.regions.notes.show(view);
App.vent.on('notify', function(options){
if (typeof options === 'string') {
options = {
type: 'info',
message: options
};
}
var note = new App.Models.Notification(options);
App.collections.notifications.add(note);
}, this);
},
// routes
index: function() {
App.vent.trigger('index');
App.regions.drawer.close();
},
list: function(term) {
if (!App.regions.drawer.$el || !App.regions.drawer.$el.has('.gt-list').length) {
App.vent.trigger('trigger:list');
var model = new Backbone.Model({ count: App.collections.triggers.length });
var view = new App.Views.List({ model: model, collection: App.collections.triggers });
App.regions.drawer.show(view);
} else if (!term) {
App.vent.trigger('trigger:list:reset');
}
if (term) {
term = decodeURIComponent(term.replace(/\+/g,'%20'));
App.vent.trigger('trigger:list:search', term);
}
},
create: function() {
App.vent.trigger('trigger:new');
var view = new App.Views.Form();
App.regions.drawer.show(view);
App.vent.trigger('trigger:new:ready');
},
edit: function(triggerId) {
var model = this.getTrigger(triggerId);
if (!model) {
App.vent.trigger('notify', {
type: 'error',
message: 'That trigger doesn\'t exist!'
});
} else {
var view = new App.Views.Form({ model: model });
App.regions.drawer.show(view);
App.vent.trigger('trigger:edit', triggerId);
view.parseShape();
}
},
notFound: function() {
App.vent.trigger('notify', {
type: 'error',
message: 'Couldn\'t find page: "' + Backbone.history.fragment + '"'
});
},
// crud
createTrigger: function(triggerData) {
App.execute('draw:clear');
App.collections.triggers.create(triggerData, {
// wait: true, // wait is broken in backbone 1.1.0
success: function() {
App.router.navigate('list', { trigger: true });
}
});
},
getTrigger: function(id) {
var model = App.collections.triggers.findWhere({'triggerId':id});
return model;
},
updateTrigger: function(triggerData) {
App.collections.triggers.once('change', function(data){
App.router.navigate('list', { trigger: true });
});
var model = App.collections.triggers.findWhere({'triggerId':triggerData.triggerId});
model.set(triggerData);
model.set('id', model.get('triggerId')); // hack to ensure proper method
model.save();
},
deleteTrigger: function(model) {
App.collections.triggers.once('remove', function(data){
if (Backbone.history.fragment.match('edit')) {
App.router.navigate('list', { trigger: true });
}
});
model.set('id', model.get('triggerId')); // hack to ensure proper method
model.destroy();
}
});
// Editor Initializer
// ------------------
//
// Get the Editor up and running by initializing the mediator
// when the the application is started, pulling in all of the
// existing triggers and displaying them.
Editor.addInitializer(function() {
// initialize collections
App.collections = App.collections || {};
App.collections.triggers = new App.Models.Triggers();
App.collections.notifications = new App.Models.Notifications();
// initialize controller
var controller = new Controller();
// initialize router
App.router = new Router({ controller: controller });
controller.start();
});
}); | src/js/controllers/editor.js | GeotriggerEditor.module('Editor', function(Editor, App, Backbone, Marionette, $, _) {
// Editor Router
// ---------------
//
// Handle routes to show the active vs complete todo items
var Router = Marionette.AppRouter.extend({
appRoutes: {
'': 'index',
'list': 'list',
'list/:term': 'list',
'new': 'create',
'edit/:id': 'edit',
'*notfound': 'notFound'
}
});
// Editor Controller (Mediator)
// ------------------------------
//
// Control the workflow and logic that exists at the application
// level, above the implementation detail of views and models
var Controller = function() {};
_.extend(Controller.prototype, {
// initialization
start: function() {
this.setup();
App.vent.trigger('notify', 'Fetching application data..');
if (window.location.hash.match('edit')) {
App._zoomToLayer = true;
}
App.collections.triggers.fetch({
fetch: true,
reset: true,
success: function (model, response, options) {
App.vent.trigger('notify:clear');
// don't start history until triggers have been fetched
Backbone.history.start();
if (response && response.length === 0) {
App.router.navigate('list', { trigger: true });
}
else if (App.config.fitOnLoad && !Backbone.history.fragment.match('edit')) {
App.execute('map:fit');
}
}
});
App.vent.on('draw:new', function(options){
if (Backbone.history.fragment === 'new' ||
Backbone.history.fragment.match('edit')) {
} else {
App.router.navigate('new', { trigger: true });
}
}, this);
App.vent.on('trigger:create', this.createTrigger, this);
App.vent.on('trigger:update', this.updateTrigger, this);
App.vent.on('trigger:destroy', this.deleteTrigger, this);
},
// setup
setup: function() {
this.setupMap();
this.setupDrawer();
this.setupControls();
this.setupNotifications();
},
setupMap: function() {
var view = new App.Views.Map({ collection: App.collections.triggers });
App.regions.map.show(view);
},
setupDrawer: function() {
var drawer = App.regions.drawer;
var content = App.mainRegion.$el.find('#gt-content');
drawer.on('show', function(){
content.addClass('gt-active');
});
drawer.on('close', function(){
content.removeClass('gt-active');
});
},
setupControls: function() {
var view = new App.Views.Controls();
App.regions.controls.show(view);
},
setupNotifications: function() {
var view = new App.Views.NotificationList({
collection: App.collections.notifications
});
App.regions.notes.show(view);
App.vent.on('notify', function(options){
if (typeof options === 'string') {
options = {
type: 'info',
message: options
};
}
var note = new App.Models.Notification(options);
App.collections.notifications.add(note);
}, this);
},
// routes
index: function() {
App.vent.trigger('index');
App.regions.drawer.close();
},
list: function(term) {
if (!App.regions.drawer.$el || !App.regions.drawer.$el.has('.gt-list').length) {
App.vent.trigger('trigger:list');
var model = new Backbone.Model({ count: App.collections.triggers.length });
var view = new App.Views.List({ model: model, collection: App.collections.triggers });
App.regions.drawer.show(view);
} else if (!term) {
App.vent.trigger('trigger:list:reset');
}
if (term) {
term = decodeURIComponent(term.replace(/\+/g,'%20'));
App.vent.trigger('trigger:list:search', term);
}
},
create: function() {
App.vent.trigger('trigger:new');
var view = new App.Views.Form();
App.regions.drawer.show(view);
App.vent.trigger('trigger:new:ready');
},
edit: function(triggerId) {
var model = this.getTrigger(triggerId);
if (!model) {
App.vent.trigger('notify', {
type: 'error',
message: 'That trigger doesn\'t exist!'
});
} else {
var view = new App.Views.Form({ model: model });
App.regions.drawer.show(view);
App.vent.trigger('trigger:edit', triggerId);
view.parseShape();
}
},
notFound: function() {
App.vent.trigger('notify', {
type: 'error',
message: 'Couldn\'t find page: "' + Backbone.history.fragment + '"'
});
},
// crud
createTrigger: function(triggerData) {
App.execute('draw:clear');
App.collections.triggers.create(triggerData, {
// wait: true, // wait is broken in backbone 1.1.0
success: function() {
App.router.navigate('list', { trigger: true });
}
});
},
getTrigger: function(id) {
var model = App.collections.triggers.findWhere({'triggerId':id});
return model;
},
updateTrigger: function(triggerData) {
App.collections.triggers.once('change', function(data){
App.router.navigate('list', { trigger: true });
});
var model = App.collections.triggers.findWhere({'triggerId':triggerData.triggerId});
model.set(triggerData);
model.save();
},
deleteTrigger: function(model) {
App.collections.triggers.once('remove', function(data){
if (Backbone.history.fragment.match('edit')) {
App.router.navigate('list', { trigger: true });
}
});
model.destroy();
}
});
// Editor Initializer
// ------------------
//
// Get the Editor up and running by initializing the mediator
// when the the application is started, pulling in all of the
// existing triggers and displaying them.
Editor.addInitializer(function() {
// initialize collections
App.collections = App.collections || {};
App.collections.triggers = new App.Models.Triggers();
App.collections.notifications = new App.Models.Notifications();
// initialize controller
var controller = new Controller();
// initialize router
App.router = new Router({ controller: controller });
controller.start();
});
}); | fix broken delete/update
| src/js/controllers/editor.js | fix broken delete/update | <ide><path>rc/js/controllers/editor.js
<ide> });
<ide> var model = App.collections.triggers.findWhere({'triggerId':triggerData.triggerId});
<ide> model.set(triggerData);
<add> model.set('id', model.get('triggerId')); // hack to ensure proper method
<ide> model.save();
<ide> },
<ide>
<ide> App.router.navigate('list', { trigger: true });
<ide> }
<ide> });
<add> model.set('id', model.get('triggerId')); // hack to ensure proper method
<ide> model.destroy();
<ide> }
<ide> }); |
|
JavaScript | mit | 9db05e9cae85d826995dec9c80345cadaa981f11 | 0 | pratikd650/colorWheel,pratikd650/colorWheel | var globalColorWheel;
var timersList = [];
var outerWheel, innerWheel;
var count = 0;
function callTimerCallbacks() {
count = (count + 1) % 60;
for(var i = 0; i < timersList.length; i++) {
timersList[i](count);
}
}
//---------------------------------------------------------------------------------
var Led = React.createClass({
getInitialState:function() {
return {rgb:{r:255, g:0, b:0}}; // Set it to red
},
setLed: function() {
this.setState({rgb:globalColorWheel.state.rgb});
},
render: function(){
var x = this.props.x;
var y = this.props.y;
var a = this.props.angle;
var thickness = this.props.thickness;
var dx = Math.round(Math.cos(a) * (thickness-2));
var dy = Math.round(Math.sin(a) * (thickness-2));
var rgb = this.state.rgb;
return(
<path
d={
"M" + x + "," + y + " " +
"l" + (+dy/2) + "," + (dx/2) + " " +
"l" + (+dx) + "," + (-dy) + " " +
"l" + (-dy) + "," + (-dx) + " " +
"l" + (-dx) + "," + (+dy) + " " +
"z"
}
fill={"rgb(" + rgb.r + "," + rgb.g + "," + rgb.b + ")"}
stroke = "black"
onClick = {this.setLed}
/>);
}
})
//---------------------------------------------------------------------------------
var LedOneWheel = React.createClass({
getInitialState:function() {
return {speed:0, angle:0, counter:60};
},
changeSpeed:function(speedInc) {
if ((speedInc == 1 && this.state.speed < 1)
|| (speedInc == -1 && this.state.speed > -1)) {
console.log("LedOneWheel n=", this.props.n, " speedInc=", speedInc);
this.setState({speed:this.state.speed + speedInc})
}
},
tick:function(count) {
if (this.state.speed == 0)
return;
if (count==0 || count % this.state.counter == 0) {
var a = this.state.angle;
a = (a + this.state.speed) % this.props.n;
this.setState({angle:a});
}
},
componentDidMount: function() {
timersList.push(this.tick);
console.log("Adding timer for LedOneWheel");
},
componentWillUnmount: function() {
var index = timersList.indexof(this.tick);
if (index > -1) timersList.splice( index, 1 );
console.log("Removing timer for LedOneWheel");
},
render:function() {
var n = this.props.n;
var radius = this.props.radius;
var r = this.props.r;
var thickness = this.props.thickness;
var r2 = r - thickness;
var leds = [];
for(var i = 0; i < n; i++) {
var a1 = Math.PI * 2 * i / n;
var x = radius + Math.round(Math.cos(a1)*r);
var y = radius - Math.round(Math.sin(a1)*r);
leds.push(<Led key={i} angle={a1} thickness={thickness-2} x={x} y={y}/>);
}
return (<g transform={"rotate(" + (360* this.state.angle/n) + " " + radius + " " + radius + ")"}>{leds}</g>);
}
})
//---------------------------------------------------------------------------------
var LedWheel = React.createClass({
// The state is minumum of the radius sepcified in the props, and the available radius
getInitialState:function() {
console.log("LedWheel.getInitialState", this.props.radius);
return {radius:this.props.radius};
},
computeAvailableRadius:function() {
console.log("LedWheel.computeAvailableRadius", this.props.radius);
if (this.elem) {
// calculate parent's width - padding
var p = this.elem.parentNode;
var s= window.getComputedStyle(p);
var w = p.clientWidth - parseFloat(s.paddingLeft) - parseFloat(s.paddingLeft); // Need parseFloat to get rid of px in 14px
// Divide width by 2, and leave off an extra pixel
var r = Math.min(this.props.radius, Math.round(w/2));
console.log("Computed Radius", r);
this.setState({radius:r})
}
},
handleResize: function(e) {
this.computeAvailableRadius();
},
componentDidMount: function() {
this.computeAvailableRadius();
window.addEventListener('resize', 100, this.handleResize);
},
componentWillUnmount: function() {
window.removeEventListener('resize', this.handleResize);
},
getDefaultProps: function() {
return { radius:200 };
},
// thickeness is calculated from radius as follows
// radius^2 = thickness/2 ^2 + (r1 + thickness)^2
// thickness/2 / r1 = tan(PI/24)
// Solving
// r1 = thickness / (2*tan(PI/24))
// radius^2 = thickness^2 * ( (1/2)^2 + (1/(2*tan(PI/24) + 1)^2 )
render: function() {
var radius = this.state.radius-1;
var thickness = radius / Math.sqrt(0.25 + Math.pow(1 + (1/(2*Math.tan(Math.PI/24))), 2) );
var r1 = thickness / (2 * Math.tan(Math.PI/24));
var r2 = thickness / (2 * Math.tan(Math.PI/12));
var self = this;
return (<svg
ref={function(input) { self.elem = input; }}
height={radius*2} width={radius*2}>
<LedOneWheel
ref={function(input) { outerWheel = input; }}
key="g0" n={24} radius={radius} thickness={thickness} circleIndex={0} r={r1}/>
<LedOneWheel
ref={function(input) { innerWheel = input; }}
key="g1" n={12} radius={radius} thickness={thickness} circleIndex={1} r={r2}/>
</svg>);
}
})
//---------------------------------------------------------------------------------
var HueSquare = React.createClass({
getInitialState: function() {
return {hue:0}; // initial hue is 0, inicial color is red
},
getDefaultProps: function() {
return { n: 8, radius:100, thickness:30 };
},
render: function() {
var n = this.props.n;
var radius = this.props.radius;
var thickness = this.props.thickness;
var radius2 = radius - thickness - thickness/2;
var squareSize = 2 * radius2/Math.sqrt(2) - 2; // side of square that fits in inner circle
var smallSquareSize = squareSize/n;
var colorSquares = [];
var sat = 255;
for(var j = 0; j < n; j++) {
var val = 255;
for(var i = 0; i < n; i++) {
var hsv = {hue:this.state.hue, sat:sat, val:val};
var rgb = hsv2rgb(hsv);
//console.log(hsv, rgb);
colorSquares.push(<path
key={"path" + j + "_" + i}
d={
"M" + (radius -squareSize/2 + squareSize*j/n) + "," + (radius - squareSize/2 + squareSize*i/n) + " " +
"l" + (+smallSquareSize) + "," + 0 + " " +
"l" + 0 + "," + (+smallSquareSize) + " " +
"l" + (-smallSquareSize) + "," + 0 + " " +
"z"
}
fill={"rgb(" + rgb.r + "," + rgb.g + "," + rgb.b + ")"}
stroke = "none"
/>);
val = val -256/n;
}
sat = sat -256/n;
}
return (<g>{colorSquares}</g>);
}
})
//---------------------------------------------------------------------------------
var ColorWheel = React.createClass({
// The state is minumum of the radius sepcified in the props, and the available radius
getInitialState:function() {
console.log("ColorWheel.getInitialState", this.props.radius);
return {radius:this.props.radius, hueIndex:0, hue:0, rgb:{r:255,g:0,b:0}}; // initial hue is 0, inicial color is red
},
computeAvailableRadius:function() {
if (this.elem) {
// calculate parent's width - padding
var p = this.elem.parentNode;
var s= window.getComputedStyle(p);
var w = p.clientWidth - parseFloat(s.paddingLeft) - parseFloat(s.paddingLeft); // Need parseFloat to get rid of px in 14px
// Divide width by 2, and leave off an extra pixel
var r = Math.min(this.props.radius, Math.round(w/2));
console.log("Computed Radius", r);
this.setState({radius:r})
}
},
handleResize: function(e) {
this.computeAvailableRadius();
},
componentDidMount: function() {
this.computeAvailableRadius();
window.addEventListener('resize', this.handleResize);
globalColorWheel = this;
},
componentWillUnmount: function() {
window.removeEventListener('resize', this.handleResize);
},
selectHue: function(i, hue, rgb) {
this.setState({hueIndex:i, hue:hue, rgb:rgb});
this.hueSquare.setState({hue:hue});
},
getDefaultProps: function() {
return { n: 24, radius:100};
},
render: function() {
var n = this.props.n;
var radius = this.state.radius -1;
var thickness = Math.round(radius/3);
// radus is the outer radius
var radius2 = radius - thickness - thickness/2;
var radius3 = radius - thickness/2;
var colorSegments = [];
for(var i = 0; i < n; i++) {
var a1 = Math.PI * 2 * i / n;
var a2 = Math.PI * 2 * (i+1)/n;
var hue = Math.round(256 * i/n);
var hsv = {hue:hue, sat:255, val:255};
var rgb = hsv2rgb(hsv);
var r = this.state.hueIndex == i ? radius : radius3;
//console.log(hsv, rgb);
colorSegments.push(<path
key={"path" + i}
id={"path" + i}
d={
"M" + (radius + Math.round(Math.cos(a1) * r)) + "," + (radius - Math.round(Math.sin(a1) * r)) + " " +
"A" + r + "," + r + " 0 0,0 " + (radius + Math.round(Math.cos(a2) * r)) + "," + (radius - Math.round(Math.sin(a2) * r)) + " " +
"L" + (radius + Math.round(Math.cos(a2) * radius2)) + "," + (radius - Math.round(Math.sin(a2) * radius2)) + " " +
"A" + radius2 + "," + radius2 + " 0 0,1 " + (radius + Math.round(Math.cos(a1) * radius2)) + "," + (radius - Math.round(Math.sin(a1) * radius2)) + " " +
"Z"
}
fill={"rgb(" + rgb.r + "," + rgb.g + "," + rgb.b + ")"}
stroke = "black"
strokeWidth = {this.state.hueIndex == i ? "1.5" : "1"}
onClick = {this.selectHue.bind(this, i, hue, rgb)}
/>);
}
console.log("ColorWheel", radius);
var self = this;
return (<svg height={radius*2} width={radius*2}
ref={function(input) { self.elem = input; }}
>
<g>{colorSegments}</g>
<HueSquare
ref={function(input) {self.hueSquare = input }}
radius={this.state.radius} n={8} thickness={thickness} />
</svg>);
}
})
//---------------------------------------------------------------------------------
var LeftRightArrow = React.createClass({
changeSpeed:function(speedInc) {
this.setState({speed:(this.state.speed + speedInc)});
},
getInitialState: function() {
return {speed:0};
},
render: function() {
return(
<div className="inline fields">
<div class="field">
<label>{this.props.label}</label>
<button type="button" className="ui compact icon button" onClick={this.changeSpeed.bind(this, -1)}><i className="left chevron icon"></i></button>
<label>{this.state.speed}</label>
<button type="button" className="ui compact icon button" onClick={this.changeSpeed.bind(this, +1)}><i className="right chevron icon"></i></button>
</div>
</div>);
}
})
//---------------------------------------------------------------------------------
ReactDOM.render(
<LedWheel radius={200}/>,
document.getElementById('main')
)
ReactDOM.render(
<ColorWheel radius={100} n={24}/>,
document.getElementById('right')
)
ReactDOM.render(
<form className="ui form">
<LeftRightArrow label="Outer Circle" wheelObj={outerWheel}/>
<LeftRightArrow label="Inner Circle" wheelObj={innerWheel}/>
</form>,
document.getElementById('left')
)
window.setInterval(callTimerCallbacks, 20);
| scripts/main.js | var globalColorWheel;
var timersList = [];
var outerWheel, innerWheel;
var count = 0;
function callTimerCallbacks() {
count = (count + 1) % 60;
for(var i = 0; i < timersList.length; i++) {
timersList[i](count);
}
}
//---------------------------------------------------------------------------------
var Led = React.createClass({
getInitialState:function() {
return {rgb:{r:255, g:0, b:0}}; // Set it to red
},
setLed: function() {
this.setState({rgb:globalColorWheel.state.rgb});
},
render: function(){
var x = this.props.x;
var y = this.props.y;
var a = this.props.angle;
var thickness = this.props.thickness;
var dx = Math.round(Math.cos(a) * (thickness-2));
var dy = Math.round(Math.sin(a) * (thickness-2));
var rgb = this.state.rgb;
return(
<path
d={
"M" + x + "," + y + " " +
"l" + (+dy/2) + "," + (dx/2) + " " +
"l" + (+dx) + "," + (-dy) + " " +
"l" + (-dy) + "," + (-dx) + " " +
"l" + (-dx) + "," + (+dy) + " " +
"z"
}
fill={"rgb(" + rgb.r + "," + rgb.g + "," + rgb.b + ")"}
stroke = "black"
onClick = {this.setLed}
/>);
}
})
//---------------------------------------------------------------------------------
var LedOneWheel = React.createClass({
getInitialState:function() {
return {speed:0, angle:0, counter:60};
},
changeSpeed:function(speedInc) {
if ((speedInc == 1 && this.state.speed < 1)
|| (speedInc == -1 && this.state.speed > -1)) {
console.log("LedOneWheel n=", this.props.n, " speedInc=", speedInc);
this.setState({speed:this.state.speed + speedInc})
}
},
tick:function(count) {
if (this.state.speed == 0)
return;
if (count==0 || count % this.state.counter == 0) {
var a = this.state.angle;
a = (a + this.state.speed) % this.props.n;
this.setState({angle:a});
}
},
componentDidMount: function() {
timersList.push(this.tick);
console.log("Adding timer for LedOneWheel");
},
componentWillUnmount: function() {
var index = timersList.indexof(this.tick);
if (index > -1) timersList.splice( index, 1 );
console.log("Removing timer for LedOneWheel");
},
render:function() {
var n = this.props.n;
var radius = this.props.radius;
var r = this.props.r;
var thickness = this.props.thickness;
var r2 = r - thickness;
var leds = [];
for(var i = 0; i < n; i++) {
var a1 = Math.PI * 2 * i / n;
var x = radius + Math.round(Math.cos(a1)*r);
var y = radius - Math.round(Math.sin(a1)*r);
leds.push(<Led key={i} angle={a1} thickness={thickness-2} x={x} y={y}/>);
}
return (<g transform={"rotate(" + (360* this.state.angle/n) + " " + radius + " " + radius + ")"}>{leds}</g>);
}
})
//---------------------------------------------------------------------------------
var LedWheel = React.createClass({
// The state is minumum of the radius sepcified in the props, and the available radius
getInitialState:function() {
console.log("LedWheel.getInitialState", this.props.radius);
return {radius:this.props.radius};
},
computeAvailableRadius:function() {
console.log("LedWheel.computeAvailableRadius", this.props.radius);
if (this.elem) {
// calculate parent's width - padding
var p = this.elem.parentNode;
var s= window.getComputedStyle(p);
var w = p.clientWidth - parseFloat(s.paddingLeft) - parseFloat(s.paddingLeft); // Need parseFloat to get rid of px in 14px
// Divide width by 2, and leave off an extra pixel
var r = Math.min(this.props.radius, Math.round(w/2));
console.log("Computed Radius", r);
this.setState({radius:r})
}
},
handleResize: function(e) {
this.computeAvailableRadius();
},
componentDidMount: function() {
this.computeAvailableRadius();
window.addEventListener('resize', 100, this.handleResize);
},
componentWillUnmount: function() {
window.removeEventListener('resize', this.handleResize);
},
getDefaultProps: function() {
return { radius:200 };
},
// thickeness is calculated from radius as follows
// radius^2 = thickness/2 ^2 + (r1 + thickness)^2
// thickness/2 / r1 = tan(PI/24)
// Solving
// r1 = thickness / (2*tan(PI/24))
// radius^2 = thickness^2 * ( (1/2)^2 + (1/(2*tan(PI/24) + 1)^2 )
render: function() {
var radius = this.state.radius-1;
var thickness = radius / Math.sqrt(0.25 + Math.pow(1 + (1/(2*Math.tan(Math.PI/24))), 2) );
var r1 = thickness / (2 * Math.tan(Math.PI/24));
var r2 = thickness / (2 * Math.tan(Math.PI/12));
var self = this;
return (<svg
ref={function(input) { self.elem = input; }}
height={radius*2} width={radius*2}>
<LedOneWheel
ref={function(input) { outerWheel = input; }}
key="g0" n={24} radius={radius} thickness={thickness} circleIndex={0} r={r1}/>
<LedOneWheel
ref={function(input) { innerWheel = input; }}
key="g1" n={12} radius={radius} thickness={thickness} circleIndex={1} r={r2}/>
</svg>);
}
})
//---------------------------------------------------------------------------------
var HueSquare = React.createClass({
getInitialState: function() {
return {hue:0}; // initial hue is 0, inicial color is red
},
getDefaultProps: function() {
return { n: 8, radius:100, thickness:30 };
},
render: function() {
var n = this.props.n;
var radius = this.props.radius;
var thickness = this.props.thickness;
var radius2 = radius - thickness - thickness/2;
var squareSize = 2 * radius2/Math.sqrt(2) - 2; // side of square that fits in inner circle
var smallSquareSize = squareSize/n;
var colorSquares = [];
var sat = 255;
for(var j = 0; j < n; j++) {
var val = 255;
for(var i = 0; i < n; i++) {
var hsv = {hue:this.state.hue, sat:sat, val:val};
var rgb = hsv2rgb(hsv);
//console.log(hsv, rgb);
colorSquares.push(<path
key={"path" + j + "_" + i}
d={
"M" + (radius -squareSize/2 + squareSize*j/n) + "," + (radius - squareSize/2 + squareSize*i/n) + " " +
"l" + (+smallSquareSize) + "," + 0 + " " +
"l" + 0 + "," + (+smallSquareSize) + " " +
"l" + (-smallSquareSize) + "," + 0 + " " +
"z"
}
fill={"rgb(" + rgb.r + "," + rgb.g + "," + rgb.b + ")"}
stroke = "none"
/>);
val = val -256/n;
}
sat = sat -256/n;
}
return (<g>{colorSquares}</g>);
}
})
//---------------------------------------------------------------------------------
var ColorWheel = React.createClass({
// The state is minumum of the radius sepcified in the props, and the available radius
getInitialState:function() {
console.log("ColorWheel.getInitialState", this.props.radius);
return {radius:this.props.radius, hueIndex:0, hue:0, rgb:{r:255,g:0,b:0}}; // initial hue is 0, inicial color is red
},
computeAvailableRadius:function() {
if (this.elem) {
// calculate parent's width - padding
var p = this.elem.parentNode;
var s= window.getComputedStyle(p);
var w = p.clientWidth - parseFloat(s.paddingLeft) - parseFloat(s.paddingLeft); // Need parseFloat to get rid of px in 14px
// Divide width by 2, and leave off an extra pixel
var r = Math.min(this.props.radius, Math.round(w/2));
console.log("Computed Radius", r);
this.setState({radius:r})
}
},
handleResize: function(e) {
this.computeAvailableRadius();
},
componentDidMount: function() {
this.computeAvailableRadius();
window.addEventListener('resize', this.handleResize);
globalColorWheel = this;
},
componentWillUnmount: function() {
window.removeEventListener('resize', this.handleResize);
},
selectHue: function(i, hue, rgb) {
this.setState({hueIndex:i, hue:hue, rgb:rgb});
this.hueSquare.setState({hue:hue});
},
getDefaultProps: function() {
return { n: 24, radius:100};
},
render: function() {
var n = this.props.n;
var radius = this.state.radius -1;
var thickness = Math.round(radius/3);
// radus is the outer radius
var radius2 = radius - thickness - thickness/2;
var radius3 = radius - thickness/2;
var colorSegments = [];
for(var i = 0; i < n; i++) {
var a1 = Math.PI * 2 * i / n;
var a2 = Math.PI * 2 * (i+1)/n;
var hue = Math.round(256 * i/n);
var hsv = {hue:hue, sat:255, val:255};
var rgb = hsv2rgb(hsv);
var r = this.state.hueIndex == i ? radius : radius3;
//console.log(hsv, rgb);
colorSegments.push(<path
key={"path" + i}
id={"path" + i}
d={
"M" + (radius + Math.round(Math.cos(a1) * r)) + "," + (radius - Math.round(Math.sin(a1) * r)) + " " +
"A" + r + "," + r + " 0 0,0 " + (radius + Math.round(Math.cos(a2) * r)) + "," + (radius - Math.round(Math.sin(a2) * r)) + " " +
"L" + (radius + Math.round(Math.cos(a2) * radius2)) + "," + (radius - Math.round(Math.sin(a2) * radius2)) + " " +
"A" + radius2 + "," + radius2 + " 0 0,1 " + (radius + Math.round(Math.cos(a1) * radius2)) + "," + (radius - Math.round(Math.sin(a1) * radius2)) + " " +
"Z"
}
fill={"rgb(" + rgb.r + "," + rgb.g + "," + rgb.b + ")"}
stroke = "black"
strokeWidth = {this.state.hueIndex == i ? "1.5" : "1"}
onClick = {this.selectHue.bind(this, i, hue, rgb)}
/>);
}
console.log("ColorWheel", radius);
var self = this;
return (<svg height={radius*2} width={radius*2}
ref={function(input) { self.elem = input; }}
>
<g>{colorSegments}</g>
<HueSquare
ref={function(input) {self.hueSquare = input }}
radius={this.state.radius} n={8} thickness={thickness} />
</svg>);
}
})
//---------------------------------------------------------------------------------
var LeftRightArrow = React.createClass({
changeSpeed:function(speedInc) {
this.setState({speed:(this.state.speed + speedInc)});
},
getInitialState: function() {
return {speed:0};
},
render: function() {
return( <div className="inline fields">
<label>{this.props.label}</label>
<button type="button" className="ui compact icon button" onClick={this.changeSpeed.bind(this, -1)}><i className="left chevron icon"></i></button>
<label>{this.state.speed}</label>
<button type="button" className="ui compact icon button" onClick={this.changeSpeed.bind(this, +1)}><i className="right chevron icon"></i></button>
</div>);
}
})
//---------------------------------------------------------------------------------
ReactDOM.render(
<LedWheel radius={200}/>,
document.getElementById('main')
)
ReactDOM.render(
<ColorWheel radius={100} n={24}/>,
document.getElementById('right')
)
ReactDOM.render(
<form className="ui form">
<LeftRightArrow label="Outer Circle" wheelObj={outerWheel}/>
<LeftRightArrow label="Inner Circle" wheelObj={innerWheel}/>
</form>,
document.getElementById('left')
)
window.setInterval(callTimerCallbacks, 20);
| Update main.js | scripts/main.js | Update main.js | <ide><path>cripts/main.js
<ide> },
<ide>
<ide> render: function() {
<del> return( <div className="inline fields">
<add> return(
<add> <div className="inline fields">
<add> <div class="field">
<ide> <label>{this.props.label}</label>
<ide> <button type="button" className="ui compact icon button" onClick={this.changeSpeed.bind(this, -1)}><i className="left chevron icon"></i></button>
<ide> <label>{this.state.speed}</label>
<ide> <button type="button" className="ui compact icon button" onClick={this.changeSpeed.bind(this, +1)}><i className="right chevron icon"></i></button>
<del> </div>);
<add> </div>
<add> </div>);
<ide> }
<ide> })
<ide> |
|
JavaScript | mit | 4ca344922ca0fe7aedaec8e2d2ef1d95fda62c3a | 0 | monkbroc/handwriting-sheet,monkbroc/handwriting-sheet | $(document).ready(function() {
/* === Models === */
var EditorState = Backbone.Model.extend({
defaults: {
wideSpacing: true,
allCaps: true,
mode: 'singleLine',
},
singleLine: function() {
return this.get('mode') == 'singleLine';
},
multiLine: function() {
return !this.singleLine();
},
id: 'singleton',
localStorage: new Backbone.LocalStorage("EditorState"),
});
var PracticeText = Backbone.Model.extend({
defaults: {
lines: ['ABC'],
},
id: 'singleton',
localStorage: new Backbone.LocalStorage("PracticeText"),
});
/* === Views === */
var ControlsView = Backbone.View.extend({
/* Pass in state and el to constructor */
initialize: function(options) {
_.extend(this, options);
this.$wideSpacing = this.$("#wide-spacing");
this.$allCaps = this.$("#all-caps");
this.$mode = this.$('input[name="mode"]');
},
events: {
'change #wide-spacing': 'wideSpacingChanged',
'change #all-caps': 'allCapsChanged',
'change [name="mode"]': 'modeChanged',
'click #print': 'print',
},
wideSpacingChanged: function(event) {
var val = this.$wideSpacing.prop('checked');
this.state.save('wideSpacing', val);
},
allCapsChanged: function(event) {
var val = this.$allCaps.prop('checked');
this.state.save('allCaps', val);
},
modeChanged: function(event) {
var val = this.$mode.filter(function(index, element) {
return element.checked;
}).val();
this.state.save('mode', val);
},
render: function() {
this.$wideSpacing.prop('checked', this.state.get('wideSpacing'));
this.$allCaps.prop('checked', this.state.get('allCaps'));
var mode = this.state.get('mode');
this.$mode.filter(function(index, element) {
return $(element).val() == mode;
}).prop('checked', true);
return this;
},
print: function() {
window.print();
},
});
var SheetView = Backbone.View.extend({
/* Pass model, state and el to constructor */
initialize: function(options) {
_.extend(this, options);
_.bindAll(this, 'render');
this.listenTo(this.model, 'change', this.render);
this.listenTo(this.state, 'change', this.render);
this.$guidelines = this.$(".guideline");
this.$firstLine = this.$guidelines.first();
this.$otherLines = this.$guidelines.slice(1);
this.$writeHere = this.$(".write-here");
},
events: {
"input .guideline": "updateLine",
// Events for old IE
"keyup .guideline": "updateLine",
"cut .guideline": "updateLine",
"blur .guideline": "updateLine",
"paste .guideline": "updateLine",
},
updateLine: function(event) {
var $el = $(event.target);
var lineNum = this.$guidelines.index($el);
if(lineNum < 0) {
console.log("Bad line number in updateLine");
return;
}
var lines = _.clone(this.model.get('lines'));
lines[lineNum] = $el.html();
this.model.save('lines', lines);
},
render: function() {
this.$el.toggleClass("all-caps", this.state.get('allCaps'));
this.$el.toggleClass("wide-spacing", this.state.get('wideSpacing'));
var lines = this.model.get('lines');
this.$el.toggleClass("single-line-mode", this.state.singleLine());
var mode = this.state.get('mode');
var $active = $(document.activeElement);
switch(mode) {
case 'singleLine':
var text = lines[0];
this.$firstLine.attr('contenteditable', true);
this.$otherLines.attr('contenteditable', false);
this.$guidelines.not($active).html(text);
break;
case 'multiLine':
this.$guidelines.attr('contenteditable', true);
this.$guidelines.each(function(line) {
$(this).not($active).html(lines[line] || '');
});
break;
}
},
});
/* === Application start === */
var editorState = new EditorState();
var practiceText = new PracticeText();
var controls = new ControlsView({
state: editorState,
el: $(".controls")
});
var sheet = new SheetView({
state: editorState,
model: practiceText,
el: $(".sheet")
});
editorState.fetch();
practiceText.fetch();
controls.render();
sheet.render();
/* === Widgets === */
$('[data-toggle="check"]').radiocheck();
$('[data-toggle="radio"]').radiocheck();
});
// vim: sw=2 expandtab
| js/handwriting.js | $(document).ready(function() {
/* === Models === */
var EditorState = Backbone.Model.extend({
defaults: {
wideSpacing: true,
allCaps: true,
mode: 'singleLine',
},
singleLine: function() {
return this.get('mode') == 'singleLine';
},
multiLine: function() {
return !this.singleLine();
},
id: 'singleton',
localStorage: new Backbone.LocalStorage("EditorState"),
});
var PracticeText = Backbone.Model.extend({
defaults: {
lines: ['ABC'],
},
id: 'singleton',
localStorage: new Backbone.LocalStorage("PracticeText"),
});
/* === Views === */
var ControlsView = Backbone.View.extend({
/* Pass in state and el to constructor */
initialize: function(options) {
_.extend(this, options);
this.$wideSpacing = this.$("#wide-spacing");
this.$allCaps = this.$("#all-caps");
this.$mode = this.$('input[name="mode"]');
},
events: {
'change #wide-spacing': 'wideSpacingChanged',
'change #all-caps': 'allCapsChanged',
'change [name="mode"]': 'modeChanged',
'click #print': 'print',
},
wideSpacingChanged: function(event) {
var val = this.$wideSpacing.prop('checked');
this.state.save('wideSpacing', val);
},
allCapsChanged: function(event) {
var val = this.$allCaps.prop('checked');
this.state.save('allCaps', val);
},
modeChanged: function(event) {
var val = this.$mode.filter(function(index, element) {
return element.checked;
}).val();
this.state.save('mode', val);
},
render: function() {
this.$wideSpacing.prop('checked', this.state.get('wideSpacing'));
this.$allCaps.prop('checked', this.state.get('allCaps'));
var mode = this.state.get('mode');
this.$mode.filter(function(index, element) {
return $(element).val() == mode;
}).prop('checked', true);
return this;
},
print: function() {
window.print();
},
});
var SheetView = Backbone.View.extend({
/* Pass model, state and el to constructor */
initialize: function(options) {
_.extend(this, options);
_.bindAll(this, 'render');
this.listenTo(this.model, 'change', this.render);
this.listenTo(this.state, 'change', this.render);
this.$guidelines = this.$(".guideline");
this.$firstLine = this.$guidelines.first();
this.$otherLines = this.$guidelines.slice(1);
this.$writeHere = this.$(".write-here");
},
events: {
"input .guideline": "updateLine",
// Events for old IE
"keyup .guideline": "updateLine",
"cut .guideline": "updateLine",
"blur .guideline": "updateLine",
"paste .guideline": "updateLine",
},
updateLine: function(event) {
var $el = $(event.target);
var lineNum = this.$guidelines.index($el);
if(lineNum < 0) {
console.log("Bad line number in updateLine");
return;
}
var lines = _.clone(this.model.get('lines'));
lines[lineNum] = $el.html();
this.model.save('lines', lines);
},
render: function() {
this.$el.toggleClass("all-caps", this.state.get('allCaps'));
this.$el.toggleClass("wide-spacing", this.state.get('wideSpacing'));
var lines = this.model.get('lines');
this.$el.toggleClass("single-line-mode", this.state.singleLine());
var mode = this.state.get('mode');
switch(mode) {
case 'singleLine':
var text = lines[0];
this.$firstLine.attr('contenteditable', true);
this.$otherLines.attr('contenteditable', false);
this.$guidelines.html(text);
break;
case 'multiLine':
this.$guidelines.attr('contenteditable', true);
this.$guidelines.each(function(line) {
$(this).html(lines[line] || '');
});
break;
}
},
});
/* === Application start === */
var editorState = new EditorState();
var practiceText = new PracticeText();
var controls = new ControlsView({
state: editorState,
el: $(".controls")
});
var sheet = new SheetView({
state: editorState,
model: practiceText,
el: $(".sheet")
});
editorState.fetch();
practiceText.fetch();
controls.render();
sheet.render();
/* === Widgets === */
$('[data-toggle="check"]').radiocheck();
$('[data-toggle="radio"]').radiocheck();
});
// vim: sw=2 expandtab
| Work around Firefox issue with replacing HTML of focused element
| js/handwriting.js | Work around Firefox issue with replacing HTML of focused element | <ide><path>s/handwriting.js
<ide> this.$el.toggleClass("single-line-mode", this.state.singleLine());
<ide>
<ide> var mode = this.state.get('mode');
<add> var $active = $(document.activeElement);
<ide> switch(mode) {
<ide> case 'singleLine':
<ide> var text = lines[0];
<ide> this.$firstLine.attr('contenteditable', true);
<ide> this.$otherLines.attr('contenteditable', false);
<del> this.$guidelines.html(text);
<add> this.$guidelines.not($active).html(text);
<ide> break;
<ide> case 'multiLine':
<ide> this.$guidelines.attr('contenteditable', true);
<ide> this.$guidelines.each(function(line) {
<del> $(this).html(lines[line] || '');
<add> $(this).not($active).html(lines[line] || '');
<ide> });
<ide> break;
<ide> } |
|
Java | apache-2.0 | 2ca30191d2bb430a4b27b125177406cf263d444f | 0 | apache/kafka,Chasego/kafka,TiVo/kafka,TiVo/kafka,TiVo/kafka,Chasego/kafka,noslowerdna/kafka,lindong28/kafka,apache/kafka,lindong28/kafka,sslavic/kafka,lindong28/kafka,noslowerdna/kafka,apache/kafka,noslowerdna/kafka,guozhangwang/kafka,lindong28/kafka,sslavic/kafka,Chasego/kafka,guozhangwang/kafka,guozhangwang/kafka,sslavic/kafka,noslowerdna/kafka,sslavic/kafka,guozhangwang/kafka,apache/kafka,TiVo/kafka,Chasego/kafka | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.kafka.clients.producer.internals;
import java.nio.ByteBuffer;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.kafka.clients.ApiVersions;
import org.apache.kafka.clients.producer.Callback;
import org.apache.kafka.common.Cluster;
import org.apache.kafka.common.KafkaException;
import org.apache.kafka.common.MetricName;
import org.apache.kafka.common.Node;
import org.apache.kafka.common.PartitionInfo;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.errors.UnsupportedVersionException;
import org.apache.kafka.common.header.Header;
import org.apache.kafka.common.metrics.Measurable;
import org.apache.kafka.common.metrics.MetricConfig;
import org.apache.kafka.common.metrics.Metrics;
import org.apache.kafka.common.metrics.Sensor;
import org.apache.kafka.common.metrics.stats.Meter;
import org.apache.kafka.common.record.AbstractRecords;
import org.apache.kafka.common.record.CompressionRatioEstimator;
import org.apache.kafka.common.record.CompressionType;
import org.apache.kafka.common.record.MemoryRecords;
import org.apache.kafka.common.record.MemoryRecordsBuilder;
import org.apache.kafka.common.record.Record;
import org.apache.kafka.common.record.RecordBatch;
import org.apache.kafka.common.record.TimestampType;
import org.apache.kafka.common.utils.CopyOnWriteMap;
import org.apache.kafka.common.utils.LogContext;
import org.apache.kafka.common.utils.Time;
import org.slf4j.Logger;
/**
* This class acts as a queue that accumulates records into {@link MemoryRecords}
* instances to be sent to the server.
* <p>
* The accumulator uses a bounded amount of memory and append calls will block when that memory is exhausted, unless
* this behavior is explicitly disabled.
*/
public final class RecordAccumulator {
private final Logger log;
private volatile boolean closed;
private final AtomicInteger flushesInProgress;
private final AtomicInteger appendsInProgress;
private final int batchSize;
private final CompressionType compression;
private final int lingerMs;
private final long retryBackoffMs;
private final int deliveryTimeoutMs;
private final BufferPool free;
private final Time time;
private final ApiVersions apiVersions;
private final ConcurrentMap<TopicPartition, Deque<ProducerBatch>> batches;
private final IncompleteBatches incomplete;
// The following variables are only accessed by the sender thread, so we don't need to protect them.
private final Map<TopicPartition, Long> muted;
private int drainIndex;
private final TransactionManager transactionManager;
private long nextBatchExpiryTimeMs = Long.MAX_VALUE; // the earliest time (absolute) a batch will expire.
/**
* Create a new record accumulator
*
* @param logContext The log context used for logging
* @param batchSize The size to use when allocating {@link MemoryRecords} instances
* @param compression The compression codec for the records
* @param lingerMs An artificial delay time to add before declaring a records instance that isn't full ready for
* sending. This allows time for more records to arrive. Setting a non-zero lingerMs will trade off some
* latency for potentially better throughput due to more batching (and hence fewer, larger requests).
* @param retryBackoffMs An artificial delay time to retry the produce request upon receiving an error. This avoids
* exhausting all retries in a short period of time.
* @param metrics The metrics
* @param time The time instance to use
* @param apiVersions Request API versions for current connected brokers
* @param transactionManager The shared transaction state object which tracks producer IDs, epochs, and sequence
* numbers per partition.
*/
public RecordAccumulator(LogContext logContext,
int batchSize,
CompressionType compression,
int lingerMs,
long retryBackoffMs,
int deliveryTimeoutMs,
Metrics metrics,
String metricGrpName,
Time time,
ApiVersions apiVersions,
TransactionManager transactionManager,
BufferPool bufferPool) {
this.log = logContext.logger(RecordAccumulator.class);
this.drainIndex = 0;
this.closed = false;
this.flushesInProgress = new AtomicInteger(0);
this.appendsInProgress = new AtomicInteger(0);
this.batchSize = batchSize;
this.compression = compression;
this.lingerMs = lingerMs;
this.retryBackoffMs = retryBackoffMs;
this.deliveryTimeoutMs = deliveryTimeoutMs;
this.batches = new CopyOnWriteMap<>();
this.free = bufferPool;
this.incomplete = new IncompleteBatches();
this.muted = new HashMap<>();
this.time = time;
this.apiVersions = apiVersions;
this.transactionManager = transactionManager;
registerMetrics(metrics, metricGrpName);
}
private void registerMetrics(Metrics metrics, String metricGrpName) {
MetricName metricName = metrics.metricName("waiting-threads", metricGrpName, "The number of user threads blocked waiting for buffer memory to enqueue their records");
Measurable waitingThreads = new Measurable() {
public double measure(MetricConfig config, long now) {
return free.queued();
}
};
metrics.addMetric(metricName, waitingThreads);
metricName = metrics.metricName("buffer-total-bytes", metricGrpName, "The maximum amount of buffer memory the client can use (whether or not it is currently used).");
Measurable totalBytes = new Measurable() {
public double measure(MetricConfig config, long now) {
return free.totalMemory();
}
};
metrics.addMetric(metricName, totalBytes);
metricName = metrics.metricName("buffer-available-bytes", metricGrpName, "The total amount of buffer memory that is not being used (either unallocated or in the free list).");
Measurable availableBytes = new Measurable() {
public double measure(MetricConfig config, long now) {
return free.availableMemory();
}
};
metrics.addMetric(metricName, availableBytes);
Sensor bufferExhaustedRecordSensor = metrics.sensor("buffer-exhausted-records");
MetricName rateMetricName = metrics.metricName("buffer-exhausted-rate", metricGrpName, "The average per-second number of record sends that are dropped due to buffer exhaustion");
MetricName totalMetricName = metrics.metricName("buffer-exhausted-total", metricGrpName, "The total number of record sends that are dropped due to buffer exhaustion");
bufferExhaustedRecordSensor.add(new Meter(rateMetricName, totalMetricName));
}
/**
* Add a record to the accumulator, return the append result
* <p>
* The append result will contain the future metadata, and flag for whether the appended batch is full or a new batch is created
* <p>
*
* @param tp The topic/partition to which this record is being sent
* @param timestamp The timestamp of the record
* @param key The key for the record
* @param value The value for the record
* @param headers the Headers for the record
* @param callback The user-supplied callback to execute when the request is complete
* @param maxTimeToBlock The maximum time in milliseconds to block for buffer memory to be available
* @param abortOnNewBatch A boolean that indicates returning before a new batch is created and
* running the the partitioner's onNewBatch method before trying to append again
*/
public RecordAppendResult append(TopicPartition tp,
long timestamp,
byte[] key,
byte[] value,
Header[] headers,
Callback callback,
long maxTimeToBlock,
boolean abortOnNewBatch) throws InterruptedException {
// We keep track of the number of appending thread to make sure we do not miss batches in
// abortIncompleteBatches().
appendsInProgress.incrementAndGet();
ByteBuffer buffer = null;
if (headers == null) headers = Record.EMPTY_HEADERS;
try {
// check if we have an in-progress batch
Deque<ProducerBatch> dq = getOrCreateDeque(tp);
synchronized (dq) {
if (closed)
throw new KafkaException("Producer closed while send in progress");
RecordAppendResult appendResult = tryAppend(timestamp, key, value, headers, callback, dq);
if (appendResult != null)
return appendResult;
}
// we don't have an in-progress record batch try to allocate a new batch
if (abortOnNewBatch) {
// Return a result that will cause another call to append.
return new RecordAppendResult(null, false, false, true);
}
byte maxUsableMagic = apiVersions.maxUsableProduceMagic();
int size = Math.max(this.batchSize, AbstractRecords.estimateSizeInBytesUpperBound(maxUsableMagic, compression, key, value, headers));
log.trace("Allocating a new {} byte message buffer for topic {} partition {}", size, tp.topic(), tp.partition());
buffer = free.allocate(size, maxTimeToBlock);
synchronized (dq) {
// Need to check if producer is closed again after grabbing the dequeue lock.
if (closed)
throw new KafkaException("Producer closed while send in progress");
RecordAppendResult appendResult = tryAppend(timestamp, key, value, headers, callback, dq);
if (appendResult != null) {
// Somebody else found us a batch, return the one we waited for! Hopefully this doesn't happen often...
return appendResult;
}
MemoryRecordsBuilder recordsBuilder = recordsBuilder(buffer, maxUsableMagic);
ProducerBatch batch = new ProducerBatch(tp, recordsBuilder, time.milliseconds());
FutureRecordMetadata future = Objects.requireNonNull(batch.tryAppend(timestamp, key, value, headers,
callback, time.milliseconds()));
dq.addLast(batch);
incomplete.add(batch);
// Don't deallocate this buffer in the finally block as it's being used in the record batch
buffer = null;
return new RecordAppendResult(future, dq.size() > 1 || batch.isFull(), true, false);
}
} finally {
if (buffer != null)
free.deallocate(buffer);
appendsInProgress.decrementAndGet();
}
}
private MemoryRecordsBuilder recordsBuilder(ByteBuffer buffer, byte maxUsableMagic) {
if (transactionManager != null && maxUsableMagic < RecordBatch.MAGIC_VALUE_V2) {
throw new UnsupportedVersionException("Attempting to use idempotence with a broker which does not " +
"support the required message format (v2). The broker must be version 0.11 or later.");
}
return MemoryRecords.builder(buffer, maxUsableMagic, compression, TimestampType.CREATE_TIME, 0L);
}
/**
* Try to append to a ProducerBatch.
*
* If it is full, we return null and a new batch is created. We also close the batch for record appends to free up
* resources like compression buffers. The batch will be fully closed (ie. the record batch headers will be written
* and memory records built) in one of the following cases (whichever comes first): right before send,
* if it is expired, or when the producer is closed.
*/
private RecordAppendResult tryAppend(long timestamp, byte[] key, byte[] value, Header[] headers,
Callback callback, Deque<ProducerBatch> deque) {
ProducerBatch last = deque.peekLast();
if (last != null) {
FutureRecordMetadata future = last.tryAppend(timestamp, key, value, headers, callback, time.milliseconds());
if (future == null)
last.closeForRecordAppends();
else
return new RecordAppendResult(future, deque.size() > 1 || last.isFull(), false, false);
}
return null;
}
private boolean isMuted(TopicPartition tp, long now) {
// Take care to avoid unnecessary map look-ups because this method is a hotspot if producing to a
// large number of partitions
Long throttleUntilTime = muted.get(tp);
if (throttleUntilTime == null)
return false;
if (now >= throttleUntilTime) {
muted.remove(tp);
return false;
}
return true;
}
public void resetNextBatchExpiryTime() {
nextBatchExpiryTimeMs = Long.MAX_VALUE;
}
public void maybeUpdateNextBatchExpiryTime(ProducerBatch batch) {
if (batch.createdMs + deliveryTimeoutMs > 0) {
// the non-negative check is to guard us against potential overflow due to setting
// a large value for deliveryTimeoutMs
nextBatchExpiryTimeMs = Math.min(nextBatchExpiryTimeMs, batch.createdMs + deliveryTimeoutMs);
} else {
log.warn("Skipping next batch expiry time update due to addition overflow: "
+ "batch.createMs={}, deliveryTimeoutMs={}", batch.createdMs, deliveryTimeoutMs);
}
}
/**
* Get a list of batches which have been sitting in the accumulator too long and need to be expired.
*/
public List<ProducerBatch> expiredBatches(long now) {
List<ProducerBatch> expiredBatches = new ArrayList<>();
for (Map.Entry<TopicPartition, Deque<ProducerBatch>> entry : this.batches.entrySet()) {
// expire the batches in the order of sending
Deque<ProducerBatch> deque = entry.getValue();
synchronized (deque) {
while (!deque.isEmpty()) {
ProducerBatch batch = deque.getFirst();
if (batch.hasReachedDeliveryTimeout(deliveryTimeoutMs, now)) {
deque.poll();
batch.abortRecordAppends();
expiredBatches.add(batch);
} else {
maybeUpdateNextBatchExpiryTime(batch);
break;
}
}
}
}
return expiredBatches;
}
public long getDeliveryTimeoutMs() {
return deliveryTimeoutMs;
}
/**
* Re-enqueue the given record batch in the accumulator. In Sender.completeBatch method, we check
* whether the batch has reached deliveryTimeoutMs or not. Hence we do not do the delivery timeout check here.
*/
public void reenqueue(ProducerBatch batch, long now) {
batch.reenqueued(now);
Deque<ProducerBatch> deque = getOrCreateDeque(batch.topicPartition);
synchronized (deque) {
if (transactionManager != null)
insertInSequenceOrder(deque, batch);
else
deque.addFirst(batch);
}
}
/**
* Split the big batch that has been rejected and reenqueue the split batches in to the accumulator.
* @return the number of split batches.
*/
public int splitAndReenqueue(ProducerBatch bigBatch) {
// Reset the estimated compression ratio to the initial value or the big batch compression ratio, whichever
// is bigger. There are several different ways to do the reset. We chose the most conservative one to ensure
// the split doesn't happen too often.
CompressionRatioEstimator.setEstimation(bigBatch.topicPartition.topic(), compression,
Math.max(1.0f, (float) bigBatch.compressionRatio()));
Deque<ProducerBatch> dq = bigBatch.split(this.batchSize);
int numSplitBatches = dq.size();
Deque<ProducerBatch> partitionDequeue = getOrCreateDeque(bigBatch.topicPartition);
while (!dq.isEmpty()) {
ProducerBatch batch = dq.pollLast();
incomplete.add(batch);
// We treat the newly split batches as if they are not even tried.
synchronized (partitionDequeue) {
if (transactionManager != null) {
// We should track the newly created batches since they already have assigned sequences.
transactionManager.addInFlightBatch(batch);
insertInSequenceOrder(partitionDequeue, batch);
} else {
partitionDequeue.addFirst(batch);
}
}
}
return numSplitBatches;
}
// We will have to do extra work to ensure the queue is in order when requests are being retried and there are
// multiple requests in flight to that partition. If the first in flight request fails to append, then all the
// subsequent in flight requests will also fail because the sequence numbers will not be accepted.
//
// Further, once batches are being retried, we are reduced to a single in flight request for that partition. So when
// the subsequent batches come back in sequence order, they will have to be placed further back in the queue.
//
// Note that this assumes that all the batches in the queue which have an assigned sequence also have the current
// producer id. We will not attempt to reorder messages if the producer id has changed, we will throw an
// IllegalStateException instead.
private void insertInSequenceOrder(Deque<ProducerBatch> deque, ProducerBatch batch) {
// When we are requeing and have enabled idempotence, the reenqueued batch must always have a sequence.
if (batch.baseSequence() == RecordBatch.NO_SEQUENCE)
throw new IllegalStateException("Trying to re-enqueue a batch which doesn't have a sequence even " +
"though idempotency is enabled.");
if (transactionManager.nextBatchBySequence(batch.topicPartition) == null)
throw new IllegalStateException("We are re-enqueueing a batch which is not tracked as part of the in flight " +
"requests. batch.topicPartition: " + batch.topicPartition + "; batch.baseSequence: " + batch.baseSequence());
ProducerBatch firstBatchInQueue = deque.peekFirst();
if (firstBatchInQueue != null && firstBatchInQueue.hasSequence() && firstBatchInQueue.baseSequence() < batch.baseSequence()) {
// The incoming batch can't be inserted at the front of the queue without violating the sequence ordering.
// This means that the incoming batch should be placed somewhere further back.
// We need to find the right place for the incoming batch and insert it there.
// We will only enter this branch if we have multiple inflights sent to different brokers and we need to retry
// the inflight batches.
//
// Since we reenqueue exactly one batch a time and ensure that the queue is ordered by sequence always, it
// is a simple linear scan of a subset of the in flight batches to find the right place in the queue each time.
List<ProducerBatch> orderedBatches = new ArrayList<>();
while (deque.peekFirst() != null && deque.peekFirst().hasSequence() && deque.peekFirst().baseSequence() < batch.baseSequence())
orderedBatches.add(deque.pollFirst());
log.debug("Reordered incoming batch with sequence {} for partition {}. It was placed in the queue at " +
"position {}", batch.baseSequence(), batch.topicPartition, orderedBatches.size());
// Either we have reached a point where there are batches without a sequence (ie. never been drained
// and are hence in order by default), or the batch at the front of the queue has a sequence greater
// than the incoming batch. This is the right place to add the incoming batch.
deque.addFirst(batch);
// Now we have to re insert the previously queued batches in the right order.
for (int i = orderedBatches.size() - 1; i >= 0; --i) {
deque.addFirst(orderedBatches.get(i));
}
// At this point, the incoming batch has been queued in the correct place according to its sequence.
} else {
deque.addFirst(batch);
}
}
/**
* Get a list of nodes whose partitions are ready to be sent, and the earliest time at which any non-sendable
* partition will be ready; Also return the flag for whether there are any unknown leaders for the accumulated
* partition batches.
* <p>
* A destination node is ready to send data if:
* <ol>
* <li>There is at least one partition that is not backing off its send
* <li><b>and</b> those partitions are not muted (to prevent reordering if
* {@value org.apache.kafka.clients.producer.ProducerConfig#MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION}
* is set to one)</li>
* <li><b>and <i>any</i></b> of the following are true</li>
* <ul>
* <li>The record set is full</li>
* <li>The record set has sat in the accumulator for at least lingerMs milliseconds</li>
* <li>The accumulator is out of memory and threads are blocking waiting for data (in this case all partitions
* are immediately considered ready).</li>
* <li>The accumulator has been closed</li>
* </ul>
* </ol>
*/
public ReadyCheckResult ready(Cluster cluster, long nowMs) {
Set<Node> readyNodes = new HashSet<>();
long nextReadyCheckDelayMs = Long.MAX_VALUE;
Set<String> unknownLeaderTopics = new HashSet<>();
boolean exhausted = this.free.queued() > 0;
for (Map.Entry<TopicPartition, Deque<ProducerBatch>> entry : this.batches.entrySet()) {
Deque<ProducerBatch> deque = entry.getValue();
synchronized (deque) {
// When producing to a large number of partitions, this path is hot and deques are often empty.
// We check whether a batch exists first to avoid the more expensive checks whenever possible.
ProducerBatch batch = deque.peekFirst();
if (batch != null) {
TopicPartition part = entry.getKey();
Node leader = cluster.leaderFor(part);
if (leader == null) {
// This is a partition for which leader is not known, but messages are available to send.
// Note that entries are currently not removed from batches when deque is empty.
unknownLeaderTopics.add(part.topic());
} else if (!readyNodes.contains(leader) && !isMuted(part, nowMs)) {
long waitedTimeMs = batch.waitedTimeMs(nowMs);
boolean backingOff = batch.attempts() > 0 && waitedTimeMs < retryBackoffMs;
long timeToWaitMs = backingOff ? retryBackoffMs : lingerMs;
boolean full = deque.size() > 1 || batch.isFull();
boolean expired = waitedTimeMs >= timeToWaitMs;
boolean sendable = full || expired || exhausted || closed || flushInProgress();
if (sendable && !backingOff) {
readyNodes.add(leader);
} else {
long timeLeftMs = Math.max(timeToWaitMs - waitedTimeMs, 0);
// Note that this results in a conservative estimate since an un-sendable partition may have
// a leader that will later be found to have sendable data. However, this is good enough
// since we'll just wake up and then sleep again for the remaining time.
nextReadyCheckDelayMs = Math.min(timeLeftMs, nextReadyCheckDelayMs);
}
}
}
}
}
return new ReadyCheckResult(readyNodes, nextReadyCheckDelayMs, unknownLeaderTopics);
}
/**
* Check whether there are any batches which haven't been drained
*/
public boolean hasUndrained() {
for (Map.Entry<TopicPartition, Deque<ProducerBatch>> entry : this.batches.entrySet()) {
Deque<ProducerBatch> deque = entry.getValue();
synchronized (deque) {
if (!deque.isEmpty())
return true;
}
}
return false;
}
private boolean shouldStopDrainBatchesForPartition(ProducerBatch first, TopicPartition tp) {
ProducerIdAndEpoch producerIdAndEpoch = null;
if (transactionManager != null) {
if (!transactionManager.isSendToPartitionAllowed(tp))
return true;
producerIdAndEpoch = transactionManager.producerIdAndEpoch();
if (!producerIdAndEpoch.isValid())
// we cannot send the batch until we have refreshed the producer id
return true;
if (!first.hasSequence() && transactionManager.hasUnresolvedSequence(first.topicPartition))
// Don't drain any new batches while the state of previous sequence numbers
// is unknown. The previous batches would be unknown if they were aborted
// on the client after being sent to the broker at least once.
return true;
int firstInFlightSequence = transactionManager.firstInFlightSequence(first.topicPartition);
if (firstInFlightSequence != RecordBatch.NO_SEQUENCE && first.hasSequence()
&& first.baseSequence() != firstInFlightSequence)
// If the queued batch already has an assigned sequence, then it is being retried.
// In this case, we wait until the next immediate batch is ready and drain that.
// We only move on when the next in line batch is complete (either successfully or due to
// a fatal broker error). This effectively reduces our in flight request count to 1.
return true;
}
return false;
}
private List<ProducerBatch> drainBatchesForOneNode(Cluster cluster, Node node, int maxSize, long now) {
int size = 0;
List<PartitionInfo> parts = cluster.partitionsForNode(node.id());
List<ProducerBatch> ready = new ArrayList<>();
/* to make starvation less likely this loop doesn't start at 0 */
int start = drainIndex = drainIndex % parts.size();
do {
PartitionInfo part = parts.get(drainIndex);
TopicPartition tp = new TopicPartition(part.topic(), part.partition());
this.drainIndex = (this.drainIndex + 1) % parts.size();
// Only proceed if the partition has no in-flight batches.
if (isMuted(tp, now))
continue;
Deque<ProducerBatch> deque = getDeque(tp);
if (deque == null)
continue;
synchronized (deque) {
// invariant: !isMuted(tp,now) && deque != null
ProducerBatch first = deque.peekFirst();
if (first == null)
continue;
// first != null
boolean backoff = first.attempts() > 0 && first.waitedTimeMs(now) < retryBackoffMs;
// Only drain the batch if it is not during backoff period.
if (backoff)
continue;
if (size + first.estimatedSizeInBytes() > maxSize && !ready.isEmpty()) {
// there is a rare case that a single batch size is larger than the request size due to
// compression; in this case we will still eventually send this batch in a single request
break;
} else {
if (shouldStopDrainBatchesForPartition(first, tp))
break;
boolean isTransactional = transactionManager != null && transactionManager.isTransactional();
ProducerIdAndEpoch producerIdAndEpoch =
transactionManager != null ? transactionManager.producerIdAndEpoch() : null;
ProducerBatch batch = deque.pollFirst();
if (producerIdAndEpoch != null && !batch.hasSequence()) {
// If the batch already has an assigned sequence, then we should not change the producer id and
// sequence number, since this may introduce duplicates. In particular, the previous attempt
// may actually have been accepted, and if we change the producer id and sequence here, this
// attempt will also be accepted, causing a duplicate.
//
// Additionally, we update the next sequence number bound for the partition, and also have
// the transaction manager track the batch so as to ensure that sequence ordering is maintained
// even if we receive out of order responses.
batch.setProducerState(producerIdAndEpoch, transactionManager.sequenceNumber(batch.topicPartition), isTransactional);
transactionManager.incrementSequenceNumber(batch.topicPartition, batch.recordCount);
log.debug("Assigned producerId {} and producerEpoch {} to batch with base sequence " +
"{} being sent to partition {}", producerIdAndEpoch.producerId,
producerIdAndEpoch.epoch, batch.baseSequence(), tp);
transactionManager.addInFlightBatch(batch);
}
batch.close();
size += batch.records().sizeInBytes();
ready.add(batch);
batch.drained(now);
}
}
} while (start != drainIndex);
return ready;
}
/**
* Drain all the data for the given nodes and collate them into a list of batches that will fit within the specified
* size on a per-node basis. This method attempts to avoid choosing the same topic-node over and over.
*
* @param cluster The current cluster metadata
* @param nodes The list of node to drain
* @param maxSize The maximum number of bytes to drain
* @param now The current unix time in milliseconds
* @return A list of {@link ProducerBatch} for each node specified with total size less than the requested maxSize.
*/
public Map<Integer, List<ProducerBatch>> drain(Cluster cluster, Set<Node> nodes, int maxSize, long now) {
if (nodes.isEmpty())
return Collections.emptyMap();
Map<Integer, List<ProducerBatch>> batches = new HashMap<>();
for (Node node : nodes) {
List<ProducerBatch> ready = drainBatchesForOneNode(cluster, node, maxSize, now);
batches.put(node.id(), ready);
}
return batches;
}
/**
* The earliest absolute time a batch will expire (in milliseconds)
*/
public Long nextExpiryTimeMs() {
return this.nextBatchExpiryTimeMs;
}
private Deque<ProducerBatch> getDeque(TopicPartition tp) {
return batches.get(tp);
}
/**
* Get the deque for the given topic-partition, creating it if necessary.
*/
private Deque<ProducerBatch> getOrCreateDeque(TopicPartition tp) {
Deque<ProducerBatch> d = this.batches.get(tp);
if (d != null)
return d;
d = new ArrayDeque<>();
Deque<ProducerBatch> previous = this.batches.putIfAbsent(tp, d);
if (previous == null)
return d;
else
return previous;
}
/**
* Deallocate the record batch
*/
public void deallocate(ProducerBatch batch) {
incomplete.remove(batch);
// Only deallocate the batch if it is not a split batch because split batch are allocated outside the
// buffer pool.
if (!batch.isSplitBatch())
free.deallocate(batch.buffer(), batch.initialCapacity());
}
/**
* Package private for unit test. Get the buffer pool remaining size in bytes.
*/
long bufferPoolAvailableMemory() {
return free.availableMemory();
}
/**
* Are there any threads currently waiting on a flush?
*
* package private for test
*/
boolean flushInProgress() {
return flushesInProgress.get() > 0;
}
/* Visible for testing */
Map<TopicPartition, Deque<ProducerBatch>> batches() {
return Collections.unmodifiableMap(batches);
}
/**
* Initiate the flushing of data from the accumulator...this makes all requests immediately ready
*/
public void beginFlush() {
this.flushesInProgress.getAndIncrement();
}
/**
* Are there any threads currently appending messages?
*/
private boolean appendsInProgress() {
return appendsInProgress.get() > 0;
}
/**
* Mark all partitions as ready to send and block until the send is complete
*/
public void awaitFlushCompletion() throws InterruptedException {
try {
for (ProducerBatch batch : this.incomplete.copyAll())
batch.produceFuture.await();
} finally {
this.flushesInProgress.decrementAndGet();
}
}
/**
* Check whether there are any pending batches (whether sent or unsent).
*/
public boolean hasIncomplete() {
return !this.incomplete.isEmpty();
}
/**
* This function is only called when sender is closed forcefully. It will fail all the
* incomplete batches and return.
*/
public void abortIncompleteBatches() {
// We need to keep aborting the incomplete batch until no thread is trying to append to
// 1. Avoid losing batches.
// 2. Free up memory in case appending threads are blocked on buffer full.
// This is a tight loop but should be able to get through very quickly.
do {
abortBatches();
} while (appendsInProgress());
// After this point, no thread will append any messages because they will see the close
// flag set. We need to do the last abort after no thread was appending in case there was a new
// batch appended by the last appending thread.
abortBatches();
this.batches.clear();
}
/**
* Go through incomplete batches and abort them.
*/
private void abortBatches() {
abortBatches(new KafkaException("Producer is closed forcefully."));
}
/**
* Abort all incomplete batches (whether they have been sent or not)
*/
void abortBatches(final RuntimeException reason) {
for (ProducerBatch batch : incomplete.copyAll()) {
Deque<ProducerBatch> dq = getDeque(batch.topicPartition);
synchronized (dq) {
batch.abortRecordAppends();
dq.remove(batch);
}
batch.abort(reason);
deallocate(batch);
}
}
/**
* Abort any batches which have not been drained
*/
void abortUndrainedBatches(RuntimeException reason) {
for (ProducerBatch batch : incomplete.copyAll()) {
Deque<ProducerBatch> dq = getDeque(batch.topicPartition);
boolean aborted = false;
synchronized (dq) {
if ((transactionManager != null && !batch.hasSequence()) || (transactionManager == null && !batch.isClosed())) {
aborted = true;
batch.abortRecordAppends();
dq.remove(batch);
}
}
if (aborted) {
batch.abort(reason);
deallocate(batch);
}
}
}
public void mutePartition(TopicPartition tp) {
muted.put(tp, Long.MAX_VALUE);
}
public void unmutePartition(TopicPartition tp, long throttleUntilTimeMs) {
muted.put(tp, throttleUntilTimeMs);
}
/**
* Close this accumulator and force all the record buffers to be drained
*/
public void close() {
this.closed = true;
}
/*
* Metadata about a record just appended to the record accumulator
*/
public final static class RecordAppendResult {
public final FutureRecordMetadata future;
public final boolean batchIsFull;
public final boolean newBatchCreated;
public final boolean abortForNewBatch;
public RecordAppendResult(FutureRecordMetadata future, boolean batchIsFull, boolean newBatchCreated, boolean abortForNewBatch) {
this.future = future;
this.batchIsFull = batchIsFull;
this.newBatchCreated = newBatchCreated;
this.abortForNewBatch = abortForNewBatch;
}
}
/*
* The set of nodes that have at least one complete record batch in the accumulator
*/
public final static class ReadyCheckResult {
public final Set<Node> readyNodes;
public final long nextReadyCheckDelayMs;
public final Set<String> unknownLeaderTopics;
public ReadyCheckResult(Set<Node> readyNodes, long nextReadyCheckDelayMs, Set<String> unknownLeaderTopics) {
this.readyNodes = readyNodes;
this.nextReadyCheckDelayMs = nextReadyCheckDelayMs;
this.unknownLeaderTopics = unknownLeaderTopics;
}
}
}
| clients/src/main/java/org/apache/kafka/clients/producer/internals/RecordAccumulator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.kafka.clients.producer.internals;
import java.nio.ByteBuffer;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.kafka.clients.ApiVersions;
import org.apache.kafka.clients.producer.Callback;
import org.apache.kafka.common.Cluster;
import org.apache.kafka.common.KafkaException;
import org.apache.kafka.common.MetricName;
import org.apache.kafka.common.Node;
import org.apache.kafka.common.PartitionInfo;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.errors.UnsupportedVersionException;
import org.apache.kafka.common.header.Header;
import org.apache.kafka.common.metrics.Measurable;
import org.apache.kafka.common.metrics.MetricConfig;
import org.apache.kafka.common.metrics.Metrics;
import org.apache.kafka.common.metrics.Sensor;
import org.apache.kafka.common.metrics.stats.Meter;
import org.apache.kafka.common.record.AbstractRecords;
import org.apache.kafka.common.record.CompressionRatioEstimator;
import org.apache.kafka.common.record.CompressionType;
import org.apache.kafka.common.record.MemoryRecords;
import org.apache.kafka.common.record.MemoryRecordsBuilder;
import org.apache.kafka.common.record.Record;
import org.apache.kafka.common.record.RecordBatch;
import org.apache.kafka.common.record.TimestampType;
import org.apache.kafka.common.utils.CopyOnWriteMap;
import org.apache.kafka.common.utils.LogContext;
import org.apache.kafka.common.utils.Time;
import org.slf4j.Logger;
/**
* This class acts as a queue that accumulates records into {@link MemoryRecords}
* instances to be sent to the server.
* <p>
* The accumulator uses a bounded amount of memory and append calls will block when that memory is exhausted, unless
* this behavior is explicitly disabled.
*/
public final class RecordAccumulator {
private final Logger log;
private volatile boolean closed;
private final AtomicInteger flushesInProgress;
private final AtomicInteger appendsInProgress;
private final int batchSize;
private final CompressionType compression;
private final int lingerMs;
private final long retryBackoffMs;
private final int deliveryTimeoutMs;
private final BufferPool free;
private final Time time;
private final ApiVersions apiVersions;
private final ConcurrentMap<TopicPartition, Deque<ProducerBatch>> batches;
private final IncompleteBatches incomplete;
// The following variables are only accessed by the sender thread, so we don't need to protect them.
private final Map<TopicPartition, Long> muted;
private int drainIndex;
private final TransactionManager transactionManager;
private long nextBatchExpiryTimeMs = Long.MAX_VALUE; // the earliest time (absolute) a batch will expire.
/**
* Create a new record accumulator
*
* @param logContext The log context used for logging
* @param batchSize The size to use when allocating {@link MemoryRecords} instances
* @param compression The compression codec for the records
* @param lingerMs An artificial delay time to add before declaring a records instance that isn't full ready for
* sending. This allows time for more records to arrive. Setting a non-zero lingerMs will trade off some
* latency for potentially better throughput due to more batching (and hence fewer, larger requests).
* @param retryBackoffMs An artificial delay time to retry the produce request upon receiving an error. This avoids
* exhausting all retries in a short period of time.
* @param metrics The metrics
* @param time The time instance to use
* @param apiVersions Request API versions for current connected brokers
* @param transactionManager The shared transaction state object which tracks producer IDs, epochs, and sequence
* numbers per partition.
*/
public RecordAccumulator(LogContext logContext,
int batchSize,
CompressionType compression,
int lingerMs,
long retryBackoffMs,
int deliveryTimeoutMs,
Metrics metrics,
String metricGrpName,
Time time,
ApiVersions apiVersions,
TransactionManager transactionManager,
BufferPool bufferPool) {
this.log = logContext.logger(RecordAccumulator.class);
this.drainIndex = 0;
this.closed = false;
this.flushesInProgress = new AtomicInteger(0);
this.appendsInProgress = new AtomicInteger(0);
this.batchSize = batchSize;
this.compression = compression;
this.lingerMs = lingerMs;
this.retryBackoffMs = retryBackoffMs;
this.deliveryTimeoutMs = deliveryTimeoutMs;
this.batches = new CopyOnWriteMap<>();
this.free = bufferPool;
this.incomplete = new IncompleteBatches();
this.muted = new HashMap<>();
this.time = time;
this.apiVersions = apiVersions;
this.transactionManager = transactionManager;
registerMetrics(metrics, metricGrpName);
}
private void registerMetrics(Metrics metrics, String metricGrpName) {
MetricName metricName = metrics.metricName("waiting-threads", metricGrpName, "The number of user threads blocked waiting for buffer memory to enqueue their records");
Measurable waitingThreads = new Measurable() {
public double measure(MetricConfig config, long now) {
return free.queued();
}
};
metrics.addMetric(metricName, waitingThreads);
metricName = metrics.metricName("buffer-total-bytes", metricGrpName, "The maximum amount of buffer memory the client can use (whether or not it is currently used).");
Measurable totalBytes = new Measurable() {
public double measure(MetricConfig config, long now) {
return free.totalMemory();
}
};
metrics.addMetric(metricName, totalBytes);
metricName = metrics.metricName("buffer-available-bytes", metricGrpName, "The total amount of buffer memory that is not being used (either unallocated or in the free list).");
Measurable availableBytes = new Measurable() {
public double measure(MetricConfig config, long now) {
return free.availableMemory();
}
};
metrics.addMetric(metricName, availableBytes);
Sensor bufferExhaustedRecordSensor = metrics.sensor("buffer-exhausted-records");
MetricName rateMetricName = metrics.metricName("buffer-exhausted-rate", metricGrpName, "The average per-second number of record sends that are dropped due to buffer exhaustion");
MetricName totalMetricName = metrics.metricName("buffer-exhausted-total", metricGrpName, "The total number of record sends that are dropped due to buffer exhaustion");
bufferExhaustedRecordSensor.add(new Meter(rateMetricName, totalMetricName));
}
/**
* Add a record to the accumulator, return the append result
* <p>
* The append result will contain the future metadata, and flag for whether the appended batch is full or a new batch is created
* <p>
*
* @param tp The topic/partition to which this record is being sent
* @param timestamp The timestamp of the record
* @param key The key for the record
* @param value The value for the record
* @param headers the Headers for the record
* @param callback The user-supplied callback to execute when the request is complete
* @param maxTimeToBlock The maximum time in milliseconds to block for buffer memory to be available
* @param abortOnNewBatch A boolean that indicates returning before a new batch is created and
* running the the partitioner's onNewBatch method before trying to append again
*/
public RecordAppendResult append(TopicPartition tp,
long timestamp,
byte[] key,
byte[] value,
Header[] headers,
Callback callback,
long maxTimeToBlock,
boolean abortOnNewBatch) throws InterruptedException {
// We keep track of the number of appending thread to make sure we do not miss batches in
// abortIncompleteBatches().
appendsInProgress.incrementAndGet();
ByteBuffer buffer = null;
if (headers == null) headers = Record.EMPTY_HEADERS;
try {
// check if we have an in-progress batch
Deque<ProducerBatch> dq = getOrCreateDeque(tp);
synchronized (dq) {
if (closed)
throw new KafkaException("Producer closed while send in progress");
RecordAppendResult appendResult = tryAppend(timestamp, key, value, headers, callback, dq);
if (appendResult != null)
return appendResult;
}
// we don't have an in-progress record batch try to allocate a new batch
if (abortOnNewBatch) {
// Return a result that will cause another call to append.
return new RecordAppendResult(null, false, false, true);
}
byte maxUsableMagic = apiVersions.maxUsableProduceMagic();
int size = Math.max(this.batchSize, AbstractRecords.estimateSizeInBytesUpperBound(maxUsableMagic, compression, key, value, headers));
log.trace("Allocating a new {} byte message buffer for topic {} partition {}", size, tp.topic(), tp.partition());
buffer = free.allocate(size, maxTimeToBlock);
synchronized (dq) {
// Need to check if producer is closed again after grabbing the dequeue lock.
if (closed)
throw new KafkaException("Producer closed while send in progress");
RecordAppendResult appendResult = tryAppend(timestamp, key, value, headers, callback, dq);
if (appendResult != null) {
// Somebody else found us a batch, return the one we waited for! Hopefully this doesn't happen often...
return appendResult;
}
MemoryRecordsBuilder recordsBuilder = recordsBuilder(buffer, maxUsableMagic);
ProducerBatch batch = new ProducerBatch(tp, recordsBuilder, time.milliseconds());
FutureRecordMetadata future = Objects.requireNonNull(batch.tryAppend(timestamp, key, value, headers,
callback, time.milliseconds()));
dq.addLast(batch);
incomplete.add(batch);
// Don't deallocate this buffer in the finally block as it's being used in the record batch
buffer = null;
return new RecordAppendResult(future, dq.size() > 1 || batch.isFull(), true, false);
}
} finally {
if (buffer != null)
free.deallocate(buffer);
appendsInProgress.decrementAndGet();
}
}
private MemoryRecordsBuilder recordsBuilder(ByteBuffer buffer, byte maxUsableMagic) {
if (transactionManager != null && maxUsableMagic < RecordBatch.MAGIC_VALUE_V2) {
throw new UnsupportedVersionException("Attempting to use idempotence with a broker which does not " +
"support the required message format (v2). The broker must be version 0.11 or later.");
}
return MemoryRecords.builder(buffer, maxUsableMagic, compression, TimestampType.CREATE_TIME, 0L);
}
/**
* Try to append to a ProducerBatch.
*
* If it is full, we return null and a new batch is created. We also close the batch for record appends to free up
* resources like compression buffers. The batch will be fully closed (ie. the record batch headers will be written
* and memory records built) in one of the following cases (whichever comes first): right before send,
* if it is expired, or when the producer is closed.
*/
private RecordAppendResult tryAppend(long timestamp, byte[] key, byte[] value, Header[] headers,
Callback callback, Deque<ProducerBatch> deque) {
ProducerBatch last = deque.peekLast();
if (last != null) {
FutureRecordMetadata future = last.tryAppend(timestamp, key, value, headers, callback, time.milliseconds());
if (future == null)
last.closeForRecordAppends();
else
return new RecordAppendResult(future, deque.size() > 1 || last.isFull(), false, false);
}
return null;
}
private boolean isMuted(TopicPartition tp, long now) {
// Take care to avoid unnecessary map look-ups because this method is a hotspot if producing to a
// large number of partitions
Long throttleUntilTime = muted.get(tp);
if (throttleUntilTime == null)
return false;
if (now >= throttleUntilTime) {
muted.remove(tp);
return false;
}
return true;
}
public void resetNextBatchExpiryTime() {
nextBatchExpiryTimeMs = Long.MAX_VALUE;
}
public void maybeUpdateNextBatchExpiryTime(ProducerBatch batch) {
if (batch.createdMs + deliveryTimeoutMs > 0) {
// the non-negative check is to guard us against potential overflow due to setting
// a large value for deliveryTimeoutMs
nextBatchExpiryTimeMs = Math.min(nextBatchExpiryTimeMs, batch.createdMs + deliveryTimeoutMs);
} else {
log.warn("Skipping next batch expiry time update due to addition overflow: "
+ "batch.createMs={}, deliveryTimeoutMs={}", batch.createdMs, deliveryTimeoutMs);
}
}
/**
* Get a list of batches which have been sitting in the accumulator too long and need to be expired.
*/
public List<ProducerBatch> expiredBatches(long now) {
List<ProducerBatch> expiredBatches = new ArrayList<>();
for (Map.Entry<TopicPartition, Deque<ProducerBatch>> entry : this.batches.entrySet()) {
// expire the batches in the order of sending
Deque<ProducerBatch> deque = entry.getValue();
synchronized (deque) {
while (!deque.isEmpty()) {
ProducerBatch batch = deque.getFirst();
if (batch.hasReachedDeliveryTimeout(deliveryTimeoutMs, now)) {
deque.poll();
batch.abortRecordAppends();
expiredBatches.add(batch);
} else {
maybeUpdateNextBatchExpiryTime(batch);
break;
}
}
}
}
return expiredBatches;
}
public long getDeliveryTimeoutMs() {
return deliveryTimeoutMs;
}
/**
* Re-enqueue the given record batch in the accumulator. In Sender.completeBatch method, we check
* whether the batch has reached deliveryTimeoutMs or not. Hence we do not do the delivery timeout check here.
*/
public void reenqueue(ProducerBatch batch, long now) {
batch.reenqueued(now);
Deque<ProducerBatch> deque = getOrCreateDeque(batch.topicPartition);
synchronized (deque) {
if (transactionManager != null)
insertInSequenceOrder(deque, batch);
else
deque.addFirst(batch);
}
}
/**
* Split the big batch that has been rejected and reenqueue the split batches in to the accumulator.
* @return the number of split batches.
*/
public int splitAndReenqueue(ProducerBatch bigBatch) {
// Reset the estimated compression ratio to the initial value or the big batch compression ratio, whichever
// is bigger. There are several different ways to do the reset. We chose the most conservative one to ensure
// the split doesn't happen too often.
CompressionRatioEstimator.setEstimation(bigBatch.topicPartition.topic(), compression,
Math.max(1.0f, (float) bigBatch.compressionRatio()));
Deque<ProducerBatch> dq = bigBatch.split(this.batchSize);
int numSplitBatches = dq.size();
Deque<ProducerBatch> partitionDequeue = getOrCreateDeque(bigBatch.topicPartition);
while (!dq.isEmpty()) {
ProducerBatch batch = dq.pollLast();
incomplete.add(batch);
// We treat the newly split batches as if they are not even tried.
synchronized (partitionDequeue) {
if (transactionManager != null) {
// We should track the newly created batches since they already have assigned sequences.
transactionManager.addInFlightBatch(batch);
insertInSequenceOrder(partitionDequeue, batch);
} else {
partitionDequeue.addFirst(batch);
}
}
}
return numSplitBatches;
}
// We will have to do extra work to ensure the queue is in order when requests are being retried and there are
// multiple requests in flight to that partition. If the first in flight request fails to append, then all the
// subsequent in flight requests will also fail because the sequence numbers will not be accepted.
//
// Further, once batches are being retried, we are reduced to a single in flight request for that partition. So when
// the subsequent batches come back in sequence order, they will have to be placed further back in the queue.
//
// Note that this assumes that all the batches in the queue which have an assigned sequence also have the current
// producer id. We will not attempt to reorder messages if the producer id has changed, we will throw an
// IllegalStateException instead.
private void insertInSequenceOrder(Deque<ProducerBatch> deque, ProducerBatch batch) {
// When we are requeing and have enabled idempotence, the reenqueued batch must always have a sequence.
if (batch.baseSequence() == RecordBatch.NO_SEQUENCE)
throw new IllegalStateException("Trying to re-enqueue a batch which doesn't have a sequence even " +
"though idempotency is enabled.");
if (transactionManager.nextBatchBySequence(batch.topicPartition) == null)
throw new IllegalStateException("We are re-enqueueing a batch which is not tracked as part of the in flight " +
"requests. batch.topicPartition: " + batch.topicPartition + "; batch.baseSequence: " + batch.baseSequence());
ProducerBatch firstBatchInQueue = deque.peekFirst();
if (firstBatchInQueue != null && firstBatchInQueue.hasSequence() && firstBatchInQueue.baseSequence() < batch.baseSequence()) {
// The incoming batch can't be inserted at the front of the queue without violating the sequence ordering.
// This means that the incoming batch should be placed somewhere further back.
// We need to find the right place for the incoming batch and insert it there.
// We will only enter this branch if we have multiple inflights sent to different brokers and we need to retry
// the inflight batches.
//
// Since we reenqueue exactly one batch a time and ensure that the queue is ordered by sequence always, it
// is a simple linear scan of a subset of the in flight batches to find the right place in the queue each time.
List<ProducerBatch> orderedBatches = new ArrayList<>();
while (deque.peekFirst() != null && deque.peekFirst().hasSequence() && deque.peekFirst().baseSequence() < batch.baseSequence())
orderedBatches.add(deque.pollFirst());
log.debug("Reordered incoming batch with sequence {} for partition {}. It was placed in the queue at " +
"position {}", batch.baseSequence(), batch.topicPartition, orderedBatches.size());
// Either we have reached a point where there are batches without a sequence (ie. never been drained
// and are hence in order by default), or the batch at the front of the queue has a sequence greater
// than the incoming batch. This is the right place to add the incoming batch.
deque.addFirst(batch);
// Now we have to re insert the previously queued batches in the right order.
for (int i = orderedBatches.size() - 1; i >= 0; --i) {
deque.addFirst(orderedBatches.get(i));
}
// At this point, the incoming batch has been queued in the correct place according to its sequence.
} else {
deque.addFirst(batch);
}
}
/**
* Get a list of nodes whose partitions are ready to be sent, and the earliest time at which any non-sendable
* partition will be ready; Also return the flag for whether there are any unknown leaders for the accumulated
* partition batches.
* <p>
* A destination node is ready to send data if:
* <ol>
* <li>There is at least one partition that is not backing off its send
* <li><b>and</b> those partitions are not muted (to prevent reordering if
* {@value org.apache.kafka.clients.producer.ProducerConfig#MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION}
* is set to one)</li>
* <li><b>and <i>any</i></b> of the following are true</li>
* <ul>
* <li>The record set is full</li>
* <li>The record set has sat in the accumulator for at least lingerMs milliseconds</li>
* <li>The accumulator is out of memory and threads are blocking waiting for data (in this case all partitions
* are immediately considered ready).</li>
* <li>The accumulator has been closed</li>
* </ul>
* </ol>
*/
public ReadyCheckResult ready(Cluster cluster, long nowMs) {
Set<Node> readyNodes = new HashSet<>();
long nextReadyCheckDelayMs = Long.MAX_VALUE;
Set<String> unknownLeaderTopics = new HashSet<>();
boolean exhausted = this.free.queued() > 0;
for (Map.Entry<TopicPartition, Deque<ProducerBatch>> entry : this.batches.entrySet()) {
TopicPartition part = entry.getKey();
Deque<ProducerBatch> deque = entry.getValue();
Node leader = cluster.leaderFor(part);
synchronized (deque) {
if (leader == null && !deque.isEmpty()) {
// This is a partition for which leader is not known, but messages are available to send.
// Note that entries are currently not removed from batches when deque is empty.
unknownLeaderTopics.add(part.topic());
} else if (!readyNodes.contains(leader) && !isMuted(part, nowMs)) {
ProducerBatch batch = deque.peekFirst();
if (batch != null) {
long waitedTimeMs = batch.waitedTimeMs(nowMs);
boolean backingOff = batch.attempts() > 0 && waitedTimeMs < retryBackoffMs;
long timeToWaitMs = backingOff ? retryBackoffMs : lingerMs;
boolean full = deque.size() > 1 || batch.isFull();
boolean expired = waitedTimeMs >= timeToWaitMs;
boolean sendable = full || expired || exhausted || closed || flushInProgress();
if (sendable && !backingOff) {
readyNodes.add(leader);
} else {
long timeLeftMs = Math.max(timeToWaitMs - waitedTimeMs, 0);
// Note that this results in a conservative estimate since an un-sendable partition may have
// a leader that will later be found to have sendable data. However, this is good enough
// since we'll just wake up and then sleep again for the remaining time.
nextReadyCheckDelayMs = Math.min(timeLeftMs, nextReadyCheckDelayMs);
}
}
}
}
}
return new ReadyCheckResult(readyNodes, nextReadyCheckDelayMs, unknownLeaderTopics);
}
/**
* Check whether there are any batches which haven't been drained
*/
public boolean hasUndrained() {
for (Map.Entry<TopicPartition, Deque<ProducerBatch>> entry : this.batches.entrySet()) {
Deque<ProducerBatch> deque = entry.getValue();
synchronized (deque) {
if (!deque.isEmpty())
return true;
}
}
return false;
}
private boolean shouldStopDrainBatchesForPartition(ProducerBatch first, TopicPartition tp) {
ProducerIdAndEpoch producerIdAndEpoch = null;
if (transactionManager != null) {
if (!transactionManager.isSendToPartitionAllowed(tp))
return true;
producerIdAndEpoch = transactionManager.producerIdAndEpoch();
if (!producerIdAndEpoch.isValid())
// we cannot send the batch until we have refreshed the producer id
return true;
if (!first.hasSequence() && transactionManager.hasUnresolvedSequence(first.topicPartition))
// Don't drain any new batches while the state of previous sequence numbers
// is unknown. The previous batches would be unknown if they were aborted
// on the client after being sent to the broker at least once.
return true;
int firstInFlightSequence = transactionManager.firstInFlightSequence(first.topicPartition);
if (firstInFlightSequence != RecordBatch.NO_SEQUENCE && first.hasSequence()
&& first.baseSequence() != firstInFlightSequence)
// If the queued batch already has an assigned sequence, then it is being retried.
// In this case, we wait until the next immediate batch is ready and drain that.
// We only move on when the next in line batch is complete (either successfully or due to
// a fatal broker error). This effectively reduces our in flight request count to 1.
return true;
}
return false;
}
private List<ProducerBatch> drainBatchesForOneNode(Cluster cluster, Node node, int maxSize, long now) {
int size = 0;
List<PartitionInfo> parts = cluster.partitionsForNode(node.id());
List<ProducerBatch> ready = new ArrayList<>();
/* to make starvation less likely this loop doesn't start at 0 */
int start = drainIndex = drainIndex % parts.size();
do {
PartitionInfo part = parts.get(drainIndex);
TopicPartition tp = new TopicPartition(part.topic(), part.partition());
this.drainIndex = (this.drainIndex + 1) % parts.size();
// Only proceed if the partition has no in-flight batches.
if (isMuted(tp, now))
continue;
Deque<ProducerBatch> deque = getDeque(tp);
if (deque == null)
continue;
synchronized (deque) {
// invariant: !isMuted(tp,now) && deque != null
ProducerBatch first = deque.peekFirst();
if (first == null)
continue;
// first != null
boolean backoff = first.attempts() > 0 && first.waitedTimeMs(now) < retryBackoffMs;
// Only drain the batch if it is not during backoff period.
if (backoff)
continue;
if (size + first.estimatedSizeInBytes() > maxSize && !ready.isEmpty()) {
// there is a rare case that a single batch size is larger than the request size due to
// compression; in this case we will still eventually send this batch in a single request
break;
} else {
if (shouldStopDrainBatchesForPartition(first, tp))
break;
boolean isTransactional = transactionManager != null && transactionManager.isTransactional();
ProducerIdAndEpoch producerIdAndEpoch =
transactionManager != null ? transactionManager.producerIdAndEpoch() : null;
ProducerBatch batch = deque.pollFirst();
if (producerIdAndEpoch != null && !batch.hasSequence()) {
// If the batch already has an assigned sequence, then we should not change the producer id and
// sequence number, since this may introduce duplicates. In particular, the previous attempt
// may actually have been accepted, and if we change the producer id and sequence here, this
// attempt will also be accepted, causing a duplicate.
//
// Additionally, we update the next sequence number bound for the partition, and also have
// the transaction manager track the batch so as to ensure that sequence ordering is maintained
// even if we receive out of order responses.
batch.setProducerState(producerIdAndEpoch, transactionManager.sequenceNumber(batch.topicPartition), isTransactional);
transactionManager.incrementSequenceNumber(batch.topicPartition, batch.recordCount);
log.debug("Assigned producerId {} and producerEpoch {} to batch with base sequence " +
"{} being sent to partition {}", producerIdAndEpoch.producerId,
producerIdAndEpoch.epoch, batch.baseSequence(), tp);
transactionManager.addInFlightBatch(batch);
}
batch.close();
size += batch.records().sizeInBytes();
ready.add(batch);
batch.drained(now);
}
}
} while (start != drainIndex);
return ready;
}
/**
* Drain all the data for the given nodes and collate them into a list of batches that will fit within the specified
* size on a per-node basis. This method attempts to avoid choosing the same topic-node over and over.
*
* @param cluster The current cluster metadata
* @param nodes The list of node to drain
* @param maxSize The maximum number of bytes to drain
* @param now The current unix time in milliseconds
* @return A list of {@link ProducerBatch} for each node specified with total size less than the requested maxSize.
*/
public Map<Integer, List<ProducerBatch>> drain(Cluster cluster, Set<Node> nodes, int maxSize, long now) {
if (nodes.isEmpty())
return Collections.emptyMap();
Map<Integer, List<ProducerBatch>> batches = new HashMap<>();
for (Node node : nodes) {
List<ProducerBatch> ready = drainBatchesForOneNode(cluster, node, maxSize, now);
batches.put(node.id(), ready);
}
return batches;
}
/**
* The earliest absolute time a batch will expire (in milliseconds)
*/
public Long nextExpiryTimeMs() {
return this.nextBatchExpiryTimeMs;
}
private Deque<ProducerBatch> getDeque(TopicPartition tp) {
return batches.get(tp);
}
/**
* Get the deque for the given topic-partition, creating it if necessary.
*/
private Deque<ProducerBatch> getOrCreateDeque(TopicPartition tp) {
Deque<ProducerBatch> d = this.batches.get(tp);
if (d != null)
return d;
d = new ArrayDeque<>();
Deque<ProducerBatch> previous = this.batches.putIfAbsent(tp, d);
if (previous == null)
return d;
else
return previous;
}
/**
* Deallocate the record batch
*/
public void deallocate(ProducerBatch batch) {
incomplete.remove(batch);
// Only deallocate the batch if it is not a split batch because split batch are allocated outside the
// buffer pool.
if (!batch.isSplitBatch())
free.deallocate(batch.buffer(), batch.initialCapacity());
}
/**
* Package private for unit test. Get the buffer pool remaining size in bytes.
*/
long bufferPoolAvailableMemory() {
return free.availableMemory();
}
/**
* Are there any threads currently waiting on a flush?
*
* package private for test
*/
boolean flushInProgress() {
return flushesInProgress.get() > 0;
}
/* Visible for testing */
Map<TopicPartition, Deque<ProducerBatch>> batches() {
return Collections.unmodifiableMap(batches);
}
/**
* Initiate the flushing of data from the accumulator...this makes all requests immediately ready
*/
public void beginFlush() {
this.flushesInProgress.getAndIncrement();
}
/**
* Are there any threads currently appending messages?
*/
private boolean appendsInProgress() {
return appendsInProgress.get() > 0;
}
/**
* Mark all partitions as ready to send and block until the send is complete
*/
public void awaitFlushCompletion() throws InterruptedException {
try {
for (ProducerBatch batch : this.incomplete.copyAll())
batch.produceFuture.await();
} finally {
this.flushesInProgress.decrementAndGet();
}
}
/**
* Check whether there are any pending batches (whether sent or unsent).
*/
public boolean hasIncomplete() {
return !this.incomplete.isEmpty();
}
/**
* This function is only called when sender is closed forcefully. It will fail all the
* incomplete batches and return.
*/
public void abortIncompleteBatches() {
// We need to keep aborting the incomplete batch until no thread is trying to append to
// 1. Avoid losing batches.
// 2. Free up memory in case appending threads are blocked on buffer full.
// This is a tight loop but should be able to get through very quickly.
do {
abortBatches();
} while (appendsInProgress());
// After this point, no thread will append any messages because they will see the close
// flag set. We need to do the last abort after no thread was appending in case there was a new
// batch appended by the last appending thread.
abortBatches();
this.batches.clear();
}
/**
* Go through incomplete batches and abort them.
*/
private void abortBatches() {
abortBatches(new KafkaException("Producer is closed forcefully."));
}
/**
* Abort all incomplete batches (whether they have been sent or not)
*/
void abortBatches(final RuntimeException reason) {
for (ProducerBatch batch : incomplete.copyAll()) {
Deque<ProducerBatch> dq = getDeque(batch.topicPartition);
synchronized (dq) {
batch.abortRecordAppends();
dq.remove(batch);
}
batch.abort(reason);
deallocate(batch);
}
}
/**
* Abort any batches which have not been drained
*/
void abortUndrainedBatches(RuntimeException reason) {
for (ProducerBatch batch : incomplete.copyAll()) {
Deque<ProducerBatch> dq = getDeque(batch.topicPartition);
boolean aborted = false;
synchronized (dq) {
if ((transactionManager != null && !batch.hasSequence()) || (transactionManager == null && !batch.isClosed())) {
aborted = true;
batch.abortRecordAppends();
dq.remove(batch);
}
}
if (aborted) {
batch.abort(reason);
deallocate(batch);
}
}
}
public void mutePartition(TopicPartition tp) {
muted.put(tp, Long.MAX_VALUE);
}
public void unmutePartition(TopicPartition tp, long throttleUntilTimeMs) {
muted.put(tp, throttleUntilTimeMs);
}
/**
* Close this accumulator and force all the record buffers to be drained
*/
public void close() {
this.closed = true;
}
/*
* Metadata about a record just appended to the record accumulator
*/
public final static class RecordAppendResult {
public final FutureRecordMetadata future;
public final boolean batchIsFull;
public final boolean newBatchCreated;
public final boolean abortForNewBatch;
public RecordAppendResult(FutureRecordMetadata future, boolean batchIsFull, boolean newBatchCreated, boolean abortForNewBatch) {
this.future = future;
this.batchIsFull = batchIsFull;
this.newBatchCreated = newBatchCreated;
this.abortForNewBatch = abortForNewBatch;
}
}
/*
* The set of nodes that have at least one complete record batch in the accumulator
*/
public final static class ReadyCheckResult {
public final Set<Node> readyNodes;
public final long nextReadyCheckDelayMs;
public final Set<String> unknownLeaderTopics;
public ReadyCheckResult(Set<Node> readyNodes, long nextReadyCheckDelayMs, Set<String> unknownLeaderTopics) {
this.readyNodes = readyNodes;
this.nextReadyCheckDelayMs = nextReadyCheckDelayMs;
this.unknownLeaderTopics = unknownLeaderTopics;
}
}
}
| MINOR: Avoid unnecessary leaderFor calls when ProducerBatch queue empty (#7196)
The RecordAccumulator ready calls `leaderFor` unnecessarily when the ProducerBatch
queue is empty. When producing to many partitions, the queue is often empty and the
`leaderFor` call can be expensive in comparison. Remove the unnecessary call.
Reviewers: Ismael Juma <[email protected]> | clients/src/main/java/org/apache/kafka/clients/producer/internals/RecordAccumulator.java | MINOR: Avoid unnecessary leaderFor calls when ProducerBatch queue empty (#7196) | <ide><path>lients/src/main/java/org/apache/kafka/clients/producer/internals/RecordAccumulator.java
<ide>
<ide> boolean exhausted = this.free.queued() > 0;
<ide> for (Map.Entry<TopicPartition, Deque<ProducerBatch>> entry : this.batches.entrySet()) {
<del> TopicPartition part = entry.getKey();
<ide> Deque<ProducerBatch> deque = entry.getValue();
<del>
<del> Node leader = cluster.leaderFor(part);
<ide> synchronized (deque) {
<del> if (leader == null && !deque.isEmpty()) {
<del> // This is a partition for which leader is not known, but messages are available to send.
<del> // Note that entries are currently not removed from batches when deque is empty.
<del> unknownLeaderTopics.add(part.topic());
<del> } else if (!readyNodes.contains(leader) && !isMuted(part, nowMs)) {
<del> ProducerBatch batch = deque.peekFirst();
<del> if (batch != null) {
<add> // When producing to a large number of partitions, this path is hot and deques are often empty.
<add> // We check whether a batch exists first to avoid the more expensive checks whenever possible.
<add> ProducerBatch batch = deque.peekFirst();
<add> if (batch != null) {
<add> TopicPartition part = entry.getKey();
<add> Node leader = cluster.leaderFor(part);
<add> if (leader == null) {
<add> // This is a partition for which leader is not known, but messages are available to send.
<add> // Note that entries are currently not removed from batches when deque is empty.
<add> unknownLeaderTopics.add(part.topic());
<add> } else if (!readyNodes.contains(leader) && !isMuted(part, nowMs)) {
<ide> long waitedTimeMs = batch.waitedTimeMs(nowMs);
<ide> boolean backingOff = batch.attempts() > 0 && waitedTimeMs < retryBackoffMs;
<ide> long timeToWaitMs = backingOff ? retryBackoffMs : lingerMs; |
|
Java | apache-2.0 | d033270582538fcc584da8e2ae0c56a3f52a703d | 0 | bozimmerman/CoffeeMud,MaxRau/CoffeeMud,Tycheo/coffeemud,Tycheo/coffeemud,oriontribunal/CoffeeMud,MaxRau/CoffeeMud,sfunk1x/CoffeeMud,sfunk1x/CoffeeMud,Tycheo/coffeemud,bozimmerman/CoffeeMud,bozimmerman/CoffeeMud,bozimmerman/CoffeeMud,sfunk1x/CoffeeMud,MaxRau/CoffeeMud,MaxRau/CoffeeMud,oriontribunal/CoffeeMud,oriontribunal/CoffeeMud,oriontribunal/CoffeeMud,sfunk1x/CoffeeMud,Tycheo/coffeemud | package com.planet_ink.coffee_mud.MOBS;
import com.planet_ink.coffee_mud.interfaces.*;
import com.planet_ink.coffee_mud.common.*;
import com.planet_ink.coffee_mud.utils.*;
import java.util.*;
public class StdRideable extends StdMOB implements Rideable
{
protected int rideBasis=Rideable.RIDEABLE_LAND;
protected int mobCapacity=2;
protected Vector riders=new Vector();
public StdRideable()
{
super();
Username="a horse";
setDescription("A brown riding horse looks sturdy and reliable.");
setDisplayText("a horse stands here.");
baseEnvStats().setWeight(700);
recoverEnvStats();
}
public Environmental newInstance()
{
return new StdRideable();
}
public DeadBody killMeDead()
{
while(riders.size()>0)
{
MOB mob=fetchRider(0);
if(mob!=null)
{
mob.setRiding(null);
delRider(mob);
}
}
return super.killMeDead();
}
// common item/mob stuff
public int rideBasis(){return rideBasis;}
public void setRideBasis(int basis){rideBasis=basis;}
public int mobCapacity(){ return mobCapacity;}
public void setMobCapacity(int newCapacity){mobCapacity=newCapacity;}
public int numRiders(){return riders.size();}
public boolean mobileRideBasis(){return true;}
public MOB fetchRider(int which)
{
try { return (MOB)riders.elementAt(which); }
catch(java.lang.ArrayIndexOutOfBoundsException e){}
return null;
}
public void addRider(MOB mob)
{
if(mob!=null)
riders.addElement(mob);
}
public void delRider(MOB mob)
{
if(mob!=null)
riders.removeElement(mob);
}
public void recoverEnvStats()
{
super.recoverEnvStats();
if(rideBasis==Rideable.RIDEABLE_AIR)
envStats().setDisposition(envStats().disposition()|EnvStats.IS_FLYING);
else
if(rideBasis==Rideable.RIDEABLE_WATER)
envStats().setDisposition(envStats().disposition()|EnvStats.IS_SWIMMING);
}
public void affectEnvStats(Environmental affected, EnvStats affectableStats)
{
super.affectEnvStats(affected,affectableStats);
if(affected instanceof MOB)
{
MOB mob=(MOB)affected;
if((mob.isInCombat())&&(mob.rangeToTarget()==0)&&(amRiding(mob)))
{
affectableStats.setAttackAdjustment(affectableStats.attackAdjustment()-mob.baseEnvStats().attackAdjustment());
affectableStats.setDamage(affectableStats.damage()-mob.baseEnvStats().damage());
}
}
}
public boolean amRiding(MOB mob)
{
return riders.contains(mob);
}
public String stateString(){return "riding on";}
public String mountString(int commandType){return "mount(s)";}
public String dismountString(){return "dismount(s)";}
public String stateStringSubject(){return "being ridden by";}
public boolean okAffect(Affect affect)
{
switch(affect.targetMinor())
{
case Affect.TYP_DISMOUNT:
if(affect.amITarget(this))
{
if(!amRiding(affect.source()))
{
affect.source().tell("You are not "+stateString()+" "+name()+"!");
if(affect.source().riding()==this)
affect.source().setRiding(null);
return false;
}
// protects from standard mob rejection
return true;
}
break;
case Affect.TYP_SIT:
if(amRiding(affect.source()))
{
affect.source().tell("You are "+stateString()+" "+name()+"!");
affect.source().setRiding(this);
return false;
}
else
if(affect.amITarget(this))
{
affect.source().tell("You cannot simply sit on "+name()+", try 'mount'.");
return false;
}
break;
case Affect.TYP_SLEEP:
if(amRiding(affect.source()))
{
affect.source().tell("You are "+stateString()+" "+name()+"!");
affect.source().setRiding(this);
return false;
}
else
if(affect.amITarget(this))
{
affect.source().tell("You cannot lie down on "+name()+".");
return false;
}
break;
case Affect.TYP_MOUNT:
if(amRiding(affect.source()))
{
affect.source().tell("You are "+stateString()+" "+name()+"!");
affect.source().setRiding(this);
return false;
}
else
if(affect.amITarget(this))
{
if(numRiders()>=mobCapacity())
{
// for items
//affect.source().tell(name()+" is full.");
// for mobs
affect.source().tell("No more can fit on "+name()+".");
return false;
}
// protects from standard mob rejection
return true;
}
break;
case Affect.TYP_ENTER:
if(amRiding(affect.source())
&&(affect.target()!=null)
&&(affect.target() instanceof Room))
{
Room sourceRoom=(Room)affect.source().location();
Room targetRoom=(Room)affect.target();
if((sourceRoom!=null)&&(!affect.amITarget(sourceRoom)))
{
boolean ok=!((targetRoom.domainType()&Room.INDOORS)>0);
switch(rideBasis)
{
case Rideable.RIDEABLE_LAND:
if((targetRoom.domainType()==Room.DOMAIN_OUTDOORS_AIR)
||(targetRoom.domainType()==Room.DOMAIN_OUTDOORS_UNDERWATER)
||(targetRoom.domainType()==Room.DOMAIN_INDOORS_UNDERWATER)
||(targetRoom.domainType()==Room.DOMAIN_INDOORS_WATERSURFACE)
||(targetRoom.domainType()==Room.DOMAIN_INDOORS_AIR)
||(targetRoom.domainType()==Room.DOMAIN_OUTDOORS_WATERSURFACE))
ok=false;
break;
case Rideable.RIDEABLE_AIR:
break;
case Rideable.RIDEABLE_WATER:
if((sourceRoom.domainType()!=Room.DOMAIN_OUTDOORS_WATERSURFACE)
&&(targetRoom.domainType()!=Room.DOMAIN_OUTDOORS_WATERSURFACE)
&&(sourceRoom.domainType()!=Room.DOMAIN_INDOORS_WATERSURFACE)
&&(targetRoom.domainType()!=Room.DOMAIN_INDOORS_WATERSURFACE))
ok=false;
break;
}
if(!ok)
{
affect.source().tell("You cannot ride "+name()+" that way.");
return false;
}
if(Sense.isSitting(affect.source()))
{
affect.source().tell("You cannot crawl while "+stateString()+" "+name()+".");
return false;
}
}
}
break;
case Affect.TYP_BUY:
case Affect.TYP_SELL:
if(amRiding(affect.source()))
{
affect.source().tell("You cannot do that while "+stateString()+" "+name()+".");
return false;
}
break;
}
if((Util.bset(affect.sourceMajor(),Affect.ACT_HANDS))&&(amRiding(affect.source())))
{
if(((affect.target()!=null)&&(affect.target() instanceof Item)&&(affect.target()!=this)&&(affect.source().location()!=null)&&(affect.source().location().isContent((Item)affect.target())))
|| ((affect.tool()!=null)&&(affect.tool() instanceof Item)&&(affect.tool()!=this)&&(affect.source().location()!=null)&&(affect.source().location().isContent((Item)affect.tool())))
|| ((affect.sourceMinor()==Affect.TYP_GIVE)&&(affect.target()!=null)&&(affect.target() instanceof MOB)&&(affect.target()!=this)&&(!amRiding((MOB)affect.target()))))
{
affect.source().tell("You cannot do that while "+stateString()+" "+name()+".");
return false;
}
}
if(Util.bset(affect.targetCode(),Affect.MASK_MALICIOUS))
{
if((affect.amITarget(this))
&&((affect.source().riding()==this)
||(this.amRiding(affect.source()))))
{
affect.source().tell("You can't attack "+name()+" right now.");
if(getVictim()==affect.source()) setVictim(null);
if(affect.source().getVictim()==this) affect.source().setVictim(null);
return false;
}
else
if((affect.amISource(this))
&&(affect.target()!=null)
&&(affect.target() instanceof MOB)
&&((amRiding((MOB)affect.target()))
||(((MOB)affect.target()).riding()==this)))
{
MOB targ=(MOB)affect.target();
tell("You can't attack "+targ.name()+" right now.");
if(getVictim()==targ) setVictim(null);
if(targ.getVictim()==this) targ.setVictim(null);
return false;
}
}
return super.okAffect(affect);
}
public void affect(Affect affect)
{
super.affect(affect);
switch(affect.targetMinor())
{
case Affect.TYP_DISMOUNT:
if(amRiding(affect.source()))
affect.source().setRiding(null);
break;
case Affect.TYP_MOUNT:
if((affect.amITarget(this))&&(!amRiding(affect.source())))
affect.source().setRiding(this);
break;
}
}
}
| com/planet_ink/coffee_mud/MOBS/StdRideable.java | package com.planet_ink.coffee_mud.MOBS;
import com.planet_ink.coffee_mud.interfaces.*;
import com.planet_ink.coffee_mud.common.*;
import com.planet_ink.coffee_mud.utils.*;
import java.util.*;
public class StdRideable extends StdMOB implements Rideable
{
protected int rideBasis=Rideable.RIDEABLE_LAND;
protected int mobCapacity=2;
protected Vector riders=new Vector();
public StdRideable()
{
super();
Username="a horse";
setDescription("A brown riding horse looks sturdy and reliable.");
setDisplayText("a horse stands here.");
baseEnvStats().setWeight(700);
recoverEnvStats();
}
public Environmental newInstance()
{
return new StdRideable();
}
public DeadBody killMeDead()
{
while(riders.size()>0)
{
MOB mob=fetchRider(0);
if(mob!=null)
{
mob.setRiding(null);
delRider(mob);
}
}
return super.killMeDead();
}
// common item/mob stuff
public int rideBasis(){return rideBasis;}
public void setRideBasis(int basis){rideBasis=basis;}
public int mobCapacity(){ return mobCapacity;}
public void setMobCapacity(int newCapacity){mobCapacity=newCapacity;}
public int numRiders(){return riders.size();}
public boolean mobileRideBasis(){return true;}
public MOB fetchRider(int which)
{
try { return (MOB)riders.elementAt(which); }
catch(java.lang.ArrayIndexOutOfBoundsException e){}
return null;
}
public void addRider(MOB mob)
{
if(mob!=null)
riders.addElement(mob);
}
public void delRider(MOB mob)
{
if(mob!=null)
riders.removeElement(mob);
}
public void recoverEnvStats()
{
super.recoverEnvStats();
if(rideBasis==Rideable.RIDEABLE_AIR)
envStats().setDisposition(envStats().disposition()|EnvStats.IS_FLYING);
else
if(rideBasis==Rideable.RIDEABLE_WATER)
envStats().setDisposition(envStats().disposition()|EnvStats.IS_SWIMMING);
}
public void affectEnvStats(Environmental affected, EnvStats affectableStats)
{
super.affectEnvStats(affected,affectableStats);
if(affected instanceof MOB)
{
MOB mob=(MOB)affected;
if((mob.isInCombat())&&(mob.rangeToTarget()==0)&&(amRiding(mob)))
{
affectableStats.setAttackAdjustment(affectableStats.attackAdjustment()-mob.baseEnvStats().attackAdjustment());
affectableStats.setDamage(affectableStats.damage()-mob.baseEnvStats().damage());
}
}
}
public boolean amRiding(MOB mob)
{
return riders.contains(mob);
}
public String stateString(){return "riding on";}
public String mountString(int commandType){return "mount(s)";}
public String dismountString(){return "dismount(s)";}
public String stateStringSubject(){return "being ridden by";}
public boolean okAffect(Affect affect)
{
switch(affect.targetMinor())
{
case Affect.TYP_DISMOUNT:
if(affect.amITarget(this))
{
if(!amRiding(affect.source()))
{
affect.source().tell("You are not "+stateString()+" "+name()+"!");
if(affect.source().riding()==this)
affect.source().setRiding(null);
return false;
}
// protects from standard mob rejection
return true;
}
break;
case Affect.TYP_SIT:
if(amRiding(affect.source()))
{
affect.source().tell("You are "+stateString()+" "+name()+"!");
affect.source().setRiding(this);
return false;
}
else
if(affect.amITarget(this))
{
affect.source().tell("You cannot simply sit on "+name()+", try 'mount'.");
return false;
}
break;
case Affect.TYP_SLEEP:
if(amRiding(affect.source()))
{
affect.source().tell("You are "+stateString()+" "+name()+"!");
affect.source().setRiding(this);
return false;
}
else
if(affect.amITarget(this))
{
affect.source().tell("You cannot lie down on "+name()+".");
return false;
}
break;
case Affect.TYP_MOUNT:
if(amRiding(affect.source()))
{
affect.source().tell("You are "+stateString()+" "+name()+"!");
affect.source().setRiding(this);
return false;
}
else
if(affect.amITarget(this))
{
if(numRiders()>=mobCapacity())
{
// for items
//affect.source().tell(name()+" is full.");
// for mobs
affect.source().tell("No more can fit on "+name()+".");
return false;
}
// protects from standard mob rejection
return true;
}
break;
case Affect.TYP_ENTER:
if(amRiding(affect.source())
&&(affect.target()!=null)
&&(affect.target() instanceof Room))
{
Room sourceRoom=(Room)affect.source().location();
Room targetRoom=(Room)affect.target();
if((sourceRoom!=null)&&(!affect.amITarget(sourceRoom)))
{
boolean ok=!((targetRoom.domainType()&Room.INDOORS)>0);
switch(rideBasis)
{
case Rideable.RIDEABLE_LAND:
if((targetRoom.domainType()==Room.DOMAIN_OUTDOORS_AIR)
||(targetRoom.domainType()==Room.DOMAIN_OUTDOORS_UNDERWATER)
||(targetRoom.domainType()==Room.DOMAIN_INDOORS_UNDERWATER)
||(targetRoom.domainType()==Room.DOMAIN_INDOORS_WATERSURFACE)
||(targetRoom.domainType()==Room.DOMAIN_INDOORS_AIR)
||(targetRoom.domainType()==Room.DOMAIN_OUTDOORS_WATERSURFACE))
ok=false;
break;
case Rideable.RIDEABLE_AIR:
break;
case Rideable.RIDEABLE_WATER:
if((sourceRoom.domainType()!=Room.DOMAIN_OUTDOORS_WATERSURFACE)
&&(targetRoom.domainType()!=Room.DOMAIN_OUTDOORS_WATERSURFACE)
&&(sourceRoom.domainType()!=Room.DOMAIN_INDOORS_WATERSURFACE)
&&(targetRoom.domainType()!=Room.DOMAIN_INDOORS_WATERSURFACE))
ok=false;
break;
}
if(!ok)
{
affect.source().tell("You cannot ride "+name()+" that way.");
return false;
}
if(Sense.isSitting(affect.source()))
{
affect.source().tell("You cannot crawl while "+stateString()+" "+name()+".");
return false;
}
}
}
break;
case Affect.TYP_BUY:
case Affect.TYP_SELL:
if(amRiding(affect.source()))
{
affect.source().tell("You cannot do that while "+stateString()+" "+name()+".");
return false;
}
break;
}
if((Util.bset(affect.sourceMajor(),Affect.ACT_HANDS))&&(amRiding(affect.source())))
{
if(((affect.target()!=null)&&(affect.target() instanceof Item)&&(affect.target()!=this)&&(affect.source().location()!=null)&&(affect.source().location().isContent((Item)affect.target())))
|| ((affect.tool()!=null)&&(affect.tool() instanceof Item)&&(affect.tool()!=this)&&(affect.source().location()!=null)&&(affect.source().location().isContent((Item)affect.tool())))
|| ((affect.sourceMinor()==Affect.TYP_GIVE)&&(affect.target()!=null)&&(affect.target() instanceof MOB)&&(affect.target()!=this)&&(!amRiding((MOB)affect.target()))))
{
affect.source().tell("You cannot do that while "+stateString()+" "+name()+".");
return false;
}
}
if(Util.bset(affect.targetCode(),Affect.MASK_MALICIOUS))
{
if((affect.amITarget(this))
&&((affect.source().riding()==this)
||(this.amRiding(affect.source()))))
{
affect.source().tell("You can't attack "+riding().name()+" right now.");
if(getVictim()==affect.source()) setVictim(null);
if(affect.source().getVictim()==this) affect.source().setVictim(null);
return false;
}
else
if((affect.amISource(this))
&&(affect.target()!=null)
&&(affect.target() instanceof MOB)
&&((amRiding((MOB)affect.target()))
||(((MOB)affect.target()).riding()==this)))
{
MOB targ=(MOB)affect.target();
tell("You can't attack "+targ.name()+" right now.");
if(getVictim()==targ) setVictim(null);
if(targ.getVictim()==this) targ.setVictim(null);
return false;
}
}
return super.okAffect(affect);
}
public void affect(Affect affect)
{
super.affect(affect);
switch(affect.targetMinor())
{
case Affect.TYP_DISMOUNT:
if(amRiding(affect.source()))
affect.source().setRiding(null);
break;
case Affect.TYP_MOUNT:
if((affect.amITarget(this))&&(!amRiding(affect.source())))
affect.source().setRiding(this);
break;
}
}
}
|
git-svn-id: svn://192.168.1.10/public/CoffeeMud@1215 0d6f1817-ed0e-0410-87c9-987e46238f29
| com/planet_ink/coffee_mud/MOBS/StdRideable.java | <ide><path>om/planet_ink/coffee_mud/MOBS/StdRideable.java
<ide> &&((affect.source().riding()==this)
<ide> ||(this.amRiding(affect.source()))))
<ide> {
<del> affect.source().tell("You can't attack "+riding().name()+" right now.");
<add> affect.source().tell("You can't attack "+name()+" right now.");
<ide> if(getVictim()==affect.source()) setVictim(null);
<ide> if(affect.source().getVictim()==this) affect.source().setVictim(null);
<ide> return false; |
||
JavaScript | mit | 04aa2de3552262e93a07698ca35eafad5a1b24de | 0 | rickbergfalk/marky-mark,rickbergfalk/marky-mark | exports.getFrontMatter = function(lines) {
if ((/^---/).test(lines[0].trim())) {
var frontMatter = [];
lines.shift();
var line;
// Keep shifting off lines till we find the next ---
while (!(/^---/).test(line = lines.shift())) {
frontMatter.push(line);
}
return frontMatter.join('\n');
} else {
return '';
}
};
| lib/content.js | exports.getFrontMatter = function(lines) {
if ((/^---/).test(lines[0].trim())) {
var frontMatter = [];
lines.shift();
var line;
// Keep shifting off lines till we find the next ---
while (!(/^---/).test(line = lines.shift().trim())) {
frontMatter.push(line);
}
return frontMatter.join('\n');
} else {
return '';
}
};
| don't remove indentation in yaml | lib/content.js | don't remove indentation in yaml | <ide><path>ib/content.js
<ide> lines.shift();
<ide> var line;
<ide> // Keep shifting off lines till we find the next ---
<del> while (!(/^---/).test(line = lines.shift().trim())) {
<add> while (!(/^---/).test(line = lines.shift())) {
<ide> frontMatter.push(line);
<ide> }
<ide> return frontMatter.join('\n'); |
|
Java | agpl-3.0 | daaca99d1699ab8383bf57e4d77085246f483480 | 0 | cloudcoderdotorg/CloudCoder,daveho/CloudCoder,jspacco/CloudCoder2,jspacco/CloudCoder2,jspacco/CloudCoder,vjpudelski/CloudCoder,vjpudelski/CloudCoder,daveho/CloudCoder,jspacco/CloudCoder,csirkeee/CloudCoder,x77686d/CloudCoder,jspacco/CloudCoder,csirkeee/CloudCoder,aayushmudgal/CloudCoder,x77686d/CloudCoder,wicky-info/CloudCoder,cloudcoderdotorg/CloudCoder,ndrppnc/CloudCoder,wicky-info/CloudCoder,daveho/CloudCoder,vjpudelski/CloudCoder,csirkeee/CloudCoder,daveho/CloudCoder,cloudcoderdotorg/CloudCoder,ndrppnc/CloudCoder,daveho/CloudCoder,ndrppnc/CloudCoder,cloudcoderdotorg/CloudCoder,jspacco/CloudCoder2,wicky-info/CloudCoder,csirkeee/CloudCoder,daveho/CloudCoder,jspacco/CloudCoder2,vjpudelski/CloudCoder,jspacco/CloudCoder,jspacco/CloudCoder2,aayushmudgal/CloudCoder,x77686d/CloudCoder,x77686d/CloudCoder,daveho/CloudCoder,csirkeee/CloudCoder,jspacco/CloudCoder,wicky-info/CloudCoder,wicky-info/CloudCoder,jspacco/CloudCoder,cloudcoderdotorg/CloudCoder,csirkeee/CloudCoder,vjpudelski/CloudCoder,cloudcoderdotorg/CloudCoder,jspacco/CloudCoder2,aayushmudgal/CloudCoder,aayushmudgal/CloudCoder,aayushmudgal/CloudCoder,x77686d/CloudCoder,wicky-info/CloudCoder,ndrppnc/CloudCoder,x77686d/CloudCoder,x77686d/CloudCoder,vjpudelski/CloudCoder,ndrppnc/CloudCoder,vjpudelski/CloudCoder,cloudcoderdotorg/CloudCoder,csirkeee/CloudCoder,jspacco/CloudCoder2,wicky-info/CloudCoder,aayushmudgal/CloudCoder,jspacco/CloudCoder | // CloudCoder - a web-based pedagogical programming environment
// Copyright (C) 2011-2012, Jaime Spacco <[email protected]>
// Copyright (C) 2011-2012, David H. Hovemeyer <[email protected]>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package org.cloudcoder.app.server.persist;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import java.util.Scanner;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.cloudcoder.app.shared.model.Change;
import org.cloudcoder.app.shared.model.ConfigurationSetting;
import org.cloudcoder.app.shared.model.ConfigurationSettingName;
import org.cloudcoder.app.shared.model.Course;
import org.cloudcoder.app.shared.model.CourseRegistration;
import org.cloudcoder.app.shared.model.CourseRegistrationType;
import org.cloudcoder.app.shared.model.Event;
import org.cloudcoder.app.shared.model.ModelObjectField;
import org.cloudcoder.app.shared.model.ModelObjectSchema;
import org.cloudcoder.app.shared.model.Problem;
import org.cloudcoder.app.shared.model.ProblemLicense;
import org.cloudcoder.app.shared.model.ProblemType;
import org.cloudcoder.app.shared.model.SubmissionReceipt;
import org.cloudcoder.app.shared.model.Term;
import org.cloudcoder.app.shared.model.TestCase;
import org.cloudcoder.app.shared.model.TestResult;
import org.cloudcoder.app.shared.model.User;
/**
* Create the webapp database, using the metadata information
* specified by the model classes.
*
* @author David Hovemeyer
*/
public class CreateWebappDatabase {
private static final boolean DEBUG = false;
private static class ConfigProperties {
private Properties properties;
public ConfigProperties() throws FileNotFoundException, IOException {
properties = new Properties();
properties.load(new FileReader("../local.properties"));
}
public String get(String propName) {
String value = properties.getProperty("cloudcoder.db." + propName);
if (value == null) {
throw new IllegalArgumentException("Unknown property: " + propName);
}
return value;
}
}
public static void main(String[] args) throws Exception {
configureLog4j();
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a username for your CloudCoder account: ");
String ccUserName = keyboard.nextLine();
System.out.print("Enter a password for your CloudCoder account: ");
String ccPassword = keyboard.nextLine();
System.out.print("What is your institution name (e.g, 'Unseen University')? ");
String ccInstitutionName = keyboard.nextLine();
Class.forName("com.mysql.jdbc.Driver");
ConfigProperties config = new ConfigProperties();
String dbUser = config.get("user");
String dbPasswd = config.get("passwd");
String dbName = config.get("databaseName");
String dbHost = config.get("host");
// Connect to the database server, but don't specify a database name
Connection conn = DriverManager.getConnection("jdbc:mysql://" + dbHost + "/?user=" + dbUser + "&password=" + dbPasswd);
System.out.println("Creating database");
DBUtil.execSql(conn, "create database " + dbName);
conn.close();
// Reconnect to the newly-created database
conn = DriverManager.getConnection("jdbc:mysql://" + dbHost + "/" + dbName + "?user=" + dbUser + "&password=" + dbPasswd);
// Create tables and indexes
createTable(conn, JDBCDatabase.CHANGES, Change.SCHEMA);
createTable(conn, JDBCDatabase.CONFIGURATION_SETTINGS, ConfigurationSetting.SCHEMA);
createTable(conn, JDBCDatabase.COURSES, Course.SCHEMA);
createTable(conn, JDBCDatabase.COURSE_REGISTRATIONS, CourseRegistration.SCHEMA);
createTable(conn, JDBCDatabase.EVENTS, Event.SCHEMA);
createTable(conn, JDBCDatabase.PROBLEMS, Problem.SCHEMA);
createTable(conn, JDBCDatabase.SUBMISSION_RECEIPTS, SubmissionReceipt.SCHEMA);
createTable(conn, JDBCDatabase.TERMS, Term.SCHEMA);
createTable(conn, JDBCDatabase.TEST_CASES, TestCase.SCHEMA);
createTable(conn, JDBCDatabase.TEST_RESULTS, TestResult.SCHEMA);
createTable(conn, JDBCDatabase.USERS, User.SCHEMA);
// Create initial database contents
// Set institution name
ConfigurationSetting instName = new ConfigurationSetting();
instName.setName(ConfigurationSettingName.PUB_TEXT_INSTITUTION);
instName.setValue(ccInstitutionName);
storeBean(conn, instName, ConfigurationSetting.SCHEMA, JDBCDatabase.CONFIGURATION_SETTINGS);
// Terms
System.out.println("Creating terms...");
storeTerm(conn, "Winter", 0, JDBCDatabase.TERMS);
storeTerm(conn, "Spring", 1, JDBCDatabase.TERMS);
storeTerm(conn, "Summer", 2, JDBCDatabase.TERMS);
storeTerm(conn, "Summer 1", 3, JDBCDatabase.TERMS);
storeTerm(conn, "Summer 2", 4, JDBCDatabase.TERMS);
Term fall = storeTerm(conn, "Fall", 5, JDBCDatabase.TERMS);
// Create an initial demo course
System.out.println("Creating demo course...");
Course course = new Course();
course.setName("CCDemo");
course.setTitle("CloudCoder demo course");
course.setTermId(fall.getId());
course.setTerm(fall);
course.setYear(2012);
course.setUrl("http://cloudcoder.org/");
storeBean(conn, course, Course.SCHEMA, JDBCDatabase.COURSES);
// Create an initial user
System.out.println("Creating initial user...");
User user = new User();
user.setUsername(ccUserName);
user.setPasswordHash(BCrypt.hashpw(ccPassword, BCrypt.gensalt(12)));
storeBean(conn, user, User.SCHEMA, JDBCDatabase.USERS);
// Register the user as an instructor in the demo course
System.out.println("Registering initial user for demo course...");
CourseRegistration courseReg = new CourseRegistration();
courseReg.setCourseId(course.getId());
courseReg.setUserId(user.getId());
courseReg.setRegistrationType(CourseRegistrationType.INSTRUCTOR);
courseReg.setSection(101);
storeBean(conn, courseReg, CourseRegistration.SCHEMA, JDBCDatabase.COURSE_REGISTRATIONS);
// Create a Problem
System.out.println("Creating hello, world problem in demo course...");
Problem problem = new Problem();
problem.setCourseId(course.getId());
problem.setWhenAssigned(System.currentTimeMillis());
problem.setWhenDue(problem.getWhenAssigned() + (24L*60*60*1000));
problem.setVisible(true);
problem.setProblemType(ProblemType.C_PROGRAM);
problem.setTestname("hello");
problem.setBriefDescription("Print hello, world");
problem.setDescription(
"<p>Print a line with the following text:</p>\n" +
"<blockquote><pre>Hello, world</pre></blockquote>\n"
); // At the moment, we don't need to allow NULL field values.
problem.setSkeleton(
"#include <stdio.h>\n\n" +
"int main(void) {\n" +
"\t// TODO - add your code here\n\n" +
"\treturn 0;\n" +
"}\n"
);
problem.setSchemaVersion(Problem.CURRENT_SCHEMA_VERSION);
problem.setAuthorName("A. User");
problem.setAuthorEmail("[email protected]");
problem.setAuthorWebsite("http://cs.unseen.edu/~auser");
problem.setTimestampUtc(System.currentTimeMillis());
problem.setLicense(ProblemLicense.CC_ATTRIB_SHAREALIKE_3_0);
storeBean(conn, problem, Problem.SCHEMA, JDBCDatabase.PROBLEMS);
// Add a TestCase
System.out.println("Creating test case for hello, world problem...");
TestCase testCase = new TestCase();
testCase.setProblemId(problem.getProblemId());
testCase.setTestCaseName("hello");
testCase.setInput("");
testCase.setOutput("^\\s*Hello\\s*,\\s*world\\s*$i");
testCase.setSecret(false);
storeBean(conn, testCase, TestCase.SCHEMA, JDBCDatabase.TEST_CASES);
conn.close();
System.out.println("Success!");
}
private static void createTable(Connection conn, String tableName, ModelObjectSchema schema) throws SQLException {
System.out.println("Creating table " + tableName);
String sql = DBUtil.getCreateTableStatement(schema, tableName);
if (DEBUG) {
System.out.println(sql);
}
DBUtil.execSql(conn, sql);
}
private static Term storeTerm(Connection conn, String name, int seq, String tableName) throws SQLException {
Term term = new Term();
term.setName(name);
term.setSeq(seq);
storeBean(conn, term, Term.SCHEMA, tableName);
return term;
}
// Use introspection to store an arbitrary bean in the database.
// Eventually we could use this sort of approach to replace much
// of our hand-written JDBC code, although I don't know how great
// and idea that would be (for example, it might not yield adequate
// performance.) For just creating the database, it should be
// fine.
private static void storeBean(Connection conn, Object bean, ModelObjectSchema schema, String tableName) throws SQLException {
StringBuilder buf = new StringBuilder();
buf.append("insert into " + tableName);
buf.append(" values (");
buf.append(DBUtil.getInsertPlaceholdersNoId(schema));
buf.append(")");
PreparedStatement stmt = null;
ResultSet genKeys = null;
try {
stmt = conn.prepareStatement(buf.toString(), schema.hasUniqueId() ? PreparedStatement.RETURN_GENERATED_KEYS : 0);
// Now for the magic: iterate through the schema fields
// and bind the query parameters based on the bean properties.
int index = 1;
for (ModelObjectField field : schema.getFieldList()) {
if (field.isUniqueId()) {
continue;
}
try {
Object value = PropertyUtils.getProperty(bean, field.getPropertyName());
if (value instanceof Enum) {
// Enum values are converted to integers
value = Integer.valueOf(((Enum<?>)value).ordinal());
}
stmt.setObject(index++, value);
} catch (Exception e) {
throw new SQLException(
"Couldn't get property " + field.getPropertyName() +
" of " + bean.getClass().getName() + " object");
}
}
// Execute the insert
stmt.executeUpdate();
if (schema.hasUniqueId()) {
genKeys = stmt.getGeneratedKeys();
if (!genKeys.next()) {
throw new SQLException("Couldn't get generated id for " + bean.getClass().getName());
}
int id = genKeys.getInt(1);
// Set the unique id value in the bean
try {
BeanUtils.setProperty(bean, schema.getUniqueIdField().getPropertyName(), id);
} catch (Exception e) {
throw new SQLException("Couldn't set generated unique id for " + bean.getClass().getName());
}
}
} finally {
DBUtil.closeQuietly(genKeys);
DBUtil.closeQuietly(stmt);
}
}
private static void configureLog4j() {
// See: http://robertmaldon.blogspot.com/2007/09/programmatically-configuring-log4j-and.html
Logger rootLogger = Logger.getRootLogger();
if (!rootLogger.getAllAppenders().hasMoreElements()) {
rootLogger.setLevel(Level.INFO);
rootLogger.addAppender(new ConsoleAppender(new PatternLayout("%-5p [%t]: %m%n")));
}
}
}
| CloudCoderModelClassesPersistence/src/org/cloudcoder/app/server/persist/CreateWebappDatabase.java | // CloudCoder - a web-based pedagogical programming environment
// Copyright (C) 2011-2012, Jaime Spacco <[email protected]>
// Copyright (C) 2011-2012, David H. Hovemeyer <[email protected]>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package org.cloudcoder.app.server.persist;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import java.util.Scanner;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.cloudcoder.app.shared.model.Change;
import org.cloudcoder.app.shared.model.ConfigurationSetting;
import org.cloudcoder.app.shared.model.ConfigurationSettingName;
import org.cloudcoder.app.shared.model.Course;
import org.cloudcoder.app.shared.model.CourseRegistration;
import org.cloudcoder.app.shared.model.CourseRegistrationType;
import org.cloudcoder.app.shared.model.Event;
import org.cloudcoder.app.shared.model.ModelObjectField;
import org.cloudcoder.app.shared.model.ModelObjectSchema;
import org.cloudcoder.app.shared.model.Problem;
import org.cloudcoder.app.shared.model.ProblemLicense;
import org.cloudcoder.app.shared.model.ProblemType;
import org.cloudcoder.app.shared.model.SubmissionReceipt;
import org.cloudcoder.app.shared.model.Term;
import org.cloudcoder.app.shared.model.TestCase;
import org.cloudcoder.app.shared.model.TestResult;
import org.cloudcoder.app.shared.model.User;
/**
* Create the webapp database, using the metadata information
* specified by the model classes.
*
* @author David Hovemeyer
*/
public class CreateWebappDatabase {
private static final boolean DEBUG = false;
private static class ConfigProperties {
private Properties properties;
public ConfigProperties() throws FileNotFoundException, IOException {
properties = new Properties();
properties.load(new FileReader("../local.properties"));
}
public String get(String propName) {
String value = properties.getProperty("cloudcoder.db." + propName);
if (value == null) {
throw new IllegalArgumentException("Unknown property: " + propName);
}
return value;
}
}
public static void main(String[] args) throws Exception {
configureLog4j();
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a username for your CloudCoder account: ");
String ccUserName = keyboard.nextLine();
System.out.print("Enter a password for your CloudCoder account: ");
String ccPassword = keyboard.nextLine();
System.out.print("What is your institution name (e.g, 'Unseen University')? ");
String ccInstitutionName = keyboard.nextLine();
Class.forName("com.mysql.jdbc.Driver");
ConfigProperties config = new ConfigProperties();
String dbUser = config.get("user");
String dbPasswd = config.get("passwd");
String dbName = config.get("databaseName");
String dbHost = config.get("host");
// Connect to the database server, but don't specify a database name
Connection conn = DriverManager.getConnection("jdbc:mysql://" + dbHost + "/?user=" + dbUser + "&password=" + dbPasswd);
System.out.println("Creating database");
DBUtil.execSql(conn, "create database " + dbName);
conn.close();
// Reconnect to the newly-created database
conn = DriverManager.getConnection("jdbc:mysql://" + dbHost + "/" + dbName + "?user=" + dbUser + "&password=" + dbPasswd);
// Create tables and indexes
createTable(conn, JDBCDatabase.CHANGES, Change.SCHEMA);
createTable(conn, JDBCDatabase.CONFIGURATION_SETTINGS, ConfigurationSetting.SCHEMA);
createTable(conn, JDBCDatabase.COURSES, Course.SCHEMA);
createTable(conn, JDBCDatabase.COURSE_REGISTRATIONS, CourseRegistration.SCHEMA);
createTable(conn, JDBCDatabase.EVENTS, Event.SCHEMA);
createTable(conn, JDBCDatabase.PROBLEMS, Problem.SCHEMA);
createTable(conn, JDBCDatabase.SUBMISSION_RECEIPTS, SubmissionReceipt.SCHEMA);
createTable(conn, JDBCDatabase.TERMS, Term.SCHEMA);
createTable(conn, JDBCDatabase.TEST_CASES, TestCase.SCHEMA);
createTable(conn, JDBCDatabase.TEST_RESULTS, TestResult.SCHEMA);
createTable(conn, JDBCDatabase.USERS, User.SCHEMA);
// Create initial database contents
// Set institution name
ConfigurationSetting instName = new ConfigurationSetting();
instName.setName(ConfigurationSettingName.PUB_TEXT_INSTITUTION);
instName.setValue(ccInstitutionName);
storeBean(conn, instName, ConfigurationSetting.SCHEMA, JDBCDatabase.CONFIGURATION_SETTINGS);
// Terms
System.out.println("Creating terms...");
storeTerm(conn, "Winter", 0, JDBCDatabase.TERMS);
storeTerm(conn, "Spring", 1, JDBCDatabase.TERMS);
storeTerm(conn, "Summer", 2, JDBCDatabase.TERMS);
storeTerm(conn, "Summer 1", 3, JDBCDatabase.TERMS);
storeTerm(conn, "Summer 2", 4, JDBCDatabase.TERMS);
Term fall = storeTerm(conn, "Fall", 5, JDBCDatabase.TERMS);
// Create an initial demo course
System.out.println("Creating demo course...");
Course course = new Course();
course.setName("CCDemo");
course.setTitle("CloudCoder demo course");
course.setTermId(fall.getId());
course.setTerm(fall);
course.setYear(2012);
course.setUrl("http://cloudcoder.org/");
storeBean(conn, course, Course.SCHEMA, JDBCDatabase.COURSES);
// Create an initial user
System.out.println("Creating initial user...");
User user = new User();
user.setUsername(ccUserName);
user.setPasswordHash(BCrypt.hashpw(ccPassword, BCrypt.gensalt(12)));
storeBean(conn, user, User.SCHEMA, JDBCDatabase.USERS);
// Register the user as an instructor in the demo course
System.out.println("Registering initial user for demo course...");
CourseRegistration courseReg = new CourseRegistration();
courseReg.setCourseId(course.getId());
courseReg.setUserId(user.getId());
courseReg.setRegistrationType(CourseRegistrationType.INSTRUCTOR);
courseReg.setSection(101);
storeBean(conn, courseReg, CourseRegistration.SCHEMA, JDBCDatabase.COURSE_REGISTRATIONS);
// Create a Problem
System.out.println("Creating hello, world problem in demo course...");
Problem problem = new Problem();
problem.setCourseId(course.getId());
problem.setWhenAssigned(System.currentTimeMillis());
problem.setWhenDue(problem.getWhenAssigned() + (24L*60*60*1000));
problem.setVisible(true);
problem.setProblemType(ProblemType.C_PROGRAM);
problem.setTestname("hello");
problem.setBriefDescription("Print hello, world");
problem.setDescription(
"<p>Print a line with the following text:</p>\n" +
"<blockquote><pre>Hello, world</pre></blockquote>\n"
); // At the moment, we don't need to allow NULL field values.
problem.setSkeleton(
"#include <stdio.h>\n\n" +
"int main(void) {\n" +
"\t// TODO - add your code here\n\n" +
"\treturn 0;\n" +
"}\n"
);
problem.setSchemaVersion(Problem.CURRENT_SCHEMA_VERSION);
problem.setAuthorName("A. User");
problem.setAuthorEmail("[email protected]");
problem.setAuthorWebsite("http://cs.unseen.edu/~auser");
problem.setTimestampUtc(System.currentTimeMillis());
problem.setLicense(ProblemLicense.CC_ATTRIB_SHAREALIKE_3_0);
storeBean(conn, problem, Problem.SCHEMA, JDBCDatabase.PROBLEMS);
// Add a TestCase
System.out.println("Creating test case for hello, world problem...");
TestCase testCase = new TestCase();
testCase.setProblemId(problem.getProblemId());
testCase.setTestCaseName("hello");
testCase.setInput("");
testCase.setOutput("^\\s*Hello\\s*,\\s*world\\s*$i");
testCase.setSecret(false);
storeBean(conn, testCase, TestCase.SCHEMA, JDBCDatabase.TEST_CASES);
conn.close();
System.out.println("Success!");
}
private static void createTable(Connection conn, String tableName, ModelObjectSchema schema) throws SQLException {
System.out.println("Creating table " + tableName);
String sql = DBUtil.getCreateTableStatement(schema, tableName);
if (DEBUG) {
System.out.println(sql);
}
DBUtil.execSql(conn, sql);
}
private static Term storeTerm(Connection conn, String name, int seq, String tableName) throws SQLException {
Term term = new Term();
term.setName(name);
term.setSeq(seq);
storeBean(conn, term, Term.SCHEMA, tableName);
return term;
}
// Use introspection to store an arbitrary bean in the database.
// Eventually we could use this sort of approach to replace much
// of our hand-written JDBC code, although I don't know how great
// and idea that would be (for example, it might not yield adequate
// performance.) For just creating the database, it should be
// fine.
private static void storeBean(Connection conn, Object bean, ModelObjectSchema schema, String tableName) throws SQLException {
StringBuilder buf = new StringBuilder();
buf.append("insert into " + tableName);
buf.append(" values (");
buf.append(DBUtil.getInsertPlaceholdersNoId(schema));
buf.append(")");
PreparedStatement stmt = null;
ResultSet genKeys = null;
try {
stmt = conn.prepareStatement(buf.toString(), schema.hasUniqueId() ? PreparedStatement.RETURN_GENERATED_KEYS : 0);
// Now for the magic: iterate through the schema fields
// and bind the query parameters based on the bean properties.
int index = 1;
for (ModelObjectField field : schema.getFieldList()) {
if (field.isUniqueId()) {
continue;
}
try {
Object value = PropertyUtils.getProperty(bean, field.getPropertyName());
if (value instanceof Enum) {
// Enum values are converted to integers
value = Integer.valueOf(((Enum<?>)value).ordinal());
}
stmt.setObject(index++, value);
} catch (Exception e) {
throw new SQLException(
"Couldn't get property " + field.getPropertyName() +
" of " + bean.getClass().getName() + " object");
}
}
// Execute the insert
stmt.executeUpdate();
if (schema.hasUniqueId()) {
genKeys = stmt.getGeneratedKeys();
if (!genKeys.next()) {
throw new SQLException("Couldn't get generated id for " + bean.getClass().getName());
}
int id = genKeys.getInt(1);
// Set the unique id value in the bean
try {
BeanUtils.setProperty(bean, schema.getUniqueIdField().getPropertyName(), id);
} catch (Exception e) {
throw new SQLException("Couldn't set generated unique id for " + bean.getClass().getName());
}
}
} finally {
DBUtil.closeQuietly(genKeys);
DBUtil.closeQuietly(stmt);
}
}
private static void configureLog4j() {
// See: http://robertmaldon.blogspot.com/2007/09/programmatically-configuring-log4j-and.html
Logger rootLogger = Logger.getRootLogger();
if (!rootLogger.getAllAppenders().hasMoreElements()) {
rootLogger.setLevel(Level.INFO);
rootLogger.addAppender(new ConsoleAppender(
new PatternLayout("%-5p [%t]: %m%n")));
// The TTCC_CONVERSION_PATTERN contains more info than
// the pattern we used for the root logger
Logger pkgLogger = rootLogger.getLoggerRepository().getLogger("robertmaldon.moneymachine");
pkgLogger.setLevel(Level.DEBUG);
pkgLogger.addAppender(new ConsoleAppender(
new PatternLayout(PatternLayout.TTCC_CONVERSION_PATTERN)));
}
}
}
| when configuring log4j, only need to create the root logger | CloudCoderModelClassesPersistence/src/org/cloudcoder/app/server/persist/CreateWebappDatabase.java | when configuring log4j, only need to create the root logger | <ide><path>loudCoderModelClassesPersistence/src/org/cloudcoder/app/server/persist/CreateWebappDatabase.java
<ide> Logger rootLogger = Logger.getRootLogger();
<ide> if (!rootLogger.getAllAppenders().hasMoreElements()) {
<ide> rootLogger.setLevel(Level.INFO);
<del> rootLogger.addAppender(new ConsoleAppender(
<del> new PatternLayout("%-5p [%t]: %m%n")));
<del>
<del> // The TTCC_CONVERSION_PATTERN contains more info than
<del> // the pattern we used for the root logger
<del> Logger pkgLogger = rootLogger.getLoggerRepository().getLogger("robertmaldon.moneymachine");
<del> pkgLogger.setLevel(Level.DEBUG);
<del> pkgLogger.addAppender(new ConsoleAppender(
<del> new PatternLayout(PatternLayout.TTCC_CONVERSION_PATTERN)));
<add> rootLogger.addAppender(new ConsoleAppender(new PatternLayout("%-5p [%t]: %m%n")));
<ide> }
<ide> }
<ide> } |
|
Java | mit | 44afe12f1bada9bb7724a3678553c86aa31b907c | 0 | raeleus/skin-composer | package com.ray3k.skincomposer;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.scenes.scene2d.*;
import com.badlogic.gdx.scenes.scene2d.actions.Actions;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.WidgetGroup;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.scenes.scene2d.utils.Disableable;
import com.badlogic.gdx.scenes.scene2d.utils.Drawable;
import com.badlogic.gdx.utils.Align;
import static com.badlogic.gdx.scenes.scene2d.actions.Actions.*;
public class PopTable extends Table {
private Stage stage;
private Image stageBackground;
private WidgetGroup group;
private final static Vector2 temp = new Vector2();
private boolean hideOnUnfocus;
private int preferredEdge;
private boolean keepSizedWithinStage;
private boolean automaticallyResized;
public PopTable() {
this(new PopTableStyle());
}
public PopTable(Skin skin) {
this(skin.get(PopTableStyle.class));
}
public PopTable(Skin skin, String style) {
this(skin.get(style, PopTableStyle.class));
}
public PopTable(PopTableStyle style) {
setTouchable(Touchable.enabled);
stageBackground = new Image(style.stageBackground);
stageBackground.setFillParent(true);
stageBackground.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
super.clicked(event, x, y);
if (hideOnUnfocus) {
hide();
}
}
});
setBackground(style.background);
hideOnUnfocus = true;
preferredEdge = Align.top;
keepSizedWithinStage = true;
automaticallyResized = true;
}
public void alignToActorEdge(Actor actor, int edge) {
float widgetX;
switch (edge) {
case Align.left:
case Align.bottomLeft:
case Align.topLeft:
widgetX = -getWidth();
break;
case Align.right:
case Align.bottomRight:
case Align.topRight:
widgetX = actor.getWidth();
break;
default:
widgetX = actor.getWidth() / 2f - getWidth() / 2f;
break;
}
float widgetY;
switch (edge) {
case Align.bottom:
case Align.bottomLeft:
case Align.bottomRight:
widgetY = -getHeight();
break;
case Align.top:
case Align.topLeft:
case Align.topRight:
widgetY = actor.getHeight();
break;
default:
widgetY = actor.getHeight() / 2f - getHeight() / 2f;
break;
}
temp.set(widgetX, widgetY);
actor.localToStageCoordinates(temp);
setPosition(temp.x, temp.y);
}
private float actorEdgeStageHorizontalDistance(Actor actor, int edge) {
temp.set(0, 0);
actor.localToStageCoordinates(temp);
setPosition(temp.x, temp.y);
float returnValue;
switch (edge) {
case Align.left:
case Align.bottomLeft:
case Align.topLeft:
returnValue = temp.x;
break;
case Align.right:
case Align.bottomRight:
case Align.topRight:
returnValue = stage.getWidth() - (temp.x + actor.getWidth());
break;
default:
returnValue = 0;
break;
}
return returnValue;
}
private float actorEdgeStageVerticalDistance(Actor actor, int edge) {
temp.set(0, 0);
actor.localToStageCoordinates(temp);
setPosition(temp.x, temp.y);
float returnValue;
switch (edge) {
case Align.bottom:
case Align.bottomLeft:
case Align.bottomRight:
returnValue = temp.y;
break;
case Align.top:
case Align.topLeft:
case Align.topRight:
returnValue = stage.getHeight() - (temp.y + actor.getHeight());
break;
default:
returnValue = 0;
break;
}
return returnValue;
}
public void moveToInsideStage() {
if (getStage() != null) {
if (getX() < 0) setX(0);
else if (getX() + getWidth() > getStage().getWidth()) setX(getStage().getWidth() - getWidth());
if (getY() < 0) setY(0);
else if (getY() + getHeight() > getStage().getHeight()) setY(getStage().getHeight() - getHeight());
}
}
public boolean isOutsideStage() {
return getX() < 0 || getX() + getWidth() > getStage().getWidth() || getY() < 0 || getY() + getHeight() > getStage().getHeight();
}
public void hide() {
hide(fadeOut(.2f));
}
public void hide(Action action) {
fire(new TableHiddenEvent());
group.addAction(sequence(action, Actions.removeActor()));
}
public void show(Stage stage) {
Action action = sequence(alpha(0), fadeIn(.2f));
this.show(stage, action);
}
public void show(Stage stage, Action action) {
this.stage = stage;
group = new WidgetGroup();
group.setFillParent(true);
stage.addActor(group);
group.addActor(stageBackground);
group.addActor(this);
pack();
if (keepSizedWithinStage) {
if (getWidth() > stage.getWidth()) {
setWidth(stage.getWidth());
}
if (getHeight() > stage.getHeight()) {
setHeight(stage.getHeight());
}
}
setPosition((int) (stage.getWidth() / 2f - getWidth() / 2f), (int) (stage.getHeight() / 2f - getHeight() / 2f));
group.addAction(action);
}
public static class PopTableStyle {
/*Optional*/
public Drawable background, stageBackground;
public PopTableStyle() {
}
public PopTableStyle(PopTableStyle style) {
background = style.background;
stageBackground = style.stageBackground;
}
}
public static class PopTableClickListener extends ClickListener {
protected PopTable popTable;
public PopTableClickListener(Skin skin) {
this(skin.get(PopTableStyle.class));
}
public PopTableClickListener(Skin skin, String style) {
this(skin.get(style, PopTableStyle.class));
}
public PopTableClickListener(PopTableStyle style) {
popTable = new PopTable(style);
popTable.automaticallyResized = false;
popTable.addListener(new TableHiddenListener() {
@Override
public void tableHidden(Event event) {
PopTableClickListener.this.tableHidden(event);
}
});
}
@Override
public void clicked(InputEvent event, float x, float y) {
super.clicked(event, x, y);
var stage = event.getListenerActor().getStage();
var actor = event.getListenerActor();
if (actor instanceof Disableable) {
if (((Disableable) actor).isDisabled()) return;
}
popTable.show(stage);
int edge = popTable.getPreferredEdge();
popTable.alignToActorEdge(actor, edge);
var rightDistance = popTable.actorEdgeStageHorizontalDistance(actor, Align.right);
var leftDistance = popTable.actorEdgeStageHorizontalDistance(actor, Align.left);
switch (edge) {
case Align.left:
case Align.topLeft:
case Align.bottomLeft:
if (popTable.getX() < 0) {
if (rightDistance > leftDistance) {
edge &= ~Align.left;
edge |= Align.right;
popTable.setWidth(Math.min(popTable.getWidth(), rightDistance));
} else {
popTable.setWidth(Math.min(popTable.getWidth(), leftDistance));
}
}
break;
case Align.right:
case Align.bottomRight:
case Align.topRight:
if (popTable.getX() + popTable.getWidth() > stage.getWidth()) {
if (leftDistance > rightDistance) {
edge &= ~Align.right;
edge |= Align.left;
popTable.setWidth(Math.min(popTable.getWidth(), leftDistance));
} else {
popTable.setWidth(Math.min(popTable.getWidth(), rightDistance));
}
}
break;
}
var topDistance = popTable.actorEdgeStageVerticalDistance(actor, Align.top);
var bottomDistance = popTable.actorEdgeStageVerticalDistance(actor, Align.bottom);
switch (edge) {
case Align.bottom:
case Align.bottomLeft:
case Align.bottomRight:
if (popTable.getY() < 0) {
if (topDistance > bottomDistance) {
edge &= ~Align.bottom;
edge |= Align.top;
popTable.setHeight(Math.min(popTable.getHeight(), topDistance));
} else {
popTable.setHeight(Math.min(popTable.getHeight(), bottomDistance));
}
}
break;
case Align.top:
case Align.topLeft:
case Align.topRight:
if (popTable.getY() + popTable.getHeight() > stage.getHeight()) {
if (bottomDistance > topDistance) {
edge &= ~Align.top;
edge |= Align.bottom;
popTable.setHeight(Math.min(popTable.getHeight(), bottomDistance));
} else {
popTable.setHeight(Math.min(popTable.getHeight(), topDistance));
}
}
break;
}
popTable.alignToActorEdge(actor, edge);
popTable.moveToInsideStage();
}
public PopTable getPopTable() {
return popTable;
}
/**
* Override this method to be performed when the popTable is hidden or dismissed.
*/
public void tableHidden(Event event) {
}
}
public static class TableHiddenEvent extends Event {
}
public static abstract class TableHiddenListener implements EventListener {
@Override
public boolean handle(Event event) {
if (event instanceof TableHiddenEvent) {
tableHidden(event);
return true;
} else{
return false;
}
}
public abstract void tableHidden(Event event);
}
public boolean isHideOnUnfocus() {
return hideOnUnfocus;
}
public void setHideOnUnfocus(boolean hideOnUnfocus) {
this.hideOnUnfocus = hideOnUnfocus;
}
public int getPreferredEdge() {
return preferredEdge;
}
public void setPreferredEdge(int preferredEdge) {
this.preferredEdge = preferredEdge;
}
public boolean isKeepSizedWithinStage() {
return keepSizedWithinStage;
}
public void setKeepSizedWithinStage(boolean keepSizedWithinStage) {
this.keepSizedWithinStage = keepSizedWithinStage;
}
public boolean isAutomaticallyResized() {
return automaticallyResized;
}
public void setAutomaticallyResized(boolean automaticallyResized) {
this.automaticallyResized = automaticallyResized;
}
@Override
public void layout() {
super.layout();
if (automaticallyResized) {
var centerX = getX(Align.center);
var centerY = getY(Align.center);
pack();
if (keepSizedWithinStage) {
moveToInsideStage();
}
setPosition(centerX, centerY, Align.center);
setPosition(MathUtils.floor(getX()), MathUtils.floor(getY()));
}
}
} | core/src/com/ray3k/skincomposer/PopTable.java | package com.ray3k.skincomposer;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.scenes.scene2d.*;
import com.badlogic.gdx.scenes.scene2d.actions.Actions;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.WidgetGroup;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.scenes.scene2d.utils.Disableable;
import com.badlogic.gdx.scenes.scene2d.utils.Drawable;
import com.badlogic.gdx.utils.Align;
import static com.badlogic.gdx.scenes.scene2d.actions.Actions.*;
public class PopTable extends Table {
private Stage stage;
private Image stageBackground;
private WidgetGroup group;
private final static Vector2 temp = new Vector2();
private boolean hideOnUnfocus;
private int preferredEdge;
private boolean keepSizedWithinStage;
public PopTable() {
this(new PopTableStyle());
}
public PopTable(Skin skin) {
this(skin.get(PopTableStyle.class));
}
public PopTable(Skin skin, String style) {
this(skin.get(style, PopTableStyle.class));
}
public PopTable(PopTableStyle style) {
setTouchable(Touchable.enabled);
stageBackground = new Image(style.stageBackground);
stageBackground.setFillParent(true);
stageBackground.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
super.clicked(event, x, y);
if (hideOnUnfocus) {
hide();
}
}
});
setBackground(style.background);
hideOnUnfocus = true;
preferredEdge = Align.top;
keepSizedWithinStage = true;
}
public void alignToActorEdge(Actor actor, int edge) {
float widgetX;
switch (edge) {
case Align.left:
case Align.bottomLeft:
case Align.topLeft:
widgetX = -getWidth();
break;
case Align.right:
case Align.bottomRight:
case Align.topRight:
widgetX = actor.getWidth();
break;
default:
widgetX = actor.getWidth() / 2f - getWidth() / 2f;
break;
}
float widgetY;
switch (edge) {
case Align.bottom:
case Align.bottomLeft:
case Align.bottomRight:
widgetY = -getHeight();
break;
case Align.top:
case Align.topLeft:
case Align.topRight:
widgetY = actor.getHeight();
break;
default:
widgetY = actor.getHeight() / 2f - getHeight() / 2f;
break;
}
temp.set(widgetX, widgetY);
actor.localToStageCoordinates(temp);
setPosition(temp.x, temp.y);
}
private float actorEdgeStageHorizontalDistance(Actor actor, int edge) {
temp.set(0, 0);
actor.localToStageCoordinates(temp);
setPosition(temp.x, temp.y);
float returnValue;
switch (edge) {
case Align.left:
case Align.bottomLeft:
case Align.topLeft:
returnValue = temp.x;
break;
case Align.right:
case Align.bottomRight:
case Align.topRight:
returnValue = stage.getWidth() - (temp.x + actor.getWidth());
break;
default:
returnValue = 0;
break;
}
return returnValue;
}
private float actorEdgeStageVerticalDistance(Actor actor, int edge) {
temp.set(0, 0);
actor.localToStageCoordinates(temp);
setPosition(temp.x, temp.y);
float returnValue;
switch (edge) {
case Align.bottom:
case Align.bottomLeft:
case Align.bottomRight:
returnValue = temp.y;
break;
case Align.top:
case Align.topLeft:
case Align.topRight:
returnValue = stage.getHeight() - (temp.y + actor.getHeight());
break;
default:
returnValue = 0;
break;
}
return returnValue;
}
public void moveToInsideStage() {
if (getStage() != null) {
if (getX() < 0) setX(0);
else if (getX() + getWidth() > getStage().getWidth()) setX(getStage().getWidth() - getWidth());
if (getY() < 0) setY(0);
else if (getY() + getHeight() > getStage().getHeight()) setY(getStage().getHeight() - getHeight());
}
}
public boolean isOutsideStage() {
return getX() < 0 || getX() + getWidth() > getStage().getWidth() || getY() < 0 || getY() + getHeight() > getStage().getHeight();
}
public void hide() {
hide(fadeOut(.2f));
}
public void hide(Action action) {
fire(new TableHiddenEvent());
group.addAction(sequence(action, Actions.removeActor()));
}
public void show(Stage stage) {
Action action = sequence(alpha(0), fadeIn(.2f));
this.show(stage, action);
}
public void show(Stage stage, Action action) {
this.stage = stage;
group = new WidgetGroup();
group.setFillParent(true);
stage.addActor(group);
group.addActor(stageBackground);
group.addActor(this);
pack();
if (keepSizedWithinStage) {
if (getWidth() > stage.getWidth()) {
setWidth(stage.getWidth());
}
if (getHeight() > stage.getHeight()) {
setHeight(stage.getHeight());
}
}
setPosition((int) (stage.getWidth() / 2f - getWidth() / 2f), (int) (stage.getHeight() / 2f - getHeight() / 2f));
group.addAction(action);
}
public static class PopTableStyle {
/*Optional*/
public Drawable background, stageBackground;
public PopTableStyle() {
}
public PopTableStyle(PopTableStyle style) {
background = style.background;
stageBackground = style.stageBackground;
}
}
public static class PopTableClickListener extends ClickListener {
protected PopTable popTable;
public PopTableClickListener(Skin skin) {
this(skin.get(PopTableStyle.class));
}
public PopTableClickListener(Skin skin, String style) {
this(skin.get(style, PopTableStyle.class));
}
public PopTableClickListener(PopTableStyle style) {
popTable = new PopTable(style);
popTable.addListener(new TableHiddenListener() {
@Override
public void tableHidden(Event event) {
PopTableClickListener.this.tableHidden(event);
}
});
}
@Override
public void clicked(InputEvent event, float x, float y) {
super.clicked(event, x, y);
var stage = event.getListenerActor().getStage();
var actor = event.getListenerActor();
if (actor instanceof Disableable) {
if (((Disableable) actor).isDisabled()) return;
}
popTable.show(stage);
int edge = popTable.getPreferredEdge();
popTable.alignToActorEdge(actor, edge);
var rightDistance = popTable.actorEdgeStageHorizontalDistance(actor, Align.right);
var leftDistance = popTable.actorEdgeStageHorizontalDistance(actor, Align.left);
switch (edge) {
case Align.left:
case Align.topLeft:
case Align.bottomLeft:
if (popTable.getX() < 0) {
if (rightDistance > leftDistance) {
edge &= ~Align.left;
edge |= Align.right;
popTable.setWidth(Math.min(popTable.getWidth(), rightDistance));
} else {
popTable.setWidth(Math.min(popTable.getWidth(), leftDistance));
}
}
break;
case Align.right:
case Align.bottomRight:
case Align.topRight:
if (popTable.getX() + popTable.getWidth() > stage.getWidth()) {
if (leftDistance > rightDistance) {
edge &= ~Align.right;
edge |= Align.left;
popTable.setWidth(Math.min(popTable.getWidth(), leftDistance));
} else {
popTable.setWidth(Math.min(popTable.getWidth(), rightDistance));
}
}
break;
}
var topDistance = popTable.actorEdgeStageVerticalDistance(actor, Align.top);
var bottomDistance = popTable.actorEdgeStageVerticalDistance(actor, Align.bottom);
switch (edge) {
case Align.bottom:
case Align.bottomLeft:
case Align.bottomRight:
if (popTable.getY() < 0) {
if (topDistance > bottomDistance) {
edge &= ~Align.bottom;
edge |= Align.top;
popTable.setHeight(Math.min(popTable.getHeight(), topDistance));
} else {
popTable.setHeight(Math.min(popTable.getHeight(), bottomDistance));
}
}
break;
case Align.top:
case Align.topLeft:
case Align.topRight:
if (popTable.getY() + popTable.getHeight() > stage.getHeight()) {
if (bottomDistance > topDistance) {
edge &= ~Align.top;
edge |= Align.bottom;
popTable.setHeight(Math.min(popTable.getHeight(), bottomDistance));
} else {
popTable.setHeight(Math.min(popTable.getHeight(), topDistance));
}
}
break;
}
popTable.alignToActorEdge(actor, edge);
popTable.moveToInsideStage();
}
public PopTable getPopTable() {
return popTable;
}
/**
* Override this method to be performed when the popTable is hidden or dismissed.
*/
public void tableHidden(Event event) {
}
}
public static class TableHiddenEvent extends Event {
}
public static abstract class TableHiddenListener implements EventListener {
@Override
public boolean handle(Event event) {
if (event instanceof TableHiddenEvent) {
tableHidden(event);
return true;
} else{
return false;
}
}
public abstract void tableHidden(Event event);
}
public boolean isHideOnUnfocus() {
return hideOnUnfocus;
}
public void setHideOnUnfocus(boolean hideOnUnfocus) {
this.hideOnUnfocus = hideOnUnfocus;
}
public int getPreferredEdge() {
return preferredEdge;
}
public void setPreferredEdge(int preferredEdge) {
this.preferredEdge = preferredEdge;
}
public boolean isKeepSizedWithinStage() {
return keepSizedWithinStage;
}
public void setKeepSizedWithinStage(boolean keepSizedWithinStage) {
this.keepSizedWithinStage = keepSizedWithinStage;
}
} | Added automaticallyResized option to PopTable.
| core/src/com/ray3k/skincomposer/PopTable.java | Added automaticallyResized option to PopTable. | <ide><path>ore/src/com/ray3k/skincomposer/PopTable.java
<ide> package com.ray3k.skincomposer;
<ide>
<add>import com.badlogic.gdx.math.MathUtils;
<ide> import com.badlogic.gdx.math.Vector2;
<ide> import com.badlogic.gdx.scenes.scene2d.*;
<ide> import com.badlogic.gdx.scenes.scene2d.actions.Actions;
<ide> import com.badlogic.gdx.scenes.scene2d.ui.Skin;
<ide> import com.badlogic.gdx.scenes.scene2d.ui.Table;
<ide> import com.badlogic.gdx.scenes.scene2d.ui.WidgetGroup;
<del>import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
<ide> import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
<ide> import com.badlogic.gdx.scenes.scene2d.utils.Disableable;
<ide> import com.badlogic.gdx.scenes.scene2d.utils.Drawable;
<ide> private boolean hideOnUnfocus;
<ide> private int preferredEdge;
<ide> private boolean keepSizedWithinStage;
<add> private boolean automaticallyResized;
<ide>
<ide> public PopTable() {
<ide> this(new PopTableStyle());
<ide> hideOnUnfocus = true;
<ide> preferredEdge = Align.top;
<ide> keepSizedWithinStage = true;
<add> automaticallyResized = true;
<ide> }
<ide>
<ide> public void alignToActorEdge(Actor actor, int edge) {
<ide>
<ide> public PopTableClickListener(PopTableStyle style) {
<ide> popTable = new PopTable(style);
<add> popTable.automaticallyResized = false;
<ide> popTable.addListener(new TableHiddenListener() {
<ide> @Override
<ide> public void tableHidden(Event event) {
<ide> public void setKeepSizedWithinStage(boolean keepSizedWithinStage) {
<ide> this.keepSizedWithinStage = keepSizedWithinStage;
<ide> }
<del>
<add>
<add> public boolean isAutomaticallyResized() {
<add> return automaticallyResized;
<add> }
<add>
<add> public void setAutomaticallyResized(boolean automaticallyResized) {
<add> this.automaticallyResized = automaticallyResized;
<add> }
<add>
<add> @Override
<add> public void layout() {
<add> super.layout();
<add> if (automaticallyResized) {
<add> var centerX = getX(Align.center);
<add> var centerY = getY(Align.center);
<add> pack();
<add> if (keepSizedWithinStage) {
<add> moveToInsideStage();
<add> }
<add> setPosition(centerX, centerY, Align.center);
<add> setPosition(MathUtils.floor(getX()), MathUtils.floor(getY()));
<add> }
<add> }
<ide> } |
|
Java | mit | a5e621592f0bf7295ed66449a1780a489830941a | 0 | Permafrost/Tundra.java,Permafrost/Tundra.java | /*
* The MIT License (MIT)
*
* Copyright (c) 2021 Lachlan Dowding
*
* 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 permafrost.tundra.data;
import com.wm.data.IData;
import com.wm.data.IDataCursor;
import com.wm.data.IDataFactory;
import com.wm.lang.ns.NSField;
import com.wm.lang.ns.NSRecord;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Collection of convenience methods for working with IDataCursor objects.
*/
public class IDataCursorHelper {
/**
* Disallow instantiation of this class.
*/
private IDataCursorHelper() {}
/**
* Append all elements in the given source cursor to the end of the given target cursor.
*
* @param sourceCursor The cursor containing elements to be appended.
* @param targetCursor The cursor to which the elements will be appended.
*/
public static void append(IDataCursor sourceCursor, IDataCursor targetCursor) {
if (sourceCursor != null && targetCursor != null) {
targetCursor.last();
if (sourceCursor.first()) {
targetCursor.insertAfter(sourceCursor.getKey(), sourceCursor.getValue());
while (sourceCursor.next()) {
targetCursor.insertAfter(sourceCursor.getKey(), sourceCursor.getValue());
}
}
}
}
/**
* Prepend all elements in the given source cursor to the beginning of the given target cursor.
*
* @param sourceCursor The cursor containing elements to be appended.
* @param targetCursor The cursor to which the elements will be appended.
*/
public static void prepend(IDataCursor sourceCursor, IDataCursor targetCursor) {
if (sourceCursor != null && targetCursor != null) {
targetCursor.first();
if (sourceCursor.last()) {
targetCursor.insertBefore(sourceCursor.getKey(), sourceCursor.getValue());
while (sourceCursor.previous()) {
targetCursor.insertBefore(sourceCursor.getKey(), sourceCursor.getValue());
}
}
}
}
/**
* Removes all elements from the given cursor.
*
* @param cursor The cursor from which to remove all elements.
*/
public static void clear(IDataCursor cursor) {
clear(cursor, null);
}
/**
* Removes all elements from the given cursor.
*
* @param cursor The cursor from which to remove all elements.
*/
public static void clear(IDataCursor cursor, Iterable<String> keysToPreserve) {
if (cursor != null) {
IDataCursor preservedCursor = null;
try {
if (keysToPreserve != null) {
IData preservedDocument = IDataFactory.create();
preservedCursor = preservedDocument.getCursor();
for (String key : keysToPreserve) {
if (key != null) {
while(cursor.first(key)) {
preservedCursor.insertAfter(key, cursor.getValue());
cursor.delete();
}
}
}
}
cursor.first();
while (cursor.delete());
append(preservedCursor, cursor);
} finally {
if (preservedCursor != null) {
preservedCursor.destroy();
}
}
}
}
/**
* Positions the cursor on the first element with the given key whose value has the specified class.
*
* @param cursor The cursor to be positioned.
* @param valueClass The required class of the element's value.
* @param key The element's key.
* @param <V> The required class of the element's value.
* @return True if the key existed with a value of the required class and the cursor was repositioned,
* otherwise false.
*/
@SuppressWarnings("unchecked")
public static <V> boolean first(IDataCursor cursor, Class<V> valueClass, String key) {
boolean first = false;
if (cursor != null) {
if (cursor.first(key)) {
Object candidateValue = cursor.getValue();
if (valueClass.isInstance(candidateValue)) {
first = true;
} else {
while(cursor.next(key)) {
candidateValue = cursor.getValue();
if (valueClass.isInstance(candidateValue)) {
first = true;
break;
}
}
}
}
}
return first;
}
/**
* Returns the value of the first element in the cursor with the given key whose value has the specified class.
*
* @param cursor The cursor containing elements.
* @param valueClass The required class of the element's value.
* @param key The element's key.
* @param <V> The required class of the element's value.
* @return The value associated with the given key, if any.
*/
@SuppressWarnings("unchecked")
public static <V> V get(IDataCursor cursor, Class<V> valueClass, String key) {
V value;
if (first(cursor, valueClass, key)) {
value = (V)cursor.getValue();
} else {
value = null;
}
return value;
}
/**
* Removes the first element in the cursor with the given key whose value has the specified class.
*
* @param cursor The cursor containing elements.
* @param valueClass The required class of the element's value.
* @param key The element's key.
* @param <V> The required class of the element's value.
* @return The value associated with the given key, if any.
*/
@SuppressWarnings("unchecked")
public static <V> V remove(IDataCursor cursor, Class<V> valueClass, String key) {
V value;
if (first(cursor, valueClass, key)) {
value = (V)cursor.getValue();
cursor.delete();
} else {
value = null;
}
return value;
}
/**
* Renames the first element's key in the cursor with the given key whose value has the specified class.
*
* @param cursor The cursor containing elements.
* @param valueClass The required class of the element's value.
* @param sourceKey The element's key before renaming.
* @param targetKey The element's key after renaming.
* @param <V> The required class of the element's value.
* @return The value associated with the given key, if any.
*/
@SuppressWarnings("unchecked")
public static <V> V rename(IDataCursor cursor, Class<V> valueClass, String sourceKey, String targetKey) {
V value;
if (first(cursor, valueClass, sourceKey)) {
value = (V)cursor.getValue();
cursor.delete();
cursor.insertAfter(targetKey, value);
} else {
value = null;
}
return value;
}
/**
* Replaces the value of the first element in the cursor with the given key whose existing value has the specified
* class.
*
* @param cursor The cursor containing elements.
* @param valueClass The required class of the element's existing value.
* @param key The element's key.
* @param newValue The new value to be associated with the given key.
* @param <V> The required class of the element's existing value.
*/
@SuppressWarnings("unchecked")
public static <V> void replace(IDataCursor cursor, Class<V> valueClass, String key, Object newValue) {
if (first(cursor, valueClass, key)) {
cursor.setValue(newValue);
}
}
/**
* Replaces all elements in the given target cursor with the elements in the given source cursor.
*
* @param sourceCursor The cursor containing the elements to be used to replace the target cursor elements.
* @param targetCursor The cursor whose elements are to be replaced with the source cursor elements.
*/
public static void replace(IDataCursor sourceCursor, IDataCursor targetCursor) {
clear(targetCursor);
append(sourceCursor, targetCursor);
}
/**
* Lexicographically sorts the elements in the given cursor by key.
*
* @param cursor The cursor whose elements are to be sorted.
*/
public static void sort(IDataCursor cursor) {
if (cursor != null) {
if (cursor.first()) {
List<String> keys = keys(cursor);
Collections.sort(keys);
IData sortedDocument = IDataFactory.create();
IDataCursor sortedCursor = sortedDocument.getCursor();
try {
for(String key : keys) {
if (cursor.first(key)) {
sortedCursor.insertAfter(key, cursor.getValue());
cursor.delete();
}
}
replace(sortedCursor, cursor);
} finally {
sortedCursor.destroy();
}
}
}
}
/**
* Returns true if the given cursor is empty.
*
* @param cursor The cursor to be checked if empty.
* @return True if the cursor contains no elements, otherwise false.
*/
public static boolean isEmpty(IDataCursor cursor) {
return cursor == null || !cursor.first();
}
/**
* Returns the number of items in the given cursor.
*
* @param cursor The cursor whose size is to be returned.
* @return The number of items in the given cursor.
*/
public static int size(IDataCursor cursor) {
int size = 0;
if (cursor != null) {
if (cursor.first()) {
size++;
while (cursor.next()) {
size++;
}
}
}
return size;
}
/**
* Returns the list of keys present in the given cursor.
*
* @param cursor The cursor to return the list of keys from.
* @return The list of keys present in the given cursor.
*/
public static List<String> keys(IDataCursor cursor) {
ArrayList<String> keys = new ArrayList<String>(size(cursor));
if (cursor != null) {
if (cursor.first()) {
keys.add(cursor.getKey());
while(cursor.next()) {
keys.add(cursor.getKey());
}
}
}
return keys;
}
/**
* Returns the list of values present in the given cursor.
*
* @param cursor The cursor to return the list of values from.
* @return The list of values present in the given cursor.
*/
public static List<Object> values(IDataCursor cursor) {
ArrayList<Object> values = new ArrayList<Object>(size(cursor));
if (cursor != null) {
if (cursor.first()) {
values.add(cursor.getValue());
while(cursor.next()) {
values.add(cursor.getValue());
}
}
}
return values;
}
/**
* Sanitizes the given cursor against the given record by removing all disallowed unspecified values.
*
* @param cursor The cursor to be sanitized.
* @param record The record that defines the structure the cursor will be sanitized against.
* @param recurse Whether to recursively sanitize child IData and IData[] elements.
*/
public static void sanitize(IDataCursor cursor, NSRecord record, boolean recurse) {
if (cursor != null && record != null) {
NSField[] fields = record.getFields();
if (fields != null) {
IData sanitizedDocument = IDataFactory.create();
IDataCursor sanitizedCursor = sanitizedDocument.getCursor();
try {
for (NSField field : fields) {
if (field != null) {
String key = field.getName();
if (cursor.first(key)) {
Object value = sanitize(cursor.getValue(), field, recurse);
if (value != null) {
sanitizedCursor.insertAfter(key, value);
cursor.delete();
} else {
while(cursor.next(key)) {
value = sanitize(cursor.getValue(), field, recurse);
if (value != null) {
sanitizedCursor.insertAfter(key, value);
cursor.delete();
break;
}
}
}
}
}
}
if (record.isClosed()) {
// if the record disallows unspecified fields, then remove all remaining unsanitized fields
clear(cursor);
} else {
// if the record allows unspecified fields, then include any remaining keys at the end of the
// document, but sort them lexicographically for predictable repeatable results
sort(cursor);
}
prepend(sanitizedCursor, cursor);
} finally {
sanitizedCursor.destroy();
}
}
}
}
/**
* Sanitizes the given value against the given field.
*
* @param value The value to sanitize.
* @param field The field against which to sanitize.
* @param recurse Whether to recursively sanitize child IData and IData[] objects.
* @return The sanitized value, or null if not a valid value for this field.
*/
private static Object sanitize(Object value, NSField field, boolean recurse) {
Object sanitizedValue = null;
int fieldType = field.getType();
int fieldDimensions = field.getDimensions();
if (field instanceof NSRecord) {
if (fieldDimensions == NSField.DIM_ARRAY) {
IData[] array = IDataHelper.toIDataArray(value);
if (array != null) {
if (recurse) {
for (IData document : array) {
if (document != null) {
IDataCursor documentCursor = document.getCursor();
try {
sanitize(documentCursor, (NSRecord)field, recurse);
} finally {
documentCursor.destroy();
}
}
}
}
sanitizedValue = array;
}
} else if (fieldDimensions == NSField.DIM_SCALAR) {
IData document = IDataHelper.toIData(value);
if (document != null) {
if (recurse) {
IDataCursor documentCursor = document.getCursor();
try {
sanitize(documentCursor, (NSRecord)field, recurse);
} finally {
documentCursor.destroy();
}
}
sanitizedValue = document;
}
}
} else if (fieldType == NSField.FIELD_STRING) {
if ((fieldDimensions == NSField.DIM_TABLE && value instanceof String[][]) ||
(fieldDimensions == NSField.DIM_ARRAY && value instanceof String[]) ||
(fieldDimensions == NSField.DIM_SCALAR && value instanceof String)) {
sanitizedValue = value;
}
} else {
if ((fieldDimensions == NSField.DIM_TABLE && value instanceof Object[][]) ||
(fieldDimensions == NSField.DIM_ARRAY && value instanceof Object[]) ||
(fieldDimensions == NSField.DIM_SCALAR && value instanceof Object)) {
sanitizedValue = value;
}
}
return sanitizedValue;
}
}
| src/main/java/permafrost/tundra/data/IDataCursorHelper.java | /*
* The MIT License (MIT)
*
* Copyright (c) 2021 Lachlan Dowding
*
* 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 permafrost.tundra.data;
import com.wm.data.IData;
import com.wm.data.IDataCursor;
import com.wm.data.IDataFactory;
import com.wm.lang.ns.NSField;
import com.wm.lang.ns.NSRecord;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Collection of convenience methods for working with IDataCursor objects.
*/
public class IDataCursorHelper {
/**
* Disallow instantiation of this class.
*/
private IDataCursorHelper() {}
/**
* Append all elements in the given source cursor to the end of the given target cursor.
*
* @param sourceCursor The cursor containing elements to be appended.
* @param targetCursor The cursor to which the elements will be appended.
*/
public static void append(IDataCursor sourceCursor, IDataCursor targetCursor) {
if (sourceCursor != null && targetCursor != null) {
targetCursor.last();
if (sourceCursor.first()) {
targetCursor.insertAfter(sourceCursor.getKey(), sourceCursor.getValue());
while (sourceCursor.next()) {
targetCursor.insertAfter(sourceCursor.getKey(), sourceCursor.getValue());
}
}
}
}
/**
* Prepend all elements in the given source cursor to the beginning of the given target cursor.
*
* @param sourceCursor The cursor containing elements to be appended.
* @param targetCursor The cursor to which the elements will be appended.
*/
public static void prepend(IDataCursor sourceCursor, IDataCursor targetCursor) {
if (sourceCursor != null && targetCursor != null) {
targetCursor.first();
if (sourceCursor.last()) {
targetCursor.insertBefore(sourceCursor.getKey(), sourceCursor.getValue());
while (sourceCursor.previous()) {
targetCursor.insertBefore(sourceCursor.getKey(), sourceCursor.getValue());
}
}
}
}
/**
* Removes all elements from the given cursor.
*
* @param cursor The cursor from which to remove all elements.
*/
public static void clear(IDataCursor cursor) {
clear(cursor, null);
}
/**
* Removes all elements from the given cursor.
*
* @param cursor The cursor from which to remove all elements.
*/
public static void clear(IDataCursor cursor, Iterable<String> keysToPreserve) {
if (cursor != null) {
IDataCursor preservedCursor = null;
try {
if (keysToPreserve != null) {
IData preservedDocument = IDataFactory.create();
preservedCursor = preservedDocument.getCursor();
for (String key : keysToPreserve) {
if (key != null) {
while(cursor.first(key)) {
preservedCursor.insertAfter(key, cursor.getValue());
cursor.delete();
}
}
}
}
cursor.first();
while (cursor.delete());
append(preservedCursor, cursor);
} finally {
if (preservedCursor != null) {
preservedCursor.destroy();
}
}
}
}
/**
* Replaces all elements in the given target cursor with the elements in the given source cursor.
*
* @param sourceCursor The cursor containing the elements to be used to replace the target cursor elements.
* @param targetCursor The cursor whose elements are to be replaced with the source cursor elements.
*/
public static void replace(IDataCursor sourceCursor, IDataCursor targetCursor) {
clear(targetCursor);
append(sourceCursor, targetCursor);
}
/**
* Lexicographically sorts the elements in the given cursor by key.
*
* @param cursor The cursor whose elements are to be sorted.
*/
public static void sort(IDataCursor cursor) {
if (cursor != null) {
if (cursor.first()) {
List<String> keys = keys(cursor);
Collections.sort(keys);
IData sortedDocument = IDataFactory.create();
IDataCursor sortedCursor = sortedDocument.getCursor();
try {
for(String key : keys) {
if (cursor.first(key)) {
sortedCursor.insertAfter(key, cursor.getValue());
cursor.delete();
}
}
replace(sortedCursor, cursor);
} finally {
sortedCursor.destroy();
}
}
}
}
/**
* Returns the number of items in the given cursor.
*
* @param cursor The cursor whose size is to be returned.
* @return The number of items in the given cursor.
*/
public static int size(IDataCursor cursor) {
int size = 0;
if (cursor != null) {
if (cursor.first()) {
size++;
while (cursor.next()) {
size++;
}
}
}
return size;
}
/**
* Returns the list of keys present in the given cursor.
*
* @param cursor The cursor to return the list of keys from.
* @return The list of keys present in the given cursor.
*/
public static List<String> keys(IDataCursor cursor) {
ArrayList<String> keys = new ArrayList<String>(size(cursor));
if (cursor != null) {
if (cursor.first()) {
keys.add(cursor.getKey());
while(cursor.next()) {
keys.add(cursor.getKey());
}
}
}
return keys;
}
/**
* Returns the list of values present in the given cursor.
*
* @param cursor The cursor to return the list of values from.
* @return The list of values present in the given cursor.
*/
public static List<Object> values(IDataCursor cursor) {
ArrayList<Object> values = new ArrayList<Object>(size(cursor));
if (cursor != null) {
if (cursor.first()) {
values.add(cursor.getValue());
while(cursor.next()) {
values.add(cursor.getValue());
}
}
}
return values;
}
/**
* Sanitizes the given cursor against the given record by removing all disallowed unspecified values.
*
* @param cursor The cursor to be sanitized.
* @param record The record that defines the structure the cursor will be sanitized against.
* @param recurse Whether to recursively sanitize child IData and IData[] elements.
*/
public static void sanitize(IDataCursor cursor, NSRecord record, boolean recurse) {
if (cursor != null && record != null) {
NSField[] fields = record.getFields();
if (fields != null) {
IData sanitizedDocument = IDataFactory.create();
IDataCursor sanitizedCursor = sanitizedDocument.getCursor();
try {
for (NSField field : fields) {
if (field != null) {
String key = field.getName();
if (cursor.first(key)) {
Object value = sanitize(cursor.getValue(), field, recurse);
if (value != null) {
sanitizedCursor.insertAfter(key, value);
cursor.delete();
} else {
while(cursor.next(key)) {
value = sanitize(cursor.getValue(), field, recurse);
if (value != null) {
sanitizedCursor.insertAfter(key, value);
cursor.delete();
break;
}
}
}
}
}
}
if (record.isClosed()) {
// if the record disallows unspecified fields, then remove all remaining unsanitized fields
clear(cursor);
} else {
// if the record allows unspecified fields, then include any remaining keys at the end of the
// document, but sort them lexicographically for predictable repeatable results
sort(cursor);
}
prepend(sanitizedCursor, cursor);
} finally {
sanitizedCursor.destroy();
}
}
}
}
/**
* Sanitizes the given value against the given field.
*
* @param value The value to sanitize.
* @param field The field against which to sanitize.
* @param recurse Whether to recursively sanitize child IData and IData[] objects.
* @return The sanitized value, or null if not a valid value for this field.
*/
private static Object sanitize(Object value, NSField field, boolean recurse) {
Object sanitizedValue = null;
int fieldType = field.getType();
int fieldDimensions = field.getDimensions();
if (field instanceof NSRecord) {
if (fieldDimensions == NSField.DIM_ARRAY) {
IData[] array = IDataHelper.toIDataArray(value);
if (array != null) {
if (recurse) {
for (IData document : array) {
if (document != null) {
IDataCursor documentCursor = document.getCursor();
try {
sanitize(documentCursor, (NSRecord)field, recurse);
} finally {
documentCursor.destroy();
}
}
}
}
sanitizedValue = array;
}
} else if (fieldDimensions == NSField.DIM_SCALAR) {
IData document = IDataHelper.toIData(value);
if (document != null) {
if (recurse) {
IDataCursor documentCursor = document.getCursor();
try {
sanitize(documentCursor, (NSRecord)field, recurse);
} finally {
documentCursor.destroy();
}
}
sanitizedValue = document;
}
}
} else if (fieldType == NSField.FIELD_STRING) {
if ((fieldDimensions == NSField.DIM_TABLE && value instanceof String[][]) ||
(fieldDimensions == NSField.DIM_ARRAY && value instanceof String[]) ||
(fieldDimensions == NSField.DIM_SCALAR && value instanceof String)) {
sanitizedValue = value;
}
} else {
if ((fieldDimensions == NSField.DIM_TABLE && value instanceof Object[][]) ||
(fieldDimensions == NSField.DIM_ARRAY && value instanceof Object[]) ||
(fieldDimensions == NSField.DIM_SCALAR && value instanceof Object)) {
sanitizedValue = value;
}
}
return sanitizedValue;
}
}
| Add IDataCursorHelper methods first, get, remove, and rename
| src/main/java/permafrost/tundra/data/IDataCursorHelper.java | Add IDataCursorHelper methods first, get, remove, and rename | <ide><path>rc/main/java/permafrost/tundra/data/IDataCursorHelper.java
<ide> }
<ide>
<ide> /**
<add> * Positions the cursor on the first element with the given key whose value has the specified class.
<add> *
<add> * @param cursor The cursor to be positioned.
<add> * @param valueClass The required class of the element's value.
<add> * @param key The element's key.
<add> * @param <V> The required class of the element's value.
<add> * @return True if the key existed with a value of the required class and the cursor was repositioned,
<add> * otherwise false.
<add> */
<add> @SuppressWarnings("unchecked")
<add> public static <V> boolean first(IDataCursor cursor, Class<V> valueClass, String key) {
<add> boolean first = false;
<add> if (cursor != null) {
<add> if (cursor.first(key)) {
<add> Object candidateValue = cursor.getValue();
<add> if (valueClass.isInstance(candidateValue)) {
<add> first = true;
<add> } else {
<add> while(cursor.next(key)) {
<add> candidateValue = cursor.getValue();
<add> if (valueClass.isInstance(candidateValue)) {
<add> first = true;
<add> break;
<add> }
<add> }
<add> }
<add> }
<add> }
<add> return first;
<add> }
<add>
<add> /**
<add> * Returns the value of the first element in the cursor with the given key whose value has the specified class.
<add> *
<add> * @param cursor The cursor containing elements.
<add> * @param valueClass The required class of the element's value.
<add> * @param key The element's key.
<add> * @param <V> The required class of the element's value.
<add> * @return The value associated with the given key, if any.
<add> */
<add> @SuppressWarnings("unchecked")
<add> public static <V> V get(IDataCursor cursor, Class<V> valueClass, String key) {
<add> V value;
<add> if (first(cursor, valueClass, key)) {
<add> value = (V)cursor.getValue();
<add> } else {
<add> value = null;
<add> }
<add> return value;
<add> }
<add>
<add> /**
<add> * Removes the first element in the cursor with the given key whose value has the specified class.
<add> *
<add> * @param cursor The cursor containing elements.
<add> * @param valueClass The required class of the element's value.
<add> * @param key The element's key.
<add> * @param <V> The required class of the element's value.
<add> * @return The value associated with the given key, if any.
<add> */
<add> @SuppressWarnings("unchecked")
<add> public static <V> V remove(IDataCursor cursor, Class<V> valueClass, String key) {
<add> V value;
<add> if (first(cursor, valueClass, key)) {
<add> value = (V)cursor.getValue();
<add> cursor.delete();
<add> } else {
<add> value = null;
<add> }
<add> return value;
<add> }
<add>
<add> /**
<add> * Renames the first element's key in the cursor with the given key whose value has the specified class.
<add> *
<add> * @param cursor The cursor containing elements.
<add> * @param valueClass The required class of the element's value.
<add> * @param sourceKey The element's key before renaming.
<add> * @param targetKey The element's key after renaming.
<add> * @param <V> The required class of the element's value.
<add> * @return The value associated with the given key, if any.
<add> */
<add> @SuppressWarnings("unchecked")
<add> public static <V> V rename(IDataCursor cursor, Class<V> valueClass, String sourceKey, String targetKey) {
<add> V value;
<add> if (first(cursor, valueClass, sourceKey)) {
<add> value = (V)cursor.getValue();
<add> cursor.delete();
<add> cursor.insertAfter(targetKey, value);
<add> } else {
<add> value = null;
<add> }
<add> return value;
<add> }
<add>
<add> /**
<add> * Replaces the value of the first element in the cursor with the given key whose existing value has the specified
<add> * class.
<add> *
<add> * @param cursor The cursor containing elements.
<add> * @param valueClass The required class of the element's existing value.
<add> * @param key The element's key.
<add> * @param newValue The new value to be associated with the given key.
<add> * @param <V> The required class of the element's existing value.
<add> */
<add> @SuppressWarnings("unchecked")
<add> public static <V> void replace(IDataCursor cursor, Class<V> valueClass, String key, Object newValue) {
<add> if (first(cursor, valueClass, key)) {
<add> cursor.setValue(newValue);
<add> }
<add> }
<add>
<add> /**
<ide> * Replaces all elements in the given target cursor with the elements in the given source cursor.
<ide> *
<ide> * @param sourceCursor The cursor containing the elements to be used to replace the target cursor elements.
<ide> }
<ide> }
<ide> }
<add> }
<add>
<add> /**
<add> * Returns true if the given cursor is empty.
<add> *
<add> * @param cursor The cursor to be checked if empty.
<add> * @return True if the cursor contains no elements, otherwise false.
<add> */
<add> public static boolean isEmpty(IDataCursor cursor) {
<add> return cursor == null || !cursor.first();
<ide> }
<ide>
<ide> /**
<ide> try {
<ide> for (NSField field : fields) {
<ide> if (field != null) {
<del>
<ide> String key = field.getName();
<ide> if (cursor.first(key)) {
<ide> Object value = sanitize(cursor.getValue(), field, recurse); |
|
Java | apache-2.0 | dc66d42a74aee604fa261942105f03fa89d2c859 | 0 | katre/bazel,katre/bazel,cushon/bazel,bazelbuild/bazel,cushon/bazel,katre/bazel,cushon/bazel,cushon/bazel,bazelbuild/bazel,bazelbuild/bazel,bazelbuild/bazel,katre/bazel,katre/bazel,katre/bazel,cushon/bazel,bazelbuild/bazel,cushon/bazel,bazelbuild/bazel | // Copyright 2018 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License
package com.google.devtools.build.lib.rules.config;
import static com.google.devtools.build.lib.analysis.config.StarlarkDefinedConfigTransition.COMMAND_LINE_OPTION_PREFIX;
import com.google.common.collect.Sets;
import com.google.devtools.build.lib.analysis.config.StarlarkDefinedConfigTransition;
import com.google.devtools.build.lib.analysis.config.StarlarkDefinedConfigTransition.Settings;
import com.google.devtools.build.lib.cmdline.BazelModuleContext;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.starlarkbuildapi.config.ConfigGlobalLibraryApi;
import com.google.devtools.build.lib.starlarkbuildapi.config.ConfigurationTransitionApi;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import net.starlark.java.eval.Dict;
import net.starlark.java.eval.EvalException;
import net.starlark.java.eval.Module;
import net.starlark.java.eval.Sequence;
import net.starlark.java.eval.Starlark;
import net.starlark.java.eval.StarlarkCallable;
import net.starlark.java.eval.StarlarkSemantics;
import net.starlark.java.eval.StarlarkThread;
import net.starlark.java.syntax.Location;
/**
* Implementation of {@link ConfigGlobalLibraryApi}.
*
* <p>A collection of top-level Starlark functions pertaining to configuration.
*/
public class ConfigGlobalLibrary implements ConfigGlobalLibraryApi {
@Override
public ConfigurationTransitionApi transition(
StarlarkCallable implementation,
Sequence<?> inputs, // <String> expected
Sequence<?> outputs, // <String> expected
StarlarkThread thread)
throws EvalException {
StarlarkSemantics semantics = thread.getSemantics();
List<String> inputsList = Sequence.cast(inputs, String.class, "inputs");
List<String> outputsList = Sequence.cast(outputs, String.class, "outputs");
validateBuildSettingKeys(inputsList, Settings.INPUTS);
validateBuildSettingKeys(outputsList, Settings.OUTPUTS);
BazelModuleContext moduleContext =
BazelModuleContext.of(Module.ofInnermostEnclosingStarlarkFunction(thread));
Location location = thread.getCallerLocation();
return StarlarkDefinedConfigTransition.newRegularTransition(
implementation,
inputsList,
outputsList,
semantics,
moduleContext.label(),
location,
moduleContext.repoMapping());
}
@Override
public ConfigurationTransitionApi analysisTestTransition(
Dict<?, ?> changedSettings, // <String, String> expected
StarlarkThread thread)
throws EvalException {
Map<String, Object> changedSettingsMap =
Dict.cast(changedSettings, String.class, Object.class, "changed_settings dict");
validateBuildSettingKeys(changedSettingsMap.keySet(), Settings.OUTPUTS);
BazelModuleContext moduleContext =
BazelModuleContext.of(Module.ofInnermostEnclosingStarlarkFunction(thread));
Location location = thread.getCallerLocation();
return StarlarkDefinedConfigTransition.newAnalysisTestTransition(
changedSettingsMap, moduleContext.repoMapping(), moduleContext.label(), location);
}
private void validateBuildSettingKeys(Iterable<String> optionKeys, Settings keyErrorDescriptor)
throws EvalException {
HashSet<String> processedOptions = Sets.newHashSet();
String singularErrorDescriptor = keyErrorDescriptor == Settings.INPUTS ? "input" : "output";
for (String optionKey : optionKeys) {
if (!optionKey.startsWith(COMMAND_LINE_OPTION_PREFIX)) {
try {
Label.parseAbsoluteUnchecked(optionKey);
} catch (IllegalArgumentException e) {
throw Starlark.errorf(
"invalid transition %s '%s'. If this is intended as a native option, "
+ "it must begin with //command_line_option: %s",
singularErrorDescriptor, optionKey, e.getMessage());
}
} else {
String optionName = optionKey.substring(COMMAND_LINE_OPTION_PREFIX.length());
if (!validOptionName(optionName)) {
throw Starlark.errorf(
"Invalid transition %s '%s'. Cannot transition on --experimental_* or "
+ "--incompatible_* options",
singularErrorDescriptor, optionKey);
}
}
if (!processedOptions.add(optionKey)) {
throw Starlark.errorf("duplicate transition %s '%s'", singularErrorDescriptor, optionKey);
}
}
}
private static boolean validOptionName(String optionName) {
if (optionName.startsWith("experimental_")) {
// Don't allow experimental flags.
return false;
}
if (optionName.equals("incompatible_enable_cc_toolchain_resolution")
|| optionName.equals("incompatible_enable_cgo_toolchain_resolution")
|| optionName.equals("incompatible_enable_apple_toolchain_resolution")) {
// This is specifically allowed.
return true;
} else if (optionName.startsWith("incompatible_")) {
// Don't allow other incompatible flags.
return false;
}
return true;
}
}
| src/main/java/com/google/devtools/build/lib/rules/config/ConfigGlobalLibrary.java | // Copyright 2018 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License
package com.google.devtools.build.lib.rules.config;
import static com.google.devtools.build.lib.analysis.config.StarlarkDefinedConfigTransition.COMMAND_LINE_OPTION_PREFIX;
import com.google.common.collect.Sets;
import com.google.devtools.build.lib.analysis.config.StarlarkDefinedConfigTransition;
import com.google.devtools.build.lib.analysis.config.StarlarkDefinedConfigTransition.Settings;
import com.google.devtools.build.lib.cmdline.BazelModuleContext;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.starlarkbuildapi.config.ConfigGlobalLibraryApi;
import com.google.devtools.build.lib.starlarkbuildapi.config.ConfigurationTransitionApi;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import net.starlark.java.eval.Dict;
import net.starlark.java.eval.EvalException;
import net.starlark.java.eval.Module;
import net.starlark.java.eval.Sequence;
import net.starlark.java.eval.Starlark;
import net.starlark.java.eval.StarlarkCallable;
import net.starlark.java.eval.StarlarkSemantics;
import net.starlark.java.eval.StarlarkThread;
import net.starlark.java.syntax.Location;
/**
* Implementation of {@link ConfigGlobalLibraryApi}.
*
* <p>A collection of top-level Starlark functions pertaining to configuration.
*/
public class ConfigGlobalLibrary implements ConfigGlobalLibraryApi {
@Override
public ConfigurationTransitionApi transition(
StarlarkCallable implementation,
Sequence<?> inputs, // <String> expected
Sequence<?> outputs, // <String> expected
StarlarkThread thread)
throws EvalException {
StarlarkSemantics semantics = thread.getSemantics();
List<String> inputsList = Sequence.cast(inputs, String.class, "inputs");
List<String> outputsList = Sequence.cast(outputs, String.class, "outputs");
validateBuildSettingKeys(inputsList, Settings.INPUTS);
validateBuildSettingKeys(outputsList, Settings.OUTPUTS);
BazelModuleContext moduleContext =
BazelModuleContext.of(Module.ofInnermostEnclosingStarlarkFunction(thread));
Location location = thread.getCallerLocation();
return StarlarkDefinedConfigTransition.newRegularTransition(
implementation,
inputsList,
outputsList,
semantics,
moduleContext.label(),
location,
moduleContext.repoMapping());
}
@Override
public ConfigurationTransitionApi analysisTestTransition(
Dict<?, ?> changedSettings, // <String, String> expected
StarlarkThread thread)
throws EvalException {
Map<String, Object> changedSettingsMap =
Dict.cast(changedSettings, String.class, Object.class, "changed_settings dict");
validateBuildSettingKeys(changedSettingsMap.keySet(), Settings.OUTPUTS);
BazelModuleContext moduleContext =
BazelModuleContext.of(Module.ofInnermostEnclosingStarlarkFunction(thread));
Location location = thread.getCallerLocation();
return StarlarkDefinedConfigTransition.newAnalysisTestTransition(
changedSettingsMap, moduleContext.repoMapping(), moduleContext.label(), location);
}
private void validateBuildSettingKeys(Iterable<String> optionKeys, Settings keyErrorDescriptor)
throws EvalException {
HashSet<String> processedOptions = Sets.newHashSet();
String singularErrorDescriptor = keyErrorDescriptor == Settings.INPUTS ? "input" : "output";
for (String optionKey : optionKeys) {
if (!optionKey.startsWith(COMMAND_LINE_OPTION_PREFIX)) {
try {
Label.parseAbsoluteUnchecked(optionKey);
} catch (IllegalArgumentException e) {
throw Starlark.errorf(
"invalid transition %s '%s'. If this is intended as a native option, "
+ "it must begin with //command_line_option: %s",
singularErrorDescriptor, optionKey, e.getMessage());
}
} else {
String optionName = optionKey.substring(COMMAND_LINE_OPTION_PREFIX.length());
if (!validOptionName(optionName)) {
throw Starlark.errorf(
"Invalid transition %s '%s'. Cannot transition on --experimental_* or "
+ "--incompatible_* options",
singularErrorDescriptor, optionKey);
}
}
if (!processedOptions.add(optionKey)) {
throw Starlark.errorf("duplicate transition %s '%s'", singularErrorDescriptor, optionKey);
}
}
}
private static boolean validOptionName(String optionName) {
if (optionName.startsWith("experimental_")) {
// Don't allow experimental flags.
return false;
}
if (optionName.equals("incompatible_enable_cc_toolchain_resolution")
|| optionName.equals("incompatible_enable_apple_toolchain_resolution")) {
// This is specifically allowed.
return true;
} else if (optionName.startsWith("incompatible_")) {
// Don't allow other incompatible flags.
return false;
}
return true;
}
}
| Add command option incompatible_enable_cgo_toolchain_resolution
PiperOrigin-RevId: 464537505
Change-Id: Icab8a3d5277939e4968aa04e69016a99b8e009e9
| src/main/java/com/google/devtools/build/lib/rules/config/ConfigGlobalLibrary.java | Add command option incompatible_enable_cgo_toolchain_resolution | <ide><path>rc/main/java/com/google/devtools/build/lib/rules/config/ConfigGlobalLibrary.java
<ide> }
<ide>
<ide> if (optionName.equals("incompatible_enable_cc_toolchain_resolution")
<add> || optionName.equals("incompatible_enable_cgo_toolchain_resolution")
<ide> || optionName.equals("incompatible_enable_apple_toolchain_resolution")) {
<ide> // This is specifically allowed.
<ide> return true; |
|
Java | bsd-3-clause | 507a343f705e8360601579500b2acef5bb05e6b4 | 0 | mrdon/PLUG | package com.atlassian.plugin;
import java.io.InputStream;
import java.net.URL;
import java.util.*;
public interface Plugin extends Resourced, Comparable<Plugin>
{
/**
* @deprecated since 2.2.0. This comparator only takes into account the plugin name and assumes it is not null,
* yet a) that constraint is not validated anywhere in plugin loading and b) the plugin could have used the i18n
* name, and only the application can resolve that to a name useful for comparisons.
*/
public static final Comparator<Plugin> NAME_COMPARATOR = new PluginNameComparator();
/**
* Gets the version of the plugins system to handle this plugin
* @return The plugins version. If undefined, assumed to be 1.
*/
int getPluginsVersion();
/**
* Sets the version of the plugins system
* @param version The version
*/
void setPluginsVersion(int version);
String getName();
void setName(String name);
String getI18nNameKey();
void setI18nNameKey(String i18nNameKey);
String getKey();
void setKey(String aPackage);
void addModuleDescriptor(ModuleDescriptor<?> moduleDescriptor);
/**
* Get the {@link Collection} of {@link ModuleDescriptor descriptors}. The iteration order of the collection is
* the order that the modules will be enabled, and should be the same order that the modules appear in the
* plugin descriptor.
*
* @return the modules contained by this plugin in the order they are to be enabled
*/
Collection<ModuleDescriptor<?>> getModuleDescriptors();
/**
* Get the {@link ModuleDescriptor} for a particular key. Returns <tt>null</tt> if the plugin does not exist.
* <p>
* Note: The {@link ModuleDescriptor#getModule()} may throw {@link ClassCastException} if the expected type is incorrect.
*
* @param key the {@link String} complete key of the module, in the form "org.example.plugin:module-key".
* @return the {@link ModuleDescriptor} of the expected type.
*/
ModuleDescriptor<?> getModuleDescriptor(String key);
/**
* Get the {@link ModuleDescriptor descriptors} whose module class implements or is assignable from the supplied {@link Class}.
* <p>
* Note: The {@link ModuleDescriptor#getModule()} may throw {@link ClassCastException} if the expected type is incorrect.
* Normally this method would not be supplied with anything other than {@link Object} or <?>, unless you are
* confident in the super type of the module classes this {@link Plugin} provides.
*
* @param <M> The expected module type of the returned {@link ModuleDescriptor descriptors}.
* @param moduleClass the {@link Class super class} the {@link ModuleDescriptor descriptors} return.
* @return the {@link List} of {@link ModuleDescriptor descriptors} of the expected type.
*/
<M> List<ModuleDescriptor<M>> getModuleDescriptorsByModuleClass(Class<M> moduleClass);
boolean isEnabledByDefault();
void setEnabledByDefault(boolean enabledByDefault);
PluginInformation getPluginInformation();
void setPluginInformation(PluginInformation pluginInformation);
void setResources(Resourced resources);
/**
* @return the current state of the plugin
* @since 2.2.0
*/
PluginState getPluginState();
/**
* @deprecated since 2.2.0, use {@link #getPluginState()} instead
* @return
*/
boolean isEnabled();
/**
* Whether the plugin is a "system" plugin that shouldn't be made visible to the user
*/
boolean isSystemPlugin();
boolean containsSystemModule();
void setSystemPlugin(boolean system);
/**
* Whether the plugin is a "bundled" plugin that can't be removed.
*/
boolean isBundledPlugin();
/**
* The date this plugin was loaded into the system.
*/
Date getDateLoaded();
/**
* Whether or not this plugin can be 'uninstalled'.
*/
boolean isUninstallable();
/**
* Should the plugin file be deleted on unistall?
*/
boolean isDeleteable();
/**
* Whether or not this plugin is loaded dynamically at runtime
*/
boolean isDynamicallyLoaded();
/**
* Get the plugin to load a specific class.
*
* @param clazz The name of the class to be loaded
* @param callingClass The class calling the loading (used to help find a classloader)
* @return The loaded class.
* @throws ClassNotFoundException
*/
<T> Class<T> loadClass(String clazz, Class<?> callingClass) throws ClassNotFoundException;
/**
* Get the classloader for the plugin.
*
* @return The classloader used to load classes for this plugin
*/
ClassLoader getClassLoader();
/**
* Retrieve the URL of the resource from the plugin.
*
* @param path the name of the resource to be loaded
* @return The URL to the resource, or null if the resource is not found
*/
URL getResource(String path);
/**
* Load a given resource from the plugin. Plugins that are loaded dynamically will need
* to implement this in a way that loads the resource from the same context as the plugin.
* Static plugins can just pull them from their own classloader.
*
* @param name The name of the resource to be loaded.
* @return An InputStream for the resource, or null if the resource is not found.
*/
InputStream getResourceAsStream(String name);
/**
* @deprecated Since 2.2.0, use {@link #enable()} or {@link #disable()} instead
*/
void setEnabled(boolean enabled);
/**
* Free any resources held by this plugin. To be called during uninstallation of the {@link Plugin}.
* @deprecated Since 2.2.0, use {@link #uninstall()} instead
*/
void close();
/**
* Installs the plugin into any internal, managing container. This method will be called on every startup. Unless
* an exception is thrown, the plugin should be in the {@link PluginState#INSTALLED} state. If the plugin is already
* in the {@link PluginState#INSTALLED} state, nothing will happen.
*
* @since 2.2.0
* @throws PluginException If the plugin could not be installed
*/
void install() throws PluginException;
/**
* Uninstalls the plugin from any internal container. This method will be called on every shutdown. Unless an
* exception is thrown, the plugin should be in the {@link PluginState#UNINSTALLED} state. If the plugin is already
* in the {@link PluginState#UNINSTALLED} state, nothing will happen.
*
* @since 2.2.0
* @throws PluginException If the plugin could not be uninstalled
*/
void uninstall() throws PluginException;
/**
* Enables the plugin. Unless an exception is thrown, the plugin should then be in either the
* {@link PluginState#ENABLING} or {@link PluginState#ENABLED} state. If the plugin is already in the
* {@link PluginState#ENABLING} or {@link PluginState#ENABLED} state, nothing will happen.
*
*
* @since 2.2.0
* @throws PluginException If the plugin could not be enabled
*/
void enable() throws PluginException;
/**
* Disables the plugin. Unless an exception is thrown, the plugin should be in the {@link PluginState#DISABLED}
* state. If the plugin is already in the {@link PluginState#DISABLED} state, nothing will happen.
*
* @since 2.2.0 If the plugin could not be disabled
* @throws PluginException
*/
void disable() throws PluginException;
/**
* @return A list of plugin keys that this plugin is dependent upon, or an empty list if none
* @since 2.2.0
*/
Set<String> getRequiredPlugins();
}
| atlassian-plugins-core/src/main/java/com/atlassian/plugin/Plugin.java | package com.atlassian.plugin;
import java.io.InputStream;
import java.net.URL;
import java.util.*;
public interface Plugin extends Resourced, Comparable<Plugin>
{
public static final Comparator<Plugin> NAME_COMPARATOR = new PluginNameComparator();
/**
* Gets the version of the plugins system to handle this plugin
* @return The plugins version. If undefined, assumed to be 1.
*/
int getPluginsVersion();
/**
* Sets the version of the plugins system
* @param version The version
*/
void setPluginsVersion(int version);
String getName();
void setName(String name);
String getI18nNameKey();
void setI18nNameKey(String i18nNameKey);
String getKey();
void setKey(String aPackage);
void addModuleDescriptor(ModuleDescriptor<?> moduleDescriptor);
/**
* Get the {@link Collection} of {@link ModuleDescriptor descriptors}. The iteration order of the collection is
* the order that the modules will be enabled, and should be the same order that the modules appear in the
* plugin descriptor.
*
* @return the modules contained by this plugin in the order they are to be enabled
*/
Collection<ModuleDescriptor<?>> getModuleDescriptors();
/**
* Get the {@link ModuleDescriptor} for a particular key. Returns <tt>null</tt> if the plugin does not exist.
* <p>
* Note: The {@link ModuleDescriptor#getModule()} may throw {@link ClassCastException} if the expected type is incorrect.
*
* @param key the {@link String} complete key of the module, in the form "org.example.plugin:module-key".
* @return the {@link ModuleDescriptor} of the expected type.
*/
ModuleDescriptor<?> getModuleDescriptor(String key);
/**
* Get the {@link ModuleDescriptor descriptors} whose module class implements or is assignable from the supplied {@link Class}.
* <p>
* Note: The {@link ModuleDescriptor#getModule()} may throw {@link ClassCastException} if the expected type is incorrect.
* Normally this method would not be supplied with anything other than {@link Object} or <?>, unless you are
* confident in the super type of the module classes this {@link Plugin} provides.
*
* @param <M> The expected module type of the returned {@link ModuleDescriptor descriptors}.
* @param moduleClass the {@link Class super class} the {@link ModuleDescriptor descriptors} return.
* @return the {@link List} of {@link ModuleDescriptor descriptors} of the expected type.
*/
<M> List<ModuleDescriptor<M>> getModuleDescriptorsByModuleClass(Class<M> moduleClass);
boolean isEnabledByDefault();
void setEnabledByDefault(boolean enabledByDefault);
PluginInformation getPluginInformation();
void setPluginInformation(PluginInformation pluginInformation);
void setResources(Resourced resources);
/**
* @return the current state of the plugin
* @since 2.2.0
*/
PluginState getPluginState();
/**
* @deprecated since 2.2.0, use {@link #getPluginState()} instead
* @return
*/
boolean isEnabled();
/**
* Whether the plugin is a "system" plugin that shouldn't be made visible to the user
*/
boolean isSystemPlugin();
boolean containsSystemModule();
void setSystemPlugin(boolean system);
/**
* Whether the plugin is a "bundled" plugin that can't be removed.
*/
boolean isBundledPlugin();
/**
* The date this plugin was loaded into the system.
*/
Date getDateLoaded();
/**
* Whether or not this plugin can be 'uninstalled'.
*/
boolean isUninstallable();
/**
* Should the plugin file be deleted on unistall?
*/
boolean isDeleteable();
/**
* Whether or not this plugin is loaded dynamically at runtime
*/
boolean isDynamicallyLoaded();
/**
* Get the plugin to load a specific class.
*
* @param clazz The name of the class to be loaded
* @param callingClass The class calling the loading (used to help find a classloader)
* @return The loaded class.
* @throws ClassNotFoundException
*/
<T> Class<T> loadClass(String clazz, Class<?> callingClass) throws ClassNotFoundException;
/**
* Get the classloader for the plugin.
*
* @return The classloader used to load classes for this plugin
*/
ClassLoader getClassLoader();
/**
* Retrieve the URL of the resource from the plugin.
*
* @param path the name of the resource to be loaded
* @return The URL to the resource, or null if the resource is not found
*/
URL getResource(String path);
/**
* Load a given resource from the plugin. Plugins that are loaded dynamically will need
* to implement this in a way that loads the resource from the same context as the plugin.
* Static plugins can just pull them from their own classloader.
*
* @param name The name of the resource to be loaded.
* @return An InputStream for the resource, or null if the resource is not found.
*/
InputStream getResourceAsStream(String name);
/**
* @deprecated Since 2.2.0, use {@link #enable()} or {@link #disable()} instead
*/
void setEnabled(boolean enabled);
/**
* Free any resources held by this plugin. To be called during uninstallation of the {@link Plugin}.
* @deprecated Since 2.2.0, use {@link #uninstall()} instead
*/
void close();
/**
* Installs the plugin into any internal, managing container. This method will be called on every startup. Unless
* an exception is thrown, the plugin should be in the {@link PluginState#INSTALLED} state. If the plugin is already
* in the {@link PluginState#INSTALLED} state, nothing will happen.
*
* @since 2.2.0
* @throws PluginException If the plugin could not be installed
*/
void install() throws PluginException;
/**
* Uninstalls the plugin from any internal container. This method will be called on every shutdown. Unless an
* exception is thrown, the plugin should be in the {@link PluginState#UNINSTALLED} state. If the plugin is already
* in the {@link PluginState#UNINSTALLED} state, nothing will happen.
*
* @since 2.2.0
* @throws PluginException If the plugin could not be uninstalled
*/
void uninstall() throws PluginException;
/**
* Enables the plugin. Unless an exception is thrown, the plugin should then be in either the
* {@link PluginState#ENABLING} or {@link PluginState#ENABLED} state. If the plugin is already in the
* {@link PluginState#ENABLING} or {@link PluginState#ENABLED} state, nothing will happen.
*
*
* @since 2.2.0
* @throws PluginException If the plugin could not be enabled
*/
void enable() throws PluginException;
/**
* Disables the plugin. Unless an exception is thrown, the plugin should be in the {@link PluginState#DISABLED}
* state. If the plugin is already in the {@link PluginState#DISABLED} state, nothing will happen.
*
* @since 2.2.0 If the plugin could not be disabled
* @throws PluginException
*/
void disable() throws PluginException;
/**
* @return A list of plugin keys that this plugin is dependent upon, or an empty list if none
* @since 2.2.0
*/
Set<String> getRequiredPlugins();
}
| Deprecating plugin name comparator because it doesn't take into account i18n names
PLUG-340
git-svn-id: 3d1f0b8d955af71bf8e09c956c180519124e4717@31515 2c54a935-e501-0410-bc05-97a93f6bca70
| atlassian-plugins-core/src/main/java/com/atlassian/plugin/Plugin.java | Deprecating plugin name comparator because it doesn't take into account i18n names PLUG-340 | <ide><path>tlassian-plugins-core/src/main/java/com/atlassian/plugin/Plugin.java
<ide>
<ide> public interface Plugin extends Resourced, Comparable<Plugin>
<ide> {
<add> /**
<add> * @deprecated since 2.2.0. This comparator only takes into account the plugin name and assumes it is not null,
<add> * yet a) that constraint is not validated anywhere in plugin loading and b) the plugin could have used the i18n
<add> * name, and only the application can resolve that to a name useful for comparisons.
<add> */
<ide> public static final Comparator<Plugin> NAME_COMPARATOR = new PluginNameComparator();
<ide>
<ide> /** |
|
Java | apache-2.0 | e167d1c9baff9f945acc582541937a2a82b428e5 | 0 | o19s/elasticsearch-learning-to-rank,o19s/elasticsearch-learning-to-rank | /*
* Copyright [2017] Wikimedia 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.
*/
package com.o19s.es.ltr.rest;
import com.o19s.es.ltr.action.CreateModelFromSetAction;
import com.o19s.es.ltr.action.CreateModelFromSetAction.CreateModelFromSetRequestBuilder;
import com.o19s.es.ltr.feature.FeatureValidation;
import com.o19s.es.ltr.feature.store.StoredLtrModel;
import org.elasticsearch.ExceptionsHelper;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.client.node.NodeClient;
import org.elasticsearch.xcontent.ParseField;
import org.elasticsearch.common.ParsingException;
import org.elasticsearch.xcontent.ObjectParser;
import org.elasticsearch.xcontent.XContentParser;
import org.elasticsearch.index.engine.VersionConflictEngineException;
import org.elasticsearch.rest.BytesRestResponse;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.rest.action.RestStatusToXContentListener;
import java.io.IOException;
import java.util.List;
import static java.util.Arrays.asList;
import static java.util.Collections.unmodifiableList;
public class RestCreateModelFromSet extends FeatureStoreBaseRestHandler {
@Override
public String getName() {
return "Create initial models for features";
}
@Override
public List<Route> routes() {
return unmodifiableList(asList(
new Route(RestRequest.Method.POST , "/_ltr/{store}/_featureset/{name}/_createmodel"),
new Route(RestRequest.Method.POST, "/_ltr/_featureset/{name}/_createmodel" )));
}
@Override
protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) throws IOException {
if (!request.hasContentOrSourceParam()) {
throw new IllegalArgumentException("Missing content or source param.");
}
String store = indexName(request);
Long expectedVersion = null;
if (request.hasParam("version")) {
expectedVersion = request.paramAsLong("version", -1);
if (expectedVersion <= 0) {
throw new IllegalArgumentException("version must be a strictly positive long value");
}
}
String routing = request.param("routing");
ParserState state = new ParserState();
request.withContentOrSourceParamParserOrNull((p) -> ParserState.parse(p, state));
CreateModelFromSetRequestBuilder builder = new CreateModelFromSetRequestBuilder(client);
if (expectedVersion != null) {
builder.withVersion(store, request.param("name"), expectedVersion, state.model.name, state.model.model);
} else {
builder.withoutVersion(store, request.param("name"), state.model.name, state.model.model);
}
builder.request().setValidation(state.validation);
builder.routing(routing);
return (channel) -> builder.execute(ActionListener.wrap(
response -> new RestStatusToXContentListener<CreateModelFromSetAction.CreateModelFromSetResponse>(channel,
(r) -> r.getResponse().getLocation(routing)).onResponse(response),
(e) -> {
final Exception exc;
final RestStatus status;
if (ExceptionsHelper.unwrap(e, VersionConflictEngineException.class) != null) {
exc = new IllegalArgumentException("Element of type [" + StoredLtrModel.TYPE +
"] are not updatable, please create a new one instead.");
exc.addSuppressed(e);
status = RestStatus.METHOD_NOT_ALLOWED;
} else {
exc = e;
status = ExceptionsHelper.status(exc);
}
try {
channel.sendResponse(new BytesRestResponse(channel, status, exc));
} catch (Exception inner) {
inner.addSuppressed(e);
logger.error("failed to send failure response", inner);
}
}
));
}
private static class ParserState {
private static final ObjectParser<ParserState, Void> PARSER = new ObjectParser<>("create_model_from_set", ParserState::new);
static {
PARSER.declareObject(ParserState::setModel, Model.MODEL_PARSER::apply, new ParseField("model"));
PARSER.declareObject(ParserState::setValidation, FeatureValidation.PARSER::apply, new ParseField("validation"));
}
private Model model;
private FeatureValidation validation;
public Model getModel() {
return model;
}
public void setModel(Model model) {
this.model = model;
}
public FeatureValidation getValidation() {
return validation;
}
public void setValidation(FeatureValidation validation) {
this.validation = validation;
}
public static void parse(XContentParser parser, ParserState value) throws IOException {
PARSER.parse(parser, value, null);
if (value.model == null) {
throw new ParsingException(parser.getTokenLocation(), "Missing required value [model]");
}
}
private static class Model {
private static final ObjectParser<Model, Void> MODEL_PARSER = new ObjectParser<>("model", Model::new);
static {
MODEL_PARSER.declareString(Model::setName, new ParseField("name"));
MODEL_PARSER.declareObject(Model::setModel,
StoredLtrModel.LtrModelDefinition::parse,
new ParseField("model"));
}
String name;
StoredLtrModel.LtrModelDefinition model;
public void setName(String name) {
this.name = name;
}
public void setModel(StoredLtrModel.LtrModelDefinition model) {
this.model = model;
}
public static void parse(XContentParser parser, Model value) throws IOException {
MODEL_PARSER.parse(parser, value, null);
if (value.name == null) {
throw new ParsingException(parser.getTokenLocation(), "Missing required value [name]");
}
}
}
}
}
| src/main/java/com/o19s/es/ltr/rest/RestCreateModelFromSet.java | /*
* Copyright [2017] Wikimedia 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.
*/
package com.o19s.es.ltr.rest;
import com.o19s.es.ltr.action.CreateModelFromSetAction;
import com.o19s.es.ltr.action.CreateModelFromSetAction.CreateModelFromSetRequestBuilder;
import com.o19s.es.ltr.feature.FeatureValidation;
import com.o19s.es.ltr.feature.store.StoredLtrModel;
import org.elasticsearch.ExceptionsHelper;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.client.node.NodeClient;
import org.elasticsearch.xcontent.ParseField;
import org.elasticsearch.common.ParsingException;
import org.elasticsearch.xcontent.ObjectParser;
import org.elasticsearch.xcontent.XContentParser;
import org.elasticsearch.index.engine.VersionConflictEngineException;
import org.elasticsearch.rest.BytesRestResponse;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.rest.action.RestStatusToXContentListener;
import java.io.IOException;
import java.util.List;
import static java.util.Arrays.asList;
import static java.util.Collections.unmodifiableList;
public class RestCreateModelFromSet extends FeatureStoreBaseRestHandler {
@Override
public String getName() {
return "Create initial models for features";
}
@Override
public List<Route> routes() {
return unmodifiableList(asList(
new Route(RestRequest.Method.POST , "/_ltr/{store}/_featureset/{name}/_createmodel"),
new Route(RestRequest.Method.POST, "/_ltr/_featureset/{name}/_createmodel" )));
}
@Override
protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) throws IOException {
String store = indexName(request);
Long expectedVersion = null;
if (request.hasParam("version")) {
expectedVersion = request.paramAsLong("version", -1);
if (expectedVersion <= 0) {
throw new IllegalArgumentException("version must be a strictly positive long value");
}
}
String routing = request.param("routing");
ParserState state = new ParserState();
request.withContentOrSourceParamParserOrNull((p) -> ParserState.parse(p, state));
CreateModelFromSetRequestBuilder builder = new CreateModelFromSetRequestBuilder(client);
if (expectedVersion != null) {
builder.withVersion(store, request.param("name"), expectedVersion, state.model.name, state.model.model);
} else {
builder.withoutVersion(store, request.param("name"), state.model.name, state.model.model);
}
builder.request().setValidation(state.validation);
builder.routing(routing);
return (channel) -> builder.execute(ActionListener.wrap(
response -> new RestStatusToXContentListener<CreateModelFromSetAction.CreateModelFromSetResponse>(channel,
(r) -> r.getResponse().getLocation(routing)).onResponse(response),
(e) -> {
final Exception exc;
final RestStatus status;
if (ExceptionsHelper.unwrap(e, VersionConflictEngineException.class) != null) {
exc = new IllegalArgumentException("Element of type [" + StoredLtrModel.TYPE +
"] are not updatable, please create a new one instead.");
exc.addSuppressed(e);
status = RestStatus.METHOD_NOT_ALLOWED;
} else {
exc = e;
status = ExceptionsHelper.status(exc);
}
try {
channel.sendResponse(new BytesRestResponse(channel, status, exc));
} catch (Exception inner) {
inner.addSuppressed(e);
logger.error("failed to send failure response", inner);
}
}
));
}
private static class ParserState {
private static final ObjectParser<ParserState, Void> PARSER = new ObjectParser<>("create_model_from_set", ParserState::new);
static {
PARSER.declareObject(ParserState::setModel, Model.MODEL_PARSER::apply, new ParseField("model"));
PARSER.declareObject(ParserState::setValidation, FeatureValidation.PARSER::apply, new ParseField("validation"));
}
private Model model;
private FeatureValidation validation;
public Model getModel() {
return model;
}
public void setModel(Model model) {
this.model = model;
}
public FeatureValidation getValidation() {
return validation;
}
public void setValidation(FeatureValidation validation) {
this.validation = validation;
}
public static void parse(XContentParser parser, ParserState value) throws IOException {
PARSER.parse(parser, value, null);
if (value.model == null) {
throw new ParsingException(parser.getTokenLocation(), "Missing required value [model]");
}
}
private static class Model {
private static final ObjectParser<Model, Void> MODEL_PARSER = new ObjectParser<>("model", Model::new);
static {
MODEL_PARSER.declareString(Model::setName, new ParseField("name"));
MODEL_PARSER.declareObject(Model::setModel,
StoredLtrModel.LtrModelDefinition::parse,
new ParseField("model"));
}
String name;
StoredLtrModel.LtrModelDefinition model;
public void setName(String name) {
this.name = name;
}
public void setModel(StoredLtrModel.LtrModelDefinition model) {
this.model = model;
}
public static void parse(XContentParser parser, Model value) throws IOException {
MODEL_PARSER.parse(parser, value, null);
if (value.name == null) {
throw new ParsingException(parser.getTokenLocation(), "Missing required value [name]");
}
}
}
}
}
| Do not fail _createmodel with NPE when no content is provided (#415)
relates #401 | src/main/java/com/o19s/es/ltr/rest/RestCreateModelFromSet.java | Do not fail _createmodel with NPE when no content is provided (#415) | <ide><path>rc/main/java/com/o19s/es/ltr/rest/RestCreateModelFromSet.java
<ide>
<ide> @Override
<ide> protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) throws IOException {
<add> if (!request.hasContentOrSourceParam()) {
<add> throw new IllegalArgumentException("Missing content or source param.");
<add> }
<ide> String store = indexName(request);
<ide> Long expectedVersion = null;
<ide> if (request.hasParam("version")) { |
|
JavaScript | mit | 664c19eabb3369109d6ca06f986e282f0cfb357f | 0 | nanowang/aozora-phonegap-build,project-yoru/aozora-phonegap-build,project-yoru/aozora-phonegap-build,nanowang/aozora-phonegap-build | (function() {
document.addEventListener('deviceready', (function() {
return console.log('device ready');
}), false);
}).call(this);
| scripts/main.js | disable useMin for main.js
| scripts/main.js | disable useMin for main.js | <ide><path>cripts/main.js
<add>(function() {
<add> document.addEventListener('deviceready', (function() {
<add> return console.log('device ready');
<add> }), false);
<add>
<add>}).call(this); |
||
Java | apache-2.0 | 648b21aa4f356e7a59dcc55fec722e9a519bfc64 | 0 | pacozaa/BoofCV,pacozaa/BoofCV,pacozaa/BoofCV,pacozaa/BoofCV | /*
* Copyright (c) 2011-2013, Peter Abeles. All Rights Reserved.
*
* This file is part of BoofCV (http://boofcv.org).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package boofcv.alg.sfm.d2;
import boofcv.abst.feature.detect.interest.ConfigFastHessian;
import boofcv.abst.feature.detect.interest.ConfigGeneralDetector;
import boofcv.abst.feature.tracker.PkltConfig;
import boofcv.factory.feature.tracker.FactoryPointTracker;
import boofcv.gui.image.ShowImages;
import boofcv.io.PathLabel;
import boofcv.struct.image.ImageFloat32;
import boofcv.struct.image.ImageSInt16;
import boofcv.struct.image.ImageSingleBand;
import boofcv.struct.image.ImageUInt8;
import georegression.struct.InvertibleTransform;
import georegression.struct.affine.Affine2D_F64;
import georegression.struct.homo.Homography2D_F64;
import georegression.struct.point.Point2D_F64;
import java.util.ArrayList;
import java.util.List;
/**
* Creates a mosaic from an image sequence using tracked point features. Each the input window
* moaes toward the mosaic image's boundary it is automatically reset. When reset the current
* image is put in the initial position and the mosaic distorted accordingly.
*
* @author Peter Abeles
* @param <I> Input image type
* @param <D> Image derivative type
*/
// TODO add support for color again
// TODO comment and clean up code
public class VideoMosaicSequentialPointApp<I extends ImageSingleBand, D extends ImageSingleBand,
IT extends InvertibleTransform>
extends VideoStitchBaseApp<I,IT>
{
private static int maxFeatures = 250;
public VideoMosaicSequentialPointApp(Class<I> imageType, Class<D> derivType) {
super(2,imageType,new Mosaic2DPanel());
PkltConfig<I, D> config =
PkltConfig.createDefault(imageType, derivType);
config.featureRadius = 3;
config.pyramidScaling = new int[]{1,2,4,8};
ConfigFastHessian configFH = new ConfigFastHessian();
configFH.initialSampleSize = 2;
configFH.maxFeaturesPerScale = 200;
addAlgorithm(0, "KLT", FactoryPointTracker.klt(config, new ConfigGeneralDetector(maxFeatures, 3, 1)));
addAlgorithm(0, "ST-BRIEF", FactoryPointTracker.
dda_ST_BRIEF(150, new ConfigGeneralDetector(400, 1, 10), imageType, null));
// size of the description region has been increased to improve quality.
addAlgorithm(0, "ST-NCC", FactoryPointTracker.
dda_ST_NCC(new ConfigGeneralDetector(500, 3, 9), 10, imageType, derivType));
addAlgorithm(0, "FH-SURF", FactoryPointTracker.dda_FH_SURF_Fast(configFH, null, null, imageType));
addAlgorithm(0, "ST-SURF-KLT", FactoryPointTracker.
combined_ST_SURF_KLT(new ConfigGeneralDetector(400, 3, 1), 3,
config.pyramidScaling, 75, null, null, imageType, derivType));
addAlgorithm(0, "FH-SURF-KLT", FactoryPointTracker.combined_FH_SURF_KLT(3,
config.pyramidScaling, 75, configFH, null, null, imageType));
addAlgorithm(1,"Affine", new Affine2D_F64());
addAlgorithm(1,"Homography", new Homography2D_F64());
absoluteMinimumTracks = 40;
respawnTrackFraction = 0.3;
respawnCoverageFraction = 0.8;
maxJumpFraction = 0.3;
}
private Affine2D_F64 createInitialTransform() {
float scale = 0.8f;
Affine2D_F64 H = new Affine2D_F64(scale,0,0,scale, stitchWidth /4, stitchHeight /4);
return H.invert(null);
}
@Override
protected void init(int inputWidth, int inputHeight) {
setStitchImageSize(1000, 600);
((Mosaic2DPanel)gui).setMosaicSize(stitchWidth, stitchHeight);
alg.configure(stitchWidth, stitchHeight,createInitialTransform());
}
@Override
protected boolean checkLocation(StitchingFromMotion2D.Corners corners) {
if( closeToBorder(corners.p0) )
return true;
if( closeToBorder(corners.p1) )
return true;
if( closeToBorder(corners.p2) )
return true;
if( closeToBorder(corners.p3) )
return true;
return false;
}
private boolean closeToBorder( Point2D_F64 pt ) {
if( pt.x < borderTolerance || pt.y < borderTolerance)
return true;
return( pt.x >= stitchWidth - borderTolerance || pt.y >= stitchHeight - borderTolerance);
}
public static void main( String args[] ) {
// Class type = ImageFloat32.class;
// Class derivType = type;
Class type = ImageUInt8.class;
Class derivType = ImageSInt16.class;
VideoMosaicSequentialPointApp app = new VideoMosaicSequentialPointApp(type,derivType);
List<PathLabel> inputs = new ArrayList<PathLabel>();
inputs.add(new PathLabel("Plane 1", "../data/applet/mosaic/airplane01.mjpeg"));
inputs.add(new PathLabel("Plane 2", "../data/applet/mosaic/airplane02.mjpeg"));
inputs.add(new PathLabel("Shake", "../data/applet/shake.mjpeg"));
app.setInputList(inputs);
// wait for it to process one image so that the size isn't all screwed up
while( !app.getHasProcessedImage() ) {
Thread.yield();
}
ShowImages.showWindow(app, "Video Image Mosaic");
}
}
| evaluation/visualization/src/boofcv/alg/sfm/d2/VideoMosaicSequentialPointApp.java | /*
* Copyright (c) 2011-2013, Peter Abeles. All Rights Reserved.
*
* This file is part of BoofCV (http://boofcv.org).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package boofcv.alg.sfm.d2;
import boofcv.abst.feature.detect.interest.ConfigFastHessian;
import boofcv.abst.feature.detect.interest.ConfigGeneralDetector;
import boofcv.abst.feature.tracker.PkltConfig;
import boofcv.factory.feature.tracker.FactoryPointTracker;
import boofcv.gui.image.ShowImages;
import boofcv.io.PathLabel;
import boofcv.struct.image.ImageFloat32;
import boofcv.struct.image.ImageSingleBand;
import georegression.struct.InvertibleTransform;
import georegression.struct.affine.Affine2D_F64;
import georegression.struct.homo.Homography2D_F64;
import georegression.struct.point.Point2D_F64;
import java.util.ArrayList;
import java.util.List;
/**
* Creates a mosaic from an image sequence using tracked point features. Each the input window
* moaes toward the mosaic image's boundary it is automatically reset. When reset the current
* image is put in the initial position and the mosaic distorted accordingly.
*
* @author Peter Abeles
* @param <I> Input image type
* @param <D> Image derivative type
*/
// TODO add support for color again
// TODO comment and clean up code
public class VideoMosaicSequentialPointApp<I extends ImageSingleBand, D extends ImageSingleBand,
IT extends InvertibleTransform>
extends VideoStitchBaseApp<I,IT>
{
private static int maxFeatures = 250;
public VideoMosaicSequentialPointApp(Class<I> imageType, Class<D> derivType) {
super(2,imageType,new Mosaic2DPanel());
PkltConfig<I, D> config =
PkltConfig.createDefault(imageType, derivType);
config.featureRadius = 3;
config.pyramidScaling = new int[]{1,2,4,8};
ConfigFastHessian configFH = new ConfigFastHessian();
configFH.initialSampleSize = 2;
configFH.maxFeaturesPerScale = 200;
addAlgorithm(0, "KLT", FactoryPointTracker.klt(config, new ConfigGeneralDetector(maxFeatures, 3, 1)));
addAlgorithm(0, "ST-BRIEF", FactoryPointTracker.
dda_ST_BRIEF(150, new ConfigGeneralDetector(400, 1, 10), imageType, null));
// size of the description region has been increased to improve quality.
addAlgorithm(0, "ST-NCC", FactoryPointTracker.
dda_ST_NCC(new ConfigGeneralDetector(500, 3, 9), 10, imageType, derivType));
addAlgorithm(0, "FH-SURF", FactoryPointTracker.dda_FH_SURF_Fast(configFH, null, null, imageType));
addAlgorithm(0, "ST-SURF-KLT", FactoryPointTracker.
combined_ST_SURF_KLT(new ConfigGeneralDetector(400, 3, 1), 3,
config.pyramidScaling, 75, null, null, imageType, derivType));
addAlgorithm(0, "FH-SURF-KLT", FactoryPointTracker.combined_FH_SURF_KLT(3,
config.pyramidScaling, 75, configFH, null, null, imageType));
addAlgorithm(1,"Affine", new Affine2D_F64());
addAlgorithm(1,"Homography", new Homography2D_F64());
absoluteMinimumTracks = 40;
respawnTrackFraction = 0.3;
respawnCoverageFraction = 0.8;
maxJumpFraction = 0.3;
}
private Affine2D_F64 createInitialTransform() {
float scale = 0.8f;
Affine2D_F64 H = new Affine2D_F64(scale,0,0,scale, stitchWidth /4, stitchHeight /4);
return H.invert(null);
}
@Override
protected void init(int inputWidth, int inputHeight) {
setStitchImageSize(1000, 600);
((Mosaic2DPanel)gui).setMosaicSize(stitchWidth, stitchHeight);
alg.configure(stitchWidth, stitchHeight,createInitialTransform());
}
@Override
protected boolean checkLocation(StitchingFromMotion2D.Corners corners) {
if( closeToBorder(corners.p0) )
return true;
if( closeToBorder(corners.p1) )
return true;
if( closeToBorder(corners.p2) )
return true;
if( closeToBorder(corners.p3) )
return true;
return false;
}
private boolean closeToBorder( Point2D_F64 pt ) {
if( pt.x < borderTolerance || pt.y < borderTolerance)
return true;
return( pt.x >= stitchWidth - borderTolerance || pt.y >= stitchHeight - borderTolerance);
}
public static void main( String args[] ) {
Class type = ImageFloat32.class;
Class derivType = type;
// Class type = ImageUInt8.class;
// Class derivType = ImageSInt16.class;
VideoMosaicSequentialPointApp app = new VideoMosaicSequentialPointApp(type,derivType);
List<PathLabel> inputs = new ArrayList<PathLabel>();
inputs.add(new PathLabel("Plane 1", "../data/applet/mosaic/airplane01.mjpeg"));
inputs.add(new PathLabel("Plane 2", "../data/applet/mosaic/airplane02.mjpeg"));
inputs.add(new PathLabel("Shake", "../data/applet/shake.mjpeg"));
app.setInputList(inputs);
// wait for it to process one image so that the size isn't all screwed up
while( !app.getHasProcessedImage() ) {
Thread.yield();
}
ShowImages.showWindow(app, "Video Image Mosaic");
}
}
| Updated for previous changes
| evaluation/visualization/src/boofcv/alg/sfm/d2/VideoMosaicSequentialPointApp.java | Updated for previous changes | <ide><path>valuation/visualization/src/boofcv/alg/sfm/d2/VideoMosaicSequentialPointApp.java
<ide> import boofcv.gui.image.ShowImages;
<ide> import boofcv.io.PathLabel;
<ide> import boofcv.struct.image.ImageFloat32;
<add>import boofcv.struct.image.ImageSInt16;
<ide> import boofcv.struct.image.ImageSingleBand;
<add>import boofcv.struct.image.ImageUInt8;
<ide> import georegression.struct.InvertibleTransform;
<ide> import georegression.struct.affine.Affine2D_F64;
<ide> import georegression.struct.homo.Homography2D_F64;
<ide> }
<ide>
<ide> public static void main( String args[] ) {
<del> Class type = ImageFloat32.class;
<del> Class derivType = type;
<add>// Class type = ImageFloat32.class;
<add>// Class derivType = type;
<ide>
<del>// Class type = ImageUInt8.class;
<del>// Class derivType = ImageSInt16.class;
<add> Class type = ImageUInt8.class;
<add> Class derivType = ImageSInt16.class;
<ide>
<ide> VideoMosaicSequentialPointApp app = new VideoMosaicSequentialPointApp(type,derivType);
<ide> |
|
Java | apache-2.0 | 22c2e479a28a8303fb4ca7499c9aa448c06c2f1e | 0 | alex-bl/ivyDEextension,apache/ant-ivyde,alex-bl/ivyDEextension,apache/ant-ivyde | /*
* 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.ivyde.eclipse.workspaceresolver;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.ivy.Ivy;
import org.apache.ivy.core.module.descriptor.Artifact;
import org.apache.ivy.core.module.descriptor.Configuration;
import org.apache.ivy.core.module.descriptor.DefaultArtifact;
import org.apache.ivy.core.module.descriptor.DefaultModuleDescriptor;
import org.apache.ivy.core.module.descriptor.DependencyDescriptor;
import org.apache.ivy.core.module.descriptor.ExcludeRule;
import org.apache.ivy.core.module.descriptor.License;
import org.apache.ivy.core.module.descriptor.ModuleDescriptor;
import org.apache.ivy.core.module.id.ModuleRevisionId;
import org.apache.ivy.core.report.ArtifactDownloadReport;
import org.apache.ivy.core.report.DownloadReport;
import org.apache.ivy.core.report.DownloadStatus;
import org.apache.ivy.core.report.MetadataArtifactDownloadReport;
import org.apache.ivy.core.resolve.DownloadOptions;
import org.apache.ivy.core.resolve.ResolveData;
import org.apache.ivy.core.resolve.ResolvedModuleRevision;
import org.apache.ivy.core.settings.IvySettings;
import org.apache.ivy.plugins.resolver.AbstractResolver;
import org.apache.ivy.plugins.resolver.util.ResolvedResource;
import org.apache.ivy.plugins.version.VersionMatcher;
import org.apache.ivy.util.Message;
import org.apache.ivyde.eclipse.IvyDEException;
import org.apache.ivyde.eclipse.IvyPlugin;
import org.apache.ivyde.eclipse.cpcontainer.IvyClasspathContainer;
import org.apache.ivyde.eclipse.cpcontainer.IvyClasspathUtil;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
/**
* This is an Eclipse workspace Ivy resolver. When used with the custom IvyClasspathContainer
* changes, this resolver will link dependent projects when they are open in the same workspace,
* allowing full-fledged linked project functionality Eclipse provides, such as incremental
* compilation, debugging, mouseover javadocs, and source browsing across projects.
*
* <b>How it works</b> During a resolve, it looks at all open projects in the workspace that have
* Ivy containers. The <b>first</b> project that publishes the module on which the project being
* resolved depends, will be picked and returned as a special type of artifact called "project".
*
* The IvyClasspathContainer will recognize the artifact as a project and put the eclipse project as
* a dependent project within the classpath container of the parent.
*
* If you do not want a project to be linked as a dependency, close it or delete from the workspace.
* As soon as you do that, any projects that were linked to it will automatically re-resolve (see
* {@link WorkspaceResourceChangeListener}) and use the standard Ivy means of finding the
* dependency.
*
* The {@link WorkspaceResourceChangeListener} will also auto-resolve when a new project is added or
* opened, so opening a project will automatically link it into the currently open projects where
* necessary.
*
* Since the resolver is not aware which module revision a project is publishing, it optimistically
* matches any revision of the module.
*
* Since the resolver stops after finding the first open project which matches the module, having
* multiple open versions of the same project in the workspace (for example, different branches) may
* set the wrong version as a dependency. You are advised to only open the version of the project
* which you want other projects in the workspace to depend on.
*
* NOTE: Transitive dependencies are not passed from the dependent project to the parent when
* projects are linked. If you find you are missing some transitive dependencies, just set your
* dependent eclipse project to export its ivy dependencies. (Project->Properties->Java Build
* Path->Order and Export-> -> check the ivy container) This will only export the configuration that
* project is using and not what a dependent project may ask for when it's being resolved. To do
* that, this resolver will need to be modified to pass transitive dependencies along.
*/
public class WorkspaceResolver extends AbstractResolver {
public static final String ECLIPSE_PROJECT_TYPE = "eclipse-project";
public static final String ECLIPSE_PROJECT_EXTENSION = "eclipse-project";
public static final String CACHE_NAME = "__ivyde-workspace-resolver-cache";
private final IJavaProject resolvingJavaProject;
private IJavaProject[] projects;
public WorkspaceResolver(IJavaProject javaProject, IvySettings ivySettings) {
this.resolvingJavaProject = javaProject;
setName(javaProject.getElementName() + "-ivyde-workspace-resolver");
setSettings(ivySettings);
setCache(CACHE_NAME);
try {
projects = JavaCore.create(ResourcesPlugin.getWorkspace().getRoot()).getJavaProjects();
} catch (JavaModelException e) {
IvyPlugin.log(IStatus.ERROR, "JDT Error while resolving in workspace for "
+ resolvingJavaProject.getElementName(), e);
}
}
public DownloadReport download(Artifact[] artifacts, DownloadOptions options) {
// Not much to do here - downloads are not required for workspace projects.
DownloadReport dr = new DownloadReport();
for (int i = 0; i < artifacts.length; i++) {
final ArtifactDownloadReport adr = new ArtifactDownloadReport(artifacts[i]);
dr.addArtifactReport(adr);
// Only report java projects as downloaded
if (artifacts[i].getType().equals(ECLIPSE_PROJECT_TYPE)) {
Message.verbose("\t[IN WORKSPACE] " + artifacts[i]);
adr.setDownloadStatus(DownloadStatus.NO);
adr.setSize(0);
} else {
Message.verbose("\t[Eclipse Workspace resolver] "
+ "cannot download non-project artifact: " + artifacts[i]);
adr.setDownloadStatus(DownloadStatus.FAILED);
}
}
return dr;
}
public ResolvedModuleRevision getDependency(DependencyDescriptor dd, ResolveData data)
throws ParseException {
ModuleRevisionId dependencyMrid = dd.getDependencyRevisionId();
VersionMatcher versionMatcher = getSettings().getVersionMatcher();
// Iterate over workspace to find Java project which has an Ivy
// container for this dependency
for (int i = 0; i < projects.length; i++) {
IJavaProject javaProject = projects[i];
if (resolvingJavaProject.equals(javaProject)) {
// we don't want to introduce self dependency
continue;
}
if (!javaProject.exists()) {
continue;
}
List/* <IvyClasspathContainer> */containers = IvyClasspathUtil
.getIvyClasspathContainers(javaProject);
Iterator/* <IvyClasspathContainer> */itContainer = containers.iterator();
while (itContainer.hasNext()) {
IvyClasspathContainer ivycp = (IvyClasspathContainer) itContainer.next();
ModuleDescriptor md;
try {
md = ivycp.getConf().getCachedModuleDescriptor();
} catch (IvyDEException e) {
IvyPlugin.log(IStatus.WARNING, "Resolve in workspace for '"
+ resolvingJavaProject.getElementName() + "' cannot depend on "
+ ivycp.getDescription() + " [" + e.getMessage() + "]", null);
continue;
}
if (!md.getModuleRevisionId().getModuleId().equals(dependencyMrid.getModuleId())) {
// it doesn't match org#module
continue;
}
// Found one; check if it is for the module we need
if (md.getModuleRevisionId().getRevision().equals(Ivy.getWorkingRevision())
|| versionMatcher.accept(dd.getDependencyRevisionId(), md)) {
Artifact af = new DefaultArtifact(md.getModuleRevisionId(), md
.getPublicationDate(), javaProject.getPath().toString(),
ECLIPSE_PROJECT_TYPE, ECLIPSE_PROJECT_EXTENSION);
DefaultModuleDescriptor workspaceMd = cloneMd(md, af);
MetadataArtifactDownloadReport madr = new MetadataArtifactDownloadReport(af);
madr.setDownloadStatus(DownloadStatus.SUCCESSFUL);
madr.setSearched(true);
return new ResolvedModuleRevision(this, this, workspaceMd, madr);
}
}
}
// Didn't find module in any open project, proceed to other resolvers.
return null;
}
private DefaultModuleDescriptor cloneMd(ModuleDescriptor md, Artifact af) {
DefaultModuleDescriptor newMd = new DefaultModuleDescriptor(md.getModuleRevisionId(),
"release", null, true);
newMd.addConfiguration(new Configuration(ModuleDescriptor.DEFAULT_CONFIGURATION));
newMd.setLastModified(System.currentTimeMillis());
newMd.setDescription(md.getDescription());
newMd.setHomePage(md.getHomePage());
newMd.setLastModified(md.getLastModified());
newMd.setPublicationDate(md.getPublicationDate());
newMd.setResolvedPublicationDate(md.getResolvedPublicationDate());
newMd.setStatus(md.getStatus());
Configuration[] allConfs = md.getConfigurations();
if (allConfs.length == 0) {
newMd.addArtifact(ModuleDescriptor.DEFAULT_CONFIGURATION, af);
} else {
for (int k = 0; k < allConfs.length; k++) {
newMd.addConfiguration(allConfs[k]);
newMd.addArtifact(allConfs[k].getName(), af);
}
}
DependencyDescriptor[] dependencies = md.getDependencies();
for (int k = 0; k < dependencies.length; k++) {
newMd.addDependency(dependencies[k]);
}
ExcludeRule[] allExcludeRules = md.getAllExcludeRules();
for (int k = 0; k < allExcludeRules.length; k++) {
newMd.addExcludeRule(allExcludeRules[k]);
}
Map extraInfo = md.getExtraInfo();
Iterator it = extraInfo.entrySet().iterator();
while (it.hasNext()) {
Entry entry = (Entry) it.next();
newMd.addExtraInfo((String) entry.getKey(), (String) entry.getValue());
}
License[] licenses = md.getLicenses();
for (int k = 0; k < licenses.length; k++) {
newMd.addLicense(licenses[k]);
}
return newMd;
}
public void publish(Artifact artifact, File src, boolean overwrite) throws IOException {
throw new UnsupportedOperationException("publish not supported by " + getName());
}
public ResolvedResource findIvyFileRef(DependencyDescriptor dd, ResolveData data) {
return null;
}
}
| org.apache.ivyde.eclipse/src/java/org/apache/ivyde/eclipse/workspaceresolver/WorkspaceResolver.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.ivyde.eclipse.workspaceresolver;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.ivy.core.module.descriptor.Artifact;
import org.apache.ivy.core.module.descriptor.Configuration;
import org.apache.ivy.core.module.descriptor.DefaultArtifact;
import org.apache.ivy.core.module.descriptor.DefaultModuleDescriptor;
import org.apache.ivy.core.module.descriptor.DependencyDescriptor;
import org.apache.ivy.core.module.descriptor.ExcludeRule;
import org.apache.ivy.core.module.descriptor.License;
import org.apache.ivy.core.module.descriptor.ModuleDescriptor;
import org.apache.ivy.core.module.id.ModuleRevisionId;
import org.apache.ivy.core.report.ArtifactDownloadReport;
import org.apache.ivy.core.report.DownloadReport;
import org.apache.ivy.core.report.DownloadStatus;
import org.apache.ivy.core.report.MetadataArtifactDownloadReport;
import org.apache.ivy.core.resolve.DownloadOptions;
import org.apache.ivy.core.resolve.ResolveData;
import org.apache.ivy.core.resolve.ResolvedModuleRevision;
import org.apache.ivy.core.settings.IvySettings;
import org.apache.ivy.plugins.resolver.AbstractResolver;
import org.apache.ivy.plugins.resolver.util.ResolvedResource;
import org.apache.ivy.plugins.version.VersionMatcher;
import org.apache.ivy.util.Message;
import org.apache.ivyde.eclipse.IvyDEException;
import org.apache.ivyde.eclipse.IvyPlugin;
import org.apache.ivyde.eclipse.cpcontainer.IvyClasspathContainer;
import org.apache.ivyde.eclipse.cpcontainer.IvyClasspathUtil;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
/**
* This is an Eclipse workspace Ivy resolver. When used with the custom IvyClasspathContainer
* changes, this resolver will link dependent projects when they are open in the same workspace,
* allowing full-fledged linked project functionality Eclipse provides, such as incremental
* compilation, debugging, mouseover javadocs, and source browsing across projects.
*
* <b>How it works</b> During a resolve, it looks at all open projects in the workspace that have
* Ivy containers. The <b>first</b> project that publishes the module on which the project being
* resolved depends, will be picked and returned as a special type of artifact called "project".
*
* The IvyClasspathContainer will recognize the artifact as a project and put the eclipse project as
* a dependent project within the classpath container of the parent.
*
* If you do not want a project to be linked as a dependency, close it or delete from the workspace.
* As soon as you do that, any projects that were linked to it will automatically re-resolve (see
* {@link WorkspaceResourceChangeListener}) and use the standard Ivy means of finding the
* dependency.
*
* The {@link WorkspaceResourceChangeListener} will also auto-resolve when a new project is added or
* opened, so opening a project will automatically link it into the currently open projects where
* necessary.
*
* Since the resolver is not aware which module revision a project is publishing, it optimistically
* matches any revision of the module.
*
* Since the resolver stops after finding the first open project which matches the module, having
* multiple open versions of the same project in the workspace (for example, different branches) may
* set the wrong version as a dependency. You are advised to only open the version of the project
* which you want other projects in the workspace to depend on.
*
* NOTE: Transitive dependencies are not passed from the dependent project to the parent when
* projects are linked. If you find you are missing some transitive dependencies, just set your
* dependent eclipse project to export its ivy dependencies. (Project->Properties->Java Build
* Path->Order and Export-> -> check the ivy container) This will only export the configuration that
* project is using and not what a dependent project may ask for when it's being resolved. To do
* that, this resolver will need to be modified to pass transitive dependencies along.
*/
public class WorkspaceResolver extends AbstractResolver {
public static final String ECLIPSE_PROJECT_TYPE = "eclipse-project";
public static final String ECLIPSE_PROJECT_EXTENSION = "eclipse-project";
public static final String CACHE_NAME = "__ivyde-workspace-resolver-cache";
private final IJavaProject resolvingJavaProject;
private IJavaProject[] projects;
public WorkspaceResolver(IJavaProject javaProject, IvySettings ivySettings) {
this.resolvingJavaProject = javaProject;
setName(javaProject.getElementName() + "-ivyde-workspace-resolver");
setSettings(ivySettings);
setCache(CACHE_NAME);
try {
projects = JavaCore.create(ResourcesPlugin.getWorkspace().getRoot()).getJavaProjects();
} catch (JavaModelException e) {
IvyPlugin.log(IStatus.ERROR, "JDT Error while resolving in workspace for "
+ resolvingJavaProject.getElementName(), e);
}
}
public DownloadReport download(Artifact[] artifacts, DownloadOptions options) {
// Not much to do here - downloads are not required for workspace projects.
DownloadReport dr = new DownloadReport();
for (int i = 0; i < artifacts.length; i++) {
final ArtifactDownloadReport adr = new ArtifactDownloadReport(artifacts[i]);
dr.addArtifactReport(adr);
// Only report java projects as downloaded
if (artifacts[i].getType().equals(ECLIPSE_PROJECT_TYPE)) {
Message.verbose("\t[IN WORKSPACE] " + artifacts[i]);
adr.setDownloadStatus(DownloadStatus.NO);
adr.setSize(0);
} else {
Message.verbose("\t[Eclipse Workspace resolver] "
+ "cannot download non-project artifact: " + artifacts[i]);
adr.setDownloadStatus(DownloadStatus.FAILED);
}
}
return dr;
}
public ResolvedModuleRevision getDependency(DependencyDescriptor dd, ResolveData data)
throws ParseException {
ModuleRevisionId dependencyMrid = dd.getDependencyRevisionId();
VersionMatcher versionMatcher = getSettings().getVersionMatcher();
// Iterate over workspace to find Java project which has an Ivy
// container for this dependency
for (int i = 0; i < projects.length; i++) {
IJavaProject javaProject = projects[i];
if (resolvingJavaProject.equals(javaProject)) {
// we don't want to introduce self dependency
continue;
}
if (!javaProject.exists()) {
continue;
}
List/* <IvyClasspathContainer> */containers = IvyClasspathUtil
.getIvyClasspathContainers(javaProject);
Iterator/* <IvyClasspathContainer> */itContainer = containers.iterator();
while (itContainer.hasNext()) {
IvyClasspathContainer ivycp = (IvyClasspathContainer) itContainer.next();
ModuleDescriptor md;
try {
md = ivycp.getConf().getCachedModuleDescriptor();
} catch (IvyDEException e) {
IvyPlugin.log(IStatus.WARNING, "Resolve in workspace for '"
+ resolvingJavaProject.getElementName() + "' cannot depend on "
+ ivycp.getDescription() + " [" + e.getMessage() + "]", null);
continue;
}
if (!md.getModuleRevisionId().getModuleId().equals(dependencyMrid.getModuleId())) {
// it doesn't match org#module
continue;
}
// Found one; check if it is for the module we need
if (md.getModuleRevisionId().getRevision().startsWith("working@")
|| versionMatcher.accept(dd.getDependencyRevisionId(), md)) {
Artifact af = new DefaultArtifact(md.getModuleRevisionId(), md
.getPublicationDate(), javaProject.getPath().toString(),
ECLIPSE_PROJECT_TYPE, ECLIPSE_PROJECT_EXTENSION);
DefaultModuleDescriptor workspaceMd = cloneMd(md, af);
MetadataArtifactDownloadReport madr = new MetadataArtifactDownloadReport(af);
madr.setDownloadStatus(DownloadStatus.SUCCESSFUL);
madr.setSearched(true);
return new ResolvedModuleRevision(this, this, workspaceMd, madr);
}
}
}
// Didn't find module in any open project, proceed to other resolvers.
return null;
}
private DefaultModuleDescriptor cloneMd(ModuleDescriptor md, Artifact af) {
DefaultModuleDescriptor newMd = new DefaultModuleDescriptor(md.getModuleRevisionId(),
"release", null, true);
newMd.addConfiguration(new Configuration(ModuleDescriptor.DEFAULT_CONFIGURATION));
newMd.setLastModified(System.currentTimeMillis());
newMd.setDescription(md.getDescription());
newMd.setHomePage(md.getHomePage());
newMd.setLastModified(md.getLastModified());
newMd.setPublicationDate(md.getPublicationDate());
newMd.setResolvedPublicationDate(md.getResolvedPublicationDate());
newMd.setStatus(md.getStatus());
Configuration[] allConfs = md.getConfigurations();
if (allConfs.length == 0) {
newMd.addArtifact(ModuleDescriptor.DEFAULT_CONFIGURATION, af);
} else {
for (int k = 0; k < allConfs.length; k++) {
newMd.addConfiguration(allConfs[k]);
newMd.addArtifact(allConfs[k].getName(), af);
}
}
DependencyDescriptor[] dependencies = md.getDependencies();
for (int k = 0; k < dependencies.length; k++) {
newMd.addDependency(dependencies[k]);
}
ExcludeRule[] allExcludeRules = md.getAllExcludeRules();
for (int k = 0; k < allExcludeRules.length; k++) {
newMd.addExcludeRule(allExcludeRules[k]);
}
Map extraInfo = md.getExtraInfo();
Iterator it = extraInfo.entrySet().iterator();
while (it.hasNext()) {
Entry entry = (Entry) it.next();
newMd.addExtraInfo((String) entry.getKey(), (String) entry.getValue());
}
License[] licenses = md.getLicenses();
for (int k = 0; k < licenses.length; k++) {
newMd.addLicense(licenses[k]);
}
return newMd;
}
public void publish(Artifact artifact, File src, boolean overwrite) throws IOException {
throw new UnsupportedOperationException("publish not supported by " + getName());
}
public ResolvedResource findIvyFileRef(DependencyDescriptor dd, ResolveData data) {
return null;
}
}
| more precise fix for IVYDE-186
git-svn-id: 804c0f3032317a396a1b8894d1ed8cc0b56e9f1c@814307 13f79535-47bb-0310-9956-ffa450edef68
| org.apache.ivyde.eclipse/src/java/org/apache/ivyde/eclipse/workspaceresolver/WorkspaceResolver.java | more precise fix for IVYDE-186 | <ide><path>rg.apache.ivyde.eclipse/src/java/org/apache/ivyde/eclipse/workspaceresolver/WorkspaceResolver.java
<ide> import java.util.Map;
<ide> import java.util.Map.Entry;
<ide>
<add>import org.apache.ivy.Ivy;
<ide> import org.apache.ivy.core.module.descriptor.Artifact;
<ide> import org.apache.ivy.core.module.descriptor.Configuration;
<ide> import org.apache.ivy.core.module.descriptor.DefaultArtifact;
<ide> }
<ide>
<ide> // Found one; check if it is for the module we need
<del> if (md.getModuleRevisionId().getRevision().startsWith("working@")
<add> if (md.getModuleRevisionId().getRevision().equals(Ivy.getWorkingRevision())
<ide> || versionMatcher.accept(dd.getDependencyRevisionId(), md)) {
<ide>
<ide> Artifact af = new DefaultArtifact(md.getModuleRevisionId(), md |
|
Java | apache-2.0 | 52eb713ee4562d50eb3a60ffb2b1688ececf5dfa | 0 | trask/glowroot,glowroot/glowroot,glowroot/glowroot,trask/glowroot,trask/glowroot,glowroot/glowroot,glowroot/glowroot,trask/glowroot | /*
* Copyright 2015-2018 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.glowroot.agent.plugin.cassandra;
import org.glowroot.agent.plugin.api.QueryEntry;
import org.glowroot.agent.plugin.api.checker.Nullable;
import org.glowroot.agent.plugin.api.weaving.BindReceiver;
import org.glowroot.agent.plugin.api.weaving.BindReturn;
import org.glowroot.agent.plugin.api.weaving.Mixin;
import org.glowroot.agent.plugin.api.weaving.OnReturn;
import org.glowroot.agent.plugin.api.weaving.Pointcut;
public class ResultSetAspect {
// the field and method names are verbose since they will be mixed in to existing classes
@Mixin("com.datastax.driver.core.ResultSet")
public static class ResultSetImpl implements ResultSet {
// this may be async or non-async query entry
//
// needs to be volatile, since ResultSets are thread safe, and therefore app/framework does
// *not* need to provide visibility when used across threads and so this cannot piggyback
// (unlike with jdbc ResultSets)
private volatile @Nullable QueryEntry glowroot$queryEntry;
@Override
public @Nullable QueryEntry glowroot$getQueryEntry() {
return glowroot$queryEntry;
}
@Override
public void glowroot$setQueryEntry(@Nullable QueryEntry queryEntry) {
glowroot$queryEntry = queryEntry;
}
}
// the method names are verbose since they will be mixed in to existing classes
public interface ResultSet {
@Nullable
QueryEntry glowroot$getQueryEntry();
void glowroot$setQueryEntry(@Nullable QueryEntry queryEntry);
}
@Pointcut(className = "com.datastax.driver.core.ResultSet", methodName = "one",
methodParameterTypes = {})
public static class OneAdvice {
@OnReturn
public static void onReturn(@BindReturn @Nullable Object row,
@BindReceiver ResultSet resultSet) {
QueryEntry queryEntry = resultSet.glowroot$getQueryEntry();
if (queryEntry == null) {
return;
}
if (row != null) {
queryEntry.incrementCurrRow();
} else {
queryEntry.rowNavigationAttempted();
}
}
}
@Pointcut(className = "java.lang.Iterable",
subTypeRestriction = "com.datastax.driver.core.ResultSet",
methodName = "iterator", methodParameterTypes = {})
public static class IteratorAdvice {
@OnReturn
public static void onReturn(@BindReceiver ResultSet resultSet) {
QueryEntry queryEntry = resultSet.glowroot$getQueryEntry();
if (queryEntry == null) {
// tracing must be disabled (e.g. exceeded trace entry limit)
return;
}
queryEntry.rowNavigationAttempted();
}
}
@Pointcut(className = "com.datastax.driver.core.PagingIterable"
+ "|com.datastax.driver.core.ResultSet",
subTypeRestriction = "com.datastax.driver.core.ResultSet",
methodName = "isExhausted", methodParameterTypes = {})
public static class IsExhaustedAdvice {
@OnReturn
public static void onReturn(@BindReceiver ResultSet resultSet) {
QueryEntry queryEntry = resultSet.glowroot$getQueryEntry();
if (queryEntry == null) {
// tracing must be disabled (e.g. exceeded trace entry limit)
return;
}
queryEntry.rowNavigationAttempted();
}
}
}
| agent/plugins/cassandra-plugin/src/main/java/org/glowroot/agent/plugin/cassandra/ResultSetAspect.java | /*
* Copyright 2015-2018 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.glowroot.agent.plugin.cassandra;
import org.glowroot.agent.plugin.api.QueryEntry;
import org.glowroot.agent.plugin.api.checker.Nullable;
import org.glowroot.agent.plugin.api.weaving.BindReceiver;
import org.glowroot.agent.plugin.api.weaving.BindReturn;
import org.glowroot.agent.plugin.api.weaving.Mixin;
import org.glowroot.agent.plugin.api.weaving.OnReturn;
import org.glowroot.agent.plugin.api.weaving.Pointcut;
public class ResultSetAspect {
// the field and method names are verbose since they will be mixed in to existing classes
@Mixin("com.datastax.driver.core.ResultSet")
public static class ResultSetImpl implements ResultSet {
// this may be async or non-async query entry
//
// needs to be volatile, since ResultSets are thread safe, and therefore app/framework does
// *not* need to provide visibility when used across threads and so this cannot piggyback
// (unlike with jdbc ResultSets)
private volatile @Nullable QueryEntry glowroot$queryEntry;
@Override
public @Nullable QueryEntry glowroot$getQueryEntry() {
return glowroot$queryEntry;
}
@Override
public void glowroot$setQueryEntry(@Nullable QueryEntry queryEntry) {
glowroot$queryEntry = queryEntry;
}
@Override
public boolean glowroot$hasQueryEntry() {
return glowroot$queryEntry != null;
}
}
// the method names are verbose since they will be mixed in to existing classes
public interface ResultSet {
@Nullable
QueryEntry glowroot$getQueryEntry();
void glowroot$setQueryEntry(@Nullable QueryEntry queryEntry);
boolean glowroot$hasQueryEntry();
}
@Pointcut(className = "com.datastax.driver.core.ResultSet", methodName = "one",
methodParameterTypes = {})
public static class OneAdvice {
@OnReturn
public static void onReturn(@BindReturn @Nullable Object row,
@BindReceiver ResultSet resultSet) {
QueryEntry queryEntry = resultSet.glowroot$getQueryEntry();
if (queryEntry == null) {
return;
}
if (row != null) {
queryEntry.incrementCurrRow();
} else {
queryEntry.rowNavigationAttempted();
}
}
}
@Pointcut(className = "java.lang.Iterable",
subTypeRestriction = "com.datastax.driver.core.ResultSet",
methodName = "iterator", methodParameterTypes = {})
public static class IteratorAdvice {
@OnReturn
public static void onReturn(@BindReceiver ResultSet resultSet) {
QueryEntry queryEntry = resultSet.glowroot$getQueryEntry();
if (queryEntry == null) {
// tracing must be disabled (e.g. exceeded trace entry limit)
return;
}
queryEntry.rowNavigationAttempted();
}
}
@Pointcut(className = "com.datastax.driver.core.PagingIterable"
+ "|com.datastax.driver.core.ResultSet",
subTypeRestriction = "com.datastax.driver.core.ResultSet",
methodName = "isExhausted", methodParameterTypes = {})
public static class IsExhaustedAdvice {
@OnReturn
public static void onReturn(@BindReceiver ResultSet resultSet) {
QueryEntry queryEntry = resultSet.glowroot$getQueryEntry();
if (queryEntry == null) {
// tracing must be disabled (e.g. exceeded trace entry limit)
return;
}
queryEntry.rowNavigationAttempted();
}
}
}
| Remove unused code
| agent/plugins/cassandra-plugin/src/main/java/org/glowroot/agent/plugin/cassandra/ResultSetAspect.java | Remove unused code | <ide><path>gent/plugins/cassandra-plugin/src/main/java/org/glowroot/agent/plugin/cassandra/ResultSetAspect.java
<ide> public void glowroot$setQueryEntry(@Nullable QueryEntry queryEntry) {
<ide> glowroot$queryEntry = queryEntry;
<ide> }
<del>
<del> @Override
<del> public boolean glowroot$hasQueryEntry() {
<del> return glowroot$queryEntry != null;
<del> }
<ide> }
<ide>
<ide> // the method names are verbose since they will be mixed in to existing classes
<ide> QueryEntry glowroot$getQueryEntry();
<ide>
<ide> void glowroot$setQueryEntry(@Nullable QueryEntry queryEntry);
<del>
<del> boolean glowroot$hasQueryEntry();
<ide> }
<ide>
<ide> @Pointcut(className = "com.datastax.driver.core.ResultSet", methodName = "one", |
|
JavaScript | mit | 02dc574dea6683c835d80c9f3e0ce8b6499f3e00 | 0 | joseph-roque/uOttawaCampusGuide,joseph-roque/uottawa-campus-guide,joseph-roque/uottawa-campus-guide,joseph-roque/uOttawaCampusGuide,joseph-roque/uOttawaCampusGuide,joseph-roque/uottawa-campus-guide | /**
*
* @license
* Copyright (C) 2016-2017 Joseph Roque
*
* 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 Joseph Roque
* @created 2017-03-09
* @file StudySpotList.js
* @providesModule StudySpotList
* @description Displays a list of filterable study spots
*
* @flow
*/
'use strict';
// React imports
import React from 'react';
import {
FlatList,
Image,
Platform,
StyleSheet,
Text,
TouchableOpacity,
View,
} from 'react-native';
// Types
import type { Language, StudySpot, TimeFormat } from 'types';
// Type definition for component props.
type Props = {
activeFilters: Set < string >, // Set of active study spot filters
filter: ?string, // Filter the list of buildings
studyFilters: Object, // Descriptions of study room filters
language: Language, // Language to display building names in
onSelect: (s: StudySpot) => void, // Callback for when a spot is selected
spots: Array < StudySpot >, // Study spot properties to display
timeFormat: TimeFormat, // Format to display times in
}
// Type definition for component state
type State = {
studySpots: Array < StudySpot >, // List of study spots
};
// Imports
import moment from 'moment';
import PaddedIcon from 'PaddedIcon';
import * as Configuration from 'Configuration';
import * as Constants from 'Constants';
import * as DisplayUtils from 'DisplayUtils';
import * as TextUtils from 'TextUtils';
import * as Translations from 'Translations';
const TIME_UNAVAILABLE_REGEX = /[Nn]\/[Aa]/;
export default class StudySpotList extends React.Component {
/**
* Properties this component expects to be provided by its parent.
*/
props: Props;
/**
* Current state of the component.
*/
state: State;
/**
* Constructor.
*
* @param {props} props component props
*/
constructor(props: Props) {
super(props);
this.state = { studySpots: []};
}
/**
* Loads the study spots once the view has been mounted.
*/
componentDidMount(): void {
this._filterStudySpots(this.props);
}
/**
* If a new filter is provided, update the list of study spots.
*
* @param {Props} nextProps the new props being received
*/
componentWillReceiveProps(nextProps: Props): void {
// Basic boolean comparisons to see if re-filtering needs to occur
if (nextProps.filter != this.props.filter
|| nextProps.language != this.props.language
|| nextProps.spots != this.props.spots) {
this._filterStudySpots(nextProps);
return;
}
// Compare filters to see if re-filtering needs to occur
if (this.props.activeFilters != nextProps.activeFilters) {
this._filterStudySpots(nextProps);
return;
}
}
/**
* Check if the spot contains all of the active filters.
*
* @param {Set<string>} activeFilters currently active filters
* @param {StudySpot} spot details about the study spot
* @returns {boolean} true iff the spot contains all the active filters, false otherwise
*/
_spotMatchesAllFilters(activeFilters: Set < string >, spot: StudySpot): boolean {
if (activeFilters.size === 0) {
return true;
}
let matches = 0;
spot.filters.forEach((filter) => {
if (activeFilters.has(filter)) {
matches++;
}
});
if (activeFilters.has('open')) {
if (TIME_UNAVAILABLE_REGEX.test(spot.opens)) {
matches++;
} else {
const openTime = moment(spot.opens, 'HH:mm');
const closeTime = moment(spot.closes, 'HH:mm');
const currentTime = moment();
if (openTime.diff(currentTime) < 0 && closeTime.diff(currentTime, 'hours') >= 1) {
matches++;
}
}
}
return matches === activeFilters.size;
}
/**
* Only show study spots which names or building names contain the search terms.
*
* @param {Props} props the props to use to filter
*/
_filterStudySpots({ filter, activeFilters, spots }: Props): void {
// Ignore the case of the search terms
const adjustedSearchTerms: ?string = (filter == null || filter.length === 0)
? null
: filter.toUpperCase();
// Create array for spots
const filteredSpots: Array < StudySpot > = [];
for (let i = 0; spots && i < spots.length; i++) {
const spot: Object = spots[i];
// Don't add the spot if it doesn't match all the filters
if (!this._spotMatchesAllFilters(activeFilters, spot)) {
continue;
}
// If the search terms are empty, or the spot properties contains the terms, add it to the list
if (adjustedSearchTerms == null
|| spot.building.toUpperCase().indexOf(adjustedSearchTerms) >= 0
|| spot.room.toUpperCase().indexOf(adjustedSearchTerms) >= 0
|| (spot.name && spot.name.toUpperCase().indexOf(adjustedSearchTerms) >= 0)
|| (spot.name_en && spot.name_en.toUpperCase().indexOf(adjustedSearchTerms) >= 0)
|| (spot.name_fr && spot.name_fr.toUpperCase().indexOf(adjustedSearchTerms) >= 0)) {
filteredSpots.push(spot);
continue;
}
}
this.setState({ studySpots: filteredSpots });
}
/**
* Displays a spots's name, image and description.
*
* @param {StudySpot} spot information about the study spot to display
* @returns {ReactElement<any>} an image and views describing the spot
*/
_renderItem({ item }: { item: StudySpot }): ReactElement < any > {
const altName = Translations.getName(this.props.language, item);
const name = `${item.building} ${item.room ? item.room : ''}`;
const description = Translations.getVariant(this.props.language, 'description', item) || '';
let openingTime = '';
if (TIME_UNAVAILABLE_REGEX.test(item.opens)) {
openingTime = item.opens;
} else {
openingTime = TextUtils.convertTimeFormat(this.props.timeFormat, item.opens);
}
let closingTime = '';
if (TIME_UNAVAILABLE_REGEX.test(item.closes)) {
if (!TIME_UNAVAILABLE_REGEX.test(item.opens)) {
closingTime = ` - ${item.closes}`;
}
} else {
closingTime = ` - ${TextUtils.convertTimeFormat(this.props.timeFormat, item.closes)}`;
}
return (
<TouchableOpacity
key={name}
onPress={() => this.props.onSelect(item)}>
<View style={_styles.spot}>
<Image
resizeMode={'cover'}
source={{ uri: Configuration.getImagePath(item.image) }}
style={_styles.spotImage} />
<View style={_styles.spotProperties}>
<Text style={_styles.spotName}>{name}</Text>
{altName == null ? null : <Text style={_styles.spotSubtitle}>{altName}</Text>}
<Text style={_styles.spotSubtitle}>{`${openingTime}${closingTime}`}</Text>
<Text style={_styles.spotDescription}>{description}</Text>
<View style={_styles.spotFilters}>
{item.filters.map((filter) => (
<PaddedIcon
color={Constants.Colors.primaryWhiteIcon}
icon={DisplayUtils.getPlatformIcon(Platform.OS, this.props.studyFilters[filter])}
key={filter}
size={Constants.Sizes.Icons.Medium}
width={Constants.Sizes.Icons.Medium + Constants.Sizes.Margins.Expanded} />
))}
</View>
</View>
</View>
</TouchableOpacity>
);
}
/**
* Renders a separator line between rows.
*
* @returns {ReactElement<any>} a separator for the list of study spots
*/
_renderSeparator(): ReactElement < any > {
return <View style={_styles.separator} />;
}
/**
* Returns a list of touchable views listing the study spot descriptions.
*
* @returns {ReactElement<any>} the hierarchy of views to render.
*/
render(): ReactElement < any > {
return (
<View style={_styles.container}>
<FlatList
ItemSeparatorComponent={this._renderSeparator}
data={this.state.studySpots}
keyExtractor={(studySpot) => `${studySpot.building}.${studySpot.room}`}
renderItem={this._renderItem.bind(this)} />
</View>
);
}
}
// Private styles for component
const _styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: Constants.Colors.primaryBackground,
},
spot: {
flex: 1,
margin: Constants.Sizes.Margins.Expanded,
alignItems: 'center',
flexDirection: 'row',
},
spotProperties: {
flex: 1,
},
spotImage: {
alignSelf: 'flex-start',
marginRight: Constants.Sizes.Margins.Expanded,
width: 64,
height: 64,
},
spotName: {
color: Constants.Colors.primaryWhiteText,
fontSize: Constants.Sizes.Text.Subtitle,
},
spotSubtitle: {
color: Constants.Colors.secondaryWhiteText,
fontSize: Constants.Sizes.Text.Caption,
marginTop: Constants.Sizes.Margins.Condensed,
},
spotDescription: {
color: Constants.Colors.primaryWhiteText,
fontSize: Constants.Sizes.Text.Body,
marginTop: Constants.Sizes.Margins.Condensed,
},
spotFilters: {
flexDirection: 'row',
alignSelf: 'flex-end',
marginTop: Constants.Sizes.Margins.Expanded,
},
separator: {
height: StyleSheet.hairlineWidth,
marginLeft: Constants.Sizes.Margins.Expanded,
backgroundColor: Constants.Colors.tertiaryBackground,
},
});
| src/components/StudySpotList.js | /**
*
* @license
* Copyright (C) 2016-2017 Joseph Roque
*
* 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 Joseph Roque
* @created 2017-03-09
* @file StudySpotList.js
* @providesModule StudySpotList
* @description Displays a list of filterable study spots
*
* @flow
*/
'use strict';
// React imports
import React from 'react';
import {
FlatList,
Image,
Platform,
StyleSheet,
Text,
TouchableOpacity,
View,
} from 'react-native';
// Types
import type { Language, StudySpot, TimeFormat } from 'types';
// Type definition for component props.
type Props = {
activeFilters: Set < string >, // Set of active study spot filters
filter: ?string, // Filter the list of buildings
studyFilters: Object, // Descriptions of study room filters
language: Language, // Language to display building names in
onSelect: (s: StudySpot) => void, // Callback for when a spot is selected
spots: Array < StudySpot >, // Study spot properties to display
timeFormat: TimeFormat, // Format to display times in
}
// Type definition for component state
type State = {
studySpots: Array < StudySpot >, // List of study spots
};
// Imports
import moment from 'moment';
import PaddedIcon from 'PaddedIcon';
import * as Configuration from 'Configuration';
import * as Constants from 'Constants';
import * as DisplayUtils from 'DisplayUtils';
import * as TextUtils from 'TextUtils';
import * as Translations from 'Translations';
export default class StudySpotList extends React.Component {
/**
* Properties this component expects to be provided by its parent.
*/
props: Props;
/**
* Current state of the component.
*/
state: State;
/**
* Constructor.
*
* @param {props} props component props
*/
constructor(props: Props) {
super(props);
this.state = { studySpots: []};
}
/**
* Loads the study spots once the view has been mounted.
*/
componentDidMount(): void {
this._filterStudySpots(this.props);
}
/**
* If a new filter is provided, update the list of study spots.
*
* @param {Props} nextProps the new props being received
*/
componentWillReceiveProps(nextProps: Props): void {
// Basic boolean comparisons to see if re-filtering needs to occur
if (nextProps.filter != this.props.filter
|| nextProps.language != this.props.language
|| nextProps.spots != this.props.spots) {
this._filterStudySpots(nextProps);
return;
}
// Compare filters to see if re-filtering needs to occur
if (this.props.activeFilters != nextProps.activeFilters) {
this._filterStudySpots(nextProps);
return;
}
}
/**
* Check if the spot contains all of the active filters.
*
* @param {Set<string>} activeFilters currently active filters
* @param {StudySpot} spot details about the study spot
* @returns {boolean} true iff the spot contains all the active filters, false otherwise
*/
_spotMatchesAllFilters(activeFilters: Set < string >, spot: StudySpot): boolean {
if (activeFilters.size === 0) {
return true;
}
let matches = 0;
spot.filters.forEach((filter) => {
if (activeFilters.has(filter)) {
matches++;
}
});
if (activeFilters.has('open')) {
const openTime = moment(spot.opens, 'HH:mm');
const closeTime = moment(spot.closes, 'HH:mm');
const currentTime = moment();
if (openTime.diff(currentTime) < 0 && closeTime.diff(currentTime, 'hours') >= 1) {
matches++;
}
}
return matches === activeFilters.size;
}
/**
* Only show study spots which names or building names contain the search terms.
*
* @param {Props} props the props to use to filter
*/
_filterStudySpots({ filter, activeFilters, spots }: Props): void {
// Ignore the case of the search terms
const adjustedSearchTerms: ?string = (filter == null || filter.length === 0)
? null
: filter.toUpperCase();
// Create array for spots
const filteredSpots: Array < StudySpot > = [];
for (let i = 0; spots && i < spots.length; i++) {
const spot: Object = spots[i];
// Don't add the spot if it doesn't match all the filters
if (!this._spotMatchesAllFilters(activeFilters, spot)) {
continue;
}
// If the search terms are empty, or the spot properties contains the terms, add it to the list
if (adjustedSearchTerms == null
|| spot.building.toUpperCase().indexOf(adjustedSearchTerms) >= 0
|| spot.room.toUpperCase().indexOf(adjustedSearchTerms) >= 0
|| (spot.name && spot.name.toUpperCase().indexOf(adjustedSearchTerms) >= 0)
|| (spot.name_en && spot.name_en.toUpperCase().indexOf(adjustedSearchTerms) >= 0)
|| (spot.name_fr && spot.name_fr.toUpperCase().indexOf(adjustedSearchTerms) >= 0)) {
filteredSpots.push(spot);
continue;
}
}
this.setState({ studySpots: filteredSpots });
}
/**
* Displays a spots's name, image and description.
*
* @param {StudySpot} spot information about the study spot to display
* @returns {ReactElement<any>} an image and views describing the spot
*/
_renderItem({ item }: { item: StudySpot }): ReactElement < any > {
const altName = Translations.getName(this.props.language, item);
const name = `${item.building} ${item.room}`;
const openingTime = TextUtils.convertTimeFormat(this.props.timeFormat, item.opens);
const closingTime = TextUtils.convertTimeFormat(this.props.timeFormat, item.closes);
const description = Translations.getVariant(this.props.language, 'description', item) || '';
return (
<TouchableOpacity
key={name}
onPress={() => this.props.onSelect(item)}>
<View style={_styles.spot}>
<Image
resizeMode={'cover'}
source={{ uri: Configuration.getImagePath(item.image) }}
style={_styles.spotImage} />
<View style={_styles.spotProperties}>
<Text style={_styles.spotName}>{name}</Text>
{altName == null ? null : <Text style={_styles.spotSubtitle}>{altName}</Text>}
<Text style={_styles.spotSubtitle}>{`${openingTime} - ${closingTime}`}</Text>
<Text style={_styles.spotDescription}>{description}</Text>
<View style={_styles.spotFilters}>
{item.filters.map((filter) => (
<PaddedIcon
color={Constants.Colors.primaryWhiteIcon}
icon={DisplayUtils.getPlatformIcon(Platform.OS, this.props.studyFilters[filter])}
key={filter}
size={Constants.Sizes.Icons.Medium}
width={Constants.Sizes.Icons.Medium + Constants.Sizes.Margins.Expanded} />
))}
</View>
</View>
</View>
</TouchableOpacity>
);
}
/**
* Renders a separator line between rows.
*
* @returns {ReactElement<any>} a separator for the list of study spots
*/
_renderSeparator(): ReactElement < any > {
return <View style={_styles.separator} />;
}
/**
* Returns a list of touchable views listing the study spot descriptions.
*
* @returns {ReactElement<any>} the hierarchy of views to render.
*/
render(): ReactElement < any > {
return (
<View style={_styles.container}>
<FlatList
ItemSeparatorComponent={this._renderSeparator}
data={this.state.studySpots}
keyExtractor={(studySpot) => `${studySpot.building}.${studySpot.room}`}
renderItem={this._renderItem.bind(this)} />
</View>
);
}
}
// Private styles for component
const _styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: Constants.Colors.primaryBackground,
},
spot: {
flex: 1,
margin: Constants.Sizes.Margins.Expanded,
alignItems: 'center',
flexDirection: 'row',
},
spotProperties: {
flex: 1,
},
spotImage: {
alignSelf: 'flex-start',
marginRight: Constants.Sizes.Margins.Expanded,
width: 64,
height: 64,
},
spotName: {
color: Constants.Colors.primaryWhiteText,
fontSize: Constants.Sizes.Text.Subtitle,
},
spotSubtitle: {
color: Constants.Colors.secondaryWhiteText,
fontSize: Constants.Sizes.Text.Caption,
marginTop: Constants.Sizes.Margins.Condensed,
},
spotDescription: {
color: Constants.Colors.primaryWhiteText,
fontSize: Constants.Sizes.Text.Body,
marginTop: Constants.Sizes.Margins.Condensed,
},
spotFilters: {
flexDirection: 'row',
alignSelf: 'flex-end',
marginTop: Constants.Sizes.Margins.Expanded,
},
separator: {
height: StyleSheet.hairlineWidth,
marginLeft: Constants.Sizes.Margins.Expanded,
backgroundColor: Constants.Colors.tertiaryBackground,
},
});
| Enable filtering study rooms by 'open'
| src/components/StudySpotList.js | Enable filtering study rooms by 'open' | <ide><path>rc/components/StudySpotList.js
<ide> import * as TextUtils from 'TextUtils';
<ide> import * as Translations from 'Translations';
<ide>
<add>const TIME_UNAVAILABLE_REGEX = /[Nn]\/[Aa]/;
<add>
<ide> export default class StudySpotList extends React.Component {
<ide>
<ide> /**
<ide> });
<ide>
<ide> if (activeFilters.has('open')) {
<del> const openTime = moment(spot.opens, 'HH:mm');
<del> const closeTime = moment(spot.closes, 'HH:mm');
<del> const currentTime = moment();
<del> if (openTime.diff(currentTime) < 0 && closeTime.diff(currentTime, 'hours') >= 1) {
<add> if (TIME_UNAVAILABLE_REGEX.test(spot.opens)) {
<ide> matches++;
<add> } else {
<add> const openTime = moment(spot.opens, 'HH:mm');
<add> const closeTime = moment(spot.closes, 'HH:mm');
<add> const currentTime = moment();
<add> if (openTime.diff(currentTime) < 0 && closeTime.diff(currentTime, 'hours') >= 1) {
<add> matches++;
<add> }
<ide> }
<ide> }
<ide>
<ide> */
<ide> _renderItem({ item }: { item: StudySpot }): ReactElement < any > {
<ide> const altName = Translations.getName(this.props.language, item);
<del> const name = `${item.building} ${item.room}`;
<del> const openingTime = TextUtils.convertTimeFormat(this.props.timeFormat, item.opens);
<del> const closingTime = TextUtils.convertTimeFormat(this.props.timeFormat, item.closes);
<add> const name = `${item.building} ${item.room ? item.room : ''}`;
<ide> const description = Translations.getVariant(this.props.language, 'description', item) || '';
<add>
<add> let openingTime = '';
<add> if (TIME_UNAVAILABLE_REGEX.test(item.opens)) {
<add> openingTime = item.opens;
<add> } else {
<add> openingTime = TextUtils.convertTimeFormat(this.props.timeFormat, item.opens);
<add> }
<add>
<add> let closingTime = '';
<add> if (TIME_UNAVAILABLE_REGEX.test(item.closes)) {
<add> if (!TIME_UNAVAILABLE_REGEX.test(item.opens)) {
<add> closingTime = ` - ${item.closes}`;
<add> }
<add> } else {
<add> closingTime = ` - ${TextUtils.convertTimeFormat(this.props.timeFormat, item.closes)}`;
<add> }
<ide>
<ide> return (
<ide> <TouchableOpacity
<ide> <View style={_styles.spotProperties}>
<ide> <Text style={_styles.spotName}>{name}</Text>
<ide> {altName == null ? null : <Text style={_styles.spotSubtitle}>{altName}</Text>}
<del> <Text style={_styles.spotSubtitle}>{`${openingTime} - ${closingTime}`}</Text>
<add> <Text style={_styles.spotSubtitle}>{`${openingTime}${closingTime}`}</Text>
<ide> <Text style={_styles.spotDescription}>{description}</Text>
<ide> <View style={_styles.spotFilters}>
<ide> {item.filters.map((filter) => ( |
|
Java | mit | b2c9a7967e017288d25c84e54b4c973b491f2ef5 | 0 | CS2103JAN2017-W13-B4/main,CS2103JAN2017-W13-B4/main | package seedu.doist.model.task;
import java.util.Date;
import java.util.Objects;
import seedu.doist.commons.util.CollectionUtil;
import seedu.doist.model.tag.UniqueTagList;
/**
* Represents a Task in the to-do list.
* Guarantees: details are present and not null, field values are validated.
*/
public class Task implements ReadOnlyTask {
private Description desc;
private Priority priority;
private FinishedStatus finishedStatus;
private UniqueTagList tags;
private Date startDate;
private Date endDate;
/**
* Every field must be present and not null.
*/
public Task(Description name, Priority priority, FinishedStatus finishedStatus,
UniqueTagList tags, Date startDate, Date endDate) {
assert !CollectionUtil.isAnyNull(name, priority, finishedStatus, tags);
this.desc = name;
this.priority = priority;
this.finishedStatus = finishedStatus;
this.tags = new UniqueTagList(tags); // protect internal tags from changes in the arg list
this.startDate = startDate;
this.endDate = endDate;
}
public Task(Description name, Priority priority, FinishedStatus finishedStatus, UniqueTagList tags) {
this(name, priority, finishedStatus, tags, null, null);
}
public Task(Description name, Priority priority, UniqueTagList tags) {
this(name, priority, new FinishedStatus(), tags, null, null);
}
public Task(Description name, UniqueTagList tags) {
this(name, new Priority(), new FinishedStatus(), tags, null, null);
}
public Task(Description name, Date startDate, Date endDate) {
this(name, new Priority(), new FinishedStatus(), new UniqueTagList(), startDate, endDate);
}
public Task(Description name, UniqueTagList tags, Date startDate, Date endDate) {
this(name, new Priority(), new FinishedStatus(), tags, startDate, endDate);
}
/**
* Creates a copy of the given ReadOnlyTask.
*/
public Task(ReadOnlyTask source) {
this(source.getDescription(), source.getPriority(), source.getFinishedStatus(),
source.getTags(), source.getStartDate(), source.getEndDate());
}
public void setDescription(Description desc) {
assert desc != null;
this.desc = desc;
}
@Override
public Description getDescription() {
return desc;
}
public void setPriority(Priority priority) {
assert priority != null;
this.priority = priority;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
public Date getStartDate() {
return startDate;
}
public Date getEndDate() {
return endDate;
}
@Override
public Priority getPriority() {
return priority;
}
public void setFinishedStatus(boolean isFinished) {
assert finishedStatus != null;
this.finishedStatus.setIsFinished(isFinished);
}
public void setFinishedStatus(FinishedStatus status) {
assert finishedStatus != null;
this.finishedStatus = status;
}
@Override
public FinishedStatus getFinishedStatus() {
return finishedStatus;
}
@Override
public UniqueTagList getTags() {
return new UniqueTagList(tags);
}
/**
* Replaces this person's tags with the tags in the argument tag list.
*/
public void setTags(UniqueTagList replacement) {
tags.setTags(replacement);
}
/**
* Updates this task with the details of {@code replacement}.
*/
public void resetData(ReadOnlyTask replacement) {
assert replacement != null;
this.setDescription(replacement.getDescription());
this.setPriority(replacement.getPriority());
this.setFinishedStatus(replacement.getFinishedStatus());
this.setTags(replacement.getTags());
this.setStartDate(replacement.getStartDate());
this.setEndDate(replacement.getEndDate());
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof ReadOnlyTask // instanceof handles nulls
&& this.isSameStateAs((ReadOnlyTask) other));
}
@Override
public int hashCode() {
// use this method for custom fields hashing instead of implementing your own
return Objects.hash(desc, tags);
}
@Override
public String toString() {
return getAsText();
}
}
| src/main/java/seedu/doist/model/task/Task.java | package seedu.doist.model.task;
import java.util.Date;
import java.util.Objects;
import seedu.doist.commons.util.CollectionUtil;
import seedu.doist.model.tag.UniqueTagList;
/**
* Represents a Task in the to-do list.
* Guarantees: details are present and not null, field values are validated.
*/
public class Task implements ReadOnlyTask {
private Description desc;
private Priority priority;
private FinishedStatus finishedStatus;
private UniqueTagList tags;
private Date startDate;
private Date endDate;
/**
* Every field must be present and not null.
*/
public Task(Description name, Priority priority, FinishedStatus finishedStatus,
UniqueTagList tags, Date startDate, Date endDate) {
assert !CollectionUtil.isAnyNull(name, priority, finishedStatus, tags);
this.desc = name;
this.priority = priority;
this.finishedStatus = finishedStatus;
this.tags = new UniqueTagList(tags); // protect internal tags from changes in the arg list
this.startDate = startDate;
this.endDate = endDate;
}
public Task(Description name, Priority priority, FinishedStatus finishedStatus, UniqueTagList tags) {
this(name, priority, finishedStatus, tags, null, null);
}
public Task(Description name, Priority priority, UniqueTagList tags) {
this(name, priority, new FinishedStatus(), tags, null, null);
}
public Task(Description name, UniqueTagList tags) {
this(name, new Priority(), new FinishedStatus(), tags, null, null);
}
public Task(Description name, Date startDate, Date endDate) {
this(name, new Priority(), new FinishedStatus(), new UniqueTagList(), startDate, endDate);
}
public Task(Description name, UniqueTagList tags, Date startDate, Date endDate) {
this(name, new Priority(), new FinishedStatus(), tags, startDate, endDate);
}
/**
* Creates a copy of the given ReadOnlyTask.
*/
public Task(ReadOnlyTask source) {
this(source.getDescription(), source.getPriority(), source.getFinishedStatus(),
source.getTags(), source.getStartDate(), source.getEndDate());
}
public void setDescription(Description desc) {
assert desc != null;
this.desc = desc;
}
@Override
public Description getDescription() {
return desc;
}
public void setPriority(Priority priority) {
assert priority != null;
this.priority = priority;
}
public Date getStartDate() {
return startDate;
}
public Date getEndDate() {
return endDate;
}
@Override
public Priority getPriority() {
return priority;
}
public void setFinishedStatus(boolean isFinished) {
assert finishedStatus != null;
this.finishedStatus.setIsFinished(isFinished);
}
public void setFinishedStatus(FinishedStatus status) {
assert finishedStatus != null;
this.finishedStatus = status;
}
@Override
public FinishedStatus getFinishedStatus() {
return finishedStatus;
}
@Override
public UniqueTagList getTags() {
return new UniqueTagList(tags);
}
/**
* Replaces this person's tags with the tags in the argument tag list.
*/
public void setTags(UniqueTagList replacement) {
tags.setTags(replacement);
}
/**
* Updates this task with the details of {@code replacement}.
*/
public void resetData(ReadOnlyTask replacement) {
assert replacement != null;
this.setDescription(replacement.getDescription());
this.setPriority(replacement.getPriority());
this.setFinishedStatus(replacement.getFinishedStatus());
this.setTags(replacement.getTags());
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof ReadOnlyTask // instanceof handles nulls
&& this.isSameStateAs((ReadOnlyTask) other));
}
@Override
public int hashCode() {
// use this method for custom fields hashing instead of implementing your own
return Objects.hash(desc, tags);
}
@Override
public String toString() {
return getAsText();
}
}
| Edit Task class to provide setters for Start and End Date
| src/main/java/seedu/doist/model/task/Task.java | Edit Task class to provide setters for Start and End Date | <ide><path>rc/main/java/seedu/doist/model/task/Task.java
<ide> this.priority = priority;
<ide> }
<ide>
<add> public void setStartDate(Date startDate) {
<add> this.startDate = startDate;
<add> }
<add>
<add> public void setEndDate(Date endDate) {
<add> this.endDate = endDate;
<add> }
<add>
<ide> public Date getStartDate() {
<ide> return startDate;
<ide> }
<ide> this.setPriority(replacement.getPriority());
<ide> this.setFinishedStatus(replacement.getFinishedStatus());
<ide> this.setTags(replacement.getTags());
<add> this.setStartDate(replacement.getStartDate());
<add> this.setEndDate(replacement.getEndDate());
<ide> }
<ide>
<ide> @Override |
|
Java | apache-2.0 | c50c72a784baeecd4c98643380c1febab3ed6024 | 0 | cmccabe/salvo,cmccabe/salvo | package scorched.android;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.Shader;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
/**
* A slider widget which the user can slide back and forth.
*
* There are arrows on the ends for fine adjustments.
*
* Most functions are synchronized on mState to prevent wackiness. The mState
* mutex should generally be held a pretty short amount of time.
*/
public class SalvoSlider extends View {
/* ================= Types ================= */
/** Describes the state of this slider */
public enum SliderState {
/**
* The slider is not in use. Only a blank space will be drawn. Touch
* will be disabled.
*/
DISABLED,
/**
* The slider will be drawn using a bar graphic. Touch will be
* enabled.
*/
BAR,
/**
* The slider will be drawn using the angle graphic. Touch will be
* enabled.
*/
ANGLE,
};
/** Used to hook up Listeners */
public static interface Listener {
void onPositionChange(int val);
}
/* ================= Constants ================= */
private static final String TAG = "SalvoSlider";
private static final int BUTTON_PERCENT = 20;
/* ================= Members ================= */
private SliderState mState;
// //// User input stuff
/** Listener to notify when slider value changes */
private Listener mListener;
/** Minimum slider value */
private int mMin;
/** Maximum slider value. */
private int mMax;
/** True if the slider's value increases left-to-right rather
* than left-to-right */
private boolean mReversed;
/** Current slider value */
private int mVal;
// //// Current configuration
/**
* Current slider color. If mColor == Color.WHITE then the slider is
* disabled.
*/
private int mColor;
/** Current slider width */
private int mWidth;
/** Current slider height */
private int mHeight;
// //// Things computed by cacheStuff()
/** Current left boundary of slidable area */
private int mLeftBound;
/** Current right boundary of slidable area */
private int mRightBound;
/** Gradient paint for bar */
private Paint mBarPaint;
/** Paint for text that's drawn on bars */
private Paint mFontPaint;
/////// Temporaries
private Paint mTempPaint;
private Rect mTempRect;
private Path mTempPath;
/* ================= Access ================= */
/* ================= Operations ================= */
/**
* Cache a bunch of stuff that we don't want to have to recalculate on
* each draw().
*/
private void cacheStuff() {
assert Thread.holdsLock(mState);
// Don't need to cache anything for the DISABLED state
if (mState == SliderState.DISABLED)
return;
mLeftBound = (mWidth * BUTTON_PERCENT) / 100;
mRightBound = (mWidth * (100 - BUTTON_PERCENT)) / 100;
if (mState == SliderState.BAR) {
int colors[] = new int[3];
colors[0] = Color.WHITE;
colors[1] = mColor;
colors[2] = Color.WHITE;
Shader barShader = new LinearGradient(0, 0, 0, (mHeight * 3) / 2,
colors, null, Shader.TileMode.REPEAT);
mBarPaint = new Paint();
mBarPaint.setShader(barShader);
}
mFontPaint = new Paint();
mFontPaint.setColor(Color.WHITE);
mFontPaint.setAntiAlias(true);
adjustTypefaceToFit(mFontPaint,
(mHeight * 4) / 5, Typeface.SANS_SERIF);
mFontPaint.setTextAlign(Paint.Align.CENTER);
}
@Override
protected void onDraw(Canvas canvas) {
int x;
synchronized (mState) {
super.onDraw(canvas);
switch (mState) {
case DISABLED:
canvas.drawColor(Color.BLACK);
break;
case BAR:
canvas.drawColor(Color.BLACK);
x = mLeftBound
+ (((mRightBound - mLeftBound) * (mVal - mMin)) /
(mMax - mMin));
mTempRect.set(mLeftBound, 0, x, mHeight);
canvas.drawRect(mTempRect, mBarPaint);
drawEndButtons(canvas);
drawSliderText(canvas);
break;
case ANGLE:
canvas.drawColor(Color.BLACK);
int totalWidth = mRightBound - mLeftBound;
int w = totalWidth / 6;
x = mLeftBound
+ ((totalWidth * mVal) / (mMax - mMin));
mTempPath.moveTo(x, 0);
mTempPath.lineTo(x - w, mHeight);
mTempPath.lineTo(x + w, mHeight);
mTempPaint.setColor(Color.argb(255, 236, 189, 62));
mTempPaint.setAntiAlias(true);
mTempPaint.setStrokeWidth(1);
canvas.drawPath(mTempPath, mTempPaint);
mTempPath.rewind();
drawEndButtons(canvas);
drawSliderText(canvas);
break;
}
}
}
private void drawSliderText(Canvas canvas) {
String str;
if (mReversed) {
str = "" + (mMax - mVal);
}
else {
str = "" + mVal;
}
canvas.drawText(str, mWidth / 2, (mHeight * 4) / 5, mFontPaint);
}
private void adjustTypefaceToFit(Paint p, int height, Typeface tf) {
p.setTypeface(tf);
Paint.FontMetrics metrics = new Paint.FontMetrics();
int size = 40;
p.setTextSize(size);
p.getFontMetrics(metrics);
int fontHeight = (int)(metrics.top + metrics.bottom);
if (Math.abs(fontHeight - height) > 5) {
size = (size * height) / fontHeight;
}
p.setTextSize(size);
}
private void drawEndButtons(Canvas canvas) {
// Draw end buttons
drawEndButton(canvas, 0, mLeftBound);
drawEndButton(canvas, mWidth, mRightBound);
}
private void drawEndButton(Canvas canvas, int xLeft, int xRight) {
mTempPaint.setColor(Color.BLACK);
mTempPaint.setAntiAlias(false);
mTempRect.set(xLeft, 0, xRight, mHeight);
canvas.drawRect(mTempRect, mTempPaint);
mTempPaint.setARGB(255, 236, 189, 62);
mTempPaint.setAntiAlias(false);
mTempPaint.setStrokeWidth(mHeight / 20);
canvas.drawLine(xLeft, 0, xRight, 0, mTempPaint);
canvas.drawLine(xLeft, mHeight, xRight, mHeight, mTempPaint);
canvas.drawLine(xLeft, 0, xLeft, mHeight, mTempPaint);
canvas.drawLine(xRight, 0, xRight, mHeight, mTempPaint);
mTempPaint.setStrokeWidth(1);
int w = xRight - xLeft;
mTempPath.moveTo(xLeft + (w / 5), mHeight / 2);
mTempPath.lineTo(xLeft + ((4 * w) / 5), mHeight / 5);
mTempPath.lineTo(xLeft + ((4 * w) / 5), (mHeight * 4) / 5);
mTempPaint.setAntiAlias(true);
canvas.drawPath(mTempPath, mTempPaint);
mTempPath.rewind();
}
@Override
public boolean onTouchEvent(MotionEvent me) {
boolean invalidate = false;
synchronized (mState) {
if (mState == SliderState.DISABLED) {
return true;
}
int action = me.getAction();
int x = (int)me.getX();
if (x < mLeftBound) {
invalidate = downButton(action);
}
else if (x > mRightBound) {
invalidate = upButton(action);
}
else {
int off = x - mLeftBound;
int newVal = mMin +
(off * (mMax - mMin)) /
(mRightBound - mLeftBound);
if (newVal != mVal) {
updateVal(newVal);
invalidate = true;
}
}
}
if (invalidate) {
invalidate();
}
return true;
}
private boolean downButton(int action) {
if (action == MotionEvent.ACTION_DOWN) {
updateVal(mVal - 1);
return true;
}
else {
return false;
}
}
private boolean upButton(int action) {
if (action == MotionEvent.ACTION_DOWN) {
updateVal(mVal + 1);
return true;
}
else {
return false;
}
}
private void updateVal(int val) {
assert Thread.holdsLock(mState);
if (val < mMin) {
val = mMin;
}
else if (val > mMax) {
val = mMax;
}
mVal = val;
mListener.onPositionChange(mReversed ? (mMax - mVal) : mVal);
}
/**
* Change the slider state to something else. This can be called
* from non-UI threads.
*/
public void setState(SliderState state, Listener listener, int min,
int max, int val, int color) {
Log.w(TAG, "setState state=" + state + ",min=" + min + ",max=" + max
+ ",color=" + color);
synchronized (mState) {
mState = state;
mListener = listener;
// user input stuff
assert (mListener != null);
if (min < max) {
mMin = min;
mMax = max;
mReversed = false;
mVal = val;
}
else {
mMin = max;
mMax = min;
mReversed = true;
mVal = mMax - val;
}
// configuration
mColor = color;
mWidth = getWidth();
mHeight = getHeight();
cacheStuff();
}
postInvalidate();
}
/* ================= Lifecycle ================= */
private void construct() {
mState = SliderState.DISABLED;
setFocusable(true);
// Temporaries
mTempPaint = new Paint();
mTempRect = new Rect();
mTempPath = new Path();
}
/** Constructor for "manual" instantiation */
public SalvoSlider(Context context) {
super(context);
construct();
}
/** Contructor for layout file */
public SalvoSlider(Context context, AttributeSet attrs) {
super(context, attrs);
construct();
}
}
| src/scorched/android/SalvoSlider.java | package scorched.android;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.Shader;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
/**
* A slider widget which the user can slide back and forth.
*
* There are arrows on the ends for fine adjustments.
*
* Most functions are synchronized on mState to prevent wackiness. The mState
* mutex should generally be held a pretty short amount of time.
*/
public class SalvoSlider extends View {
/* ================= Types ================= */
/** Describes the state of this slider */
public enum SliderState {
/**
* The slider is not in use. Only a blank space will be drawn. Touch
* will be disabled.
*/
DISABLED,
/**
* The slider will be drawn using a bar graphic. Touch will be enabled.
*/
BAR,
/**
* The slider will be drawn using the angle graphic. Touch will be
* enabled.
*/
ANGLE,
};
/** Used to hook up Listeners */
public static interface Listener {
void onPositionChange(int val);
}
/* ================= Constants ================= */
private static final String TAG = "SalvoSlider";
private static final int BUTTON_PERCENT = 20;
/* ================= Members ================= */
private SliderState mState;
// //// User input stuff
/** Listener to notify when slider value changes */
private Listener mListener;
/** Minimum slider value */
private int mMin;
/** Maximum slider value. */
private int mMax;
/** True if the slider's value increases left-to-right rather
* than left-to-right */
private boolean mReversed;
/** Current slider value */
private int mVal;
// //// Current configuration
/**
* Current slider color. If mColor == Color.WHITE then the slider is
* disabled.
*/
private int mColor;
/** Current slider width */
private int mWidth;
/** Current slider height */
private int mHeight;
// //// Things computed by cacheStuff()
/** Current left boundary of slidable area */
private int mLeftBound;
/** Current right boundary of slidable area */
private int mRightBound;
/** Gradient paint for bar */
private Paint mBarPaint;
/** Paint for text that's drawn on bars */
private Paint mFontPaint;
/////// Temporaries
private Paint mTempPaint;
private Rect mTempRect;
private Path mTempPath;
/* ================= Access ================= */
/* ================= Operations ================= */
/**
* Cache a bunch of stuff that we don't want to have to recalculate on each
* draw().
*/
private void cacheStuff() {
assert Thread.holdsLock(mState);
// Don't need to cache anything for the DISABLED state
if (mState == SliderState.DISABLED)
return;
mLeftBound = (mWidth * BUTTON_PERCENT) / 100;
mRightBound = (mWidth * (100 - BUTTON_PERCENT)) / 100;
if (mState == SliderState.BAR) {
int colors[] = new int[3];
colors[0] = Color.WHITE;
colors[1] = mColor;
colors[2] = Color.WHITE;
Shader barShader = new LinearGradient(0, 0, 0, (mHeight * 3) / 2,
colors, null, Shader.TileMode.REPEAT);
mBarPaint = new Paint();
mBarPaint.setShader(barShader);
}
mFontPaint = new Paint();
mFontPaint.setColor(Color.WHITE);
mFontPaint.setAntiAlias(true);
adjustTypefaceToFit(mFontPaint,
(mHeight * 4) / 5, Typeface.SANS_SERIF);
mFontPaint.setTextAlign(Paint.Align.CENTER);
}
@Override
protected void onDraw(Canvas canvas) {
int x;
synchronized (mState) {
super.onDraw(canvas);
switch (mState) {
case DISABLED:
canvas.drawColor(Color.BLACK);
break;
case BAR:
canvas.drawColor(Color.BLACK);
x = mLeftBound
+ (((mRightBound - mLeftBound) * mVal) /
(mMax - mMin));
mTempRect.set(mLeftBound, 0, x, mHeight);
canvas.drawRect(mTempRect, mBarPaint);
drawEndButtons(canvas);
drawSliderText(canvas);
break;
case ANGLE:
canvas.drawColor(Color.BLACK);
int totalWidth = mRightBound - mLeftBound;
int w = totalWidth / 6;
x = mLeftBound
+ ((totalWidth * mVal) / (mMax - mMin));
mTempPath.moveTo(x, 0);
mTempPath.lineTo(x - w, mHeight);
mTempPath.lineTo(x + w, mHeight);
mTempPaint.setColor(Color.argb(255, 236, 189, 62));
mTempPaint.setAntiAlias(true);
mTempPaint.setStrokeWidth(1);
canvas.drawPath(mTempPath, mTempPaint);
mTempPath.rewind();
drawEndButtons(canvas);
drawSliderText(canvas);
break;
}
}
}
private void drawSliderText(Canvas canvas) {
String str;
if (mReversed) {
str = "" + (mMax - mVal);
}
else {
str = "" + mVal;
}
canvas.drawText(str, mWidth / 2, (mHeight * 4) / 5, mFontPaint);
}
private void adjustTypefaceToFit(Paint p, int height, Typeface tf) {
p.setTypeface(tf);
Paint.FontMetrics metrics = new Paint.FontMetrics();
int size = 40;
p.setTextSize(size);
p.getFontMetrics(metrics);
int fontHeight = (int)(metrics.top + metrics.bottom);
if (Math.abs(fontHeight - height) > 5) {
size = (size * height) / fontHeight;
}
p.setTextSize(size);
}
private void drawEndButtons(Canvas canvas) {
// Draw end buttons
drawEndButton(canvas, 0, mLeftBound);
drawEndButton(canvas, mWidth, mRightBound);
}
private void drawEndButton(Canvas canvas, int xLeft, int xRight) {
mTempPaint.setColor(Color.BLACK);
mTempPaint.setAntiAlias(false);
mTempRect.set(xLeft, 0, xRight, mHeight);
canvas.drawRect(mTempRect, mTempPaint);
mTempPaint.setARGB(255, 236, 189, 62);
mTempPaint.setAntiAlias(false);
mTempPaint.setStrokeWidth(mHeight / 20);
canvas.drawLine(xLeft, 0, xRight, 0, mTempPaint);
canvas.drawLine(xLeft, mHeight, xRight, mHeight, mTempPaint);
canvas.drawLine(xLeft, 0, xLeft, mHeight, mTempPaint);
canvas.drawLine(xRight, 0, xRight, mHeight, mTempPaint);
mTempPaint.setStrokeWidth(1);
int w = xRight - xLeft;
mTempPath.moveTo(xLeft + (w / 5), mHeight / 2);
mTempPath.lineTo(xLeft + ((4 * w) / 5), mHeight / 5);
mTempPath.lineTo(xLeft + ((4 * w) / 5), (mHeight * 4) / 5);
mTempPaint.setAntiAlias(true);
canvas.drawPath(mTempPath, mTempPaint);
mTempPath.rewind();
}
@Override
public boolean onTouchEvent(MotionEvent me) {
boolean invalidate = false;
synchronized (mState) {
if (mState == SliderState.DISABLED) {
return true;
}
int action = me.getAction();
int x = (int)me.getX();
if (x < mLeftBound) {
invalidate = downButton(action);
}
else if (x > mRightBound) {
invalidate = upButton(action);
}
else {
int off = x - mLeftBound;
int newVal = mMin +
(off * (mMax - mMin)) /
(mRightBound - mLeftBound);
if (newVal != mVal) {
updateVal(newVal);
invalidate = true;
}
}
}
if (invalidate) {
invalidate();
}
return true;
}
private boolean downButton(int action) {
if (action == MotionEvent.ACTION_DOWN) {
updateVal(mVal - 1);
return true;
}
else {
return false;
}
}
private boolean upButton(int action) {
if (action == MotionEvent.ACTION_DOWN) {
updateVal(mVal + 1);
return true;
}
else {
return false;
}
}
private void updateVal(int val) {
assert Thread.holdsLock(mState);
if (val < mMin) {
val = mMin;
}
else if (val > mMax) {
val = mMax;
}
mVal = val;
mListener.onPositionChange(mReversed ? (mMax - mVal) : mVal);
}
/**
* Change the slider state to something else. This can be called from non-UI
* threads.
*/
public void setState(SliderState state, Listener listener, int min,
int max, int val, int color) {
Log.w(TAG, "setState state=" + state + ",min=" + min + ",max=" + max
+ ",color=" + color);
synchronized (mState) {
mState = state;
mListener = listener;
// user input stuff
assert (mListener != null);
if (min < max) {
mMin = min;
mMax = max;
mReversed = false;
mVal = val;
}
else {
mMin = max;
mMax = min;
mReversed = true;
mVal = mMax - val;
}
// configuration
mColor = color;
mWidth = getWidth();
mHeight = getHeight();
cacheStuff();
}
postInvalidate();
}
/* ================= Lifecycle ================= */
private void construct() {
mState = SliderState.DISABLED;
setFocusable(true);
// Temporaries
mTempPaint = new Paint();
mTempRect = new Rect();
mTempPath = new Path();
}
/** Constructor for "manual" instantiation */
public SalvoSlider(Context context) {
super(context);
construct();
}
/** Contructor for layout file */
public SalvoSlider(Context context, AttributeSet attrs) {
super(context, attrs);
construct();
}
}
| Fix slider draw bug and fix overlong lines
| src/scorched/android/SalvoSlider.java | Fix slider draw bug and fix overlong lines | <ide><path>rc/scorched/android/SalvoSlider.java
<ide> DISABLED,
<ide>
<ide> /**
<del> * The slider will be drawn using a bar graphic. Touch will be enabled.
<add> * The slider will be drawn using a bar graphic. Touch will be
<add> * enabled.
<ide> */
<ide> BAR,
<ide>
<ide>
<ide> /* ================= Operations ================= */
<ide> /**
<del> * Cache a bunch of stuff that we don't want to have to recalculate on each
<del> * draw().
<add> * Cache a bunch of stuff that we don't want to have to recalculate on
<add> * each draw().
<ide> */
<ide> private void cacheStuff() {
<ide> assert Thread.holdsLock(mState);
<ide> case BAR:
<ide> canvas.drawColor(Color.BLACK);
<ide> x = mLeftBound
<del> + (((mRightBound - mLeftBound) * mVal) /
<add> + (((mRightBound - mLeftBound) * (mVal - mMin)) /
<ide> (mMax - mMin));
<ide> mTempRect.set(mLeftBound, 0, x, mHeight);
<ide> canvas.drawRect(mTempRect, mBarPaint);
<ide> }
<ide>
<ide> /**
<del> * Change the slider state to something else. This can be called from non-UI
<del> * threads.
<add> * Change the slider state to something else. This can be called
<add> * from non-UI threads.
<ide> */
<ide> public void setState(SliderState state, Listener listener, int min,
<ide> int max, int val, int color) { |
|
Java | mpl-2.0 | 442717be3770f5efa39c13e9cc6540d3ea9887c3 | 0 | JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core | /*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: StorageUnitTest.java,v $
*
* $Revision: 1.7 $
*
* last change: $Author: hr $ $Date: 2005-10-27 14:07:14 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* 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 complex.storages;
import com.sun.star.lang.XMultiServiceFactory;
import com.sun.star.lang.XMultiComponentFactory;
import com.sun.star.connection.XConnector;
import com.sun.star.connection.XConnection;
import com.sun.star.bridge.XUnoUrlResolver;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XInterface;
import com.sun.star.uno.XNamingService;
import com.sun.star.uno.XComponentContext;
import com.sun.star.container.*;
import com.sun.star.beans.*;
import com.sun.star.lang.*;
import complexlib.ComplexTestCase;
import complex.storages.*;
import util.utils;
import java.util.*;
import java.io.*;
/* This unit test for storage objects is designed to
* test most important statements from storage service
* specification.
*
* Regression tests are added to extend the tested
* functionalities.
*/
public class StorageUnitTest extends ComplexTestCase
{
private XMultiServiceFactory m_xMSF = null;
private XSingleServiceFactory m_xStorageFactory = null;
public String[] getTestMethodNames()
{
return new String[] {
"ExecuteTest01",
"ExecuteTest02",
"ExecuteTest03",
"ExecuteTest04",
"ExecuteTest05",
"ExecuteTest06",
"ExecuteTest07",
"ExecuteTest08",
"ExecuteTest09",
"ExecuteTest10",
"ExecuteTest11",
"ExecuteTest12",
"ExecuteRegressionTest_114358",
"ExecuteRegressionTest_i29169",
"ExecuteRegressionTest_i30400",
"ExecuteRegressionTest_i29321",
"ExecuteRegressionTest_i30677",
"ExecuteRegressionTest_i27773",
"ExecuteRegressionTest_i46848",
"ExecuteRegressionTest_i55821"};
}
public String getTestObjectName()
{
return "StorageUnitTest";
}
public void before()
{
m_xMSF = (XMultiServiceFactory)param.getMSF();
if ( m_xMSF == null )
{
failed( "Can't create service factory!" );
return;
}
try {
Object oStorageFactory = m_xMSF.createInstance( "com.sun.star.embed.StorageFactory" );
m_xStorageFactory = (XSingleServiceFactory)UnoRuntime.queryInterface( XSingleServiceFactory.class,
oStorageFactory );
}
catch( Exception e )
{
failed( "Can't create storage factory!" );
return;
}
if ( m_xStorageFactory == null )
{
failed( "Can't create service factory!" );
return;
}
}
public void ExecuteTest01()
{
StorageTest aTest = new Test01( m_xMSF, m_xStorageFactory, log );
assure( "Test01 failed!", aTest.test() );
}
public void ExecuteTest02()
{
StorageTest aTest = new Test02( m_xMSF, m_xStorageFactory, log );
assure( "Test02 failed!", aTest.test() );
}
public void ExecuteTest03()
{
StorageTest aTest = new Test03( m_xMSF, m_xStorageFactory, log );
assure( "Test03 failed!", aTest.test() );
}
public void ExecuteTest04()
{
StorageTest aTest = new Test04( m_xMSF, m_xStorageFactory, log );
assure( "Test04 failed!", aTest.test() );
}
public void ExecuteTest05()
{
StorageTest aTest = new Test05( m_xMSF, m_xStorageFactory, log );
assure( "Test05 failed!", aTest.test() );
}
public void ExecuteTest06()
{
StorageTest aTest = new Test06( m_xMSF, m_xStorageFactory, log );
assure( "Test06 failed!", aTest.test() );
}
public void ExecuteTest07()
{
StorageTest aTest = new Test07( m_xMSF, m_xStorageFactory, log );
assure( "Test07 failed!", aTest.test() );
}
public void ExecuteTest08()
{
StorageTest aTest = new Test08( m_xMSF, m_xStorageFactory, log );
assure( "Test08 failed!", aTest.test() );
}
public void ExecuteTest09()
{
StorageTest aTest = new Test09( m_xMSF, m_xStorageFactory, log );
assure( "Test09 failed!", aTest.test() );
}
public void ExecuteTest10()
{
StorageTest aTest = new Test10( m_xMSF, m_xStorageFactory, log );
assure( "Test10 failed!", aTest.test() );
}
public void ExecuteTest11()
{
StorageTest aTest = new Test11( m_xMSF, m_xStorageFactory, log );
assure( "Test11 failed!", aTest.test() );
}
public void ExecuteTest12()
{
StorageTest aTest = new Test12( m_xMSF, m_xStorageFactory, log );
assure( "Test12 failed!", aTest.test() );
}
public void ExecuteRegressionTest_114358()
{
StorageTest aTest = new RegressionTest_114358( m_xMSF, m_xStorageFactory, log );
assure( "RegressionTest_114358 failed!", aTest.test() );
}
public void ExecuteRegressionTest_i29169()
{
StorageTest aTest = new RegressionTest_i29169( m_xMSF, m_xStorageFactory, log );
assure( "RegressionTest_i29169 failed!", aTest.test() );
}
public void ExecuteRegressionTest_i30400()
{
StorageTest aTest = new RegressionTest_i30400( m_xMSF, m_xStorageFactory, log );
assure( "RegressionTest_i30400 failed!", aTest.test() );
}
public void ExecuteRegressionTest_i29321()
{
StorageTest aTest = new RegressionTest_i29321( m_xMSF, m_xStorageFactory, log );
assure( "RegressionTest_i29321 failed!", aTest.test() );
}
public void ExecuteRegressionTest_i30677()
{
StorageTest aTest = new RegressionTest_i30677( m_xMSF, m_xStorageFactory, log );
assure( "RegressionTest_i30677 failed!", aTest.test() );
}
public void ExecuteRegressionTest_i27773()
{
StorageTest aTest = new RegressionTest_i27773( m_xMSF, m_xStorageFactory, log );
assure( "RegressionTest_i27773 failed!", aTest.test() );
}
public void ExecuteRegressionTest_i46848()
{
StorageTest aTest = new RegressionTest_i46848( m_xMSF, m_xStorageFactory, log );
assure( "RegressionTest_i46848 failed!", aTest.test() );
}
public void ExecuteRegressionTest_i55821()
{
StorageTest aTest = new RegressionTest_i55821( m_xMSF, m_xStorageFactory, log );
assure( "RegressionTest_i55821 failed!", aTest.test() );
}
}
| package/qa/storages/StorageUnitTest.java | /*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: StorageUnitTest.java,v $
*
* $Revision: 1.6 $
*
* last change: $Author: hr $ $Date: 2005-09-23 15:53:43 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* 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 complex.storages;
import com.sun.star.lang.XMultiServiceFactory;
import com.sun.star.lang.XMultiComponentFactory;
import com.sun.star.connection.XConnector;
import com.sun.star.connection.XConnection;
import com.sun.star.bridge.XUnoUrlResolver;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XInterface;
import com.sun.star.uno.XNamingService;
import com.sun.star.uno.XComponentContext;
import com.sun.star.container.*;
import com.sun.star.beans.*;
import com.sun.star.lang.*;
import complexlib.ComplexTestCase;
import complex.storages.*;
import util.utils;
import java.util.*;
import java.io.*;
/* This unit test for storage objects is designed to
* test most important statements from storage service
* specification.
*
* Regression tests are added to extend the tested
* functionalities.
*/
public class StorageUnitTest extends ComplexTestCase
{
private XMultiServiceFactory m_xMSF = null;
private XSingleServiceFactory m_xStorageFactory = null;
public String[] getTestMethodNames()
{
return new String[] {
"ExecuteTest01",
"ExecuteTest02",
"ExecuteTest03",
"ExecuteTest04",
"ExecuteTest05",
"ExecuteTest06",
"ExecuteTest07",
"ExecuteTest08",
"ExecuteTest09",
"ExecuteTest10",
"ExecuteTest11",
"ExecuteTest12",
"ExecuteRegressionTest_114358",
"ExecuteRegressionTest_i29169",
"ExecuteRegressionTest_i30400",
"ExecuteRegressionTest_i29321",
"ExecuteRegressionTest_i30677",
"ExecuteRegressionTest_i27773",
"ExecuteRegressionTest_i46848"};
}
public String getTestObjectName()
{
return "StorageUnitTest";
}
public void before()
{
m_xMSF = (XMultiServiceFactory)param.getMSF();
if ( m_xMSF == null )
{
failed( "Can't create service factory!" );
return;
}
try {
Object oStorageFactory = m_xMSF.createInstance( "com.sun.star.embed.StorageFactory" );
m_xStorageFactory = (XSingleServiceFactory)UnoRuntime.queryInterface( XSingleServiceFactory.class,
oStorageFactory );
}
catch( Exception e )
{
failed( "Can't create storage factory!" );
return;
}
if ( m_xStorageFactory == null )
{
failed( "Can't create service factory!" );
return;
}
}
public void ExecuteTest01()
{
StorageTest aTest = new Test01( m_xMSF, m_xStorageFactory, log );
assure( "Test01 failed!", aTest.test() );
}
public void ExecuteTest02()
{
StorageTest aTest = new Test02( m_xMSF, m_xStorageFactory, log );
assure( "Test02 failed!", aTest.test() );
}
public void ExecuteTest03()
{
StorageTest aTest = new Test03( m_xMSF, m_xStorageFactory, log );
assure( "Test03 failed!", aTest.test() );
}
public void ExecuteTest04()
{
StorageTest aTest = new Test04( m_xMSF, m_xStorageFactory, log );
assure( "Test04 failed!", aTest.test() );
}
public void ExecuteTest05()
{
StorageTest aTest = new Test05( m_xMSF, m_xStorageFactory, log );
assure( "Test05 failed!", aTest.test() );
}
public void ExecuteTest06()
{
StorageTest aTest = new Test06( m_xMSF, m_xStorageFactory, log );
assure( "Test06 failed!", aTest.test() );
}
public void ExecuteTest07()
{
StorageTest aTest = new Test07( m_xMSF, m_xStorageFactory, log );
assure( "Test07 failed!", aTest.test() );
}
public void ExecuteTest08()
{
StorageTest aTest = new Test08( m_xMSF, m_xStorageFactory, log );
assure( "Test08 failed!", aTest.test() );
}
public void ExecuteTest09()
{
StorageTest aTest = new Test09( m_xMSF, m_xStorageFactory, log );
assure( "Test09 failed!", aTest.test() );
}
public void ExecuteTest10()
{
StorageTest aTest = new Test10( m_xMSF, m_xStorageFactory, log );
assure( "Test10 failed!", aTest.test() );
}
public void ExecuteTest11()
{
StorageTest aTest = new Test11( m_xMSF, m_xStorageFactory, log );
assure( "Test11 failed!", aTest.test() );
}
public void ExecuteTest12()
{
StorageTest aTest = new Test12( m_xMSF, m_xStorageFactory, log );
assure( "Test12 failed!", aTest.test() );
}
public void ExecuteRegressionTest_114358()
{
StorageTest aTest = new RegressionTest_114358( m_xMSF, m_xStorageFactory, log );
assure( "RegressionTest_114358 failed!", aTest.test() );
}
public void ExecuteRegressionTest_i29169()
{
StorageTest aTest = new RegressionTest_i29169( m_xMSF, m_xStorageFactory, log );
assure( "RegressionTest_i29169 failed!", aTest.test() );
}
public void ExecuteRegressionTest_i30400()
{
StorageTest aTest = new RegressionTest_i30400( m_xMSF, m_xStorageFactory, log );
assure( "RegressionTest_i30400 failed!", aTest.test() );
}
public void ExecuteRegressionTest_i29321()
{
StorageTest aTest = new RegressionTest_i29321( m_xMSF, m_xStorageFactory, log );
assure( "RegressionTest_i29321 failed!", aTest.test() );
}
public void ExecuteRegressionTest_i30677()
{
StorageTest aTest = new RegressionTest_i30677( m_xMSF, m_xStorageFactory, log );
assure( "RegressionTest_i30677 failed!", aTest.test() );
}
public void ExecuteRegressionTest_i27773()
{
StorageTest aTest = new RegressionTest_i27773( m_xMSF, m_xStorageFactory, log );
assure( "RegressionTest_i27773 failed!", aTest.test() );
}
public void ExecuteRegressionTest_i46848()
{
StorageTest aTest = new RegressionTest_i46848( m_xMSF, m_xStorageFactory, log );
assure( "RegressionTest_i46848 failed!", aTest.test() );
}
}
| INTEGRATION: CWS fwk24 (1.6.2); FILE MERGED
2005/10/13 13:57:57 mav 1.6.2.1: #i55821# second commit of a storage with encrypted entries
| package/qa/storages/StorageUnitTest.java | INTEGRATION: CWS fwk24 (1.6.2); FILE MERGED 2005/10/13 13:57:57 mav 1.6.2.1: #i55821# second commit of a storage with encrypted entries | <ide><path>ackage/qa/storages/StorageUnitTest.java
<ide> *
<ide> * $RCSfile: StorageUnitTest.java,v $
<ide> *
<del> * $Revision: 1.6 $
<del> *
<del> * last change: $Author: hr $ $Date: 2005-09-23 15:53:43 $
<add> * $Revision: 1.7 $
<add> *
<add> * last change: $Author: hr $ $Date: 2005-10-27 14:07:14 $
<ide> *
<ide> * The Contents of this file are made available subject to
<ide> * the terms of GNU Lesser General Public License Version 2.1.
<ide> "ExecuteRegressionTest_i29321",
<ide> "ExecuteRegressionTest_i30677",
<ide> "ExecuteRegressionTest_i27773",
<del> "ExecuteRegressionTest_i46848"};
<add> "ExecuteRegressionTest_i46848",
<add> "ExecuteRegressionTest_i55821"};
<ide> }
<ide>
<ide> public String getTestObjectName()
<ide> StorageTest aTest = new RegressionTest_i46848( m_xMSF, m_xStorageFactory, log );
<ide> assure( "RegressionTest_i46848 failed!", aTest.test() );
<ide> }
<add>
<add> public void ExecuteRegressionTest_i55821()
<add> {
<add> StorageTest aTest = new RegressionTest_i55821( m_xMSF, m_xStorageFactory, log );
<add> assure( "RegressionTest_i55821 failed!", aTest.test() );
<add> }
<ide> }
<ide> |
|
JavaScript | mit | 06b2ec27ac5489691aa65fa50b8038894fd273bc | 0 | nehasingh189/mll,nehasingh189/mll,nehasingh189/mll,nehasingh189/mll | 'use strict';
let argv = require('yargs').argv;
let del = require('del');
let gulp = require('gulp');
let htmlmin = require('gulp-htmlmin');
let gulpif = require('gulp-if');
let jshint = require('gulp-jshint');
let minifycss = require('gulp-minify-css');
let rev = require('gulp-rev');
let runSequence = require('run-sequence');
let server = require('karma').Server;
let stylish = require('jshint-stylish');
let templateCache = require('gulp-angular-templatecache');
let uglify = require('gulp-uglify');
let usemin = require('gulp-usemin');
/**
* Build Task
* Cleans the dist and rebuilds files
*/
gulp.task('build', (done) => {
runSequence('cleanup', ['fonts', 'templates'], 'usemin', function() {
done();
})
});
/**
* Clean-Up Task
* Deletes the dist directory and the generated index file
*/
gulp.task('cleanup', (done) => {
del(['./dist', './index.html']);
done();
});
/**
* Develop Task
* Automatically watches files and rebuilds if there is a change
*/
gulp.task('develop', (done) => {
gulp.watch('./source/*.*', { interval: 1000 }, ['build']);
console.log('Develop is running! Make some changes in ./source/');
console.log('CTRL^C to exit');
});
/**
* Fonts Task
* Generates the fonts folder in the dist
*/
gulp.task('fonts', () => {
gulp.src('./bower_components/font-awesome/fonts/**/*.{ttf,woff,eof,svg}*')
.pipe(gulp.dest('./dist/fonts'));
gulp.src('./bower_components/bootstrap/dist/fonts/**/*.{ttf,woff,eof,svg}*')
.pipe(gulp.dest('./dist/fonts'));
gulp.src('./source/fonts/*.*')
.pipe(gulp.dest('./dist/fonts'));
});
/**
* Code Quality Task
*/
gulp.task('jshint', (done) => {
gulp.src(['./source/scripts/**/*.js', '!./source/scripts/modules/templates/*.js'])
.pipe(jshint())
.pipe(jshint.reporter(stylish));
done();
});
/**
* Generate the template-cache file
*/
gulp.task('templates', () => {
return gulp.src('./source/scripts/**/*.html')
//.pipe(htmlmin({ collapseWhitespace: true }))
.pipe(templateCache({
module: 'mllApp.templates',
standalone: true,
filename: 'templates.module.js',
/*transformUrl: (url) => url.slice(url.lastIndexOf('\\') + 1),*/
transformUrl: (url) => {
return url.substr(url.lastIndexOf('\\') + 1);
}
}))
.pipe(gulp.dest('./source/scripts/modules/templates/'));
});
/**
* Test-runner Task
*/
gulp.task('test', function (done) {
new server({
configFile: __dirname + '/karma.conf.js',
singleRun: true
}, done()).start();
});
/**
* Usemin Task
* Runs the usemin library to consolidate all the source files.
* Then generates index files with refenrences to the current build.
*/
gulp.task('usemin', ['templates'], function () {
return gulp.src('./source/index.html')
.pipe(usemin({
cssBootstrap: [minifycss(), rev()],
cssCustom: [minifycss(), rev()],
jsJQuery: [gulpif(argv.prd, uglify()), rev()],
jsBootstrap: [gulpif(argv.prd, uglify()), rev()],
jsAngular: [gulpif(argv.prd, uglify()), rev()],
jsTemplates: [gulpif(argv.prd, uglify()), rev()],
jsCustom: [rev()]
}))
.pipe(gulp.dest('./'));
});
| src/main/webapp/gulpfile.js | 'use strict';
let argv = require('yargs').argv;
let del = require('del');
let gulp = require('gulp');
let htmlmin = require('gulp-htmlmin');
let gulpif = require('gulp-if');
let jshint = require('gulp-jshint');
let minifycss = require('gulp-minify-css');
let rev = require('gulp-rev');
let runSequence = require('run-sequence');
let server = require('karma').Server;
let stylish = require('jshint-stylish');
let templateCache = require('gulp-angular-templatecache');
let uglify = require('gulp-uglify');
let usemin = require('gulp-usemin');
/**
* Build Task
* Cleans the dist and rebuilds files
*/
gulp.task('build', (done) => {
runSequence('cleanup', ['fonts', 'templates'], 'usemin', function() {
done();
})
});
/**
* Clean-Up Task
* Deletes the dist directory and the generated index file
*/
gulp.task('cleanup', (done) => {
del(['./dist', './index.html']);
done();
});
/**
* Develop Task
* Automatically watches files and rebuilds if there is a change
*/
gulp.task('develop', (done) => {
gulp.watch('./source/*.*', { interval: 1000 }, ['build']);
console.log('Develop is running! Make some changes in ./source/');
console.log('CTRL^C to exit');
});
/**
* Fonts Task
* Generates the fonts folder in the dist
*/
gulp.task('fonts', () => {
gulp.src('./bower_components/font-awesome/fonts/**/*.{ttf,woff,eof,svg}*')
.pipe(gulp.dest('./dist/fonts'));
gulp.src('./bower_components/bootstrap/dist/fonts/**/*.{ttf,woff,eof,svg}*')
.pipe(gulp.dest('./dist/fonts'));
gulp.src('./source/fonts/*.*')
.pipe(gulp.dest('./dist/fonts'));
});
/**
* Code Quality Task
*/
gulp.task('jshint', (done) => {
gulp.src(['./source/scripts/**/*.js', '!./source/scripts/modules/templates/*.js'])
.pipe(jshint())
.pipe(jshint.reporter(stylish));
done();
});
/**
* Generate the template-cache file
*/
gulp.task('templates', () => {
return gulp.src('./source/scripts/**/*.html')
//.pipe(htmlmin({ collapseWhitespace: true }))
.pipe(templateCache({
module: 'mllApp.templates',
standalone: true,
filename: 'templates.module.js',
/*transformUrl: (url) => url.slice(url.lastIndexOf('\\') + 1),*/
transformUrl: (url) => {
return url.substr(url.lastIndexOf('\\') + 1);
}
}))
.pipe(gulp.dest('./source/scripts/modules/templates/'));
});
/**
* Test-runner Task
*/
gulp.task('test', function (done) {
new server({
configFile: __dirname + '/karma.conf.js',
singleRun: true
}, done).start();
});
/**
* Usemin Task
* Runs the usemin library to consolidate all the source files.
* Then generates index files with refenrences to the current build.
*/
gulp.task('usemin', ['templates'], function () {
return gulp.src('./source/index.html')
.pipe(usemin({
cssBootstrap: [minifycss(), rev()],
cssCustom: [minifycss(), rev()],
jsJQuery: [gulpif(argv.prd, uglify()), rev()],
jsBootstrap: [gulpif(argv.prd, uglify()), rev()],
jsAngular: [gulpif(argv.prd, uglify()), rev()],
jsTemplates: [gulpif(argv.prd, uglify()), rev()],
jsCustom: [rev()]
}))
.pipe(gulp.dest('./'));
});
| add done function call to prevent gulp error in test task
| src/main/webapp/gulpfile.js | add done function call to prevent gulp error in test task | <ide><path>rc/main/webapp/gulpfile.js
<ide> new server({
<ide> configFile: __dirname + '/karma.conf.js',
<ide> singleRun: true
<del> }, done).start();
<add> }, done()).start();
<ide> });
<ide>
<ide> /** |
|
Java | mit | 457d257c251cb7d255bdd8e58cd5bf51ebd26af1 | 0 | carrot/cream | package com.carrotcreative.cream.cache;
import android.content.Context;
import com.carrotcreative.cream.tasks.ReadSerializableTask;
import com.carrotcreative.cream.tasks.WriteSerializableTask;
import java.io.File;
import java.io.FileFilter;
import java.io.Serializable;
import java.util.regex.Pattern;
public class CacheManager {
public static final String PREFIX_EXPIRATION_DELIMITER = "-CR-";
//=======================================
//============== Singleton ==============
//=======================================
private static CacheManager sInstance;
public static CacheManager getInstance(Context context){
if(sInstance == null){
sInstance = new CacheManager(context);
}
return sInstance;
}
//===================================
//============== Class ==============
//===================================
private final File mRootDir;
private final Context mContext;
private CacheManager(Context context)
{
mContext = context;
mRootDir = context.getCacheDir();
}
//============================================
//================== Cache ===================
//============================================
public void readSerializable(String directoryString, String fileExtension, String prefix, boolean regardForExpiration,
ReadSerializableTask.ReadSerializableCallback cb)
{
File directory = new File(mRootDir, directoryString);
//Finding the file
final File[] matchingFiles = getMatchingFiles(directory, prefix, fileExtension);
for(File f : matchingFiles)
{
long expiration = getFileExpiration(f, fileExtension);
//If it's not expired, or we have no regard for expiration
if(!(System.currentTimeMillis() > expiration) || !regardForExpiration) {
readSerializable(f, cb);
return;
}
}
cb.failure(null);
}
public void writeSerializable(String directoryString, long expirationMinutes, String fileExtension, String prefix, Serializable content, WriteSerializableTask.WriteSerializableCallback cb)
{
File directory = new File(mRootDir, directoryString);
long expiration = getExpirationEpochMinutes(expirationMinutes);
String fileString = prefix + PREFIX_EXPIRATION_DELIMITER + expiration + "." + fileExtension;
File file = new File(directory, fileString);
deleteAllByPrefix(prefix, directory, fileExtension);
writeSerializable(content, file, cb);
}
/**
* This goes and deletes files that are expired by trashDays
*/
public void runTrashCleanup(String directoryString, String fileExtension, long trashMinutes)
{
File cleanupDir = new File(mRootDir, directoryString);
File[] allFiles = cleanupDir.listFiles();
//http://docs.oracle.com/javase/1.5.0/docs/api/java/io/File.html#listFiles%28%29
if(allFiles != null){
for(File f : allFiles)
{
if(f.toString().endsWith(fileExtension))
{
long trashDate = getFileTrashDate(f, fileExtension, trashMinutes);
if(f.isFile() && (System.currentTimeMillis() > trashDate))
{
f.delete();
}
}
}
}
}
//==============================================
//============== Helper Functions ==============
//==============================================
/**
* Only to be ran by write functions.
*
* We're writing a fresh object, so obviously
* we want to delete all of the old ones.
*/
private void deleteAllByPrefix(String prefix, File directory, String fileExtension)
{
final File[] matchingFiles = getMatchingFiles(directory, prefix, fileExtension);
for(File f : matchingFiles)
{
f.delete();
}
}
private long getFileTrashDate(File f, String extension, long trashMinutes)
{
long fileExpiration = getFileExpiration(f, extension);
long diff = 1000 * 60 * trashMinutes;
return fileExpiration + diff;
}
private long getFileExpiration(File f, String extension)
{
String expirationString = f.getName()
.replaceFirst(".*" + PREFIX_EXPIRATION_DELIMITER, "")
.replace("." + extension, "");
return Long.parseLong(expirationString);
}
private long getExpirationEpochMinutes(long minutes)
{
long diff = 1000 * 60 * minutes;
return System.currentTimeMillis() + diff;
}
private static File[] getMatchingFiles(File root, String prefix, String fileExtension) {
String regex = prefix + PREFIX_EXPIRATION_DELIMITER + ".*" + "\\." + fileExtension;
if(!root.isDirectory())
{
root.mkdir();
return new File[0];
}
final Pattern p = Pattern.compile(regex); // careful: could also throw an exception!
return root.listFiles(new FileFilter(){
@Override
public boolean accept(File file) {
return p.matcher(file.getName()).matches();
}
});
}
private static void writeSerializable(Serializable obj, File file,
WriteSerializableTask.WriteSerializableCallback cb) {
WriteSerializableTask task = new WriteSerializableTask(obj, file, cb);
Void[] voidArray = new Void[0];
task.execute(voidArray);
}
private void readSerializable(File file, ReadSerializableTask.ReadSerializableCallback cb) {
ReadSerializableTask task = new ReadSerializableTask(cb, file);
Void[] voidArray = new Void[0];
task.execute(voidArray);
}
} | src/main/java/com/carrotcreative/cream/cache/CacheManager.java | package com.carrotcreative.cream.cache;
import android.content.Context;
import com.carrotcreative.cream.tasks.ReadSerializableTask;
import com.carrotcreative.cream.tasks.WriteSerializableTask;
import java.io.File;
import java.io.FileFilter;
import java.io.Serializable;
import java.util.regex.Pattern;
public class CacheManager {
//=======================================
//============== Singleton ==============
//=======================================
private static CacheManager sInstance;
public static CacheManager getInstance(Context context){
if(sInstance == null){
sInstance = new CacheManager(context);
}
return sInstance;
}
//===================================
//============== Class ==============
//===================================
private final File mRootDir;
private final Context mContext;
private CacheManager(Context context)
{
mContext = context;
mRootDir = context.getCacheDir();
}
//============================================
//================== Cache ===================
//============================================
public void readSerializable(String directoryString, String fileExtension, String prefix, boolean regardForExpiration,
ReadSerializableTask.ReadSerializableCallback cb)
{
File directory = new File(mRootDir, directoryString);
//Finding the file
final File[] matchingFiles = getMatchingFiles(directory, prefix, fileExtension);
for(File f : matchingFiles)
{
long expiration = getFileExpiration(f, fileExtension);
//If it's not expired, or we have no regard for expiration
if(!(System.currentTimeMillis() > expiration) || !regardForExpiration) {
readSerializable(f, cb);
return;
}
}
cb.failure(null);
}
public void writeSerializable(String directoryString, long expirationMinutes, String fileExtension, String prefix, Serializable content, WriteSerializableTask.WriteSerializableCallback cb)
{
File directory = new File(mRootDir, directoryString);
long expiration = getExpirationEpochMinutes(expirationMinutes);
String fileString = prefix + "-" + expiration + "." + fileExtension;
File file = new File(directory, fileString);
deleteAllByPrefix(prefix, directory, fileExtension);
writeSerializable(content, file, cb);
}
/**
* This goes and deletes files that are expired by trashDays
*/
public void runTrashCleanup(String directoryString, String fileExtension, long trashMinutes)
{
File cleanupDir = new File(mRootDir, directoryString);
File[] allFiles = cleanupDir.listFiles();
//http://docs.oracle.com/javase/1.5.0/docs/api/java/io/File.html#listFiles%28%29
if(allFiles != null){
for(File f : allFiles)
{
if(f.toString().endsWith(fileExtension))
{
long trashDate = getFileTrashDate(f, fileExtension, trashMinutes);
if(f.isFile() && (System.currentTimeMillis() > trashDate))
{
f.delete();
}
}
}
}
}
//==============================================
//============== Helper Functions ==============
//==============================================
/**
* Only to be ran by write functions.
*
* We're writing a fresh object, so obviously
* we want to delete all of the old ones.
*/
private void deleteAllByPrefix(String prefix, File directory, String fileExtension)
{
final File[] matchingFiles = getMatchingFiles(directory, prefix, fileExtension);
for(File f : matchingFiles)
{
f.delete();
}
}
private long getFileTrashDate(File f, String extension, long trashMinutes)
{
long fileExpiration = getFileExpiration(f, extension);
long diff = 1000 * 60 * trashMinutes;
return fileExpiration + diff;
}
private long getFileExpiration(File f, String extension)
{
String expirationString = f.getName().replaceFirst(".*-", "").replace("." + extension, "");
return Long.parseLong(expirationString);
}
private long getExpirationEpochMinutes(long minutes)
{
long diff = 1000 * 60 * minutes;
return System.currentTimeMillis() + diff;
}
private static File[] getMatchingFiles(File root, String prefix, String fileExtension) {
String regex = prefix + "-.*" + "." + fileExtension;
if(!root.isDirectory()) {
root.mkdir();
return new File[0];
}
final Pattern p = Pattern.compile(regex); // careful: could also throw an exception!
return root.listFiles(new FileFilter(){
@Override
public boolean accept(File file) {
return p.matcher(file.getName()).matches();
}
});
}
private static void writeSerializable(Serializable obj, File file,
WriteSerializableTask.WriteSerializableCallback cb) {
WriteSerializableTask task = new WriteSerializableTask(obj, file, cb);
Void[] voidArray = new Void[0];
task.execute(voidArray);
}
private void readSerializable(File file, ReadSerializableTask.ReadSerializableCallback cb) {
ReadSerializableTask task = new ReadSerializableTask(cb, file);
Void[] voidArray = new Void[0];
task.execute(voidArray);
}
} | Updating file delimiter to be more specific
Was running into issues with the actual identifier was messing with
the regex splitting between the expiration + identifier.
| src/main/java/com/carrotcreative/cream/cache/CacheManager.java | Updating file delimiter to be more specific | <ide><path>rc/main/java/com/carrotcreative/cream/cache/CacheManager.java
<ide> import java.util.regex.Pattern;
<ide>
<ide> public class CacheManager {
<add>
<add> public static final String PREFIX_EXPIRATION_DELIMITER = "-CR-";
<ide>
<ide> //=======================================
<ide> //============== Singleton ==============
<ide> public void writeSerializable(String directoryString, long expirationMinutes, String fileExtension, String prefix, Serializable content, WriteSerializableTask.WriteSerializableCallback cb)
<ide> {
<ide> File directory = new File(mRootDir, directoryString);
<del>
<ide> long expiration = getExpirationEpochMinutes(expirationMinutes);
<del> String fileString = prefix + "-" + expiration + "." + fileExtension;
<add> String fileString = prefix + PREFIX_EXPIRATION_DELIMITER + expiration + "." + fileExtension;
<ide> File file = new File(directory, fileString);
<ide> deleteAllByPrefix(prefix, directory, fileExtension);
<ide> writeSerializable(content, file, cb);
<ide>
<ide> private long getFileExpiration(File f, String extension)
<ide> {
<del> String expirationString = f.getName().replaceFirst(".*-", "").replace("." + extension, "");
<add> String expirationString = f.getName()
<add> .replaceFirst(".*" + PREFIX_EXPIRATION_DELIMITER, "")
<add> .replace("." + extension, "");
<ide> return Long.parseLong(expirationString);
<ide> }
<ide>
<ide> }
<ide>
<ide> private static File[] getMatchingFiles(File root, String prefix, String fileExtension) {
<del> String regex = prefix + "-.*" + "." + fileExtension;
<del> if(!root.isDirectory()) {
<add> String regex = prefix + PREFIX_EXPIRATION_DELIMITER + ".*" + "\\." + fileExtension;
<add> if(!root.isDirectory())
<add> {
<ide> root.mkdir();
<ide> return new File[0];
<ide> } |
|
Java | apache-2.0 | error: pathspec 'xmvn-it/src/test/java/org/fedoraproject/xmvn/it/ArchiveLayoutIntegrationTest.java' did not match any file(s) known to git
| 3fb18db2b7b119fa414a48493b2d0c74d87a3865 | 1 | fedora-java/xmvn,fedora-java/xmvn,fedora-java/xmvn | /*-
* Copyright (c) 2021 Red Hat, 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.fedoraproject.xmvn.it;
import static org.junit.jupiter.api.Assertions.fail;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import org.junit.jupiter.api.Test;
/**
* Test whether binary distribution has expected layout.
*
* @author Mikolaj Izdebski
*/
public class ArchiveLayoutIntegrationTest
extends AbstractIntegrationTest
{
private static class PathExpectation
{
private final String regex;
private final Pattern pattern;
private final int lowerBound;
private final int upperBound;
private int matchCount;
public PathExpectation( int lowerBound, int upperBound, String regex )
{
this.regex = regex;
this.lowerBound = lowerBound;
this.upperBound = upperBound;
pattern = Pattern.compile( regex );
}
public boolean matches( String path )
{
if ( pattern.matcher( path ).matches() )
{
matchCount++;
return true;
}
return false;
}
public void verify( List<String> errors )
{
if ( matchCount < lowerBound || matchCount > upperBound )
{
errors.add( "Pattern " + regex + " was expected at least " + lowerBound + " and at most " + upperBound
+ " times, but was found " + matchCount + " times" );
}
}
}
private List<PathExpectation> expectations = new ArrayList<>();
private void expect( int lowerBound, int upperBound, String regex )
{
expectations.add( new PathExpectation( lowerBound, upperBound, regex ) );
}
private void matchSingleFile( Path baseDir, Path path, String dirSuffix, List<String> errors )
{
String pathStr = baseDir.relativize( path ) + dirSuffix;
if ( expectations.stream().filter( expectation -> expectation.matches( pathStr ) ).count() == 0 )
{
errors.add( "Path " + pathStr + " did not match any pattern" );
}
}
private void matchDirectoryTree( Path baseDir, Path dir, List<String> errors )
throws Exception
{
matchSingleFile( baseDir, dir, "/", errors );
try ( DirectoryStream<Path> ds = Files.newDirectoryStream( dir ) )
{
for ( Path path : ds )
{
if ( Files.isDirectory( path, LinkOption.NOFOLLOW_LINKS ) )
{
matchDirectoryTree( baseDir, path, errors );
}
else
{
matchSingleFile( baseDir, path, "", errors );
}
}
}
}
@Test
public void testArchiveLayout()
throws Exception
{
expect( 1, 1, "/" );
expect( 1, 1, "LICENSE" );
expect( 1, 1, "NOTICE" );
expect( 1, 1, "README\\.txt" );
expect( 1, 1, "NOTICE-XMVN" );
expect( 1, 1, "AUTHORS-XMVN" );
expect( 1, 1, "README-XMVN\\.md" );
expect( 1, 1, "bin/" );
expect( 1, 1, "bin/mvn" );
expect( 1, 1, "bin/mvn\\.cmd" );
expect( 1, 1, "bin/mvnDebug" );
expect( 1, 1, "bin/mvnDebug\\.cmd" );
expect( 1, 1, "bin/mvnyjp" );
expect( 1, 1, "bin/m2\\.conf" );
expect( 1, 1, "boot/" );
expect( 1, 1, "boot/plexus-classworlds-.*\\.jar" );
expect( 1, 1, "boot/plexus-classworlds.license" );
expect( 1, 1, "conf/" );
expect( 1, 1, "conf/settings\\.xml" );
expect( 1, 1, "conf/toolchains\\.xml" );
expect( 1, 1, "conf/logging/" );
expect( 1, 1, "conf/logging/simplelogger\\.properties" );
expect( 1, 1, "lib/" );
expect( 30, 60, "lib/[^/]*\\.jar" );
expect( 15, 30, "lib/[^/]*\\.license" );
expect( 10, 100, "lib/jansi-native/.*" );
expect( 1, 1, "lib/ext/" );
expect( 1, 1, "lib/ext/README\\.txt" );
expect( 1, 1, "lib/ext/xmvn-connector-.*\\.jar" );
expect( 1, 1, "lib/ext/xmvn-core-.*\\.jar" );
expect( 1, 1, "lib/ext/xmvn-api-.*\\.jar" );
expect( 1, 1, "lib/installer/" );
expect( 1, 1, "lib/installer/xmvn-install-.*\\.jar" );
expect( 1, 1, "lib/installer/xmvn-api-.*\\.jar" );
expect( 1, 1, "lib/installer/xmvn-core-.*\\.jar" );
expect( 1, 1, "lib/installer/jcommander-.*\\.jar" );
expect( 1, 1, "lib/installer/slf4j-api-.*\\.jar" );
expect( 1, 1, "lib/installer/slf4j-simple-.*\\.jar" );
expect( 1, 1, "lib/installer/asm-.*\\.jar" );
expect( 1, 1, "lib/installer/commons-compress-.*\\.jar" );
expect( 1, 1, "lib/resolver/" );
expect( 1, 1, "lib/resolver/xmvn-resolve-.*\\.jar" );
expect( 1, 1, "lib/resolver/xmvn-api-.*\\.jar" );
expect( 1, 1, "lib/resolver/xmvn-core-.*\\.jar" );
expect( 1, 1, "lib/resolver/jcommander-.*\\.jar" );
expect( 1, 1, "lib/subst/" );
expect( 1, 1, "lib/subst/xmvn-subst-.*\\.jar" );
expect( 1, 1, "lib/subst/xmvn-api-.*\\.jar" );
expect( 1, 1, "lib/subst/xmvn-core-.*\\.jar" );
expect( 1, 1, "lib/subst/jcommander-.*\\.jar" );
Path baseDir = getMavenHome();
List<String> errors = new ArrayList<>();
matchDirectoryTree( baseDir, baseDir, errors );
for ( PathExpectation expect : expectations )
{
expect.verify( errors );
}
if ( !errors.isEmpty() )
{
fail( String.join( "\n", errors ) );
}
}
}
| xmvn-it/src/test/java/org/fedoraproject/xmvn/it/ArchiveLayoutIntegrationTest.java | [it] Add test for distribution archive layout
| xmvn-it/src/test/java/org/fedoraproject/xmvn/it/ArchiveLayoutIntegrationTest.java | [it] Add test for distribution archive layout | <ide><path>mvn-it/src/test/java/org/fedoraproject/xmvn/it/ArchiveLayoutIntegrationTest.java
<add>/*-
<add> * Copyright (c) 2021 Red Hat, Inc.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>package org.fedoraproject.xmvn.it;
<add>
<add>import static org.junit.jupiter.api.Assertions.fail;
<add>
<add>import java.nio.file.DirectoryStream;
<add>import java.nio.file.Files;
<add>import java.nio.file.LinkOption;
<add>import java.nio.file.Path;
<add>import java.util.ArrayList;
<add>import java.util.List;
<add>import java.util.regex.Pattern;
<add>
<add>import org.junit.jupiter.api.Test;
<add>
<add>/**
<add> * Test whether binary distribution has expected layout.
<add> *
<add> * @author Mikolaj Izdebski
<add> */
<add>public class ArchiveLayoutIntegrationTest
<add> extends AbstractIntegrationTest
<add>{
<add> private static class PathExpectation
<add> {
<add> private final String regex;
<add>
<add> private final Pattern pattern;
<add>
<add> private final int lowerBound;
<add>
<add> private final int upperBound;
<add>
<add> private int matchCount;
<add>
<add> public PathExpectation( int lowerBound, int upperBound, String regex )
<add> {
<add> this.regex = regex;
<add> this.lowerBound = lowerBound;
<add> this.upperBound = upperBound;
<add> pattern = Pattern.compile( regex );
<add> }
<add>
<add> public boolean matches( String path )
<add> {
<add> if ( pattern.matcher( path ).matches() )
<add> {
<add> matchCount++;
<add> return true;
<add> }
<add>
<add> return false;
<add> }
<add>
<add> public void verify( List<String> errors )
<add> {
<add> if ( matchCount < lowerBound || matchCount > upperBound )
<add> {
<add> errors.add( "Pattern " + regex + " was expected at least " + lowerBound + " and at most " + upperBound
<add> + " times, but was found " + matchCount + " times" );
<add> }
<add> }
<add> }
<add>
<add> private List<PathExpectation> expectations = new ArrayList<>();
<add>
<add> private void expect( int lowerBound, int upperBound, String regex )
<add> {
<add> expectations.add( new PathExpectation( lowerBound, upperBound, regex ) );
<add> }
<add>
<add> private void matchSingleFile( Path baseDir, Path path, String dirSuffix, List<String> errors )
<add> {
<add> String pathStr = baseDir.relativize( path ) + dirSuffix;
<add>
<add> if ( expectations.stream().filter( expectation -> expectation.matches( pathStr ) ).count() == 0 )
<add> {
<add> errors.add( "Path " + pathStr + " did not match any pattern" );
<add> }
<add> }
<add>
<add> private void matchDirectoryTree( Path baseDir, Path dir, List<String> errors )
<add> throws Exception
<add> {
<add> matchSingleFile( baseDir, dir, "/", errors );
<add>
<add> try ( DirectoryStream<Path> ds = Files.newDirectoryStream( dir ) )
<add> {
<add> for ( Path path : ds )
<add> {
<add> if ( Files.isDirectory( path, LinkOption.NOFOLLOW_LINKS ) )
<add> {
<add> matchDirectoryTree( baseDir, path, errors );
<add> }
<add> else
<add> {
<add> matchSingleFile( baseDir, path, "", errors );
<add> }
<add> }
<add> }
<add> }
<add>
<add> @Test
<add> public void testArchiveLayout()
<add> throws Exception
<add> {
<add> expect( 1, 1, "/" );
<add> expect( 1, 1, "LICENSE" );
<add> expect( 1, 1, "NOTICE" );
<add> expect( 1, 1, "README\\.txt" );
<add> expect( 1, 1, "NOTICE-XMVN" );
<add> expect( 1, 1, "AUTHORS-XMVN" );
<add> expect( 1, 1, "README-XMVN\\.md" );
<add>
<add> expect( 1, 1, "bin/" );
<add> expect( 1, 1, "bin/mvn" );
<add> expect( 1, 1, "bin/mvn\\.cmd" );
<add> expect( 1, 1, "bin/mvnDebug" );
<add> expect( 1, 1, "bin/mvnDebug\\.cmd" );
<add> expect( 1, 1, "bin/mvnyjp" );
<add> expect( 1, 1, "bin/m2\\.conf" );
<add>
<add> expect( 1, 1, "boot/" );
<add> expect( 1, 1, "boot/plexus-classworlds-.*\\.jar" );
<add> expect( 1, 1, "boot/plexus-classworlds.license" );
<add>
<add> expect( 1, 1, "conf/" );
<add> expect( 1, 1, "conf/settings\\.xml" );
<add> expect( 1, 1, "conf/toolchains\\.xml" );
<add> expect( 1, 1, "conf/logging/" );
<add> expect( 1, 1, "conf/logging/simplelogger\\.properties" );
<add>
<add> expect( 1, 1, "lib/" );
<add> expect( 30, 60, "lib/[^/]*\\.jar" );
<add> expect( 15, 30, "lib/[^/]*\\.license" );
<add> expect( 10, 100, "lib/jansi-native/.*" );
<add>
<add> expect( 1, 1, "lib/ext/" );
<add> expect( 1, 1, "lib/ext/README\\.txt" );
<add> expect( 1, 1, "lib/ext/xmvn-connector-.*\\.jar" );
<add> expect( 1, 1, "lib/ext/xmvn-core-.*\\.jar" );
<add> expect( 1, 1, "lib/ext/xmvn-api-.*\\.jar" );
<add>
<add> expect( 1, 1, "lib/installer/" );
<add> expect( 1, 1, "lib/installer/xmvn-install-.*\\.jar" );
<add> expect( 1, 1, "lib/installer/xmvn-api-.*\\.jar" );
<add> expect( 1, 1, "lib/installer/xmvn-core-.*\\.jar" );
<add> expect( 1, 1, "lib/installer/jcommander-.*\\.jar" );
<add> expect( 1, 1, "lib/installer/slf4j-api-.*\\.jar" );
<add> expect( 1, 1, "lib/installer/slf4j-simple-.*\\.jar" );
<add> expect( 1, 1, "lib/installer/asm-.*\\.jar" );
<add> expect( 1, 1, "lib/installer/commons-compress-.*\\.jar" );
<add>
<add> expect( 1, 1, "lib/resolver/" );
<add> expect( 1, 1, "lib/resolver/xmvn-resolve-.*\\.jar" );
<add> expect( 1, 1, "lib/resolver/xmvn-api-.*\\.jar" );
<add> expect( 1, 1, "lib/resolver/xmvn-core-.*\\.jar" );
<add> expect( 1, 1, "lib/resolver/jcommander-.*\\.jar" );
<add>
<add> expect( 1, 1, "lib/subst/" );
<add> expect( 1, 1, "lib/subst/xmvn-subst-.*\\.jar" );
<add> expect( 1, 1, "lib/subst/xmvn-api-.*\\.jar" );
<add> expect( 1, 1, "lib/subst/xmvn-core-.*\\.jar" );
<add> expect( 1, 1, "lib/subst/jcommander-.*\\.jar" );
<add>
<add> Path baseDir = getMavenHome();
<add> List<String> errors = new ArrayList<>();
<add> matchDirectoryTree( baseDir, baseDir, errors );
<add>
<add> for ( PathExpectation expect : expectations )
<add> {
<add> expect.verify( errors );
<add> }
<add>
<add> if ( !errors.isEmpty() )
<add> {
<add> fail( String.join( "\n", errors ) );
<add> }
<add> }
<add>} |
|
Java | apache-2.0 | 7852770916bc0a53b48bb1a6e3b28453b0ef83e9 | 0 | psoreide/bnd,psoreide/bnd,psoreide/bnd | package aQute.launchpad;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.PrintStream;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.eclipse.jdt.annotation.Nullable;
import org.osgi.annotation.versioning.ProviderType;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleException;
import org.osgi.framework.Constants;
import org.osgi.framework.Filter;
import org.osgi.framework.FrameworkEvent;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceEvent;
import org.osgi.framework.ServiceException;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
import org.osgi.framework.hooks.service.EventListenerHook;
import org.osgi.framework.hooks.service.FindHook;
import org.osgi.framework.hooks.service.ListenerHook.ListenerInfo;
import org.osgi.framework.launch.Framework;
import org.osgi.framework.namespace.PackageNamespace;
import org.osgi.framework.wiring.BundleCapability;
import org.osgi.framework.wiring.BundleWiring;
import org.osgi.framework.wiring.FrameworkWiring;
import org.osgi.util.tracker.ServiceTracker;
import aQute.bnd.service.specifications.RunSpecification;
import aQute.lib.converter.Converter;
import aQute.lib.exceptions.Exceptions;
import aQute.lib.inject.Injector;
import aQute.lib.io.IO;
import aQute.lib.strings.Strings;
import aQute.libg.glob.Glob;
import aQute.libg.parameters.ParameterMap;
/**
* This class provides an OSGi framework that is configured with the current bnd
* workspace. A project directory is used to find the workspace. This makes all
* repositories in the workspace available to the framework. To be able to test
* JUnit code against/in this framework it is necessary that all packages on the
* buildpath and testpath are actually exported in the framework. This class
* will ensure that. Once the framework is up and running it will be possible to
* add bundles to it. There are a number of ways that this can be achieved:
* <ul>
* <li>Build a bundle – A bnd Builder is provided to create a bundle and install
* it. This makes it possible to add classes from the src or test directories or
* resources. See {@link #bundle()}. Convenience methods are added to get
* services, see {@link #getService(Class)} et. al. Notice that this framework
* starts in the same process as that the JUnit code runs. This is normally a
* separately started VM.
*/
@ProviderType
public class Launchpad implements AutoCloseable {
public static final String BUNDLE_PRIORITY = "Bundle-Priority";
private static final long SERVICE_DEFAULT_TIMEOUT = 60000L;
static final AtomicInteger n = new AtomicInteger();
final File projectDir;
final Framework framework;
final List<ServiceTracker<?, ?>> trackers = new ArrayList<>();
final List<FrameworkEvent> frameworkEvents = new CopyOnWriteArrayList<FrameworkEvent>();
final Injector<Service> injector;
final Map<Class<?>, ServiceTracker<?, ?>> injectedDoNotClose = new HashMap<>();
final Set<String> frameworkExports;
final List<String> errors = new ArrayList<>();
final String name;
final String className;
final RunSpecification runspec;
final boolean hasTestBundle;
Bundle testbundle;
boolean debug;
PrintStream out = System.err;
ServiceTracker<FindHook, FindHook> hooks;
private long closeTimeout;
Launchpad(Framework framework, String name, String className,
RunSpecification runspec, long closeTimeout, boolean debug, boolean hasTestBundle) {
this.runspec = runspec;
this.closeTimeout = closeTimeout;
this.hasTestBundle = hasTestBundle;
try {
this.className = className;
this.name = name;
this.projectDir = IO.work;
this.debug = debug;
this.framework = framework;
this.framework.init();
this.injector = new Injector<>(makeConverter(), this::getService, Service.class);
this.frameworkExports = getExports(framework).keySet();
report("Initialized framework %s", this.framework);
report("Classpath %s", System.getProperty("java.class.path")
.replace(File.pathSeparatorChar, '\n'));
framework.getBundleContext()
.addFrameworkListener(frameworkEvents::add);
hooks = new ServiceTracker<FindHook, FindHook>(framework.getBundleContext(), FindHook.class, null);
hooks.open();
} catch (Exception e) {
throw Exceptions.duck(e);
}
}
public void report(String format, Object... args) {
if (!debug)
return;
out.printf(format + "%n", args);
}
/**
* Generate an error so that the test case can check if we found anything
* wrong. This is easy to check with {@link #check(String...)}
*
* @param format the format string used in
* {@link String#format(String, Object...)}
* @param args the arguments to be formatted
*/
public void error(String format, Object... args) {
report(format, args);
String msg = String.format(format, args);
errors.add(msg);
}
/**
* Check the errors found, filtering out any unwanted with globbing patters.
* Each error is filtered against all the patterns. This method return true
* if there are no unfiltered errors, otherwise false.
*
* @param patterns globbing patterns
* @return true if no errors after filtering,otherwise false
*/
public boolean check(String... patterns) {
Glob[] globs = Stream.of(patterns)
.map(Glob::new)
.toArray(Glob[]::new);
boolean[] used = new boolean[globs.length];
String[] unmatched = errors.stream()
.filter(msg -> {
for (int i = 0; i < globs.length; i++) {
if (globs[i].finds(msg) >= 0) {
used[i] = true;
return false;
}
}
return true;
})
.toArray(String[]::new);
if (unmatched.length == 0) {
List<Glob> report = new ArrayList<>();
for (int i = 0; i < used.length; i++) {
if (!used[i]) {
report.add(globs[i]);
}
}
if (report.isEmpty())
return true;
out.println("Missing patterns");
out.println(Strings.join("\n", globs));
return false;
}
out.println("Errors");
out.println(Strings.join("\n", unmatched));
return false;
}
/**
* Add a file as a bundle to the framework. This bundle will not be started.
*
* @param f the file to install
* @return the bundle object
*/
public Bundle bundle(File f) {
try {
report("Installing %s", f);
return framework.getBundleContext()
.installBundle(toInstallURI(f));
} catch (Exception e) {
report("Failed to installing %s : %s", f, e);
throw Exceptions.duck(e);
}
}
/**
* Set the debug flag
*/
public Launchpad debug() {
this.debug = true;
return this;
}
/**
* Install a number of bundles based on their bundle specification. A bundle
* specification is the format used in for example -runbundles.
*
* @param specification the bundle specifications
* @return a list of bundles
*/
public List<Bundle> bundles(String specification) {
try {
return LaunchpadBuilder.workspace.getLatestBundles(projectDir.getAbsolutePath(), specification)
.stream()
.map(File::new)
.map(this::bundle)
.collect(Collectors.toList());
} catch (Exception e) {
throw Exceptions.duck(e);
}
}
/**
* Install a number of bundles
*
* @param runbundles the list of bundles
* @return a list of bundle objects
*/
public List<Bundle> bundles(File... runbundles) {
if (runbundles == null || runbundles.length == 0)
return Collections.emptyList();
try {
List<Bundle> bundles = new ArrayList<>();
for (File f : runbundles) {
Bundle b = bundle(f);
bundles.add(b);
}
return bundles;
} catch (Exception e) {
throw Exceptions.duck(e);
}
}
/**
* Start a bundle
*
* @param b the bundle object
*/
public void start(Bundle b) {
try {
if (!isFragment(b)) {
report("Starting %s", b);
b.start();
Set<String> exports = getExports(b).keySet();
Set<String> imports = getImports(b).keySet();
exports.removeAll(imports);
exports.retainAll(frameworkExports);
if (!exports.isEmpty()) {
error(
"bundle %s is exporting but NOT importing package(s) %s that are/is also exported by the framework.\n"
+ "This means that the test code and the bundle cannot share classes of these package.",
b, exports);
}
} else {
report("Not starting fragment %s", b);
}
} catch (Exception e) {
report("Failed to start %s : %s", b, e);
throw Exceptions.duck(e);
}
}
/**
* Start all bundles
*
* @param bs a collection of bundles
*/
public void start(Collection<Bundle> bs) {
bs.forEach(this::start);
}
/**
* Close this framework
*/
@Override
public void close() throws Exception {
report("Stop the framework");
framework.stop();
report("Stopped the framework");
framework.waitForStop(closeTimeout);
report("Framework fully stopped");
}
/**
* Get the Bundle Context. If a test bundle was installed then this is the
* context of the test bundle otherwise it is the context of the framework.
* To be able to proxy services it is necessary to have a test bundle
* installed.
*
* @return the bundle context of the test bundle or the framework
*/
public BundleContext getBundleContext() {
if (testbundle != null)
return testbundle.getBundleContext();
return framework.getBundleContext();
}
/**
* Get a service registered under class. If multiple services are registered
* it will return the first
*
* @param serviceInterface the name of the service
* @return a service
*/
public <T> Optional<T> getService(Class<T> serviceInterface) {
return getService(serviceInterface, null);
}
public <T> Optional<T> getService(Class<T> serviceInterface, @Nullable String target) {
return getServices(serviceInterface, target, 0, 0, false).stream()
.map(this::getService)
.findFirst();
}
/**
* Get a list of services of a given name
*
* @param serviceClass the service name
* @return a list of services
*/
public <T> List<T> getServices(Class<T> serviceClass) {
return getServices(serviceClass, null);
}
/**
* Get a list of services in the current registry
*
* @param serviceClass the type of the service
* @param target the target, may be null
* @return a list of found services currently in the registry
*/
public <T> List<T> getServices(Class<T> serviceClass, @Nullable String target) {
return getServices(serviceClass, target, 0, 0, false).stream()
.map(this::getService)
.collect(Collectors.toList());
}
/**
* Get a service from a reference. If the service is null, then throw an
* exception.
*
* @param ref the reference
* @return the service, never null
*/
public <T> T getService(ServiceReference<T> ref) {
try {
T service = getBundleContext().getService(ref);
if (service == null) {
if (ref.getBundle() == null) {
throw new ServiceException(
"getService(" + ref + ") returns null, the service is no longer registered");
}
throw new ServiceException("getService(" + ref + ") returns null, this probbaly means the \n"
+ "component failed to activate. The cause can \n" + "generally be found in the log.\n" + "");
}
return service;
} catch (Exception e) {
throw Exceptions.duck(e);
}
}
/**
* Add the standard Gogo bundles
*/
public Launchpad gogo() {
try {
bundles("org.apache.felix.gogo.runtime,org.apache.felix.gogo.command,org.apache.felix.gogo.shell");
return this;
} catch (Exception e) {
throw Exceptions.duck(e);
}
}
/**
* Add the standard Gogo bundles
*/
public Launchpad snapshot() {
try {
bundles("biz.aQute.bnd.runtime.snapshot");
return this;
} catch (Exception e) {
throw Exceptions.duck(e);
}
}
/**
* Inject an object with services and other OSGi specific values.
*
* @param object the object to inject
*/
public Launchpad inject(Object object) {
try {
injector.inject(object);
return this;
} catch (Exception e) {
throw Exceptions.duck(e);
}
}
/**
* Install a bundle from a file
*
* @param file the file to install
* @return a bundle
*/
public Bundle install(File file) {
try {
report("Installing %s", file);
return framework.getBundleContext()
.installBundle(toInstallURI(file));
} catch (BundleException e) {
report("Failed to install %s : %s", file, e);
throw Exceptions.duck(e);
}
}
/**
* Create a new synthetic bundle.
*
* @return the bundle builder
*/
public BundleBuilder bundle() {
return new BundleBuilder(this);
}
/**
* Create a new object and inject it.
*
* @param type the type of object
* @return a new object injected and all
*/
public <T> T newInstance(Class<T> type) {
try {
return injector.newInstance(type);
} catch (Exception e) {
report("Failed to create and instance for %s : %s", type, e);
throw Exceptions.duck(e);
}
}
/**
* Show the information of how the framework is setup and is running
*/
public Launchpad report() throws InvalidSyntaxException {
boolean old = debug;
debug = true;
reportBundles();
reportServices();
reportEvents();
debug = old;
return this;
}
/**
* Show the installed bundles
*/
public void reportBundles() {
Stream.of(framework.getBundleContext()
.getBundles())
.forEach(bb -> {
report("%4s %s", bundleStateToString(bb.getState()), bb);
});
}
/**
* Show the registered service
*/
public void reportServices() throws InvalidSyntaxException {
Stream.of(framework.getBundleContext()
.getAllServiceReferences(null, null))
.forEach(sref -> {
report("%s", sref);
});
}
/**
* Wait for a Service Reference to be registered
*
* @param class1 the name of the service
* @param timeoutInMs the time to wait
* @return a service reference
*/
public <T> Optional<ServiceReference<T>> waitForServiceReference(Class<T> class1, long timeoutInMs) {
return getServices(class1, null, 1, timeoutInMs, false).stream()
.findFirst();
}
/**
* Wait for a Service Reference to be registered
*
* @param class1 the name of the service
* @param timeoutInMs the time to wait
* @return a service reference
*/
public <T> Optional<ServiceReference<T>> waitForServiceReference(Class<T> class1, long timeoutInMs, String target) {
return getServices(class1, target, 1, timeoutInMs, false).stream()
.findFirst();
}
/**
* Wait for service to be registered
*
* @param class1 name of the service
* @param timeoutInMs timeout in ms
* @return a service
*/
public <T> Optional<T> waitForService(Class<T> class1, long timeoutInMs) {
return this.waitForService(class1, timeoutInMs, null);
}
/**
* Wait for service to be registered
*
* @param class1 name of the service
* @param timeoutInMs timeout in ms
* @param target filter, may be null
* @return a service
*/
public <T> Optional<T> waitForService(Class<T> class1, long timeoutInMs, String target) {
try {
return getServices(class1, target, 1, timeoutInMs, false).stream()
.findFirst()
.map(getBundleContext()::getService);
} catch (Exception e) {
throw Exceptions.duck(e);
}
}
/**
* Turn a service reference's properties into a Map
*
* @param reference the reference
* @return a Map with all the properties of the reference
*/
public Map<String, Object> toMap(ServiceReference<?> reference) {
Map<String, Object> map = new HashMap<>();
for (String key : reference.getPropertyKeys()) {
map.put(key, reference.getProperty(key));
}
return map;
}
/**
* Get a bundle by symbolic name
*/
public Optional<Bundle> getBundle(String bsn) {
return Stream.of(getBundleContext().getBundles())
.filter(b -> bsn.equals(b.getSymbolicName()))
.findFirst();
}
/**
* Broadcast a message to many services at once
*/
@SuppressWarnings("unchecked")
public <T> int broadcast(Class<T> type, Consumer<T> consumer) {
ServiceTracker<T, T> tracker = new ServiceTracker<>(getBundleContext(), type, null);
tracker.open();
int n = 0;
try {
for (T instance : (T[]) tracker.getServices()) {
consumer.accept(instance);
n++;
}
} finally {
tracker.close();
}
return n;
}
/**
* Hide a service by registering a hook. This should in general be done
* before you let others look. In general, the Launchpad should be started
* in {@link LaunchpadBuilder#nostart()} mode. This initializes the OSGi
* framework making it possible to register a service before
*/
public Closeable hide(Class<?> type) {
return hide(type, "hide");
}
/**
* Hide a service. This will register a FindHook and an EventHook for the
* type. This will remove the visibility of all services with that type for
* all bundles _except_ the testbundle. Notice that bundles that already
* obtained a references are not affected. If you use this facility it is
* best to not start the framework before you hide a service. You can
* indicate this to the build with {@link LaunchpadBuilder#nostart()}. The
* framework can be started after creation with {@link #start()}. Notice
* that services through the testbundle remain visible for this hide.
*
* @param type the type to hide
* @param reason the reason why it is hidden
* @return a Closeable, when closed it will remove the hooks
*/
public Closeable hide(Class<?> type, String reason) {
ServiceRegistration<EventListenerHook> eventReg = framework.getBundleContext()
.registerService(EventListenerHook.class, new EventListenerHook() {
@Override
public void event(ServiceEvent event, Map<BundleContext, Collection<ListenerInfo>> listeners) {
ServiceReference<?> ref = event.getServiceReference();
if (selectForHiding(type, ref))
listeners.clear();
}
@Override
public String toString() {
return "Launchpad[" + reason + "]";
}
}, null);
ServiceRegistration<FindHook> findReg = framework.getBundleContext()
.registerService(FindHook.class, new FindHook() {
@Override
public void find(BundleContext context, String name, String filter, boolean allServices,
Collection<ServiceReference<?>> references) {
if (name == null || name.equals(type.getName())) {
references.removeIf(ref -> selectForHiding(type, ref));
}
}
@Override
public String toString() {
return "Launchpad[" + reason + "]";
}
}, null);
return () -> {
eventReg.unregister();
findReg.unregister();
};
}
/**
* Check of a service reference has one of the given types in its object
* class
*
* @param serviceReference the service reference to check
* @param types the set of types
* @return true if one of the types name is in the service reference's
* objectClass property
*/
public boolean isOneOfType(ServiceReference<?> serviceReference, Class<?>... types) {
String[] objectClasses = (String[]) serviceReference.getProperty(Constants.OBJECTCLASS);
for (Class<?> type : types) {
String name = type.getName();
for (String objectClass : objectClasses) {
if (objectClass.equals(name))
return true;
}
}
return false;
}
private boolean selectForHiding(Class<?> type, ServiceReference<?> ref) {
//
// We never hide services registered by the testbundle
//
if (ref.getBundle() == testbundle)
return false;
// only hide references when one of their
// service interfaces is of the hidden type
return isOneOfType(ref, type);
}
/**
* Start the framework if not yet started
*/
public void start() {
try {
framework.start();
List<Bundle> toBeStarted = new ArrayList<>();
for (String path : runspec.runbundles) {
File file = new File(path);
if (!file.isFile())
throw new IllegalArgumentException("-runbundle " + file + " does not exist or is not a file");
Bundle b = install(file);
if (!isFragment(b)) {
toBeStarted.add(b);
}
}
FrameworkWiring fw = framework.adapt(FrameworkWiring.class);
fw.resolveBundles(toBeStarted);
Collections.sort(toBeStarted, this::startorder);
if (hasTestBundle)
testbundle();
toBeStarted.forEach(this::start);
} catch (BundleException e) {
throw Exceptions.duck(e);
}
}
// reverse ordering. I.e. highest priority is first
int startorder(Bundle a, Bundle b) {
return Integer.compare(getPriority(b), getPriority(a));
}
private int getPriority(Bundle b) {
try {
String h = b.getHeaders()
.get(BUNDLE_PRIORITY);
if (h != null)
return Integer.parseInt(h);
} catch (Exception e) {
// ignore
}
return 0;
}
/**
* Stop the framework if not yet stopped
*/
public void stop() {
try {
report("Stopping the framework");
framework.stop();
} catch (BundleException e) {
report("Could not stop the framework : %s", e);
throw Exceptions.duck(e);
}
}
/**
* Set the test bundle
*/
public void testbundle() {
if (testbundle != null) {
throw new IllegalArgumentException("Test bundle already exists");
}
try {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
Manifest man = new Manifest();
man.getMainAttributes()
.putValue("Manifest-Version", "1");
String name = projectDir.getName()
.toUpperCase();
report("Creating test bundle %s", name);
man.getMainAttributes()
.putValue(Constants.BUNDLE_SYMBOLICNAME, name);
man.getMainAttributes()
.putValue(Constants.BUNDLE_MANIFESTVERSION, "2");
JarOutputStream jout = new JarOutputStream(bout, man);
jout.close();
ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
this.testbundle = framework.getBundleContext()
.installBundle(name, bin);
this.testbundle.start();
} catch (Exception e) {
report("Failed to create test bundle");
throw Exceptions.duck(e);
}
}
/**
* Register a service. You can specify the type and the instance as well as
* the properties. The properties are specified as varargs. That means you
* can define a property by specifying the key (which must be a String) and
* the value consecutively. The value can be any of the types allowed by the
* service properties.
*
* <pre>
* fw.register(Foo.class, instance, "foo", 10, "bar", new long[] {
* 1, 2, 3
* });
* </pre>
*
* @param type the service type
* @param instance the service object
* @param props the service properties specified as a seq of "key", value
* @return the service registration
*/
public <T> ServiceRegistration<T> register(Class<T> type, T instance, Object... props) {
report("Registering service %s %s", type, instance, Arrays.toString(props));
Hashtable<String, Object> ht = new Hashtable<>();
for (int i = 0; i < props.length; i += 2) {
String key = (String) props[i];
Object value = null;
if (i + 1 < props.length) {
value = props[i + 1];
}
ht.put(key, value);
}
return getBundleContext().registerService(type, instance, ht);
}
/**
* Return the framework object
*
* @return the framework object
*/
public Framework getFramework() {
return framework;
}
/**
* Add a component class. This creates a little bundle that holds the
* component class so that bnd adds the DS XML. However, it also imports the
* package of the component class so that in runtime DS will load it from
* the classpath.
*/
public <T> Bundle component(Class<T> type) {
return bundle().addResource(type)
.start();
}
/**
* Runs the given code within the context of a synthetic bundle. Creates a
* synthetic bundle and adds the supplied class to it using
* {@link BundleBuilder#addResourceWithCopy}. It then loads the class using
* the synthetic bundle's class loader and instantiates it using the public,
* no-parameter constructor.
*
* @param clazz the class to instantiate within the context of the
* framework.
* @return The instantiated object.
* @see BundleBuilder#addResourceWithCopy(Class)
*/
public <T> T instantiateInFramework(Class<? extends T> clazz) {
try {
clazz.getConstructor();
} catch (NoSuchMethodException e) {
Exceptions.duck(e);
}
Bundle b = bundle().addResourceWithCopy(clazz)
.start();
try {
@SuppressWarnings("unchecked")
Class<? extends T> insideClass = (Class<? extends T>) b.loadClass(clazz.getName());
return insideClass.getConstructor()
.newInstance();
} catch (Exception e) {
throw Exceptions.duck(e);
}
}
/**
* Check if a bundle is a fragement
*
* @param b the bundle to check
*/
public boolean isFragment(Bundle b) {
return b.getHeaders()
.get(Constants.FRAGMENT_HOST) != null;
}
/**
* Check if a bundle is in the ACTIVE state
*
* @param b the bundle to check
*/
public boolean isActive(Bundle b) {
return b.getState() == Bundle.ACTIVE;
}
/**
* Check if a bundle is in the RESOLVED state
*
* @param b the bundle to check
*/
public boolean isResolved(Bundle b) {
return b.getState() == Bundle.RESOLVED;
}
/**
* Check if a bundle is in the INSTALLED state
*
* @param b the bundle to check
*/
public boolean isInstalled(Bundle b) {
return b.getState() == Bundle.INSTALLED;
}
/**
* Check if a bundle is in the UNINSTALLED state
*
* @param b the bundle to check
*/
public boolean isUninstalled(Bundle b) {
return b.getState() == Bundle.UNINSTALLED;
}
/**
* Check if a bundle is in the STARTING state
*
* @param b the bundle to check
*/
public boolean isStarting(Bundle b) {
return b.getState() == Bundle.STARTING;
}
/**
* Check if a bundle is in the STOPPING state
*
* @param b the bundle to check
*/
public boolean isStopping(Bundle b) {
return b.getState() == Bundle.STOPPING;
}
/**
* Check if a bundle is in the ACTIVE or STARTING state
*
* @param b the bundle to check
*/
public boolean isRunning(Bundle b) {
return isActive(b) || isStarting(b);
}
/**
* Check if a bundle is in the RESOLVED or ACTIVE or STARTING state
*
* @param b the bundle to check
*/
public boolean isReady(Bundle b) {
return isResolved(b) || isActive(b) || isStarting(b);
}
private ParameterMap getExports(Bundle b) {
return new ParameterMap(b.getHeaders()
.get(Constants.EXPORT_PACKAGE));
}
private ParameterMap getImports(Bundle b) {
return new ParameterMap(b.getHeaders()
.get(Constants.IMPORT_PACKAGE));
}
private String toInstallURI(File c) {
return "reference:" + c.toURI();
}
Object getService(Injector.Target<Service> param) {
try {
if (param.type == BundleContext.class) {
return getBundleContext();
}
if (param.type == Bundle.class)
return testbundle;
if (param.type == Framework.class) {
return framework;
}
if (param.type == Bundle[].class) {
return framework.getBundleContext()
.getBundles();
}
Service service = param.annotation;
String target = service.target()
.isEmpty() ? null : service.target();
Class<?> serviceClass = service.service();
if (serviceClass == Object.class)
serviceClass = getServiceType(param.type);
if (serviceClass == null)
serviceClass = getServiceType(param.primaryType);
if (serviceClass == null)
throw new IllegalArgumentException("Cannot define service class for " + param);
long timeout = service.timeout();
if (timeout <= 0)
timeout = SERVICE_DEFAULT_TIMEOUT;
boolean multiple = isMultiple(param.type);
int cardinality = multiple ? service.minimum() : 1;
List<? extends ServiceReference<?>> matchedReferences = getServices(serviceClass, target, cardinality,
timeout, true);
if (multiple)
return matchedReferences;
else
return matchedReferences.get(0);
} catch (Exception e) {
throw Exceptions.duck(e);
}
}
@SuppressWarnings({
"rawtypes", "unchecked"
})
public <T> List<ServiceReference<T>> getServices(Class<T> serviceClass, @Nullable String target, int cardinality,
long timeout, boolean exception) {
try {
String className = serviceClass.getName();
ServiceTracker<?, ?> tracker = injectedDoNotClose.computeIfAbsent(serviceClass, (c) -> {
ServiceTracker<?, ?> t = new ServiceTracker<Object, Object>(framework.getBundleContext(), className,
null);
t.open(true);
return t;
});
long deadline = System.currentTimeMillis() + timeout;
while (true) {
// we get the ALL services regardless of class space or hidden
// by hooks or filters.
@SuppressWarnings("unchecked")
List<ServiceReference<T>> allReferences = (List<ServiceReference<T>>) getReferences(tracker,
serviceClass);
List<ServiceReference<T>> visibleReferences = allReferences.stream()
.filter(ref -> ref.isAssignableTo(framework, className))
.collect(Collectors.toList());
List<ServiceReference<T>> unhiddenReferences = new ArrayList<>(visibleReferences);
Map<ServiceReference<T>, FindHook> hookMap = new HashMap<>();
for (FindHook hook : this.hooks.getServices(new FindHook[0])) {
List<ServiceReference<T>> original = new ArrayList<>(unhiddenReferences);
hook.find(testbundle.getBundleContext(), className, target, true, (Collection) unhiddenReferences);
original.removeAll(unhiddenReferences);
for (ServiceReference<T> ref : original) {
hookMap.put(ref, hook);
}
}
List<ServiceReference<T>> matchedReferences;
if (target == null) {
matchedReferences = new ArrayList<>(unhiddenReferences);
} else {
Filter filter = framework.getBundleContext()
.createFilter(target);
matchedReferences = visibleReferences.stream()
.filter(filter::match)
.collect(Collectors.toList());
}
if (cardinality <= matchedReferences.size()) {
return matchedReferences;
}
if (deadline < System.currentTimeMillis()) {
String error = "Injection of service " + className;
if (target != null)
error += " with target " + target;
error += " failed.";
if (allReferences.size() > visibleReferences.size()) {
List<ServiceReference<?>> invisibleReferences = new ArrayList<>(allReferences);
invisibleReferences.removeAll(visibleReferences);
for (ServiceReference<?> r : invisibleReferences) {
error += "\nInvisible reference " + r + "[" + r.getProperty(Constants.SERVICE_ID)
+ "] from bundle " + r.getBundle();
String[] objectClass = (String[]) r.getProperty(Constants.OBJECTCLASS);
for (String clazz : objectClass) {
error += "\n " + clazz + "\n registrar: "
+ getSource(clazz, r.getBundle()).orElse("null") + "\n framework: "
+ getSource(clazz, framework).orElse("null");
}
}
}
if (visibleReferences.size() > unhiddenReferences.size()) {
List<ServiceReference<?>> hiddenReferences = new ArrayList<>(visibleReferences);
hiddenReferences.removeAll(unhiddenReferences);
for (ServiceReference<?> r : hiddenReferences) {
error += "\nHidden (FindHook) Reference " + r + " from bundle " + r.getBundle() + " hook "
+ hookMap.get(r);
}
}
if (unhiddenReferences.size() > matchedReferences.size()) {
List<ServiceReference<?>> untargetReferences = new ArrayList<>(unhiddenReferences);
untargetReferences.removeAll(matchedReferences);
error += "\nReference not matched by the target filter " + target;
for (ServiceReference<?> ref : untargetReferences) {
error += "\n " + ref + " : " + getProperties(ref);
}
}
if (exception)
throw new TimeoutException(error);
return Collections.emptyList();
}
Thread.sleep(100);
}
} catch (Exception e) {
throw Exceptions.duck(e);
}
}
private Map<String, String> getProperties(ServiceReference<?> ref) {
Map<String, String> map = new HashMap<>();
for (String k : ref.getPropertyKeys()) {
Object property = ref.getProperty(k);
String s;
if (property != null && property.getClass()
.isArray()) {
s = Arrays.deepToString((Object[]) property);
} else
s = property + "";
map.put(k, s);
}
return map;
}
private Optional<String> getSource(String className, Bundle from) {
try {
Class<?> loadClass = from.loadClass(className);
Bundle bundle = FrameworkUtil.getBundle(loadClass);
if (bundle == null)
return Optional.of("from class path");
else {
BundleWiring wiring = bundle.adapt(BundleWiring.class);
String exported = "PRIVATE! ";
List<BundleCapability> capabilities = wiring.getCapabilities(PackageNamespace.PACKAGE_NAMESPACE);
String packageName = loadClass.getPackage()
.getName();
for (BundleCapability c : capabilities) {
if (packageName.equals(c.getAttributes()
.get(PackageNamespace.PACKAGE_NAMESPACE))) {
exported = "Exported from ";
}
}
return Optional.of(exported + " " + bundle.toString());
}
} catch (Exception e) {
return Optional.empty();
}
}
void reportEvents() {
frameworkEvents.forEach(fe -> {
report("%s", fe);
});
}
private String bundleStateToString(int state) {
switch (state) {
case Bundle.UNINSTALLED :
return "UNIN";
case Bundle.INSTALLED :
return "INST";
case Bundle.RESOLVED :
return "RSLV";
case Bundle.STARTING :
return "STAR";
case Bundle.ACTIVE :
return "ACTV";
case Bundle.STOPPING :
return "STOP";
default :
return "UNKN";
}
}
private List<? extends ServiceReference<?>> getReferences(ServiceTracker<?, ?> tracker, Class<?> serviceClass) {
ServiceReference<?>[] references = tracker.getServiceReferences();
if (references == null) {
return Collections.emptyList();
}
Arrays.sort(references);
return Arrays.asList(references);
}
private Class<?> getServiceType(Type type) {
if (type instanceof Class)
return (Class<?>) type;
if (type instanceof ParameterizedType) {
Type rawType = ((ParameterizedType) type).getRawType();
if (rawType instanceof Class) {
Class<?> rawClass = (Class<?>) rawType;
if (Iterable.class.isAssignableFrom(rawClass)) {
return getServiceType(((ParameterizedType) type).getActualTypeArguments()[0]);
}
if (Optional.class.isAssignableFrom(rawClass)) {
return getServiceType(((ParameterizedType) type).getActualTypeArguments()[0]);
}
if (ServiceReference.class.isAssignableFrom(rawClass)) {
return getServiceType(((ParameterizedType) type).getActualTypeArguments()[0]);
}
}
}
return null;
}
private boolean isMultiple(Type type) {
if (type instanceof Class) {
return ((Class<?>) type).isArray();
}
if (type instanceof ParameterizedType) {
Type rawType = ((ParameterizedType) type).getRawType();
if (rawType instanceof Class) {
Class<?> clazz = (Class<?>) rawType;
if (Iterable.class.isAssignableFrom(clazz))
return true;
}
}
return false;
}
private boolean isParameterizedType(Type to, Class<?> clazz) {
if (to instanceof ParameterizedType) {
if (((ParameterizedType) to).getRawType() == clazz)
return true;
}
return false;
}
private Converter makeConverter() {
Converter converter = new Converter();
converter.hook(null, (to, from) -> {
try {
if (!(from instanceof ServiceReference))
return null;
ServiceReference<?> reference = (ServiceReference<?>) from;
if (isParameterizedType(to, ServiceReference.class))
return reference;
if (isParameterizedType(to, Map.class))
return converter.convert(to, toMap(reference));
Object service = getService(reference);
if (isParameterizedType(to, Optional.class))
return Optional.ofNullable(service);
return service;
} catch (Exception e) {
throw e;
}
});
return converter;
}
public String getName() {
return name;
}
public String getClassName() {
return className;
}
}
| biz.aQute.launchpad/src/aQute/launchpad/Launchpad.java | package aQute.launchpad;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.PrintStream;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.eclipse.jdt.annotation.Nullable;
import org.osgi.annotation.versioning.ProviderType;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleException;
import org.osgi.framework.Constants;
import org.osgi.framework.Filter;
import org.osgi.framework.FrameworkEvent;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceEvent;
import org.osgi.framework.ServiceException;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
import org.osgi.framework.hooks.service.EventListenerHook;
import org.osgi.framework.hooks.service.FindHook;
import org.osgi.framework.hooks.service.ListenerHook.ListenerInfo;
import org.osgi.framework.launch.Framework;
import org.osgi.framework.namespace.PackageNamespace;
import org.osgi.framework.wiring.BundleCapability;
import org.osgi.framework.wiring.BundleWiring;
import org.osgi.framework.wiring.FrameworkWiring;
import org.osgi.util.tracker.ServiceTracker;
import aQute.bnd.service.specifications.RunSpecification;
import aQute.lib.converter.Converter;
import aQute.lib.exceptions.Exceptions;
import aQute.lib.inject.Injector;
import aQute.lib.io.IO;
import aQute.lib.strings.Strings;
import aQute.libg.glob.Glob;
import aQute.libg.parameters.ParameterMap;
/**
* This class provides an OSGi framework that is configured with the current bnd
* workspace. A project directory is used to find the workspace. This makes all
* repositories in the workspace available to the framework. To be able to test
* JUnit code against/in this framework it is necessary that all packages on the
* buildpath and testpath are actually exported in the framework. This class
* will ensure that. Once the framework is up and running it will be possible to
* add bundles to it. There are a number of ways that this can be achieved:
* <ul>
* <li>Build a bundle – A bnd Builder is provided to create a bundle and install
* it. This makes it possible to add classes from the src or test directories or
* resources. See {@link #bundle()}. Convenience methods are added to get
* services, see {@link #getService(Class)} et. al. Notice that this framework
* starts in the same process as that the JUnit code runs. This is normally a
* separately started VM.
*/
@ProviderType
public class Launchpad implements AutoCloseable {
public static final String BUNDLE_PRIORITY = "Bundle-Priority";
private static final long SERVICE_DEFAULT_TIMEOUT = 60000L;
static final AtomicInteger n = new AtomicInteger();
final File projectDir;
final Framework framework;
final List<ServiceTracker<?, ?>> trackers = new ArrayList<>();
final List<FrameworkEvent> frameworkEvents = new CopyOnWriteArrayList<FrameworkEvent>();
final Injector<Service> injector;
final Map<Class<?>, ServiceTracker<?, ?>> injectedDoNotClose = new HashMap<>();
final Set<String> frameworkExports;
final List<String> errors = new ArrayList<>();
final String name;
final String className;
final RunSpecification runspec;
final boolean hasTestBundle;
Bundle testbundle;
boolean debug;
PrintStream out = System.err;
ServiceTracker<FindHook, FindHook> hooks;
private long closeTimeout;
Launchpad(Framework framework, String name, String className,
RunSpecification runspec, long closeTimeout, boolean debug, boolean hasTestBundle) {
this.runspec = runspec;
this.closeTimeout = closeTimeout;
this.hasTestBundle = hasTestBundle;
try {
this.className = className;
this.name = name;
this.projectDir = IO.work;
this.debug = debug;
this.framework = framework;
this.framework.init();
this.injector = new Injector<>(makeConverter(), this::getService, Service.class);
this.frameworkExports = getExports(framework).keySet();
report("Initialized framework %s", this.framework);
report("Classpath %s", System.getProperty("java.class.path")
.replace(File.pathSeparatorChar, '\n'));
framework.getBundleContext()
.addFrameworkListener(frameworkEvents::add);
hooks = new ServiceTracker<FindHook, FindHook>(framework.getBundleContext(), FindHook.class, null);
hooks.open();
} catch (Exception e) {
throw Exceptions.duck(e);
}
}
public void report(String format, Object... args) {
if (!debug)
return;
out.printf(format + "%n", args);
}
/**
* Generate an error so that the test case can check if we found anything
* wrong. This is easy to check with {@link #check(String...)}
*
* @param format the format string used in
* {@link String#format(String, Object...)}
* @param args the arguments to be formatted
*/
public void error(String format, Object... args) {
report(format, args);
String msg = String.format(format, args);
errors.add(msg);
}
/**
* Check the errors found, filtering out any unwanted with globbing patters.
* Each error is filtered against all the patterns. This method return true
* if there are no unfiltered errors, otherwise false.
*
* @param patterns globbing patterns
* @return true if no errors after filtering,otherwise false
*/
public boolean check(String... patterns) {
Glob[] globs = Stream.of(patterns)
.map(Glob::new)
.toArray(Glob[]::new);
boolean[] used = new boolean[globs.length];
String[] unmatched = errors.stream()
.filter(msg -> {
for (int i = 0; i < globs.length; i++) {
if (globs[i].finds(msg) >= 0) {
used[i] = true;
return false;
}
}
return true;
})
.toArray(String[]::new);
if (unmatched.length == 0) {
List<Glob> report = new ArrayList<>();
for (int i = 0; i < used.length; i++) {
if (!used[i]) {
report.add(globs[i]);
}
}
if (report.isEmpty())
return true;
out.println("Missing patterns");
out.println(Strings.join("\n", globs));
return false;
}
out.println("Errors");
out.println(Strings.join("\n", unmatched));
return false;
}
/**
* Add a file as a bundle to the framework. This bundle will not be started.
*
* @param f the file to install
* @return the bundle object
*/
public Bundle bundle(File f) {
try {
report("Installing %s", f);
return framework.getBundleContext()
.installBundle(toInstallURI(f));
} catch (Exception e) {
report("Failed to installing %s : %s", f, e);
throw Exceptions.duck(e);
}
}
/**
* Set the debug flag
*/
public Launchpad debug() {
this.debug = true;
return this;
}
/**
* Install a number of bundles based on their bundle specification. A bundle
* specification is the format used in for example -runbundles.
*
* @param specification the bundle specifications
* @return a list of bundles
*/
public List<Bundle> bundles(String specification) {
try {
return LaunchpadBuilder.workspace.getLatestBundles(projectDir.getAbsolutePath(), specification)
.stream()
.map(File::new)
.map(this::bundle)
.collect(Collectors.toList());
} catch (Exception e) {
throw Exceptions.duck(e);
}
}
/**
* Install a number of bundles
*
* @param runbundles the list of bundles
* @return a list of bundle objects
*/
public List<Bundle> bundles(File... runbundles) {
if (runbundles == null || runbundles.length == 0)
return Collections.emptyList();
try {
List<Bundle> bundles = new ArrayList<>();
for (File f : runbundles) {
Bundle b = bundle(f);
bundles.add(b);
}
return bundles;
} catch (Exception e) {
throw Exceptions.duck(e);
}
}
/**
* Start a bundle
*
* @param b the bundle object
*/
public void start(Bundle b) {
try {
if (!isFragment(b)) {
report("Starting %s", b);
b.start();
Set<String> exports = getExports(b).keySet();
Set<String> imports = getImports(b).keySet();
exports.removeAll(imports);
exports.retainAll(frameworkExports);
if (!exports.isEmpty()) {
error(
"bundle %s is exporting but NOT importing package(s) %s that are/is also exported by the framework.\n"
+ "This means that the test code and the bundle cannot share classes of these package.",
b, exports);
}
} else {
report("Not starting fragment %s", b);
}
} catch (Exception e) {
report("Failed to start %s : %s", b, e);
throw Exceptions.duck(e);
}
}
/**
* Start all bundles
*
* @param bs a collection of bundles
*/
public void start(Collection<Bundle> bs) {
bs.forEach(this::start);
}
/**
* Close this framework
*/
@Override
public void close() throws Exception {
report("Stop the framework");
framework.stop();
report("Stopped the framework");
framework.waitForStop(closeTimeout);
report("Framework fully stopped");
}
/**
* Get the Bundle Context. If a test bundle was installed then this is the
* context of the test bundle otherwise it is the context of the framework.
* To be able to proxy services it is necessary to have a test bundle
* installed.
*
* @return the bundle context of the test bundle or the framework
*/
public BundleContext getBundleContext() {
if (testbundle != null)
return testbundle.getBundleContext();
return framework.getBundleContext();
}
/**
* Get a service registered under class. If multiple services are registered
* it will return the first
*
* @param serviceInterface the name of the service
* @return a service
*/
public <T> Optional<T> getService(Class<T> serviceInterface) {
return getService(serviceInterface, null);
}
public <T> Optional<T> getService(Class<T> serviceInterface, @Nullable String target) {
return getServices(serviceInterface, target, 0, 0, false).stream()
.map(this::getService)
.findFirst();
}
/**
* Get a list of services of a given name
*
* @param serviceClass the service name
* @return a list of services
*/
public <T> List<T> getServices(Class<T> serviceClass) {
return getServices(serviceClass, null);
}
/**
* Get a list of services in the current registry
*
* @param serviceClass the type of the service
* @param target the target, may be null
* @return a list of found services currently in the registry
*/
public <T> List<T> getServices(Class<T> serviceClass, @Nullable String target) {
return getServices(serviceClass, target, 0, 0, false).stream()
.map(this::getService)
.collect(Collectors.toList());
}
/**
* Get a service from a reference. If the service is null, then throw an
* exception.
*
* @param ref the reference
* @return the service, never null
*/
public <T> T getService(ServiceReference<T> ref) {
try {
T service = getBundleContext().getService(ref);
if (service == null) {
if (ref.getBundle() == null) {
throw new ServiceException(
"getService(" + ref + ") returns null, the service is no longer registered");
}
throw new ServiceException("getService(" + ref + ") returns null, this probbaly means the \n"
+ "component failed to activate. The cause can \n" + "generally be found in the log.\n" + "");
}
return service;
} catch (Exception e) {
throw Exceptions.duck(e);
}
}
/**
* Add the standard Gogo bundles
*/
public Launchpad gogo() {
try {
bundles("org.apache.felix.gogo.runtime,org.apache.felix.gogo.command,org.apache.felix.gogo.shell");
return this;
} catch (Exception e) {
throw Exceptions.duck(e);
}
}
/**
* Add the standard Gogo bundles
*/
public Launchpad snapshot() {
try {
bundles("biz.aQute.bnd.runtime.snapshot");
return this;
} catch (Exception e) {
throw Exceptions.duck(e);
}
}
/**
* Inject an object with services and other OSGi specific values.
*
* @param object the object to inject
*/
public Launchpad inject(Object object) {
try {
injector.inject(object);
return this;
} catch (Exception e) {
throw Exceptions.duck(e);
}
}
/**
* Install a bundle from a file
*
* @param file the file to install
* @return a bundle
*/
public Bundle install(File file) {
try {
report("Installing %s", file);
return framework.getBundleContext()
.installBundle(toInstallURI(file));
} catch (BundleException e) {
report("Failed to install %s : %s", file, e);
throw Exceptions.duck(e);
}
}
/**
* Create a new synthetic bundle.
*
* @return the bundle builder
*/
public BundleBuilder bundle() {
return new BundleBuilder(this);
}
/**
* Create a new object and inject it.
*
* @param type the type of object
* @return a new object injected and all
*/
public <T> T newInstance(Class<T> type) {
try {
return injector.newInstance(type);
} catch (Exception e) {
report("Failed to create and instance for %s : %s", type, e);
throw Exceptions.duck(e);
}
}
/**
* Show the information of how the framework is setup and is running
*/
public Launchpad report() throws InvalidSyntaxException {
boolean old = debug;
debug = true;
reportBundles();
reportServices();
reportEvents();
debug = old;
return this;
}
/**
* Show the installed bundles
*/
public void reportBundles() {
Stream.of(framework.getBundleContext()
.getBundles())
.forEach(bb -> {
report("%4s %s", bundleStateToString(bb.getState()), bb);
});
}
/**
* Show the registered service
*/
public void reportServices() throws InvalidSyntaxException {
Stream.of(framework.getBundleContext()
.getAllServiceReferences(null, null))
.forEach(sref -> {
report("%s", sref);
});
}
/**
* Wait for a Service Reference to be registered
*
* @param class1 the name of the service
* @param timeoutInMs the time to wait
* @return a service reference
*/
public <T> Optional<ServiceReference<T>> waitForServiceReference(Class<T> class1, long timeoutInMs) {
return getServices(class1, null, 1, timeoutInMs, false).stream()
.findFirst();
}
/**
* Wait for a Service Reference to be registered
*
* @param class1 the name of the service
* @param timeoutInMs the time to wait
* @return a service reference
*/
public <T> Optional<ServiceReference<T>> waitForServiceReference(Class<T> class1, long timeoutInMs, String target) {
return getServices(class1, target, 1, timeoutInMs, false).stream()
.findFirst();
}
/**
* Wait for service to be registered
*
* @param class1 name of the service
* @param timeoutInMs timeout in ms
* @return a service
*/
public <T> Optional<T> waitForService(Class<T> class1, long timeoutInMs) {
return this.waitForService(class1, timeoutInMs, null);
}
/**
* Wait for service to be registered
*
* @param class1 name of the service
* @param timeoutInMs timeout in ms
* @param target filter, may be null
* @return a service
*/
public <T> Optional<T> waitForService(Class<T> class1, long timeoutInMs, String target) {
try {
return getServices(class1, target, 1, timeoutInMs, false).stream()
.findFirst()
.map(getBundleContext()::getService);
} catch (Exception e) {
throw Exceptions.duck(e);
}
}
/**
* Turn a service reference's properties into a Map
*
* @param reference the reference
* @return a Map with all the properties of the reference
*/
public Map<String, Object> toMap(ServiceReference<?> reference) {
Map<String, Object> map = new HashMap<>();
for (String key : reference.getPropertyKeys()) {
map.put(key, reference.getProperty(key));
}
return map;
}
/**
* Get a bundle by symbolic name
*/
public Optional<Bundle> getBundle(String bsn) {
return Stream.of(getBundleContext().getBundles())
.filter(b -> bsn.equals(b.getSymbolicName()))
.findFirst();
}
/**
* Broadcast a message to many services at once
*/
@SuppressWarnings("unchecked")
public <T> int broadcast(Class<T> type, Consumer<T> consumer) {
ServiceTracker<T, T> tracker = new ServiceTracker<>(getBundleContext(), type, null);
tracker.open();
int n = 0;
try {
for (T instance : (T[]) tracker.getServices()) {
consumer.accept(instance);
n++;
}
} finally {
tracker.close();
}
return n;
}
/**
* Hide a service by registering a hook. This should in general be done
* before you let others look. In general, the Launchpad should be started
* in {@link LaunchpadBuilder#nostart()} mode. This initializes the OSGi
* framework making it possible to register a service before
*/
public Closeable hide(Class<?> type) {
return hide(type, "hide");
}
/**
* Hide a service. This will register a FindHook and an EventHook for the
* type. This will remove the visibility of all services with that type for
* all bundles _except_ the testbundle. Notice that bundles that already
* obtained a references are not affected. If you use this facility it is
* best to not start the framework before you hide a service. You can
* indicate this to the build with {@link LaunchpadBuilder#nostart()}. The
* framework can be started after creation with {@link #start()}. Notice
* that services through the testbundle remain visible for this hide.
*
* @param type the type to hide
* @param reason the reason why it is hidden
* @return a Closeable, when closed it will remove the hooks
*/
public Closeable hide(Class<?> type, String reason) {
ServiceRegistration<EventListenerHook> eventReg = framework.getBundleContext()
.registerService(EventListenerHook.class, new EventListenerHook() {
@Override
public void event(ServiceEvent event, Map<BundleContext, Collection<ListenerInfo>> listeners) {
ServiceReference<?> ref = event.getServiceReference();
if (selectForHiding(type, ref))
listeners.clear();
}
@Override
public String toString() {
return "Launchpad[" + reason + "]";
}
}, null);
ServiceRegistration<FindHook> findReg = framework.getBundleContext()
.registerService(FindHook.class, new FindHook() {
@Override
public void find(BundleContext context, String name, String filter, boolean allServices,
Collection<ServiceReference<?>> references) {
if (name == null || name.equals(type.getName())) {
references.removeIf(ref -> selectForHiding(type, ref));
}
}
@Override
public String toString() {
return "Launchpad[" + reason + "]";
}
}, null);
return () -> {
eventReg.unregister();
findReg.unregister();
};
}
/**
* Check of a service reference has one of the given types in its object
* class
*
* @param serviceReference the service reference to check
* @param types the set of types
* @return true if one of the types name is in the service reference's
* objectClass property
*/
public boolean isOneOfType(ServiceReference<?> serviceReference, Class<?>... types) {
String[] objectClasses = (String[]) serviceReference.getProperty(Constants.OBJECTCLASS);
for (Class<?> type : types) {
String name = type.getName();
for (String objectClass : objectClasses) {
if (objectClass.equals(name))
return true;
}
}
return false;
}
private boolean selectForHiding(Class<?> type, ServiceReference<?> ref) {
//
// We never hide services registered by the testbundle
//
if (ref.getBundle() == testbundle)
return false;
// only hide references when one of their
// service interfaces is of the hidden type
return isOneOfType(ref, type);
}
/**
* Start the framework if not yet started
*/
public void start() {
try {
framework.start();
List<Bundle> toBeStarted = new ArrayList<>();
for (String path : runspec.runbundles) {
File file = new File(path);
if (!file.isFile())
throw new IllegalArgumentException("-runbundle " + file + " does not exist or is not a file");
Bundle b = install(file);
if (!isFragment(b)) {
toBeStarted.add(b);
}
}
FrameworkWiring fw = framework.adapt(FrameworkWiring.class);
fw.resolveBundles(toBeStarted);
Collections.sort(toBeStarted, this::startorder);
toBeStarted.forEach(this::start);
if (hasTestBundle)
testbundle();
toBeStarted.forEach(this::start);
} catch (BundleException e) {
throw Exceptions.duck(e);
}
}
// reverse ordering. I.e. highest priority is first
int startorder(Bundle a, Bundle b) {
return Integer.compare(getPriority(b), getPriority(a));
}
private int getPriority(Bundle b) {
try {
String h = b.getHeaders()
.get(BUNDLE_PRIORITY);
if (h != null)
return Integer.parseInt(h);
} catch (Exception e) {
// ignore
}
return 0;
}
/**
* Stop the framework if not yet stopped
*/
public void stop() {
try {
report("Stopping the framework");
framework.stop();
} catch (BundleException e) {
report("Could not stop the framework : %s", e);
throw Exceptions.duck(e);
}
}
/**
* Set the test bundle
*/
public void testbundle() {
if (testbundle != null) {
throw new IllegalArgumentException("Test bundle already exists");
}
try {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
Manifest man = new Manifest();
man.getMainAttributes()
.putValue("Manifest-Version", "1");
String name = projectDir.getName()
.toUpperCase();
report("Creating test bundle %s", name);
man.getMainAttributes()
.putValue(Constants.BUNDLE_SYMBOLICNAME, name);
man.getMainAttributes()
.putValue(Constants.BUNDLE_MANIFESTVERSION, "2");
JarOutputStream jout = new JarOutputStream(bout, man);
jout.close();
ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
this.testbundle = framework.getBundleContext()
.installBundle(name, bin);
this.testbundle.start();
} catch (Exception e) {
report("Failed to create test bundle");
throw Exceptions.duck(e);
}
}
/**
* Register a service. You can specify the type and the instance as well as
* the properties. The properties are specified as varargs. That means you
* can define a property by specifying the key (which must be a String) and
* the value consecutively. The value can be any of the types allowed by the
* service properties.
*
* <pre>
* fw.register(Foo.class, instance, "foo", 10, "bar", new long[] {
* 1, 2, 3
* });
* </pre>
*
* @param type the service type
* @param instance the service object
* @param props the service properties specified as a seq of "key", value
* @return the service registration
*/
public <T> ServiceRegistration<T> register(Class<T> type, T instance, Object... props) {
report("Registering service %s %s", type, instance, Arrays.toString(props));
Hashtable<String, Object> ht = new Hashtable<>();
for (int i = 0; i < props.length; i += 2) {
String key = (String) props[i];
Object value = null;
if (i + 1 < props.length) {
value = props[i + 1];
}
ht.put(key, value);
}
return getBundleContext().registerService(type, instance, ht);
}
/**
* Return the framework object
*
* @return the framework object
*/
public Framework getFramework() {
return framework;
}
/**
* Add a component class. This creates a little bundle that holds the
* component class so that bnd adds the DS XML. However, it also imports the
* package of the component class so that in runtime DS will load it from
* the classpath.
*/
public <T> Bundle component(Class<T> type) {
return bundle().addResource(type)
.start();
}
/**
* Runs the given code within the context of a synthetic bundle. Creates a
* synthetic bundle and adds the supplied class to it using
* {@link BundleBuilder#addResourceWithCopy}. It then loads the class using
* the synthetic bundle's class loader and instantiates it using the public,
* no-parameter constructor.
*
* @param clazz the class to instantiate within the context of the
* framework.
* @return The instantiated object.
* @see BundleBuilder#addResourceWithCopy(Class)
*/
public <T> T instantiateInFramework(Class<? extends T> clazz) {
try {
clazz.getConstructor();
} catch (NoSuchMethodException e) {
Exceptions.duck(e);
}
Bundle b = bundle().addResourceWithCopy(clazz)
.start();
try {
@SuppressWarnings("unchecked")
Class<? extends T> insideClass = (Class<? extends T>) b.loadClass(clazz.getName());
return insideClass.getConstructor()
.newInstance();
} catch (Exception e) {
throw Exceptions.duck(e);
}
}
/**
* Check if a bundle is a fragement
*
* @param b the bundle to check
*/
public boolean isFragment(Bundle b) {
return b.getHeaders()
.get(Constants.FRAGMENT_HOST) != null;
}
/**
* Check if a bundle is in the ACTIVE state
*
* @param b the bundle to check
*/
public boolean isActive(Bundle b) {
return b.getState() == Bundle.ACTIVE;
}
/**
* Check if a bundle is in the RESOLVED state
*
* @param b the bundle to check
*/
public boolean isResolved(Bundle b) {
return b.getState() == Bundle.RESOLVED;
}
/**
* Check if a bundle is in the INSTALLED state
*
* @param b the bundle to check
*/
public boolean isInstalled(Bundle b) {
return b.getState() == Bundle.INSTALLED;
}
/**
* Check if a bundle is in the UNINSTALLED state
*
* @param b the bundle to check
*/
public boolean isUninstalled(Bundle b) {
return b.getState() == Bundle.UNINSTALLED;
}
/**
* Check if a bundle is in the STARTING state
*
* @param b the bundle to check
*/
public boolean isStarting(Bundle b) {
return b.getState() == Bundle.STARTING;
}
/**
* Check if a bundle is in the STOPPING state
*
* @param b the bundle to check
*/
public boolean isStopping(Bundle b) {
return b.getState() == Bundle.STOPPING;
}
/**
* Check if a bundle is in the ACTIVE or STARTING state
*
* @param b the bundle to check
*/
public boolean isRunning(Bundle b) {
return isActive(b) || isStarting(b);
}
/**
* Check if a bundle is in the RESOLVED or ACTIVE or STARTING state
*
* @param b the bundle to check
*/
public boolean isReady(Bundle b) {
return isResolved(b) || isActive(b) || isStarting(b);
}
private ParameterMap getExports(Bundle b) {
return new ParameterMap(b.getHeaders()
.get(Constants.EXPORT_PACKAGE));
}
private ParameterMap getImports(Bundle b) {
return new ParameterMap(b.getHeaders()
.get(Constants.IMPORT_PACKAGE));
}
private String toInstallURI(File c) {
return "reference:" + c.toURI();
}
Object getService(Injector.Target<Service> param) {
try {
if (param.type == BundleContext.class) {
return getBundleContext();
}
if (param.type == Bundle.class)
return testbundle;
if (param.type == Framework.class) {
return framework;
}
if (param.type == Bundle[].class) {
return framework.getBundleContext()
.getBundles();
}
Service service = param.annotation;
String target = service.target()
.isEmpty() ? null : service.target();
Class<?> serviceClass = service.service();
if (serviceClass == Object.class)
serviceClass = getServiceType(param.type);
if (serviceClass == null)
serviceClass = getServiceType(param.primaryType);
if (serviceClass == null)
throw new IllegalArgumentException("Cannot define service class for " + param);
long timeout = service.timeout();
if (timeout <= 0)
timeout = SERVICE_DEFAULT_TIMEOUT;
boolean multiple = isMultiple(param.type);
int cardinality = multiple ? service.minimum() : 1;
List<? extends ServiceReference<?>> matchedReferences = getServices(serviceClass, target, cardinality,
timeout, true);
if (multiple)
return matchedReferences;
else
return matchedReferences.get(0);
} catch (Exception e) {
throw Exceptions.duck(e);
}
}
@SuppressWarnings({
"rawtypes", "unchecked"
})
public <T> List<ServiceReference<T>> getServices(Class<T> serviceClass, @Nullable String target, int cardinality,
long timeout, boolean exception) {
try {
String className = serviceClass.getName();
ServiceTracker<?, ?> tracker = injectedDoNotClose.computeIfAbsent(serviceClass, (c) -> {
ServiceTracker<?, ?> t = new ServiceTracker<Object, Object>(framework.getBundleContext(), className,
null);
t.open(true);
return t;
});
long deadline = System.currentTimeMillis() + timeout;
while (true) {
// we get the ALL services regardless of class space or hidden
// by hooks or filters.
@SuppressWarnings("unchecked")
List<ServiceReference<T>> allReferences = (List<ServiceReference<T>>) getReferences(tracker,
serviceClass);
List<ServiceReference<T>> visibleReferences = allReferences.stream()
.filter(ref -> ref.isAssignableTo(framework, className))
.collect(Collectors.toList());
List<ServiceReference<T>> unhiddenReferences = new ArrayList<>(visibleReferences);
Map<ServiceReference<T>, FindHook> hookMap = new HashMap<>();
for (FindHook hook : this.hooks.getServices(new FindHook[0])) {
List<ServiceReference<T>> original = new ArrayList<>(unhiddenReferences);
hook.find(testbundle.getBundleContext(), className, target, true, (Collection) unhiddenReferences);
original.removeAll(unhiddenReferences);
for (ServiceReference<T> ref : original) {
hookMap.put(ref, hook);
}
}
List<ServiceReference<T>> matchedReferences;
if (target == null) {
matchedReferences = new ArrayList<>(unhiddenReferences);
} else {
Filter filter = framework.getBundleContext()
.createFilter(target);
matchedReferences = visibleReferences.stream()
.filter(filter::match)
.collect(Collectors.toList());
}
if (cardinality <= matchedReferences.size()) {
return matchedReferences;
}
if (deadline < System.currentTimeMillis()) {
String error = "Injection of service " + className;
if (target != null)
error += " with target " + target;
error += " failed.";
if (allReferences.size() > visibleReferences.size()) {
List<ServiceReference<?>> invisibleReferences = new ArrayList<>(allReferences);
invisibleReferences.removeAll(visibleReferences);
for (ServiceReference<?> r : invisibleReferences) {
error += "\nInvisible reference " + r + "[" + r.getProperty(Constants.SERVICE_ID)
+ "] from bundle " + r.getBundle();
String[] objectClass = (String[]) r.getProperty(Constants.OBJECTCLASS);
for (String clazz : objectClass) {
error += "\n " + clazz + "\n registrar: "
+ getSource(clazz, r.getBundle()).orElse("null") + "\n framework: "
+ getSource(clazz, framework).orElse("null");
}
}
}
if (visibleReferences.size() > unhiddenReferences.size()) {
List<ServiceReference<?>> hiddenReferences = new ArrayList<>(visibleReferences);
hiddenReferences.removeAll(unhiddenReferences);
for (ServiceReference<?> r : hiddenReferences) {
error += "\nHidden (FindHook) Reference " + r + " from bundle " + r.getBundle() + " hook "
+ hookMap.get(r);
}
}
if (unhiddenReferences.size() > matchedReferences.size()) {
List<ServiceReference<?>> untargetReferences = new ArrayList<>(unhiddenReferences);
untargetReferences.removeAll(matchedReferences);
error += "\nReference not matched by the target filter " + target;
for (ServiceReference<?> ref : untargetReferences) {
error += "\n " + ref + " : " + getProperties(ref);
}
}
if (exception)
throw new TimeoutException(error);
return Collections.emptyList();
}
Thread.sleep(100);
}
} catch (Exception e) {
throw Exceptions.duck(e);
}
}
private Map<String, String> getProperties(ServiceReference<?> ref) {
Map<String, String> map = new HashMap<>();
for (String k : ref.getPropertyKeys()) {
Object property = ref.getProperty(k);
String s;
if (property != null && property.getClass()
.isArray()) {
s = Arrays.deepToString((Object[]) property);
} else
s = property + "";
map.put(k, s);
}
return map;
}
private Optional<String> getSource(String className, Bundle from) {
try {
Class<?> loadClass = from.loadClass(className);
Bundle bundle = FrameworkUtil.getBundle(loadClass);
if (bundle == null)
return Optional.of("from class path");
else {
BundleWiring wiring = bundle.adapt(BundleWiring.class);
String exported = "PRIVATE! ";
List<BundleCapability> capabilities = wiring.getCapabilities(PackageNamespace.PACKAGE_NAMESPACE);
String packageName = loadClass.getPackage()
.getName();
for (BundleCapability c : capabilities) {
if (packageName.equals(c.getAttributes()
.get(PackageNamespace.PACKAGE_NAMESPACE))) {
exported = "Exported from ";
}
}
return Optional.of(exported + " " + bundle.toString());
}
} catch (Exception e) {
return Optional.empty();
}
}
void reportEvents() {
frameworkEvents.forEach(fe -> {
report("%s", fe);
});
}
private String bundleStateToString(int state) {
switch (state) {
case Bundle.UNINSTALLED :
return "UNIN";
case Bundle.INSTALLED :
return "INST";
case Bundle.RESOLVED :
return "RSLV";
case Bundle.STARTING :
return "STAR";
case Bundle.ACTIVE :
return "ACTV";
case Bundle.STOPPING :
return "STOP";
default :
return "UNKN";
}
}
private List<? extends ServiceReference<?>> getReferences(ServiceTracker<?, ?> tracker, Class<?> serviceClass) {
ServiceReference<?>[] references = tracker.getServiceReferences();
if (references == null) {
return Collections.emptyList();
}
Arrays.sort(references);
return Arrays.asList(references);
}
private Class<?> getServiceType(Type type) {
if (type instanceof Class)
return (Class<?>) type;
if (type instanceof ParameterizedType) {
Type rawType = ((ParameterizedType) type).getRawType();
if (rawType instanceof Class) {
Class<?> rawClass = (Class<?>) rawType;
if (Iterable.class.isAssignableFrom(rawClass)) {
return getServiceType(((ParameterizedType) type).getActualTypeArguments()[0]);
}
if (Optional.class.isAssignableFrom(rawClass)) {
return getServiceType(((ParameterizedType) type).getActualTypeArguments()[0]);
}
if (ServiceReference.class.isAssignableFrom(rawClass)) {
return getServiceType(((ParameterizedType) type).getActualTypeArguments()[0]);
}
}
}
return null;
}
private boolean isMultiple(Type type) {
if (type instanceof Class) {
return ((Class<?>) type).isArray();
}
if (type instanceof ParameterizedType) {
Type rawType = ((ParameterizedType) type).getRawType();
if (rawType instanceof Class) {
Class<?> clazz = (Class<?>) rawType;
if (Iterable.class.isAssignableFrom(clazz))
return true;
}
}
return false;
}
private boolean isParameterizedType(Type to, Class<?> clazz) {
if (to instanceof ParameterizedType) {
if (((ParameterizedType) to).getRawType() == clazz)
return true;
}
return false;
}
private Converter makeConverter() {
Converter converter = new Converter();
converter.hook(null, (to, from) -> {
try {
if (!(from instanceof ServiceReference))
return null;
ServiceReference<?> reference = (ServiceReference<?>) from;
if (isParameterizedType(to, ServiceReference.class))
return reference;
if (isParameterizedType(to, Map.class))
return converter.convert(to, toMap(reference));
Object service = getService(reference);
if (isParameterizedType(to, Optional.class))
return Optional.ofNullable(service);
return service;
} catch (Exception e) {
throw e;
}
});
return converter;
}
public String getName() {
return name;
}
public String getClassName() {
return className;
}
}
| [launchpad] Started bundles twice
Signed-off-by: Peter Kriens <[email protected]>
| biz.aQute.launchpad/src/aQute/launchpad/Launchpad.java | [launchpad] Started bundles twice | <ide><path>iz.aQute.launchpad/src/aQute/launchpad/Launchpad.java
<ide> fw.resolveBundles(toBeStarted);
<ide>
<ide> Collections.sort(toBeStarted, this::startorder);
<del> toBeStarted.forEach(this::start);
<ide>
<ide> if (hasTestBundle)
<ide> testbundle(); |
|
Java | apache-2.0 | 8f463de49f685aa62fa678d7786961e0bee82a0d | 0 | scala/scala,martijnhoekstra/scala,slothspot/scala,jvican/scala,lrytz/scala,slothspot/scala,lrytz/scala,martijnhoekstra/scala,shimib/scala,lrytz/scala,slothspot/scala,shimib/scala,martijnhoekstra/scala,martijnhoekstra/scala,slothspot/scala,martijnhoekstra/scala,scala/scala,shimib/scala,scala/scala,shimib/scala,felixmulder/scala,jvican/scala,jvican/scala,felixmulder/scala,scala/scala,lrytz/scala,slothspot/scala,lrytz/scala,felixmulder/scala,jvican/scala,lrytz/scala,jvican/scala,slothspot/scala,martijnhoekstra/scala,scala/scala,felixmulder/scala,felixmulder/scala,felixmulder/scala,shimib/scala,slothspot/scala,scala/scala,felixmulder/scala,shimib/scala,jvican/scala,jvican/scala | /* ____ ____ ____ ____ ______ *\
** / __// __ \/ __// __ \/ ____/ SOcos COmpiles Scala **
** __\_ \/ /_/ / /__/ /_/ /\_ \ (c) 2002, LAMP/EPFL **
** /_____/\____/\___/\____/____/ **
**
\* */
//todo check significance of JAVA flag.
package scalac.symtab;
import scala.tools.util.Position;
import scalac.ApplicationError;
import scalac.Global;
import scalac.Phase;
import scalac.framework.History;
import scalac.util.ArrayApply;
import scalac.util.Name;
import scalac.util.Names;
import scalac.util.NameTransformer;
import scalac.util.Debug;
public abstract class Symbol implements Modifiers, Kinds {
/** An empty symbol array */
public static final Symbol[] EMPTY_ARRAY = new Symbol[0];
/** An empty array of symbol arrays */
public static final Symbol[][] EMPTY_ARRAY_ARRAY = new Symbol[0][];
/** The absent symbol */
public static final Symbol NONE = new NoSymbol();
// Attribues -------------------------------------------------------------
public static final int IS_ROOT = 0x00000001;
public static final int IS_ANONYMOUS = 0x00000002;
public static final int IS_LABEL = 0x00000010;
public static final int IS_CONSTRUCTOR = 0x00000020;
public static final int IS_ACCESSMETHOD = 0x00000100;
public static final int IS_ERROR = 0x10000000;
public static final int IS_THISTYPE = 0x20000000;
public static final int IS_LOCALDUMMY = 0x40000000;
public static final int IS_COMPOUND = 0x80000000;
// Fields -------------------------------------------------------------
/** The unique identifier generator */
private static int ids;
/** The kind of the symbol */
public int kind;
/** The position of the symbol */
public int pos;
/** The name of the symbol */
public Name name;
/** The modifiers of the symbol */
public int flags;
/** The owner of the symbol */
private Symbol owner;
/** The infos of the symbol */
private TypeIntervalList infos;
/** The attributes of the symbol */
private final int attrs;
/** The unique identifier */
public final int id;
// Constructors -----------------------------------------------------------
/** Generic symbol constructor */
public Symbol(int kind, Symbol owner, int pos, int flags, Name name, int attrs) {
this.kind = kind;
this.pos = pos;
this.name = name;
this.owner = owner == null ? this : owner;
this.flags = flags & ~(INITIALIZED | LOCKED); // safety first
this.attrs = attrs;
this.id = ids++;
}
// Factories --------------------------------------------------------------
/** Creates a new term owned by this symbol. */
public final Symbol newTerm(int pos, int flags, Name name) {
return newTerm(pos, flags, name, 0);
}
/** Creates a new constructor of this symbol. */
public final Symbol newConstructor(int pos, int flags) {
assert isType(): Debug.show(this);
return new ConstructorSymbol(this, pos, flags);
}
/** Creates a new method owned by this symbol. */
public final Symbol newMethod(int pos, int flags, Name name) {
assert isClass(): Debug.show(this);
return newTerm(pos, flags, name, 0);
}
/** Creates a new access method owned by this symbol. */
public final Symbol newAccessMethod(int pos, Name name) {
assert isClass(): Debug.show(this);
int flags = PRIVATE | FINAL | SYNTHETIC;
return newTerm(pos, flags, name, IS_ACCESSMETHOD);
}
/** Creates a new function owned by this symbol. */
public final Symbol newFunction(int pos, int flags, Name name) {
assert isTerm(): Debug.show(this);
return newTerm(pos, flags, name, 0);
}
/** Creates a new method or function owned by this symbol. */
public final Symbol newMethodOrFunction(int pos, int flags, Name name){
assert isClass() || isTerm(): Debug.show(this);
return newTerm(pos, flags, name, 0);
}
/** Creates a new label owned by this symbol. */
public final Symbol newLabel(int pos, Name name) {
assert isTerm(): Debug.show(this);
return newTerm(pos, 0, name, IS_LABEL);
}
/** Creates a new field owned by this symbol. */
public final Symbol newField(int pos, int flags, Name name) {
assert isClass(): Debug.show(this);
return newTerm(pos, flags, name, 0);
}
/** Creates a new variable owned by this symbol. */
public final Symbol newVariable(int pos, int flags, Name name) {
assert isTerm(): Debug.show(this);
return newTerm(pos, flags, name, 0);
}
/** Creates a new variable owned by this symbol. */
public final Symbol newFieldOrVariable(int pos, int flags, Name name) {
assert isClass() || isTerm(): Debug.show(this);
return newTerm(pos, flags, name, 0);
}
/** Creates a new pattern variable owned by this symbol. */
public final Symbol newPatternVariable(int pos, Name name) {
return newVariable(pos, 0, name);
}
/** Creates a new value parameter owned by this symbol. */
public final Symbol newVParam(int pos, int flags, Name name) {
assert isTerm(): Debug.show(this);
return newTerm(pos, flags | PARAM, name);
}
/**
* Creates a new value parameter owned by this symbol and
* initializes it with the type.
*/
public final Symbol newVParam(int pos, int flags, Name name, Type type) {
Symbol tparam = newVParam(pos, flags, name);
tparam.setInfo(type);
return tparam;
}
/**
* Creates a new initialized dummy symbol for template of this
* class.
*/
public final Symbol newLocalDummy() {
assert isClass(): Debug.show(this);
Symbol local = newTerm(pos, 0, Names.LOCAL(this), IS_LOCALDUMMY);
local.setInfo(Type.NoType);
return local;
}
/** Creates a new module owned by this symbol. */
public final Symbol newModule(int pos, int flags, Name name) {
return new ModuleSymbol(this, pos, flags, name);
}
/**
* Creates a new package owned by this symbol and initializes it
* with an empty scope.
*/
public final Symbol newPackage(int pos, Name name) {
return newPackage(pos, name, null);
}
/**
* Creates a new package owned by this symbol, initializes it with
* the loader and enters it in the scope if it's non-null.
*/
public final Symbol newLoadedPackage(Name name, SymbolLoader loader,
Scope scope)
{
assert loader != null: Debug.show(this) + " - " + name;
Symbol peckage = newPackage(Position.NOPOS, name, loader);
if (scope != null) scope.enterNoHide(peckage);
return peckage;
}
/**
* Creates a new error value owned by this symbol and initializes
* it with an error type.
*/
public Symbol newErrorValue(Name name) {
Symbol symbol = newTerm(pos, SYNTHETIC, name, IS_ERROR);
symbol.setInfo(Type.ErrorType);
return symbol;
}
/** Creates a new type alias owned by this symbol. */
public final Symbol newTypeAlias(int pos, int flags, Name name) {
return new AliasTypeSymbol(this, pos, flags, name, 0);
}
/** Creates a new abstract type owned by this symbol. */
public final Symbol newAbstractType(int pos, int flags, Name name) {
return new AbsTypeSymbol(this, pos, flags, name, 0);
}
/** Creates a new type parameter owned by this symbol. */
public final Symbol newTParam(int pos, int flags, Name name) {
assert isTerm(): Debug.show(this);
return newAbstractType(pos, flags | PARAM, name);
}
/**
* Creates a new type parameter owned by this symbol and
* initializes it with the type.
*/
public final Symbol newTParam(int pos, int flags, Name name, Type type) {
Symbol tparam = newTParam(pos, flags, name);
tparam.setInfo(type);
return tparam;
}
/**
* Creates a new type alias owned by this symbol and initializes
* it with the info.
*/
public final Symbol newTypeAlias(int pos, int flags, Name name, Type info){
Symbol alias = newTypeAlias(pos, flags, name);
alias.setInfo(info);
alias.allConstructors().setInfo(Type.MethodType(EMPTY_ARRAY, info));
return alias;
}
/** Creates a new class owned by this symbol. */
public final ClassSymbol newClass(int pos, int flags, Name name) {
return newClass(pos, flags, name, 0);
}
/** Creates a new anonymous class owned by this symbol. */
public final ClassSymbol newAnonymousClass(int pos, Name name) {
assert isTerm(): Debug.show(this);
return newClass(pos, 0, name, IS_ANONYMOUS);
}
/**
* Creates a new class with a linked module, both owned by this
* symbol, initializes them with the loader and enters the class
* and the module in the scope if it's non-null.
*/
public final ClassSymbol newLoadedClass(int flags, Name name,
SymbolLoader loader, Scope scope)
{
assert isPackageClass(): Debug.show(this);
assert loader != null: Debug.show(this) + " - " + name;
ClassSymbol clasz = new LinkedClassSymbol(this, flags, name);
clasz.setInfo(loader);
clasz.allConstructors().setInfo(loader);
clasz.linkedModule().setInfo(loader);
clasz.linkedModule().moduleClass().setInfo(loader);
if (scope != null) scope.enterNoHide(clasz);
if (scope != null) scope.enterNoHide(clasz.linkedModule());
return clasz;
}
/**
* Creates a new error class owned by this symbol and initializes
* it with an error type.
*/
public ClassSymbol newErrorClass(Name name) {
ClassSymbol symbol = newClass(pos, SYNTHETIC, name, IS_ERROR);
Scope scope = new ErrorScope(this);
symbol.setInfo(Type.compoundType(Type.EMPTY_ARRAY, scope, this));
symbol.allConstructors().setInfo(Type.ErrorType);
return symbol;
}
/** Creates a new term owned by this symbol. */
final Symbol newTerm(int pos, int flags, Name name, int attrs) {
return new TermSymbol(this, pos, flags, name, attrs);
}
/** Creates a new package owned by this symbol. */
final Symbol newPackage(int pos, Name name, Type info) {
assert isPackageClass(): Debug.show(this);
Symbol peckage = newModule(pos, JAVA | PACKAGE, name);
if (info == null) info = Type.compoundType(
Type.EMPTY_ARRAY, new Scope(), peckage.moduleClass());
peckage.moduleClass().setInfo(info);
return peckage;
}
/** Creates a new class owned by this symbol. */
final ClassSymbol newClass(int pos, int flags, Name name, int attrs) {
return new ClassSymbol(this, pos, flags, name, attrs);
}
/** Creates a new compound class owned by this symbol. */
final ClassSymbol newCompoundClass(Type info) {
int pos = Position.FIRSTPOS;
Name name = Names.COMPOUND_NAME.toTypeName();
int flags = ABSTRACT | SYNTHETIC;
int attrs = IS_COMPOUND;
ClassSymbol clasz = newClass(pos, flags, name, attrs);
clasz.setInfo(info);
clasz.primaryConstructor().setInfo(
Type.MethodType(Symbol.EMPTY_ARRAY, clasz.typeConstructor()));
return clasz;
}
// Copying & cloning ------------------------------------------------------
/** Return a fresh symbol with the same fields as this one.
*/
public final Symbol cloneSymbol() {
return cloneSymbol(owner);
}
/** Return a fresh symbol with the same fields as this one and the
* given owner.
*/
public final Symbol cloneSymbol(Symbol owner) {
Symbol clone = cloneSymbolImpl(owner, attrs);
clone.setInfo(info());
return clone;
}
protected abstract Symbol cloneSymbolImpl(Symbol owner, int attrs);
/** Returns a shallow copy of the given array. */
public static Symbol[] cloneArray(Symbol[] array) {
return cloneArray(0, array, 0);
}
/**
* Returns a shallow copy of the given array prefixed by "prefix"
* null items.
*/
public static Symbol[] cloneArray(int prefix, Symbol[] array) {
return cloneArray(prefix, array, 0);
}
/**
* Returns a shallow copy of the given array suffixed by "suffix"
* null items.
*/
public static Symbol[] cloneArray(Symbol[] array, int suffix) {
return cloneArray(0, array, suffix);
}
/**
* Returns a shallow copy of the given array prefixed by "prefix"
* null items and suffixed by "suffix" null items.
*/
public static Symbol[] cloneArray(int prefix, Symbol[] array, int suffix) {
assert prefix >= 0 && suffix >= 0: prefix + " - " + suffix;
int size = prefix + array.length + suffix;
if (size == 0) return EMPTY_ARRAY;
Symbol[] clone = new Symbol[size];
for (int i = 0; i < array.length; i++) clone[prefix + i] = array[i];
return clone;
}
/** Returns the concatenation of the two arrays. */
public static Symbol[] concat(Symbol[] array1, Symbol[] array2) {
if (array1.length == 0) return array2;
if (array2.length == 0) return array1;
Symbol[] clone = cloneArray(array1.length, array2);
for (int i = 0; i < array1.length; i++) clone[i] = array1[i];
return clone;
}
// Setters ---------------------------------------------------------------
/** Set owner */
public Symbol setOwner(Symbol owner) {
assert !isConstructor() && !isNone() && !isError(): Debug.show(this);
setOwner0(owner);
return this;
}
protected void setOwner0(Symbol owner) {
this.owner = owner;
}
/** Set type -- this is an alias for setInfo(Type info) */
public final Symbol setType(Type info) { return setInfo(info); }
/**
* Set initial information valid from start of current phase. This
* information is visible in the current phase and will be
* transformed by the current phase (except if current phase is
* the first one).
*/
public Symbol setInfo(Type info) {
return setInfoAt(info, Global.instance.currentPhase);
}
/**
* Set initial information valid from start of given phase. This
* information is visible in the given phase and will be
* transformed by the given phase.
*/
private final Symbol setInfoAt(Type info, Phase phase) {
assert info != null: Debug.show(this);
assert phase != null: Debug.show(this);
assert !isConstructor()
|| info instanceof Type.LazyType
|| info == Type.NoType
|| info == Type.ErrorType
|| info instanceof Type.MethodType
|| info instanceof Type.OverloadedType
|| info instanceof Type.PolyType
: "illegal type for " + this + ": " + info;
infos = new TypeIntervalList(null, info, phase);
if (info instanceof Type.LazyType) flags &= ~INITIALIZED;
else flags |= INITIALIZED;
return this;
}
/**
* Set new information valid from start of next phase. This
* information is only visible in next phase or through
* "nextInfo". It will not be transformed by the current phase.
*/
public final Symbol updateInfo(Type info) {
return updateInfoAt(info, Global.instance.currentPhase.next);
}
/**
* Set new information valid from start of given phase. This
* information is only visible from the start of the given phase
* which is also the first phase that will transform this
* information.
*/
private final Symbol updateInfoAt(Type info, Phase phase) {
assert info != null: Debug.show(this);
assert phase != null: Debug.show(this);
assert infos != null: Debug.show(this);
assert !phase.precedes(infos.limit()) :
Debug.show(this) + " -- " + phase + " -- " + infos.limit();
if (infos.limit() == phase) {
if (infos.start == phase)
infos = infos.prev;
else
infos.setLimit(infos.limit().prev);
}
infos = new TypeIntervalList(infos, info, phase);
return this;
}
/** Set type of `this' in current class
*/
public Symbol setTypeOfThis(Type tp) {
throw new ApplicationError(this + ".setTypeOfThis");
}
/** Set the low bound of this type variable
*/
public Symbol setLoBound(Type lobound) {
throw new ApplicationError("setLoBound inapplicable for " + this);
}
/** Set the view bound of this type variable
*/
public Symbol setVuBound(Type lobound) {
throw new ApplicationError("setVuBound inapplicable for " + this);
}
/** Add an auxiliary constructor to class.
*/
public void addConstructor(Symbol constr) {
throw new ApplicationError("addConstructor inapplicable for " + this);
}
// Symbol classification ----------------------------------------------------
/** Does this symbol denote an error symbol? */
public final boolean isError() {
return (attrs & IS_ERROR) != 0;
}
/** Does this symbol denote the none symbol? */
public final boolean isNone() {
return kind == Kinds.NONE;
}
/** Does this symbol denote a type? */
public final boolean isType() {
return kind == TYPE || kind == CLASS || kind == ALIAS;
}
/** Does this symbol denote a term? */
public final boolean isTerm() {
return kind == VAL;
}
/** Does this symbol denote a value? */
public final boolean isValue() {
preInitialize();
return kind == VAL && !(isModule() && isJava()) && !isPackage();
}
/** Does this symbol denote a stable value? */
public final boolean isStable() {
return kind == VAL &&
((flags & DEF) == 0) &&
((flags & STABLE) != 0 ||
(flags & MUTABLE) == 0 && type().isObjectType());
}
/** Does this symbol have the STABLE flag? */
public final boolean hasStableFlag() {
return (flags & STABLE) != 0;
}
/** Is this symbol static (i.e. with no outer instance)? */
public final boolean isStatic() {
return isRoot() || owner.isStaticOwner();
}
/** Does this symbol denote a class that defines static symbols? */
public final boolean isStaticOwner() {
return isPackageClass() || (isStatic() && isModuleClass()
// !!! remove later? translation does not work (yet?)
&& isJava());
}
/** Is this symbol final?
*/
public final boolean isFinal() {
return
(flags & (FINAL | PRIVATE)) != 0 || isLocal() || owner.isModuleClass();
}
/** Does this symbol denote a variable? */
public final boolean isVariable() {
return kind == VAL && (flags & MUTABLE) != 0;
}
/** Does this symbol denote a view bounded type variable? */
public final boolean isViewBounded() {
Global global = Global.instance;
return kind == TYPE && (flags & VIEWBOUND) != 0 &&
global.currentPhase.id <= global.PHASE.REFCHECK.id();
}
/**
* Does this symbol denote a final method? A final method is one
* that can't be overridden in a subclass. This method assumes
* that this symbol denotes a method. It doesn't test it.
*/
public final boolean isMethodFinal() {
return (flags & FINAL) != 0 || isPrivate() || isLifted();
}
/** Does this symbol denote a sealed class symbol? */
public final boolean isSealed() {
return (flags & SEALED) != 0;
}
/** Does this symbol denote a method?
*/
public final boolean isInitializedMethod() {
if (infos == null) return false;
switch (rawInfo()) {
case MethodType(_, _):
case PolyType(_, _):
return true;
case OverloadedType(Symbol[] alts, _):
for (int i = 0; i < alts.length; i++)
if (alts[i].isMethod()) return true;
return false;
default:
return false;
}
}
public final boolean isMethod() {
initialize();
return isInitializedMethod();
}
public final boolean isCaseFactory() {
return isMethod() && !isConstructor() && (flags & CASE) != 0;
}
public final boolean isAbstractClass() {
preInitialize();
return kind == CLASS && (flags & ABSTRACT) != 0 &&
this != Global.instance.definitions.ARRAY_CLASS;
}
public final boolean isAbstractOverride() {
preInitialize();
return (flags & (ABSTRACT | OVERRIDE)) == (ABSTRACT | OVERRIDE);
}
/* Does this symbol denote an anonymous class? */
public final boolean isAnonymousClass() {
return isClass() && (attrs & IS_ANONYMOUS) != 0;
}
/** Does this symbol denote the root class or root module?
*/
public final boolean isRoot() {
return (attrs & IS_ROOT) != 0;
}
/** Does this symbol denote something loaded from a Java class? */
public final boolean isJava() {
preInitialize();
return (flags & JAVA) != 0;
}
/** Does this symbol denote a Java package? */
public final boolean isPackage() {
return kind == VAL && (flags & PACKAGE) != 0;
}
/** Does this symbol denote a Java package class? */
public final boolean isPackageClass() {
return kind == CLASS && (flags & PACKAGE) != 0;
}
/** Does this symbol denote a module? */
public final boolean isModule() {
return kind == VAL && (flags & MODUL) != 0;
}
/** Does this symbol denote a module class? */
public final boolean isModuleClass() {
return kind == CLASS && (flags & MODUL) != 0;
}
/** Does this symbol denote a class? */
public final boolean isClass() {
return kind == CLASS && (flags & PACKAGE) == 0;
}
/** Does this symbol denote a case class?
*/
public final boolean isCaseClass() {
preInitialize();
return kind == CLASS && (flags & CASE) != 0;
}
/** Does this symbol denote a uniform (i.e. parameterless) class? */
public final boolean isTrait() {
//preInitialize(); todo: enable, problem is that then we cannot print
// during unpickle
return kind == CLASS && (flags & TRAIT) != 0;
}
/** Does this class symbol denote a compound type symbol? */
public final boolean isCompoundSym() {
return (attrs & IS_COMPOUND) != 0;
}
/** Does this symbol denote a this symbol? */
public final boolean isThisSym() {
return (attrs & IS_THISTYPE) != 0;
}
/** Does this symbol denote an interface? */
public final boolean isInterface() {
info(); // force delayed transformInfos that may change this flag
return (flags & INTERFACE) != 0;
}
/** Does this symbol denote a type alias? */
public final boolean isTypeAlias() {
return kind == ALIAS;
}
/** Does this symbol denote an abstract type? */
public final boolean isAbstractType() {
return kind == TYPE;
}
/** Does this symbol denote a class type? */
public final boolean isClassType() {
return kind == CLASS;
}
/** Does this symbol denote a public symbol? */
public final boolean isPublic() {
return !isProtected() && !isPrivate();
}
/** Does this symbol denote a protected symbol? */
public final boolean isProtected() {
preInitialize();
return (flags & PROTECTED) != 0;
}
/** Does this symbol denote a private symbol? */
public final boolean isPrivate() {
preInitialize();
return (flags & PRIVATE) != 0;
}
/** Has this symbol been lifted? */
public final boolean isLifted() {
preInitialize();
return (flags & LIFTED) != 0;
}
/** Does this symbol denote a deferred symbol? */
public final boolean isDeferred() {
return (flags & DEFERRED) != 0;
}
/** Does this symbol denote a synthetic symbol? */
public final boolean isSynthetic() {
return (flags & SYNTHETIC) != 0;
}
/** Does this symbol denote an accessor? */
public final boolean isAccessor() {
return (flags & ACCESSOR) != 0;
}
/** Does this symbol denote an access method? (a method to access
* private of protected members from inner classes) */
public final boolean isAccessMethod() {
return (attrs & IS_ACCESSMETHOD) != 0;
}
/** Is this symbol locally defined? I.e. not a member of a class or module */
public final boolean isLocal() {
return owner.kind == VAL &&
!((flags & PARAM) != 0 && owner.isPrimaryConstructor());
}
/** Is this symbol a parameter? Includes type parameters of methods.
*/
public final boolean isParameter() {
return (flags & PARAM) != 0;
}
/** Is this symbol a def parameter?
*/
public final boolean isDefParameter() {
return (flags & (PARAM | DEF)) == (PARAM | DEF);
}
/** Is this class locally defined?
* A class is local, if
* - it is anonymous, or
* - its owner is a value
* - it is defined within a local class
*/
public final boolean isLocalClass() {
return isClass() &&
(isAnonymousClass() ||
owner.isValue() ||
owner.isLocalClass());
}
/** Is this symbol an instance initializer? */
public boolean isInitializer() {
return false;
}
/** Is this symbol a constructor? */
public final boolean isConstructor() {
return (attrs & IS_CONSTRUCTOR) != 0;
}
/** Is this symbol the primary constructor of a type? */
public final boolean isPrimaryConstructor() {
return isConstructor() && this == constructorClass().primaryConstructor();
}
/** Symbol was preloaded from package
*/
public final boolean isExternal() {
return pos == Position.NOPOS;
}
/** Is this symbol an overloaded symbol? */
public final boolean isOverloaded() {
switch (info()) {
case OverloadedType(_,_): return true;
default : return false;
}
}
/** Does this symbol denote a label? */
public final boolean isLabel() {
return (attrs & IS_LABEL) != 0;
}
/** Is this symbol accessed? */
public final boolean isAccessed() {
return (flags & ACCESSED) != 0;
}
/** The variance of this symbol as an integer
*/
public int variance() {
if ((flags & COVARIANT) != 0) return 1;
else if ((flags & CONTRAVARIANT) != 0) return -1;
else return 0;
}
// Symbol names ----------------------------------------------------------------
/** Get the fully qualified name of this Symbol
* (this is always a normal name, never a type name)
*/
/** Get the simple name of this Symbol (this is always a term name)
*/
public Name simpleName() {
if (isConstructor()) return constructorClass().name.toTermName();
return name;
}
// Acess to related symbols -----------------------------------------------------
/** Get type parameters */
public Symbol[] typeParams() {
return EMPTY_ARRAY;
}
/** Get value parameters */
public Symbol[] valueParams() {
return EMPTY_ARRAY;
}
/** Get result type */
public final Type resultType() {
return type().resultType();
}
/** Get type parameters at start of next phase */
public final Symbol[] nextTypeParams() {
Global.instance.nextPhase();
Symbol[] tparams = typeParams();
Global.instance.prevPhase();
return tparams;
}
/** Get value parameters at start of next phase */
public final Symbol[] nextValueParams() {
Global.instance.nextPhase();
Symbol[] vparams = valueParams();
Global.instance.prevPhase();
return vparams;
}
/** Get result type at start of next phase */
public final Type nextResultType() {
return nextType().resultType();
}
/** Get all constructors of class */
public Symbol allConstructors() {
return NONE;
}
/** Get primary constructor of class */
public Symbol primaryConstructor() {
return NONE;
}
/**
* Returns the class linked to this module or null if there is no
* such class. The returned value remains the same for the whole
* life of the symbol.
*
* See method "linkedModule" to learn more about linked modules
* and classes.
*/
public ClassSymbol linkedClass() {
assert isModule(): "not a module: " + Debug.show(this);
return null;
}
/**
* Returns the module linked to this class or null if there is no
* such module. The returned value remains the same for the whole
* life of the symbol.
*
* Linked modules and classes are intended to be used by the
* symbol table loader. They are needed because it is impossible
* to know from the name of a class or source file if it defines a
* class or a module. For that reason a class and a module (each
* linked to the other) are created for each of those files. Once
* the file is read the class, the module or both are initialized
* depending on what the file defines.
*
* It is guaranteed that if a class "c" has a linked module then
* "c.linkedModule().linkedClasss() == c" and that if a module "m"
* has a linked class then "m.linkedClasss().linkedModule() == m".
*
* The linked module of a Java class, is the module that contains
* the static members of that class. A Java class has always a
* linked module.
*
* The linked module of a Scala class, is the module with the same
* name declared in the same scope. A Scala class may or may not
* have a linked module. However, this does not depend on the
* presence or absence of a module with the same name but on how
* the class is created. Therefore a Scala class may have no
* linked module even though there exists a module with the same
* name in the same scope. A Scala class may also have a linked
* module even though there exists no module with the same name in
* the same scope. In the latter case, the linked would be
* initialized to NoType (which prevents accesses to it).
*
* There is a last catch about linked modules. It may happen that
* the symbol returned by "linkedModule" is not a module (and that
* method "linkedClass" works on a non-module symbol). At creation
* time, linked modules are always modules, but at initialization
* time, it may be discovered that the module is in fact a case
* class factory method. In that case, the module is downgraded to
* a non-module term. This implies that from then on calls to its
* method "moduleClass" will fail, but the links defined by the
* methods "linkedModule" and "linkedClass" remain unchanged.
*/
public ModuleSymbol linkedModule() {
assert isClassType(): "not a class: " + Debug.show(this);
return null;
}
/** Get owner */
public Symbol owner() {
return owner;
}
/** Get owner, but if owner is primary constructor of a class,
* get class symbol instead. This is useful for type parameters
* and value parameters in classes which have the primary constructor
* as owner.
*/
public Symbol classOwner() {
Symbol owner = owner();
Symbol clazz = owner.constructorClass();
if (clazz.primaryConstructor() == owner) return clazz;
else return owner;
}
/** The next enclosing class */
public Symbol enclClass() {
return owner().enclClass();
}
/** The next enclosing method */
public Symbol enclMethod() {
return isMethod() ? this : owner().enclMethod();
}
/** If this is a constructor, return the class it constructs.
* Otherwise return the symbol itself.
*/
public Symbol constructorClass() {
return this;
}
/** Return first alternative if this has a (possibly lazy)
* overloaded type, otherwise symbol itself.
* Needed in ClassSymbol.primaryConstructor() and in UnPickle.
*/
public Symbol firstAlternative() {
if (infos == null)
return this;
else if (infos.info instanceof Type.OverloadedType)
return infos.info.alternativeSymbols()[0];
else if (infos.info instanceof LazyOverloadedType)
return ((LazyOverloadedType) infos.info).sym1.firstAlternative();
else
return this;
}
/**
* Returns the class of this module. This method may be invoked
* only on module symbols. It returns always a non-null module
* class symbol whose identity never changes.
*/
public ModuleClassSymbol moduleClass() {
throw Debug.abort("not a module", this);
}
/**
* Returns the source module of this module class. This method may
* be invoked only on module class symbols. It returns always a
* non-null module symbol whose identity never changes.
*
* This method should be used with great care. If possible, one
* should always use moduleClass instead. For example, one should
* write "m.moduleClass()==c" rather than "m==c.sourceModule()".
*
* This method is problematic because the module - module-class
* relation is not a one - one relation. There might be more than
* one module that share the same module class. In that case, the
* source module of the module class is the module that created
* the class. This implies that "m.moduleClass().sourceModule()"
* may be different of "m". However, its is guaranteed that
* "c.sourceModule().moduleClass()" always returns "c".
*
* Phases like "AddInterfaces" and "ExpandMixins" are two examples
* of phases that create additional modules referring the same
* module class.
*
* Even if a module class is related to only one module, the use
* of this method may still be dangerous. The problem is that
* modules and module classes are not always as related as one
* might expect. For example, modules declared in a function are
* lifted out of the function by phase "LambdaLift". During this
* process, the module value is transformed into a module method
* with a "Ref" argument. If the "sourceModule" method is used to
* replace references to module classes by references to their
* source modules and this is done it naively with the class of a
* lifted module, it will yield wrong code because the the "Ref"
* argument will be missing.
*/
public ModuleSymbol sourceModule() {
throw Debug.abort("not a module class", this);
}
/** if type is a (possibly lazy) overloaded type, return its alternatves
* else return array consisting of symbol itself
*/
public Symbol[] alternativeSymbols() {
Symbol[] alts = type().alternativeSymbols();
if (alts.length == 0) return new Symbol[]{this};
else return alts;
}
/** if type is a (possibly lazy) overloaded type, return its alternatves
* else return array consisting of type itself
*/
public Type[] alternativeTypes() {
return type().alternativeTypes();
}
/** The symbol accessed by this accessor function.
*/
public Symbol accessed() {
assert (flags & ACCESSOR) != 0;
String name1 = name.toString();
if (name1.endsWith(Names._EQ.toString()))
name1 = name1.substring(0, name1.length() - Names._EQ.length());
return owner.info().lookup(Name.fromString(name1 + "$"));
}
/** The members of this class or module symbol
*/
public Scope members() {
return info().members();
}
/** Lookup symbol with given name; return Symbol.NONE if not found.
*/
public Symbol lookup(Name name) {
return info().lookup(name);
}
// Symbol types --------------------------------------------------------------
/** Was symbol's type updated during given phase? */
public final boolean isUpdatedAt(Phase phase) {
Phase next = phase.next;
TypeIntervalList infos = this.infos;
while (infos != null) {
if (infos.start == next) return true;
if (infos.limit().precedes(next)) return false;
infos = infos.prev;
}
return false;
}
/** Is this symbol locked? */
public final boolean isLocked() {
return (flags & LOCKED) != 0;
}
/** Is this symbol initialized? */
public final boolean isInitialized() {
return (flags & INITIALIZED) != 0;
}
/** Initialize the symbol */
public final Symbol initialize() {
info();
return this;
}
/** Make sure symbol is entered
*/
public final void preInitialize() {
//todo: clean up
if (infos.info instanceof SymbolLoader)
infos.info.complete(this);
}
/** Get info at start of current phase; This is:
* for a term symbol, its type
* for a type variable, its bound
* for a type alias, its right-hand side
* for a class symbol, the compound type consisting of
* its baseclasses and members.
*/
public final Type info() {
//if (isModule()) moduleClass().initialize();
if ((flags & INITIALIZED) == 0) {
Global global = Global.instance;
Phase current = global.currentPhase;
global.currentPhase = rawFirstInfoStartPhase();
Type info = rawFirstInfo();
assert info != null : this;
if ((flags & LOCKED) != 0) {
setInfo(Type.ErrorType);
flags |= INITIALIZED;
throw new CyclicReference(this, info);
}
flags |= LOCKED;
//System.out.println("completing " + this);//DEBUG
info.complete(this);
flags = flags & ~LOCKED;
if (info instanceof SourceCompleter && (flags & SNDTIME) == 0) {
flags |= SNDTIME;
Type tp = info();
flags &= ~SNDTIME;
} else {
assert !(rawInfo() instanceof Type.LazyType) : this;
//flags |= INITIALIZED;
}
//System.out.println("done: " + this);//DEBUG
global.currentPhase = current;
}
return rawInfo();
}
/** Get info at start of next phase
*/
public final Type nextInfo() {
Global.instance.nextPhase();
Type info = info();
Global.instance.prevPhase();
return info;
}
/** Get info at start of given phase
*/
protected final Type infoAt(Phase phase) {
Global global = phase.global;
Phase current = global.currentPhase;
global.currentPhase = phase;
Type info = info();
global.currentPhase = current;
return info;
}
/** Get info at start of current phase, without forcing lazy types.
*/
public final Type rawInfo() {
return rawInfoAt(Global.instance.currentPhase);
}
/** Get info at start of next phase, without forcing lazy types.
*/
public final Type rawNextInfo() {
Global.instance.nextPhase();
Type info = rawInfo();
Global.instance.prevPhase();
return info;
}
/** Get info at start of given phase, without forcing lazy types.
*/
private final Type rawInfoAt(Phase phase) {
//if (infos == null) return Type.NoType;//DEBUG
assert infos != null : this;
assert phase != null : this;
if (infos.limit().id <= phase.id) {
switch (infos.info) {
case LazyType():
// don't force lazy types
return infos.info;
}
while (infos.limit() != phase) {
Phase limit = infos.limit();
Type info = transformInfo(limit, infos.info);
assert info != null: Debug.show(this) + " -- " + limit;
if (info != infos.info) {
infos = new TypeIntervalList(infos, info, limit.next);
} else {
infos.setLimit(limit.next);
}
}
return infos.info;
} else {
TypeIntervalList infos = this.infos;
while (phase.id < infos.start.id && infos.prev != null)
infos = infos.prev;
return infos.info;
}
}
// where
private Type transformInfo(Phase phase, Type info) {
Global global = phase.global;
Phase current = global.currentPhase;
switch (info) {
case ErrorType:
case NoType:
return info;
case OverloadedType(Symbol[] alts, Type[] alttypes):
global.currentPhase = phase.next;
for (int i = 0; i < alts.length; i++) {
Type type = alts[i].info();
if (type != alttypes[i]) {
Type[] types = new Type[alttypes.length];
for (int j = 0; j < i; j++) types[j] = alttypes[j];
alttypes[i] = type;
for (; i < alts.length; i++)
types[i] = alts[i].info();
global.currentPhase = current;
return Type.OverloadedType(alts, types);
}
}
global.currentPhase = current;
return info;
default:
global.currentPhase = phase;
info = phase.transformInfo(this, info);
global.currentPhase = current;
return info;
}
}
/** Get first defined info, without forcing lazy types.
*/
public final Type rawFirstInfo() {
TypeIntervalList infos = this.infos;
assert infos != null : this;
while (infos.prev != null) infos = infos.prev;
return infos.info;
}
/** Get phase that first defined an info, without forcing lazy types.
*/
public final Phase rawFirstInfoStartPhase() {
TypeIntervalList infos = this.infos;
assert infos != null : this;
while (infos.prev != null) infos = infos.prev;
return infos.start;
}
/** Get type at start of current phase. The type of a symbol is:
* for a type symbol, the type corresponding to the symbol itself
* for a term symbol, its usual type
*/
public Type type() {
return info();
}
public Type getType() {
return info();
}
/** Get type at start of next phase
*/
public final Type nextType() {
Global.instance.nextPhase();
Type type = type();
Global.instance.prevPhase();
return type;
}
/** The infos of these symbols as an array.
*/
static public Type[] info(Symbol[] syms) {
Type[] tps = new Type[syms.length];
for (int i = 0; i < syms.length; i++)
tps[i] = syms[i].info();
return tps;
}
/** The types of these symbols as an array.
*/
static public Type[] type(Symbol[] syms) {
Type[] tps = new Type[syms.length];
for (int i = 0; i < syms.length; i++)
tps[i] = syms[i].type();
return tps;
}
static public Type[] getType(Symbol[] syms) {
return type(syms);
}
/** Get static type. */
public final Type staticType() {
return staticType(Type.EMPTY_ARRAY);
}
/** Get static type with given type argument. */
public final Type staticType(Type arg0) {
return staticType(new Type[]{arg0});
}
/** Get static type with given type arguments. */
public final Type staticType(Type arg0, Type arg1) {
return staticType(new Type[]{arg0, arg1});
}
/** Get static type with given type arguments. */
public final Type staticType(Type[] args) {
Type prefix = owner.staticPrefix();
if (isType()) return Type.typeRef(prefix, this, args);
assert args.length == 0: Debug.show(this, " - ", args);
return prefix.memberType(this);
}
/** Get static prefix. */
public final Type staticPrefix() {
assert isStaticOwner(): Debug.show(this) + " - " + isTerm() + " - " + isModuleClass() + " - " + owner().isStaticOwner() + " - " + isJava();
Global global = Global.instance;
if (global.PHASE.EXPLICITOUTER.id() < global.currentPhase.id)
return Type.NoPrefix;
if (isRoot()) return thisType();
assert sourceModule().owner() == owner(): Debug.show(this);
assert sourceModule().type().isObjectType(): Debug.show(this);
return Type.singleType(owner.staticPrefix(), sourceModule());
}
/** The type constructor of a symbol is:
* For a type symbol, the type corresponding to the symbol itself, excluding
* parameters.
* Not applicable for term symbols.
*/
public Type typeConstructor() {
throw new ApplicationError("typeConstructor inapplicable for " + this);
}
/** The low bound of this type variable
*/
public Type loBound() {
return Global.instance.definitions.ALL_TYPE();
}
/** The view bound of this type variable
*/
public Type vuBound() {
return Global.instance.definitions.ANY_TYPE();
}
/** Get this.type corresponding to this symbol
*/
public Type thisType() {
return Type.NoPrefix;
}
/** Get type of `this' in current class.
*/
public Type typeOfThis() {
return type();
}
/** Get this symbol of current class
*/
public Symbol thisSym() { return this; }
/** A total ordering between symbols that refines the class
* inheritance graph (i.e. subclass.isLess(superclass) always holds).
*/
public boolean isLess(Symbol that) {
if (this == that) return false;
int diff;
if (this.isType()) {
if (that.isType()) {
diff = this.closure().length - that.closure().length;
if (diff > 0) return true;
if (diff < 0) return false;
} else {
return true;
}
} else if (that.isType()) {
return false;
}
return this.id < that.id;
}
/** Return the symbol's type itself followed by all its direct and indirect
* base types, sorted by isLess(). Overridden for class symbols.
*/
public Type[] closure() {
return info().closure();
}
/** Return position of `c' in the closure of this type; -1 if not there.
*/
public int closurePos(Symbol c) {
if (this == c) return 0;
if (c.isCompoundSym()) return -1;
Type[] closure = closure();
int lo = 0;
int hi = closure.length - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
Symbol clsym = closure[mid].symbol();
if (c == clsym) return mid;
else if (c.isLess(clsym)) hi = mid - 1;
else if (clsym.isLess(c)) lo = mid + 1;
else throw new ApplicationError();
}
return -1;
}
public Type baseType(Symbol sym) {
int i = closurePos(sym);
if (i >= 0) return closure()[i];
else return Type.NoType;
}
/** Is this class a subclass of `c'? I.e. does it have a type instance
* of `c' as indirect base class?
*/
public boolean isSubClass(Symbol c) {
return this == c ||
c.isError() ||
closurePos(c) >= 0 ||
this == Global.instance.definitions.ALL_CLASS ||
(this == Global.instance.definitions.ALLREF_CLASS &&
c != Global.instance.definitions.ALL_CLASS &&
c.isSubClass(Global.instance.definitions.ANYREF_CLASS));
}
/** Get base types of this symbol */
public Type[] parents() {
return info().parents();
}
// ToString -------------------------------------------------------------------
/** String representation of symbol's simple name.
* Translates expansions of operators back to operator symbol. E.g.
* $eq => =.
*/
public String nameString() {
return NameTransformer.decode(simpleName());
}
/** String representation, including symbol's kind
* e.g., "class Foo", "function Bar".
*/
public String toString() {
return new SymbolTablePrinter().printSymbolKindAndName(this).toString();
}
/** String representation of location.
*/
public String locationString() {
if (owner.kind == CLASS &&
!owner.isAnonymousClass() && !owner.isCompoundSym() ||
Global.instance.debug)
return " in " +
(owner.isModuleClass() ? owner.sourceModule() : owner);
else
return "";
}
/** String representation of definition.
*/
public String defString() {
return new SymbolTablePrinter().printSignature(this).toString();
}
public static String[] defString(Symbol[] defs) {
String[] strs = new String[defs.length];
for (int i = 0; i < defs.length; i++)
strs[i] = defs[i].defString();
return strs;
}
// Overloading and Overriding -------------------------------------------
/** Add another overloaded alternative to this symbol.
*/
public Symbol overloadWith(Symbol that) {
assert isTerm() : Debug.show(this);
assert this.name == that.name : Debug.show(this) + " <> " + Debug.show(that);
assert this.owner == that.owner : Debug.show(this) + " != " + Debug.show(that);
assert this.isConstructor() == that.isConstructor();
int overflags = (this.flags & that.flags & (JAVA | ACCESSFLAGS | DEFERRED | PARAM | SYNTHETIC)) |
((this.flags | that.flags) & ACCESSOR);
Symbol overloaded = (this.isConstructor())
? this.constructorClass().newConstructor(this.constructorClass().pos, overflags)
: owner.newTerm(pos, overflags, name, 0);
overloaded.setInfo(new LazyOverloadedType(this, that));
return overloaded;
}
/** A lazy type which, when forced computed the overloaded type
* of symbols `sym1' and `sym2'. It also checks that this type is well-formed.
*/
public static class LazyOverloadedType extends Type.LazyType {
Symbol sym1;
Symbol sym2;
LazyOverloadedType(Symbol sym1, Symbol sym2) {
this.sym1 = sym1;
this.sym2 = sym2;
}
public Symbol[] alternativeSymbols() {
Symbol[] alts1 = sym1.alternativeSymbols();
Symbol[] alts2 = sym2.alternativeSymbols();
Symbol[] alts3 = new Symbol[alts1.length + alts2.length];
System.arraycopy(alts1, 0, alts3, 0, alts1.length);
System.arraycopy(alts2, 0, alts3, alts1.length, alts2.length);
return alts3;
}
public Type[] alternativeTypes() {
Type[] alts1 = sym1.alternativeTypes();
Type[] alts2 = sym2.alternativeTypes();
Type[] alts3 = new Type[alts1.length + alts2.length];
System.arraycopy(alts1, 0, alts3, 0, alts1.length);
System.arraycopy(alts2, 0, alts3, alts1.length, alts2.length);
return alts3;
}
public void complete(Symbol overloaded) {
overloaded.setInfo(
Type.OverloadedType(
alternativeSymbols(), alternativeTypes()));
}
public String toString() {
return "LazyOverloadedType(" + sym1 + "," + sym2 + ")";
}
}
/**
* Returns the symbol in type "base" which is overridden by this
* symbol in class "this.owner()". Returns "NONE" if no such
* symbol exists. The type "base" must be a supertype of class
* "this.owner()". If "exact" is true, overriding is restricted to
* symbols that have the same type. The method may return this
* symbol only if "base.symbol()" is equal to "this.owner()".
*/
public final Symbol overriddenSymbol(Type base, boolean exact) {
return overriddenSymbol(base, owner(), exact);
}
public final Symbol overriddenSymbol(Type base) {
return overriddenSymbol(base, false);
}
/**
* Returns the symbol in type "base" which is overridden by this
* symbol in "clasz". Returns "NONE" if no such symbol exists. The
* type "base" must be a supertype of "clasz" and "this.owner()"
* must be a superclass of "clasz". If "exact" is true, overriding
* is restricted to symbols that have the same type. The method
* may return this symbol if "base.symbol()" is a subclass of
* "this.owner()".
*/
public final Symbol overriddenSymbol(Type base, Symbol clasz, boolean exact) {
Type.Relation relation = exact
? Type.Relation.SameType
: Type.Relation.SuperType;
return base.lookup(this, clasz.thisType(), relation);
}
public final Symbol overriddenSymbol(Type base, Symbol clasz) {
return overriddenSymbol(base, clasz, false);
}
/**
* Returns the symbol in type "sub" which overrides this symbol in
* class "sub.symbol()". Returns this symbol if no such symbol
* exists. The class "sub.symbol()" must be a subclass of
* "this.owner()". If "exact" is true, overriding is restricted to
* symbols that have the same type.
*/
public final Symbol overridingSymbol(Type sub, boolean exact) {
Type.Relation relation = exact
? Type.Relation.SameType
: Type.Relation.SubType;
return sub.lookup(this, sub, relation);
}
public final Symbol overridingSymbol(Type sub) {
return overridingSymbol(sub, false);
}
/** Does this symbol override that symbol?
*/
public boolean overrides(Symbol that) {
return
((this.flags | that.flags) & PRIVATE) == 0 &&
this.name == that.name &&
owner.thisType().memberType(this).derefDef().isSubType(
owner.thisType().memberType(that).derefDef());
}
/** Reset symbol to initial state
*/
public void reset(Type completer) {
this.flags &= SOURCEFLAGS;
this.pos = 0;
this.infos = null;
this.setInfo(completer);
}
/**
* Returns the symbol to use in case of a rebinding due to a more
* precise type prefix.
*/
public Symbol rebindSym() {
return this;
}
/** return a tag which (in the ideal case) uniquely identifies
* class symbols
*/
public int tag() {
return name.toString().hashCode();
}
}
/** A class for term symbols
*/
class TermSymbol extends Symbol {
/** Constructor */
TermSymbol(Symbol owner, int pos, int flags, Name name, int attrs) {
super(VAL, owner, pos, flags, name, attrs);
assert name.isTermName(): Debug.show(this);
}
public boolean isInitializer() {
return name == Names.INITIALIZER;
}
public Symbol[] typeParams() {
return type().typeParams();
}
public Symbol[] valueParams() {
return type().valueParams();
}
protected Symbol cloneSymbolImpl(Symbol owner, int attrs) {
return new TermSymbol(owner, pos, flags, name, attrs);
}
}
/** A class for constructor symbols */
final class ConstructorSymbol extends TermSymbol {
/** The constructed class */
private final Symbol clasz;
/** Initializes this instance. */
ConstructorSymbol(Symbol clasz, int pos, int flags) {
super(clasz.owner(), pos, flags, Names.CONSTRUCTOR, IS_CONSTRUCTOR);
this.clasz = clasz;
}
public boolean isInitializer() {
return false;
}
public Symbol constructorClass() {
return clasz;
}
protected final Symbol cloneSymbolImpl(Symbol owner, int attrs) {
throw Debug.abort("illegal clone of constructor", this);
}
}
/** A class for module symbols */
public class ModuleSymbol extends TermSymbol {
/** The module class */
private final ModuleClassSymbol clasz;
/** Initializes this instance. */
private ModuleSymbol(Symbol owner, int pos, int flags, Name name,
int attrs, ModuleClassSymbol clasz)
{
super(owner, pos, flags | MODUL | FINAL | STABLE, name, attrs);
this.clasz = clasz != null ? clasz : new ModuleClassSymbol(this);
setType(Type.typeRef(owner().thisType(), this.clasz,Type.EMPTY_ARRAY));
}
/** Initializes this instance. */
ModuleSymbol(Symbol owner, int pos, int flags, Name name) {
this(owner, pos, flags, name, 0, null);
}
public ModuleClassSymbol moduleClass() {
// test may fail because loaded modules may be downgraded to
// case class factory methods (see Symbol#linkedModule())
assert isModule(): Debug.show(this);
return clasz;
}
protected final Symbol cloneSymbolImpl(Symbol owner, int attrs) {
return new ModuleSymbol(owner, pos, flags, name, attrs, clasz);
}
}
/**
* A class for linked module symbols
*
* @see Symbol#linkedModule()
*/
final class LinkedModuleSymbol extends ModuleSymbol {
/** The linked class */
private final LinkedClassSymbol clasz;
/** Initializes this instance. */
LinkedModuleSymbol(LinkedClassSymbol clasz) {
super(clasz.owner(), clasz.pos, clasz.flags & JAVA,
clasz.name.toTermName());
this.clasz = clasz;
}
public ClassSymbol linkedClass() {
return clasz;
}
}
/** A base class for all type symbols.
* It has AliasTypeSymbol, AbsTypeSymbol, ClassSymbol as subclasses.
*/
abstract class TypeSymbol extends Symbol {
/** The history of closures of this symbol */
private final History/*<Type[]>*/ closures;
/** A cache for type constructors
*/
private Type tycon = null;
/** The primary constructor of this type */
private Symbol constructor;
/** Constructor */
public TypeSymbol(int kind, Symbol owner, int pos, int flags, Name name, int attrs) {
super(kind, owner, pos, flags, name, attrs);
this.closures = new ClosureHistory();
assert name.isTypeName() : this;
this.constructor = newConstructor(pos, flags & CONSTRFLAGS);
}
protected final void copyConstructorInfo(TypeSymbol other) {
{
Type info = primaryConstructor().info().cloneType(
primaryConstructor(), other.primaryConstructor());
if (!isTypeAlias()) info = fixConstrType(info, other);
other.primaryConstructor().setInfo(info);
}
Symbol[] alts = allConstructors().alternativeSymbols();
for (int i = 1; i < alts.length; i++) {
Symbol constr = other.newConstructor(alts[i].pos, alts[i].flags);
other.addConstructor(constr);
Type info = alts[i].info().cloneType(alts[i], constr);
if (!isTypeAlias()) info = fixConstrType(info, other);
constr.setInfo(info);
}
}
private final Type fixConstrType(Type type, Symbol clone) {
switch (type) {
case MethodType(Symbol[] vparams, Type result):
result = fixConstrType(result, clone);
return new Type.MethodType(vparams, result);
case PolyType(Symbol[] tparams, Type result):
result = fixConstrType(result, clone);
return new Type.PolyType(tparams, result);
case TypeRef(Type pre, Symbol sym, Type[] args):
if (sym != this && isTypeAlias() && owner().isCompoundSym())
return type;
assert sym == this: Debug.show(sym) + " != " + Debug.show(this);
return Type.typeRef(pre, clone, args);
case LazyType():
return type;
default:
throw Debug.abort("unexpected constructor type:" + clone + ":" + type);
}
}
/** add a constructor
*/
public final void addConstructor(Symbol constr) {
assert constr.isConstructor(): Debug.show(constr);
constructor = constructor.overloadWith(constr);
}
/** Get primary constructor */
public final Symbol primaryConstructor() {
return constructor.firstAlternative();
}
/** Get all constructors */
public final Symbol allConstructors() {
return constructor;
}
/** Get type parameters */
public final Symbol[] typeParams() {
return primaryConstructor().info().typeParams();
}
/** Get value parameters */
public final Symbol[] valueParams() {
return (kind == CLASS) ? primaryConstructor().info().valueParams()
: Symbol.EMPTY_ARRAY;
}
/** Get type constructor */
public final Type typeConstructor() {
if (tycon == null)
tycon = Type.typeRef(owner().thisType(), this, Type.EMPTY_ARRAY);
return tycon;
}
public Symbol setOwner(Symbol owner) {
tycon = null;
constructor.setOwner0(owner);
switch (constructor.type()) {
case OverloadedType(Symbol[] alts, _):
for (int i = 0; i < alts.length; i++) alts[i].setOwner0(owner);
}
return super.setOwner(owner);
}
/** Get type */
public final Type type() {
return primaryConstructor().type().resultType();
}
public final Type getType() {
return primaryConstructor().type().resultType();
}
/**
* Get closure at start of current phase. The closure of a symbol
* is a list of types which contains the type of the symbol
* followed by all its direct and indirect base types, sorted by
* isLess().
*/
public final Type[] closure() {
if (kind == ALIAS) return info().symbol().closure();
return (Type[])closures.getValue(this);
}
public void reset(Type completer) {
super.reset(completer);
closures.reset();
tycon = null;
}
protected final Symbol cloneSymbolImpl(Symbol owner, int attrs) {
TypeSymbol clone = cloneTypeSymbolImpl(owner, attrs);
copyConstructorInfo(clone);
return clone;
}
protected abstract TypeSymbol cloneTypeSymbolImpl(Symbol owner, int attrs);
}
final class AliasTypeSymbol extends TypeSymbol {
/** Initializes this instance. */
AliasTypeSymbol(Symbol owner, int pos, int flags, Name name, int attrs) {
super(ALIAS, owner, pos, flags, name, attrs);
}
protected TypeSymbol cloneTypeSymbolImpl(Symbol owner, int attrs) {
return new AliasTypeSymbol(owner, pos, flags, name, attrs);
}
}
final class AbsTypeSymbol extends TypeSymbol {
private Type lobound = null;
private Type vubound = null;
/** Initializes this instance. */
AbsTypeSymbol(Symbol owner, int pos, int flags, Name name, int attrs) {
super(TYPE, owner, pos, flags, name, attrs);
allConstructors().setInfo(Type.MethodType(EMPTY_ARRAY, Type.typeRef(owner.thisType(), this, Type.EMPTY_ARRAY)));
}
public Type loBound() {
initialize();
return lobound == null ? Global.instance.definitions.ALL_TYPE() : lobound;
}
public Type vuBound() {
initialize();
return !isViewBounded() || vubound == null
? Global.instance.definitions.ANY_TYPE() : vubound;
}
public Symbol setLoBound(Type lobound) {
this.lobound = lobound;
return this;
}
public Symbol setVuBound(Type vubound) {
this.vubound = vubound;
return this;
}
protected TypeSymbol cloneTypeSymbolImpl(Symbol owner, int attrs) {
TypeSymbol clone = new AbsTypeSymbol(owner, pos, flags, name, attrs);
clone.setLoBound(loBound());
clone.setVuBound(vuBound());
return clone;
}
}
/** A class for class symbols. */
public class ClassSymbol extends TypeSymbol {
/** The given type of self, or NoType, if no explicit type was given.
*/
private Symbol thisSym = this;
public Symbol thisSym() { return thisSym; }
/** A cache for this.thisType()
*/
final private Type thistp = Type.ThisType(this);
private final Symbol rebindSym;
/** Initializes this instance. */
ClassSymbol(Symbol owner, int pos, int flags, Name name, int attrs) {
super(CLASS, owner, pos, flags, name, attrs);
this.rebindSym = owner.newTypeAlias(pos, 0, Names.ALIAS(this));
Type rebindType = new ClassAliasLazyType();
this.rebindSym.setInfo(rebindType);
this.rebindSym.primaryConstructor().setInfo(rebindType);
}
private class ClassAliasLazyType extends Type.LazyType {
public void complete(Symbol ignored) {
Symbol clasz = ClassSymbol.this;
Symbol alias = rebindSym;
Type prefix = clasz.owner().thisType();
Type constrtype = clasz.type();
constrtype = Type.MethodType(Symbol.EMPTY_ARRAY, constrtype);
constrtype = Type.PolyType(clasz.typeParams(), constrtype);
constrtype = constrtype.cloneType(
clasz.primaryConstructor(), alias.primaryConstructor());
alias.primaryConstructor().setInfo(constrtype);
alias.setInfo(constrtype.resultType());
}
}
/** Creates the root class. */
public static Symbol newRootClass(Global global) {
int pos = Position.NOPOS;
Name name = Names.ROOT.toTypeName();
Symbol owner = Symbol.NONE;
int flags = JAVA | PACKAGE | FINAL;
int attrs = IS_ROOT;
Symbol clasz = new ClassSymbol(owner, pos, flags, name, attrs);
clasz.setInfo(global.getRootLoader());
clasz.primaryConstructor().setInfo(
Type.MethodType(Symbol.EMPTY_ARRAY, clasz.typeConstructor()));
// !!! Type.MethodType(Symbol.EMPTY_ARRAY, clasz.thisType()));
return clasz;
}
/** Creates the this-type symbol associated to this class. */
private final Symbol newThisType() {
return newTerm(pos, SYNTHETIC, Names.this_, IS_THISTYPE);
}
public Type thisType() {
Global global = Global.instance;
if (global.currentPhase.id > global.PHASE.ERASURE.id()) return type();
return thistp;
}
public Type typeOfThis() {
return thisSym.type();
}
public Symbol setTypeOfThis(Type tp) {
thisSym = newThisType();
thisSym.setInfo(tp);
return this;
}
/** Return the next enclosing class */
public Symbol enclClass() {
return this;
}
public Symbol caseFieldAccessor(int index) {
assert (flags & CASE) != 0 : this;
Scope.SymbolIterator it = info().members().iterator();
Symbol sym = null;
if ((flags & JAVA) == 0) {
for (int i = 0; i <= index; i++) {
do {
sym = it.next();
} while (sym.kind != VAL || (sym.flags & CASEACCESSOR) == 0 || !sym.isMethod());
}
//System.out.println(this + ", case field[" + index + "] = " + sym);//DEBUG
} else {
sym = it.next();
while ((sym.flags & SYNTHETIC) == 0) {
//System.out.println("skipping " + sym);
sym = it.next();
}
for (int i = 0; i < index; i++)
sym = it.next();
//System.out.println("field accessor = " + sym);//DEBUG
}
assert sym != null : this;
return sym;
}
public final Symbol rebindSym() {
return rebindSym;
}
public void reset(Type completer) {
super.reset(completer);
thisSym = this;
}
protected final TypeSymbol cloneTypeSymbolImpl(Symbol owner, int attrs) {
assert !isModuleClass(): Debug.show(this);
ClassSymbol clone = new ClassSymbol(owner, pos, flags, name, attrs);
if (thisSym != this) clone.setTypeOfThis(typeOfThis());
return clone;
}
}
/**
* A class for module class symbols
*
* @see Symbol#sourceModule()
*/
public final class ModuleClassSymbol extends ClassSymbol {
/** The source module */
private final ModuleSymbol module;
/** Initializes this instance. */
ModuleClassSymbol(ModuleSymbol module) {
super(module.owner(), module.pos,
(module.flags & MODULE2CLASSFLAGS) | MODUL | FINAL,
module.name.toTypeName(), 0);
primaryConstructor().flags |= PRIVATE;
primaryConstructor().setInfo(
Type.MethodType(Symbol.EMPTY_ARRAY, typeConstructor()));
this.module = module;
}
public ModuleSymbol sourceModule() {
return module;
}
}
/**
* A class for linked class symbols
*
* @see Symbol#linkedModule()
*/
final class LinkedClassSymbol extends ClassSymbol {
/** The linked module */
private final LinkedModuleSymbol module;
/** Initializes this instance. */
LinkedClassSymbol(Symbol owner, int flags, Name name) {
super(owner, Position.NOPOS, flags, name, 0);
this.module = new LinkedModuleSymbol(this);
}
public ModuleSymbol linkedModule() {
return module;
}
}
/** The class of Symbol.NONE
*/
final class NoSymbol extends Symbol {
/** Constructor */
public NoSymbol() {
super(Kinds.NONE, null, Position.NOPOS, 0, Names.NOSYMBOL, 0);
super.setInfo(Type.NoType);
}
/** Set type */
public Symbol setInfo(Type info) {
assert info == Type.NoType : info;
return this;
}
/** Return the next enclosing class */
public Symbol enclClass() {
return this;
}
/** Return the next enclosing method */
public Symbol enclMethod() {
return this;
}
public Symbol owner() {
throw new ApplicationError();
}
public Type thisType() {
return Type.NoPrefix;
}
public void reset(Type completer) {
}
protected Symbol cloneSymbolImpl(Symbol owner, int attrs) {
throw Debug.abort("illegal clone", this);
}
}
/** An exception for signalling cyclic references.
*/
public class CyclicReference extends Type.Error {
public Symbol sym;
public Type info;
public CyclicReference(Symbol sym, Type info) {
super("illegal cyclic reference involving " + sym);
this.sym = sym;
this.info = info;
}
}
/** A base class for values indexed by phases. */
abstract class IntervalList {
/** Interval starts at start of phase "start" (inclusive) */
public final Phase start;
/** Interval ends at start of phase "limit" (inclusive) */
private Phase limit;
public IntervalList(IntervalList prev, Phase start) {
this.start = start;
this.limit = start;
assert start != null && (prev == null || prev.limit.next == start) :
Global.instance.currentPhase + " - " + prev + " - " + start;
}
public Phase limit() {
return limit;
}
public void setLimit(Phase phase) {
assert phase != null && !phase.precedes(start) : start + " - " + phase;
limit = phase;
}
public String toString() {
return "[" + start + "->" + limit + "]";
}
}
/** A class for types indexed by phases. */
class TypeIntervalList extends IntervalList {
/** Previous interval */
public final TypeIntervalList prev;
/** Info valid during this interval */
public final Type info;
public TypeIntervalList(TypeIntervalList prev, Type info, Phase start) {
super(prev, start);
this.prev = prev;
this.info = info;
assert info != null;
}
}
| sources/scalac/symtab/Symbol.java | /* ____ ____ ____ ____ ______ *\
** / __// __ \/ __// __ \/ ____/ SOcos COmpiles Scala **
** __\_ \/ /_/ / /__/ /_/ /\_ \ (c) 2002, LAMP/EPFL **
** /_____/\____/\___/\____/____/ **
**
\* */
//todo check significance of JAVA flag.
package scalac.symtab;
import scala.tools.util.Position;
import scalac.ApplicationError;
import scalac.Global;
import scalac.Phase;
import scalac.framework.History;
import scalac.util.ArrayApply;
import scalac.util.Name;
import scalac.util.Names;
import scalac.util.NameTransformer;
import scalac.util.Debug;
public abstract class Symbol implements Modifiers, Kinds {
/** An empty symbol array */
public static final Symbol[] EMPTY_ARRAY = new Symbol[0];
/** An empty array of symbol arrays */
public static final Symbol[][] EMPTY_ARRAY_ARRAY = new Symbol[0][];
/** The absent symbol */
public static final Symbol NONE = new NoSymbol();
// Attribues -------------------------------------------------------------
public static final int IS_ROOT = 0x00000001;
public static final int IS_ANONYMOUS = 0x00000002;
public static final int IS_LABEL = 0x00000010;
public static final int IS_CONSTRUCTOR = 0x00000020;
public static final int IS_ACCESSMETHOD = 0x00000100;
public static final int IS_ERROR = 0x10000000;
public static final int IS_THISTYPE = 0x20000000;
public static final int IS_LOCALDUMMY = 0x40000000;
public static final int IS_COMPOUND = 0x80000000;
// Fields -------------------------------------------------------------
/** The unique identifier generator */
private static int ids;
/** The kind of the symbol */
public int kind;
/** The position of the symbol */
public int pos;
/** The name of the symbol */
public Name name;
/** The modifiers of the symbol */
public int flags;
/** The owner of the symbol */
private Symbol owner;
/** The infos of the symbol */
private TypeIntervalList infos;
/** The attributes of the symbol */
private final int attrs;
/** The unique identifier */
public final int id;
// Constructors -----------------------------------------------------------
/** Generic symbol constructor */
public Symbol(int kind, Symbol owner, int pos, int flags, Name name, int attrs) {
this.kind = kind;
this.pos = pos;
this.name = name;
this.owner = owner == null ? this : owner;
this.flags = flags & ~(INITIALIZED | LOCKED); // safety first
this.attrs = attrs;
this.id = ids++;
}
// Factories --------------------------------------------------------------
/** Creates a new term owned by this symbol. */
public final Symbol newTerm(int pos, int flags, Name name) {
return newTerm(pos, flags, name, 0);
}
/** Creates a new constructor of this symbol. */
public final Symbol newConstructor(int pos, int flags) {
assert isType(): Debug.show(this);
return new ConstructorSymbol(this, pos, flags);
}
/** Creates a new method owned by this symbol. */
public final Symbol newMethod(int pos, int flags, Name name) {
assert isClass(): Debug.show(this);
return newTerm(pos, flags, name, 0);
}
/** Creates a new access method owned by this symbol. */
public final Symbol newAccessMethod(int pos, Name name) {
assert isClass(): Debug.show(this);
int flags = PRIVATE | FINAL | SYNTHETIC;
return newTerm(pos, flags, name, IS_ACCESSMETHOD);
}
/** Creates a new function owned by this symbol. */
public final Symbol newFunction(int pos, int flags, Name name) {
assert isTerm(): Debug.show(this);
return newTerm(pos, flags, name, 0);
}
/** Creates a new method or function owned by this symbol. */
public final Symbol newMethodOrFunction(int pos, int flags, Name name){
assert isClass() || isTerm(): Debug.show(this);
return newTerm(pos, flags, name, 0);
}
/** Creates a new label owned by this symbol. */
public final Symbol newLabel(int pos, Name name) {
assert isTerm(): Debug.show(this);
return newTerm(pos, 0, name, IS_LABEL);
}
/** Creates a new field owned by this symbol. */
public final Symbol newField(int pos, int flags, Name name) {
assert isClass(): Debug.show(this);
return newTerm(pos, flags, name, 0);
}
/** Creates a new variable owned by this symbol. */
public final Symbol newVariable(int pos, int flags, Name name) {
assert isTerm(): Debug.show(this);
return newTerm(pos, flags, name, 0);
}
/** Creates a new variable owned by this symbol. */
public final Symbol newFieldOrVariable(int pos, int flags, Name name) {
assert isClass() || isTerm(): Debug.show(this);
return newTerm(pos, flags, name, 0);
}
/** Creates a new pattern variable owned by this symbol. */
public final Symbol newPatternVariable(int pos, Name name) {
return newVariable(pos, 0, name);
}
/** Creates a new value parameter owned by this symbol. */
public final Symbol newVParam(int pos, int flags, Name name) {
assert isTerm(): Debug.show(this);
return newTerm(pos, flags | PARAM, name);
}
/**
* Creates a new value parameter owned by this symbol and
* initializes it with the type.
*/
public final Symbol newVParam(int pos, int flags, Name name, Type type) {
Symbol tparam = newVParam(pos, flags, name);
tparam.setInfo(type);
return tparam;
}
/**
* Creates a new initialized dummy symbol for template of this
* class.
*/
public final Symbol newLocalDummy() {
assert isClass(): Debug.show(this);
Symbol local = newTerm(pos, 0, Names.LOCAL(this), IS_LOCALDUMMY);
local.setInfo(Type.NoType);
return local;
}
/** Creates a new module owned by this symbol. */
public final Symbol newModule(int pos, int flags, Name name) {
return new ModuleSymbol(this, pos, flags, name);
}
/**
* Creates a new package owned by this symbol and initializes it
* with an empty scope.
*/
public final Symbol newPackage(int pos, Name name) {
return newPackage(pos, name, null);
}
/**
* Creates a new package owned by this symbol, initializes it with
* the loader and enters it in the scope if it's non-null.
*/
public final Symbol newLoadedPackage(Name name, SymbolLoader loader,
Scope scope)
{
assert loader != null: Debug.show(this) + " - " + name;
Symbol peckage = newPackage(Position.NOPOS, name, loader);
if (scope != null) scope.enterNoHide(peckage);
return peckage;
}
/**
* Creates a new error value owned by this symbol and initializes
* it with an error type.
*/
public Symbol newErrorValue(Name name) {
Symbol symbol = newTerm(pos, SYNTHETIC, name, IS_ERROR);
symbol.setInfo(Type.ErrorType);
return symbol;
}
/** Creates a new type alias owned by this symbol. */
public final Symbol newTypeAlias(int pos, int flags, Name name) {
return new AliasTypeSymbol(this, pos, flags, name, 0);
}
/** Creates a new abstract type owned by this symbol. */
public final Symbol newAbstractType(int pos, int flags, Name name) {
return new AbsTypeSymbol(this, pos, flags, name, 0);
}
/** Creates a new type parameter owned by this symbol. */
public final Symbol newTParam(int pos, int flags, Name name) {
assert isTerm(): Debug.show(this);
return newAbstractType(pos, flags | PARAM, name);
}
/**
* Creates a new type parameter owned by this symbol and
* initializes it with the type.
*/
public final Symbol newTParam(int pos, int flags, Name name, Type type) {
Symbol tparam = newTParam(pos, flags, name);
tparam.setInfo(type);
return tparam;
}
/**
* Creates a new type alias owned by this symbol and initializes
* it with the info.
*/
public final Symbol newTypeAlias(int pos, int flags, Name name, Type info){
Symbol alias = newTypeAlias(pos, flags, name);
alias.setInfo(info);
alias.allConstructors().setInfo(Type.MethodType(EMPTY_ARRAY, info));
return alias;
}
/** Creates a new class owned by this symbol. */
public final ClassSymbol newClass(int pos, int flags, Name name) {
return newClass(pos, flags, name, 0);
}
/** Creates a new anonymous class owned by this symbol. */
public final ClassSymbol newAnonymousClass(int pos, Name name) {
assert isTerm(): Debug.show(this);
return newClass(pos, 0, name, IS_ANONYMOUS);
}
/**
* Creates a new class with a linked module, both owned by this
* symbol, initializes them with the loader and enters the class
* and the module in the scope if it's non-null.
*/
public final ClassSymbol newLoadedClass(int flags, Name name,
SymbolLoader loader, Scope scope)
{
assert isPackageClass(): Debug.show(this);
assert loader != null: Debug.show(this) + " - " + name;
ClassSymbol clasz = new LinkedClassSymbol(this, flags, name);
clasz.setInfo(loader);
clasz.allConstructors().setInfo(loader);
clasz.linkedModule().setInfo(loader);
clasz.linkedModule().moduleClass().setInfo(loader);
if (scope != null) scope.enterNoHide(clasz);
if (scope != null) scope.enterNoHide(clasz.linkedModule());
return clasz;
}
/**
* Creates a new error class owned by this symbol and initializes
* it with an error type.
*/
public ClassSymbol newErrorClass(Name name) {
ClassSymbol symbol = newClass(pos, SYNTHETIC, name, IS_ERROR);
Scope scope = new ErrorScope(this);
symbol.setInfo(Type.compoundType(Type.EMPTY_ARRAY, scope, this));
symbol.allConstructors().setInfo(Type.ErrorType);
return symbol;
}
/** Creates a new term owned by this symbol. */
final Symbol newTerm(int pos, int flags, Name name, int attrs) {
return new TermSymbol(this, pos, flags, name, attrs);
}
/** Creates a new package owned by this symbol. */
final Symbol newPackage(int pos, Name name, Type info) {
assert isPackageClass(): Debug.show(this);
Symbol peckage = newModule(pos, JAVA | PACKAGE, name);
if (info == null) info = Type.compoundType(
Type.EMPTY_ARRAY, new Scope(), peckage.moduleClass());
peckage.moduleClass().setInfo(info);
return peckage;
}
/** Creates a new class owned by this symbol. */
final ClassSymbol newClass(int pos, int flags, Name name, int attrs) {
return new ClassSymbol(this, pos, flags, name, attrs);
}
/** Creates a new compound class owned by this symbol. */
final ClassSymbol newCompoundClass(Type info) {
int pos = Position.FIRSTPOS;
Name name = Names.COMPOUND_NAME.toTypeName();
int flags = ABSTRACT | SYNTHETIC;
int attrs = IS_COMPOUND;
ClassSymbol clasz = newClass(pos, flags, name, attrs);
clasz.setInfo(info);
clasz.primaryConstructor().setInfo(
Type.MethodType(Symbol.EMPTY_ARRAY, clasz.typeConstructor()));
return clasz;
}
// Copying & cloning ------------------------------------------------------
/** Return a fresh symbol with the same fields as this one.
*/
public final Symbol cloneSymbol() {
return cloneSymbol(owner);
}
/** Return a fresh symbol with the same fields as this one and the
* given owner.
*/
public final Symbol cloneSymbol(Symbol owner) {
Symbol clone = cloneSymbolImpl(owner, attrs);
clone.setInfo(info());
return clone;
}
protected abstract Symbol cloneSymbolImpl(Symbol owner, int attrs);
/** Returns a shallow copy of the given array. */
public static Symbol[] cloneArray(Symbol[] array) {
return cloneArray(0, array, 0);
}
/**
* Returns a shallow copy of the given array prefixed by "prefix"
* null items.
*/
public static Symbol[] cloneArray(int prefix, Symbol[] array) {
return cloneArray(prefix, array, 0);
}
/**
* Returns a shallow copy of the given array suffixed by "suffix"
* null items.
*/
public static Symbol[] cloneArray(Symbol[] array, int suffix) {
return cloneArray(0, array, suffix);
}
/**
* Returns a shallow copy of the given array prefixed by "prefix"
* null items and suffixed by "suffix" null items.
*/
public static Symbol[] cloneArray(int prefix, Symbol[] array, int suffix) {
assert prefix >= 0 && suffix >= 0: prefix + " - " + suffix;
int size = prefix + array.length + suffix;
if (size == 0) return EMPTY_ARRAY;
Symbol[] clone = new Symbol[size];
for (int i = 0; i < array.length; i++) clone[prefix + i] = array[i];
return clone;
}
/** Returns the concatenation of the two arrays. */
public static Symbol[] concat(Symbol[] array1, Symbol[] array2) {
if (array1.length == 0) return array2;
if (array2.length == 0) return array1;
Symbol[] clone = cloneArray(array1.length, array2);
for (int i = 0; i < array1.length; i++) clone[i] = array1[i];
return clone;
}
// Setters ---------------------------------------------------------------
/** Set owner */
public Symbol setOwner(Symbol owner) {
assert !isConstructor() && !isNone() && !isError(): Debug.show(this);
setOwner0(owner);
return this;
}
protected void setOwner0(Symbol owner) {
this.owner = owner;
}
/** Set type -- this is an alias for setInfo(Type info) */
public final Symbol setType(Type info) { return setInfo(info); }
/**
* Set initial information valid from start of current phase. This
* information is visible in the current phase and will be
* transformed by the current phase (except if current phase is
* the first one).
*/
public Symbol setInfo(Type info) {
return setInfoAt(info, Global.instance.currentPhase);
}
/**
* Set initial information valid from start of given phase. This
* information is visible in the given phase and will be
* transformed by the given phase.
*/
private final Symbol setInfoAt(Type info, Phase phase) {
assert info != null: Debug.show(this);
assert phase != null: Debug.show(this);
assert !isConstructor()
|| info instanceof Type.LazyType
|| info == Type.NoType
|| info == Type.ErrorType
|| info instanceof Type.MethodType
|| info instanceof Type.OverloadedType
|| info instanceof Type.PolyType
: "illegal type for " + this + ": " + info;
infos = new TypeIntervalList(null, info, phase);
if (info instanceof Type.LazyType) flags &= ~INITIALIZED;
else flags |= INITIALIZED;
return this;
}
/**
* Set new information valid from start of next phase. This
* information is only visible in next phase or through
* "nextInfo". It will not be transformed by the current phase.
*/
public final Symbol updateInfo(Type info) {
return updateInfoAt(info, Global.instance.currentPhase.next);
}
/**
* Set new information valid from start of given phase. This
* information is only visible from the start of the given phase
* which is also the first phase that will transform this
* information.
*/
private final Symbol updateInfoAt(Type info, Phase phase) {
assert info != null: Debug.show(this);
assert phase != null: Debug.show(this);
assert infos != null: Debug.show(this);
assert !phase.precedes(infos.limit()) :
Debug.show(this) + " -- " + phase + " -- " + infos.limit();
if (infos.limit() == phase) {
if (infos.start == phase)
infos = infos.prev;
else
infos.setLimit(infos.limit().prev);
}
infos = new TypeIntervalList(infos, info, phase);
return this;
}
/** Set type of `this' in current class
*/
public Symbol setTypeOfThis(Type tp) {
throw new ApplicationError(this + ".setTypeOfThis");
}
/** Set the low bound of this type variable
*/
public Symbol setLoBound(Type lobound) {
throw new ApplicationError("setLoBound inapplicable for " + this);
}
/** Set the view bound of this type variable
*/
public Symbol setVuBound(Type lobound) {
throw new ApplicationError("setVuBound inapplicable for " + this);
}
/** Add an auxiliary constructor to class.
*/
public void addConstructor(Symbol constr) {
throw new ApplicationError("addConstructor inapplicable for " + this);
}
// Symbol classification ----------------------------------------------------
/** Does this symbol denote an error symbol? */
public final boolean isError() {
return (attrs & IS_ERROR) != 0;
}
/** Does this symbol denote the none symbol? */
public final boolean isNone() {
return kind == Kinds.NONE;
}
/** Does this symbol denote a type? */
public final boolean isType() {
return kind == TYPE || kind == CLASS || kind == ALIAS;
}
/** Does this symbol denote a term? */
public final boolean isTerm() {
return kind == VAL;
}
/** Does this symbol denote a value? */
public final boolean isValue() {
preInitialize();
return kind == VAL && !(isModule() && isJava()) && !isPackage();
}
/** Does this symbol denote a stable value? */
public final boolean isStable() {
return kind == VAL &&
((flags & DEF) == 0) &&
((flags & STABLE) != 0 ||
(flags & MUTABLE) == 0 && type().isObjectType());
}
/** Does this symbol have the STABLE flag? */
public final boolean hasStableFlag() {
return (flags & STABLE) != 0;
}
/** Is this symbol static (i.e. with no outer instance)? */
public final boolean isStatic() {
return owner.isStaticOwner();
}
/** Does this symbol denote a class that defines static symbols? */
public final boolean isStaticOwner() {
return isRoot() || (isStatic() && isModuleClass()
// !!! remove later? translation does not work (yet?)
&& isJava());
}
/** Is this symbol final?
*/
public final boolean isFinal() {
return
(flags & (FINAL | PRIVATE)) != 0 || isLocal() || owner.isModuleClass();
}
/** Does this symbol denote a variable? */
public final boolean isVariable() {
return kind == VAL && (flags & MUTABLE) != 0;
}
/** Does this symbol denote a view bounded type variable? */
public final boolean isViewBounded() {
Global global = Global.instance;
return kind == TYPE && (flags & VIEWBOUND) != 0 &&
global.currentPhase.id <= global.PHASE.REFCHECK.id();
}
/**
* Does this symbol denote a final method? A final method is one
* that can't be overridden in a subclass. This method assumes
* that this symbol denotes a method. It doesn't test it.
*/
public final boolean isMethodFinal() {
return (flags & FINAL) != 0 || isPrivate() || isLifted();
}
/** Does this symbol denote a sealed class symbol? */
public final boolean isSealed() {
return (flags & SEALED) != 0;
}
/** Does this symbol denote a method?
*/
public final boolean isInitializedMethod() {
if (infos == null) return false;
switch (rawInfo()) {
case MethodType(_, _):
case PolyType(_, _):
return true;
case OverloadedType(Symbol[] alts, _):
for (int i = 0; i < alts.length; i++)
if (alts[i].isMethod()) return true;
return false;
default:
return false;
}
}
public final boolean isMethod() {
initialize();
return isInitializedMethod();
}
public final boolean isCaseFactory() {
return isMethod() && !isConstructor() && (flags & CASE) != 0;
}
public final boolean isAbstractClass() {
preInitialize();
return kind == CLASS && (flags & ABSTRACT) != 0 &&
this != Global.instance.definitions.ARRAY_CLASS;
}
public final boolean isAbstractOverride() {
preInitialize();
return (flags & (ABSTRACT | OVERRIDE)) == (ABSTRACT | OVERRIDE);
}
/* Does this symbol denote an anonymous class? */
public final boolean isAnonymousClass() {
return isClass() && (attrs & IS_ANONYMOUS) != 0;
}
/** Does this symbol denote the root class or root module?
*/
public final boolean isRoot() {
return (attrs & IS_ROOT) != 0;
}
/** Does this symbol denote something loaded from a Java class? */
public final boolean isJava() {
preInitialize();
return (flags & JAVA) != 0;
}
/** Does this symbol denote a Java package? */
public final boolean isPackage() {
return kind == VAL && (flags & PACKAGE) != 0;
}
/** Does this symbol denote a Java package class? */
public final boolean isPackageClass() {
return kind == CLASS && (flags & PACKAGE) != 0;
}
/** Does this symbol denote a module? */
public final boolean isModule() {
return kind == VAL && (flags & MODUL) != 0;
}
/** Does this symbol denote a module class? */
public final boolean isModuleClass() {
return kind == CLASS && (flags & MODUL) != 0;
}
/** Does this symbol denote a class? */
public final boolean isClass() {
return kind == CLASS && (flags & PACKAGE) == 0;
}
/** Does this symbol denote a case class?
*/
public final boolean isCaseClass() {
preInitialize();
return kind == CLASS && (flags & CASE) != 0;
}
/** Does this symbol denote a uniform (i.e. parameterless) class? */
public final boolean isTrait() {
//preInitialize(); todo: enable, problem is that then we cannot print
// during unpickle
return kind == CLASS && (flags & TRAIT) != 0;
}
/** Does this class symbol denote a compound type symbol? */
public final boolean isCompoundSym() {
return (attrs & IS_COMPOUND) != 0;
}
/** Does this symbol denote a this symbol? */
public final boolean isThisSym() {
return (attrs & IS_THISTYPE) != 0;
}
/** Does this symbol denote an interface? */
public final boolean isInterface() {
info(); // force delayed transformInfos that may change this flag
return (flags & INTERFACE) != 0;
}
/** Does this symbol denote a type alias? */
public final boolean isTypeAlias() {
return kind == ALIAS;
}
/** Does this symbol denote an abstract type? */
public final boolean isAbstractType() {
return kind == TYPE;
}
/** Does this symbol denote a class type? */
public final boolean isClassType() {
return kind == CLASS;
}
/** Does this symbol denote a public symbol? */
public final boolean isPublic() {
return !isProtected() && !isPrivate();
}
/** Does this symbol denote a protected symbol? */
public final boolean isProtected() {
preInitialize();
return (flags & PROTECTED) != 0;
}
/** Does this symbol denote a private symbol? */
public final boolean isPrivate() {
preInitialize();
return (flags & PRIVATE) != 0;
}
/** Has this symbol been lifted? */
public final boolean isLifted() {
preInitialize();
return (flags & LIFTED) != 0;
}
/** Does this symbol denote a deferred symbol? */
public final boolean isDeferred() {
return (flags & DEFERRED) != 0;
}
/** Does this symbol denote a synthetic symbol? */
public final boolean isSynthetic() {
return (flags & SYNTHETIC) != 0;
}
/** Does this symbol denote an accessor? */
public final boolean isAccessor() {
return (flags & ACCESSOR) != 0;
}
/** Does this symbol denote an access method? (a method to access
* private of protected members from inner classes) */
public final boolean isAccessMethod() {
return (attrs & IS_ACCESSMETHOD) != 0;
}
/** Is this symbol locally defined? I.e. not a member of a class or module */
public final boolean isLocal() {
return owner.kind == VAL &&
!((flags & PARAM) != 0 && owner.isPrimaryConstructor());
}
/** Is this symbol a parameter? Includes type parameters of methods.
*/
public final boolean isParameter() {
return (flags & PARAM) != 0;
}
/** Is this symbol a def parameter?
*/
public final boolean isDefParameter() {
return (flags & (PARAM | DEF)) == (PARAM | DEF);
}
/** Is this class locally defined?
* A class is local, if
* - it is anonymous, or
* - its owner is a value
* - it is defined within a local class
*/
public final boolean isLocalClass() {
return isClass() &&
(isAnonymousClass() ||
owner.isValue() ||
owner.isLocalClass());
}
/** Is this symbol an instance initializer? */
public boolean isInitializer() {
return false;
}
/** Is this symbol a constructor? */
public final boolean isConstructor() {
return (attrs & IS_CONSTRUCTOR) != 0;
}
/** Is this symbol the primary constructor of a type? */
public final boolean isPrimaryConstructor() {
return isConstructor() && this == constructorClass().primaryConstructor();
}
/** Symbol was preloaded from package
*/
public final boolean isExternal() {
return pos == Position.NOPOS;
}
/** Is this symbol an overloaded symbol? */
public final boolean isOverloaded() {
switch (info()) {
case OverloadedType(_,_): return true;
default : return false;
}
}
/** Does this symbol denote a label? */
public final boolean isLabel() {
return (attrs & IS_LABEL) != 0;
}
/** Is this symbol accessed? */
public final boolean isAccessed() {
return (flags & ACCESSED) != 0;
}
/** The variance of this symbol as an integer
*/
public int variance() {
if ((flags & COVARIANT) != 0) return 1;
else if ((flags & CONTRAVARIANT) != 0) return -1;
else return 0;
}
// Symbol names ----------------------------------------------------------------
/** Get the fully qualified name of this Symbol
* (this is always a normal name, never a type name)
*/
/** Get the simple name of this Symbol (this is always a term name)
*/
public Name simpleName() {
if (isConstructor()) return constructorClass().name.toTermName();
return name;
}
// Acess to related symbols -----------------------------------------------------
/** Get type parameters */
public Symbol[] typeParams() {
return EMPTY_ARRAY;
}
/** Get value parameters */
public Symbol[] valueParams() {
return EMPTY_ARRAY;
}
/** Get result type */
public final Type resultType() {
return type().resultType();
}
/** Get type parameters at start of next phase */
public final Symbol[] nextTypeParams() {
Global.instance.nextPhase();
Symbol[] tparams = typeParams();
Global.instance.prevPhase();
return tparams;
}
/** Get value parameters at start of next phase */
public final Symbol[] nextValueParams() {
Global.instance.nextPhase();
Symbol[] vparams = valueParams();
Global.instance.prevPhase();
return vparams;
}
/** Get result type at start of next phase */
public final Type nextResultType() {
return nextType().resultType();
}
/** Get all constructors of class */
public Symbol allConstructors() {
return NONE;
}
/** Get primary constructor of class */
public Symbol primaryConstructor() {
return NONE;
}
/**
* Returns the class linked to this module or null if there is no
* such class. The returned value remains the same for the whole
* life of the symbol.
*
* See method "linkedModule" to learn more about linked modules
* and classes.
*/
public ClassSymbol linkedClass() {
assert isModule(): "not a module: " + Debug.show(this);
return null;
}
/**
* Returns the module linked to this class or null if there is no
* such module. The returned value remains the same for the whole
* life of the symbol.
*
* Linked modules and classes are intended to be used by the
* symbol table loader. They are needed because it is impossible
* to know from the name of a class or source file if it defines a
* class or a module. For that reason a class and a module (each
* linked to the other) are created for each of those files. Once
* the file is read the class, the module or both are initialized
* depending on what the file defines.
*
* It is guaranteed that if a class "c" has a linked module then
* "c.linkedModule().linkedClasss() == c" and that if a module "m"
* has a linked class then "m.linkedClasss().linkedModule() == m".
*
* The linked module of a Java class, is the module that contains
* the static members of that class. A Java class has always a
* linked module.
*
* The linked module of a Scala class, is the module with the same
* name declared in the same scope. A Scala class may or may not
* have a linked module. However, this does not depend on the
* presence or absence of a module with the same name but on how
* the class is created. Therefore a Scala class may have no
* linked module even though there exists a module with the same
* name in the same scope. A Scala class may also have a linked
* module even though there exists no module with the same name in
* the same scope. In the latter case, the linked would be
* initialized to NoType (which prevents accesses to it).
*
* There is a last catch about linked modules. It may happen that
* the symbol returned by "linkedModule" is not a module (and that
* method "linkedClass" works on a non-module symbol). At creation
* time, linked modules are always modules, but at initialization
* time, it may be discovered that the module is in fact a case
* class factory method. In that case, the module is downgraded to
* a non-module term. This implies that from then on calls to its
* method "moduleClass" will fail, but the links defined by the
* methods "linkedModule" and "linkedClass" remain unchanged.
*/
public ModuleSymbol linkedModule() {
assert isClassType(): "not a class: " + Debug.show(this);
return null;
}
/** Get owner */
public Symbol owner() {
return owner;
}
/** Get owner, but if owner is primary constructor of a class,
* get class symbol instead. This is useful for type parameters
* and value parameters in classes which have the primary constructor
* as owner.
*/
public Symbol classOwner() {
Symbol owner = owner();
Symbol clazz = owner.constructorClass();
if (clazz.primaryConstructor() == owner) return clazz;
else return owner;
}
/** The next enclosing class */
public Symbol enclClass() {
return owner().enclClass();
}
/** The next enclosing method */
public Symbol enclMethod() {
return isMethod() ? this : owner().enclMethod();
}
/** If this is a constructor, return the class it constructs.
* Otherwise return the symbol itself.
*/
public Symbol constructorClass() {
return this;
}
/** Return first alternative if this has a (possibly lazy)
* overloaded type, otherwise symbol itself.
* Needed in ClassSymbol.primaryConstructor() and in UnPickle.
*/
public Symbol firstAlternative() {
if (infos == null)
return this;
else if (infos.info instanceof Type.OverloadedType)
return infos.info.alternativeSymbols()[0];
else if (infos.info instanceof LazyOverloadedType)
return ((LazyOverloadedType) infos.info).sym1.firstAlternative();
else
return this;
}
/**
* Returns the class of this module. This method may be invoked
* only on module symbols. It returns always a non-null module
* class symbol whose identity never changes.
*/
public ModuleClassSymbol moduleClass() {
throw Debug.abort("not a module", this);
}
/**
* Returns the source module of this module class. This method may
* be invoked only on module class symbols. It returns always a
* non-null module symbol whose identity never changes.
*
* This method should be used with great care. If possible, one
* should always use moduleClass instead. For example, one should
* write "m.moduleClass()==c" rather than "m==c.sourceModule()".
*
* This method is problematic because the module - module-class
* relation is not a one - one relation. There might be more than
* one module that share the same module class. In that case, the
* source module of the module class is the module that created
* the class. This implies that "m.moduleClass().sourceModule()"
* may be different of "m". However, its is guaranteed that
* "c.sourceModule().moduleClass()" always returns "c".
*
* Phases like "AddInterfaces" and "ExpandMixins" are two examples
* of phases that create additional modules referring the same
* module class.
*
* Even if a module class is related to only one module, the use
* of this method may still be dangerous. The problem is that
* modules and module classes are not always as related as one
* might expect. For example, modules declared in a function are
* lifted out of the function by phase "LambdaLift". During this
* process, the module value is transformed into a module method
* with a "Ref" argument. If the "sourceModule" method is used to
* replace references to module classes by references to their
* source modules and this is done it naively with the class of a
* lifted module, it will yield wrong code because the the "Ref"
* argument will be missing.
*/
public ModuleSymbol sourceModule() {
throw Debug.abort("not a module class", this);
}
/** if type is a (possibly lazy) overloaded type, return its alternatves
* else return array consisting of symbol itself
*/
public Symbol[] alternativeSymbols() {
Symbol[] alts = type().alternativeSymbols();
if (alts.length == 0) return new Symbol[]{this};
else return alts;
}
/** if type is a (possibly lazy) overloaded type, return its alternatves
* else return array consisting of type itself
*/
public Type[] alternativeTypes() {
return type().alternativeTypes();
}
/** The symbol accessed by this accessor function.
*/
public Symbol accessed() {
assert (flags & ACCESSOR) != 0;
String name1 = name.toString();
if (name1.endsWith(Names._EQ.toString()))
name1 = name1.substring(0, name1.length() - Names._EQ.length());
return owner.info().lookup(Name.fromString(name1 + "$"));
}
/** The members of this class or module symbol
*/
public Scope members() {
return info().members();
}
/** Lookup symbol with given name; return Symbol.NONE if not found.
*/
public Symbol lookup(Name name) {
return info().lookup(name);
}
// Symbol types --------------------------------------------------------------
/** Was symbol's type updated during given phase? */
public final boolean isUpdatedAt(Phase phase) {
Phase next = phase.next;
TypeIntervalList infos = this.infos;
while (infos != null) {
if (infos.start == next) return true;
if (infos.limit().precedes(next)) return false;
infos = infos.prev;
}
return false;
}
/** Is this symbol locked? */
public final boolean isLocked() {
return (flags & LOCKED) != 0;
}
/** Is this symbol initialized? */
public final boolean isInitialized() {
return (flags & INITIALIZED) != 0;
}
/** Initialize the symbol */
public final Symbol initialize() {
info();
return this;
}
/** Make sure symbol is entered
*/
public final void preInitialize() {
//todo: clean up
if (infos.info instanceof SymbolLoader)
infos.info.complete(this);
}
/** Get info at start of current phase; This is:
* for a term symbol, its type
* for a type variable, its bound
* for a type alias, its right-hand side
* for a class symbol, the compound type consisting of
* its baseclasses and members.
*/
public final Type info() {
//if (isModule()) moduleClass().initialize();
if ((flags & INITIALIZED) == 0) {
Global global = Global.instance;
Phase current = global.currentPhase;
global.currentPhase = rawFirstInfoStartPhase();
Type info = rawFirstInfo();
assert info != null : this;
if ((flags & LOCKED) != 0) {
setInfo(Type.ErrorType);
flags |= INITIALIZED;
throw new CyclicReference(this, info);
}
flags |= LOCKED;
//System.out.println("completing " + this);//DEBUG
info.complete(this);
flags = flags & ~LOCKED;
if (info instanceof SourceCompleter && (flags & SNDTIME) == 0) {
flags |= SNDTIME;
Type tp = info();
flags &= ~SNDTIME;
} else {
assert !(rawInfo() instanceof Type.LazyType) : this;
//flags |= INITIALIZED;
}
//System.out.println("done: " + this);//DEBUG
global.currentPhase = current;
}
return rawInfo();
}
/** Get info at start of next phase
*/
public final Type nextInfo() {
Global.instance.nextPhase();
Type info = info();
Global.instance.prevPhase();
return info;
}
/** Get info at start of given phase
*/
protected final Type infoAt(Phase phase) {
Global global = phase.global;
Phase current = global.currentPhase;
global.currentPhase = phase;
Type info = info();
global.currentPhase = current;
return info;
}
/** Get info at start of current phase, without forcing lazy types.
*/
public final Type rawInfo() {
return rawInfoAt(Global.instance.currentPhase);
}
/** Get info at start of next phase, without forcing lazy types.
*/
public final Type rawNextInfo() {
Global.instance.nextPhase();
Type info = rawInfo();
Global.instance.prevPhase();
return info;
}
/** Get info at start of given phase, without forcing lazy types.
*/
private final Type rawInfoAt(Phase phase) {
//if (infos == null) return Type.NoType;//DEBUG
assert infos != null : this;
assert phase != null : this;
if (infos.limit().id <= phase.id) {
switch (infos.info) {
case LazyType():
// don't force lazy types
return infos.info;
}
while (infos.limit() != phase) {
Phase limit = infos.limit();
Type info = transformInfo(limit, infos.info);
assert info != null: Debug.show(this) + " -- " + limit;
if (info != infos.info) {
infos = new TypeIntervalList(infos, info, limit.next);
} else {
infos.setLimit(limit.next);
}
}
return infos.info;
} else {
TypeIntervalList infos = this.infos;
while (phase.id < infos.start.id && infos.prev != null)
infos = infos.prev;
return infos.info;
}
}
// where
private Type transformInfo(Phase phase, Type info) {
Global global = phase.global;
Phase current = global.currentPhase;
switch (info) {
case ErrorType:
case NoType:
return info;
case OverloadedType(Symbol[] alts, Type[] alttypes):
global.currentPhase = phase.next;
for (int i = 0; i < alts.length; i++) {
Type type = alts[i].info();
if (type != alttypes[i]) {
Type[] types = new Type[alttypes.length];
for (int j = 0; j < i; j++) types[j] = alttypes[j];
alttypes[i] = type;
for (; i < alts.length; i++)
types[i] = alts[i].info();
global.currentPhase = current;
return Type.OverloadedType(alts, types);
}
}
global.currentPhase = current;
return info;
default:
global.currentPhase = phase;
info = phase.transformInfo(this, info);
global.currentPhase = current;
return info;
}
}
/** Get first defined info, without forcing lazy types.
*/
public final Type rawFirstInfo() {
TypeIntervalList infos = this.infos;
assert infos != null : this;
while (infos.prev != null) infos = infos.prev;
return infos.info;
}
/** Get phase that first defined an info, without forcing lazy types.
*/
public final Phase rawFirstInfoStartPhase() {
TypeIntervalList infos = this.infos;
assert infos != null : this;
while (infos.prev != null) infos = infos.prev;
return infos.start;
}
/** Get type at start of current phase. The type of a symbol is:
* for a type symbol, the type corresponding to the symbol itself
* for a term symbol, its usual type
*/
public Type type() {
return info();
}
public Type getType() {
return info();
}
/** Get type at start of next phase
*/
public final Type nextType() {
Global.instance.nextPhase();
Type type = type();
Global.instance.prevPhase();
return type;
}
/** The infos of these symbols as an array.
*/
static public Type[] info(Symbol[] syms) {
Type[] tps = new Type[syms.length];
for (int i = 0; i < syms.length; i++)
tps[i] = syms[i].info();
return tps;
}
/** The types of these symbols as an array.
*/
static public Type[] type(Symbol[] syms) {
Type[] tps = new Type[syms.length];
for (int i = 0; i < syms.length; i++)
tps[i] = syms[i].type();
return tps;
}
static public Type[] getType(Symbol[] syms) {
return type(syms);
}
/** Get static type. */
public final Type staticType() {
return staticType(Type.EMPTY_ARRAY);
}
/** Get static type with given type argument. */
public final Type staticType(Type arg0) {
return staticType(new Type[]{arg0});
}
/** Get static type with given type arguments. */
public final Type staticType(Type arg0, Type arg1) {
return staticType(new Type[]{arg0, arg1});
}
/** Get static type with given type arguments. */
public final Type staticType(Type[] args) {
Type prefix = owner.staticPrefix();
if (isType()) return Type.typeRef(prefix, this, args);
assert args.length == 0: Debug.show(this, " - ", args);
return prefix.memberType(this);
}
/** Get static prefix. */
public final Type staticPrefix() {
assert isStaticOwner(): Debug.show(this) + " - " + isTerm() + " - " + isModuleClass() + " - " + owner().isStaticOwner() + " - " + isJava();
Global global = Global.instance;
if (global.PHASE.EXPLICITOUTER.id() < global.currentPhase.id)
return Type.NoPrefix;
if (isRoot()) return thisType();
assert sourceModule().owner() == owner(): Debug.show(this);
assert sourceModule().type().isObjectType(): Debug.show(this);
return Type.singleType(owner.staticPrefix(), sourceModule());
}
/** The type constructor of a symbol is:
* For a type symbol, the type corresponding to the symbol itself, excluding
* parameters.
* Not applicable for term symbols.
*/
public Type typeConstructor() {
throw new ApplicationError("typeConstructor inapplicable for " + this);
}
/** The low bound of this type variable
*/
public Type loBound() {
return Global.instance.definitions.ALL_TYPE();
}
/** The view bound of this type variable
*/
public Type vuBound() {
return Global.instance.definitions.ANY_TYPE();
}
/** Get this.type corresponding to this symbol
*/
public Type thisType() {
return Type.NoPrefix;
}
/** Get type of `this' in current class.
*/
public Type typeOfThis() {
return type();
}
/** Get this symbol of current class
*/
public Symbol thisSym() { return this; }
/** A total ordering between symbols that refines the class
* inheritance graph (i.e. subclass.isLess(superclass) always holds).
*/
public boolean isLess(Symbol that) {
if (this == that) return false;
int diff;
if (this.isType()) {
if (that.isType()) {
diff = this.closure().length - that.closure().length;
if (diff > 0) return true;
if (diff < 0) return false;
} else {
return true;
}
} else if (that.isType()) {
return false;
}
return this.id < that.id;
}
/** Return the symbol's type itself followed by all its direct and indirect
* base types, sorted by isLess(). Overridden for class symbols.
*/
public Type[] closure() {
return info().closure();
}
/** Return position of `c' in the closure of this type; -1 if not there.
*/
public int closurePos(Symbol c) {
if (this == c) return 0;
if (c.isCompoundSym()) return -1;
Type[] closure = closure();
int lo = 0;
int hi = closure.length - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
Symbol clsym = closure[mid].symbol();
if (c == clsym) return mid;
else if (c.isLess(clsym)) hi = mid - 1;
else if (clsym.isLess(c)) lo = mid + 1;
else throw new ApplicationError();
}
return -1;
}
public Type baseType(Symbol sym) {
int i = closurePos(sym);
if (i >= 0) return closure()[i];
else return Type.NoType;
}
/** Is this class a subclass of `c'? I.e. does it have a type instance
* of `c' as indirect base class?
*/
public boolean isSubClass(Symbol c) {
return this == c ||
c.isError() ||
closurePos(c) >= 0 ||
this == Global.instance.definitions.ALL_CLASS ||
(this == Global.instance.definitions.ALLREF_CLASS &&
c != Global.instance.definitions.ALL_CLASS &&
c.isSubClass(Global.instance.definitions.ANYREF_CLASS));
}
/** Get base types of this symbol */
public Type[] parents() {
return info().parents();
}
// ToString -------------------------------------------------------------------
/** String representation of symbol's simple name.
* Translates expansions of operators back to operator symbol. E.g.
* $eq => =.
*/
public String nameString() {
return NameTransformer.decode(simpleName());
}
/** String representation, including symbol's kind
* e.g., "class Foo", "function Bar".
*/
public String toString() {
return new SymbolTablePrinter().printSymbolKindAndName(this).toString();
}
/** String representation of location.
*/
public String locationString() {
if (owner.kind == CLASS &&
!owner.isAnonymousClass() && !owner.isCompoundSym() ||
Global.instance.debug)
return " in " +
(owner.isModuleClass() ? owner.sourceModule() : owner);
else
return "";
}
/** String representation of definition.
*/
public String defString() {
return new SymbolTablePrinter().printSignature(this).toString();
}
public static String[] defString(Symbol[] defs) {
String[] strs = new String[defs.length];
for (int i = 0; i < defs.length; i++)
strs[i] = defs[i].defString();
return strs;
}
// Overloading and Overriding -------------------------------------------
/** Add another overloaded alternative to this symbol.
*/
public Symbol overloadWith(Symbol that) {
assert isTerm() : Debug.show(this);
assert this.name == that.name : Debug.show(this) + " <> " + Debug.show(that);
assert this.owner == that.owner : Debug.show(this) + " != " + Debug.show(that);
assert this.isConstructor() == that.isConstructor();
int overflags = (this.flags & that.flags & (JAVA | ACCESSFLAGS | DEFERRED | PARAM | SYNTHETIC)) |
((this.flags | that.flags) & ACCESSOR);
Symbol overloaded = (this.isConstructor())
? this.constructorClass().newConstructor(this.constructorClass().pos, overflags)
: owner.newTerm(pos, overflags, name, 0);
overloaded.setInfo(new LazyOverloadedType(this, that));
return overloaded;
}
/** A lazy type which, when forced computed the overloaded type
* of symbols `sym1' and `sym2'. It also checks that this type is well-formed.
*/
public static class LazyOverloadedType extends Type.LazyType {
Symbol sym1;
Symbol sym2;
LazyOverloadedType(Symbol sym1, Symbol sym2) {
this.sym1 = sym1;
this.sym2 = sym2;
}
public Symbol[] alternativeSymbols() {
Symbol[] alts1 = sym1.alternativeSymbols();
Symbol[] alts2 = sym2.alternativeSymbols();
Symbol[] alts3 = new Symbol[alts1.length + alts2.length];
System.arraycopy(alts1, 0, alts3, 0, alts1.length);
System.arraycopy(alts2, 0, alts3, alts1.length, alts2.length);
return alts3;
}
public Type[] alternativeTypes() {
Type[] alts1 = sym1.alternativeTypes();
Type[] alts2 = sym2.alternativeTypes();
Type[] alts3 = new Type[alts1.length + alts2.length];
System.arraycopy(alts1, 0, alts3, 0, alts1.length);
System.arraycopy(alts2, 0, alts3, alts1.length, alts2.length);
return alts3;
}
public void complete(Symbol overloaded) {
overloaded.setInfo(
Type.OverloadedType(
alternativeSymbols(), alternativeTypes()));
}
public String toString() {
return "LazyOverloadedType(" + sym1 + "," + sym2 + ")";
}
}
/**
* Returns the symbol in type "base" which is overridden by this
* symbol in class "this.owner()". Returns "NONE" if no such
* symbol exists. The type "base" must be a supertype of class
* "this.owner()". If "exact" is true, overriding is restricted to
* symbols that have the same type. The method may return this
* symbol only if "base.symbol()" is equal to "this.owner()".
*/
public final Symbol overriddenSymbol(Type base, boolean exact) {
return overriddenSymbol(base, owner(), exact);
}
public final Symbol overriddenSymbol(Type base) {
return overriddenSymbol(base, false);
}
/**
* Returns the symbol in type "base" which is overridden by this
* symbol in "clasz". Returns "NONE" if no such symbol exists. The
* type "base" must be a supertype of "clasz" and "this.owner()"
* must be a superclass of "clasz". If "exact" is true, overriding
* is restricted to symbols that have the same type. The method
* may return this symbol if "base.symbol()" is a subclass of
* "this.owner()".
*/
public final Symbol overriddenSymbol(Type base, Symbol clasz, boolean exact) {
Type.Relation relation = exact
? Type.Relation.SameType
: Type.Relation.SuperType;
return base.lookup(this, clasz.thisType(), relation);
}
public final Symbol overriddenSymbol(Type base, Symbol clasz) {
return overriddenSymbol(base, clasz, false);
}
/**
* Returns the symbol in type "sub" which overrides this symbol in
* class "sub.symbol()". Returns this symbol if no such symbol
* exists. The class "sub.symbol()" must be a subclass of
* "this.owner()". If "exact" is true, overriding is restricted to
* symbols that have the same type.
*/
public final Symbol overridingSymbol(Type sub, boolean exact) {
Type.Relation relation = exact
? Type.Relation.SameType
: Type.Relation.SubType;
return sub.lookup(this, sub, relation);
}
public final Symbol overridingSymbol(Type sub) {
return overridingSymbol(sub, false);
}
/** Does this symbol override that symbol?
*/
public boolean overrides(Symbol that) {
return
((this.flags | that.flags) & PRIVATE) == 0 &&
this.name == that.name &&
owner.thisType().memberType(this).derefDef().isSubType(
owner.thisType().memberType(that).derefDef());
}
/** Reset symbol to initial state
*/
public void reset(Type completer) {
this.flags &= SOURCEFLAGS;
this.pos = 0;
this.infos = null;
this.setInfo(completer);
}
/**
* Returns the symbol to use in case of a rebinding due to a more
* precise type prefix.
*/
public Symbol rebindSym() {
return this;
}
/** return a tag which (in the ideal case) uniquely identifies
* class symbols
*/
public int tag() {
return name.toString().hashCode();
}
}
/** A class for term symbols
*/
class TermSymbol extends Symbol {
/** Constructor */
TermSymbol(Symbol owner, int pos, int flags, Name name, int attrs) {
super(VAL, owner, pos, flags, name, attrs);
assert name.isTermName(): Debug.show(this);
}
public boolean isInitializer() {
return name == Names.INITIALIZER;
}
public Symbol[] typeParams() {
return type().typeParams();
}
public Symbol[] valueParams() {
return type().valueParams();
}
protected Symbol cloneSymbolImpl(Symbol owner, int attrs) {
return new TermSymbol(owner, pos, flags, name, attrs);
}
}
/** A class for constructor symbols */
final class ConstructorSymbol extends TermSymbol {
/** The constructed class */
private final Symbol clasz;
/** Initializes this instance. */
ConstructorSymbol(Symbol clasz, int pos, int flags) {
super(clasz.owner(), pos, flags, Names.CONSTRUCTOR, IS_CONSTRUCTOR);
this.clasz = clasz;
}
public boolean isInitializer() {
return false;
}
public Symbol constructorClass() {
return clasz;
}
protected final Symbol cloneSymbolImpl(Symbol owner, int attrs) {
throw Debug.abort("illegal clone of constructor", this);
}
}
/** A class for module symbols */
public class ModuleSymbol extends TermSymbol {
/** The module class */
private final ModuleClassSymbol clasz;
/** Initializes this instance. */
private ModuleSymbol(Symbol owner, int pos, int flags, Name name,
int attrs, ModuleClassSymbol clasz)
{
super(owner, pos, flags | MODUL | FINAL | STABLE, name, attrs);
this.clasz = clasz != null ? clasz : new ModuleClassSymbol(this);
setType(Type.typeRef(owner().thisType(), this.clasz,Type.EMPTY_ARRAY));
}
/** Initializes this instance. */
ModuleSymbol(Symbol owner, int pos, int flags, Name name) {
this(owner, pos, flags, name, 0, null);
}
public ModuleClassSymbol moduleClass() {
// test may fail because loaded modules may be downgraded to
// case class factory methods (see Symbol#linkedModule())
assert isModule(): Debug.show(this);
return clasz;
}
protected final Symbol cloneSymbolImpl(Symbol owner, int attrs) {
return new ModuleSymbol(owner, pos, flags, name, attrs, clasz);
}
}
/**
* A class for linked module symbols
*
* @see Symbol#linkedModule()
*/
final class LinkedModuleSymbol extends ModuleSymbol {
/** The linked class */
private final LinkedClassSymbol clasz;
/** Initializes this instance. */
LinkedModuleSymbol(LinkedClassSymbol clasz) {
super(clasz.owner(), clasz.pos, clasz.flags & JAVA,
clasz.name.toTermName());
this.clasz = clasz;
}
public ClassSymbol linkedClass() {
return clasz;
}
}
/** A base class for all type symbols.
* It has AliasTypeSymbol, AbsTypeSymbol, ClassSymbol as subclasses.
*/
abstract class TypeSymbol extends Symbol {
/** The history of closures of this symbol */
private final History/*<Type[]>*/ closures;
/** A cache for type constructors
*/
private Type tycon = null;
/** The primary constructor of this type */
private Symbol constructor;
/** Constructor */
public TypeSymbol(int kind, Symbol owner, int pos, int flags, Name name, int attrs) {
super(kind, owner, pos, flags, name, attrs);
this.closures = new ClosureHistory();
assert name.isTypeName() : this;
this.constructor = newConstructor(pos, flags & CONSTRFLAGS);
}
protected final void copyConstructorInfo(TypeSymbol other) {
{
Type info = primaryConstructor().info().cloneType(
primaryConstructor(), other.primaryConstructor());
if (!isTypeAlias()) info = fixConstrType(info, other);
other.primaryConstructor().setInfo(info);
}
Symbol[] alts = allConstructors().alternativeSymbols();
for (int i = 1; i < alts.length; i++) {
Symbol constr = other.newConstructor(alts[i].pos, alts[i].flags);
other.addConstructor(constr);
Type info = alts[i].info().cloneType(alts[i], constr);
if (!isTypeAlias()) info = fixConstrType(info, other);
constr.setInfo(info);
}
}
private final Type fixConstrType(Type type, Symbol clone) {
switch (type) {
case MethodType(Symbol[] vparams, Type result):
result = fixConstrType(result, clone);
return new Type.MethodType(vparams, result);
case PolyType(Symbol[] tparams, Type result):
result = fixConstrType(result, clone);
return new Type.PolyType(tparams, result);
case TypeRef(Type pre, Symbol sym, Type[] args):
if (sym != this && isTypeAlias() && owner().isCompoundSym())
return type;
assert sym == this: Debug.show(sym) + " != " + Debug.show(this);
return Type.typeRef(pre, clone, args);
case LazyType():
return type;
default:
throw Debug.abort("unexpected constructor type:" + clone + ":" + type);
}
}
/** add a constructor
*/
public final void addConstructor(Symbol constr) {
assert constr.isConstructor(): Debug.show(constr);
constructor = constructor.overloadWith(constr);
}
/** Get primary constructor */
public final Symbol primaryConstructor() {
return constructor.firstAlternative();
}
/** Get all constructors */
public final Symbol allConstructors() {
return constructor;
}
/** Get type parameters */
public final Symbol[] typeParams() {
return primaryConstructor().info().typeParams();
}
/** Get value parameters */
public final Symbol[] valueParams() {
return (kind == CLASS) ? primaryConstructor().info().valueParams()
: Symbol.EMPTY_ARRAY;
}
/** Get type constructor */
public final Type typeConstructor() {
if (tycon == null)
tycon = Type.typeRef(owner().thisType(), this, Type.EMPTY_ARRAY);
return tycon;
}
public Symbol setOwner(Symbol owner) {
tycon = null;
constructor.setOwner0(owner);
switch (constructor.type()) {
case OverloadedType(Symbol[] alts, _):
for (int i = 0; i < alts.length; i++) alts[i].setOwner0(owner);
}
return super.setOwner(owner);
}
/** Get type */
public final Type type() {
return primaryConstructor().type().resultType();
}
public final Type getType() {
return primaryConstructor().type().resultType();
}
/**
* Get closure at start of current phase. The closure of a symbol
* is a list of types which contains the type of the symbol
* followed by all its direct and indirect base types, sorted by
* isLess().
*/
public final Type[] closure() {
if (kind == ALIAS) return info().symbol().closure();
return (Type[])closures.getValue(this);
}
public void reset(Type completer) {
super.reset(completer);
closures.reset();
tycon = null;
}
protected final Symbol cloneSymbolImpl(Symbol owner, int attrs) {
TypeSymbol clone = cloneTypeSymbolImpl(owner, attrs);
copyConstructorInfo(clone);
return clone;
}
protected abstract TypeSymbol cloneTypeSymbolImpl(Symbol owner, int attrs);
}
final class AliasTypeSymbol extends TypeSymbol {
/** Initializes this instance. */
AliasTypeSymbol(Symbol owner, int pos, int flags, Name name, int attrs) {
super(ALIAS, owner, pos, flags, name, attrs);
}
protected TypeSymbol cloneTypeSymbolImpl(Symbol owner, int attrs) {
return new AliasTypeSymbol(owner, pos, flags, name, attrs);
}
}
final class AbsTypeSymbol extends TypeSymbol {
private Type lobound = null;
private Type vubound = null;
/** Initializes this instance. */
AbsTypeSymbol(Symbol owner, int pos, int flags, Name name, int attrs) {
super(TYPE, owner, pos, flags, name, attrs);
allConstructors().setInfo(Type.MethodType(EMPTY_ARRAY, Type.typeRef(owner.thisType(), this, Type.EMPTY_ARRAY)));
}
public Type loBound() {
initialize();
return lobound == null ? Global.instance.definitions.ALL_TYPE() : lobound;
}
public Type vuBound() {
initialize();
return !isViewBounded() || vubound == null
? Global.instance.definitions.ANY_TYPE() : vubound;
}
public Symbol setLoBound(Type lobound) {
this.lobound = lobound;
return this;
}
public Symbol setVuBound(Type vubound) {
this.vubound = vubound;
return this;
}
protected TypeSymbol cloneTypeSymbolImpl(Symbol owner, int attrs) {
TypeSymbol clone = new AbsTypeSymbol(owner, pos, flags, name, attrs);
clone.setLoBound(loBound());
clone.setVuBound(vuBound());
return clone;
}
}
/** A class for class symbols. */
public class ClassSymbol extends TypeSymbol {
/** The given type of self, or NoType, if no explicit type was given.
*/
private Symbol thisSym = this;
public Symbol thisSym() { return thisSym; }
/** A cache for this.thisType()
*/
final private Type thistp = Type.ThisType(this);
private final Symbol rebindSym;
/** Initializes this instance. */
ClassSymbol(Symbol owner, int pos, int flags, Name name, int attrs) {
super(CLASS, owner, pos, flags, name, attrs);
this.rebindSym = owner.newTypeAlias(pos, 0, Names.ALIAS(this));
Type rebindType = new ClassAliasLazyType();
this.rebindSym.setInfo(rebindType);
this.rebindSym.primaryConstructor().setInfo(rebindType);
}
private class ClassAliasLazyType extends Type.LazyType {
public void complete(Symbol ignored) {
Symbol clasz = ClassSymbol.this;
Symbol alias = rebindSym;
Type prefix = clasz.owner().thisType();
Type constrtype = clasz.type();
constrtype = Type.MethodType(Symbol.EMPTY_ARRAY, constrtype);
constrtype = Type.PolyType(clasz.typeParams(), constrtype);
constrtype = constrtype.cloneType(
clasz.primaryConstructor(), alias.primaryConstructor());
alias.primaryConstructor().setInfo(constrtype);
alias.setInfo(constrtype.resultType());
}
}
/** Creates the root class. */
public static Symbol newRootClass(Global global) {
int pos = Position.NOPOS;
Name name = Names.ROOT.toTypeName();
Symbol owner = Symbol.NONE;
int flags = JAVA | PACKAGE | FINAL;
int attrs = IS_ROOT;
Symbol clasz = new ClassSymbol(owner, pos, flags, name, attrs);
clasz.setInfo(global.getRootLoader());
clasz.primaryConstructor().setInfo(
Type.MethodType(Symbol.EMPTY_ARRAY, clasz.typeConstructor()));
// !!! Type.MethodType(Symbol.EMPTY_ARRAY, clasz.thisType()));
return clasz;
}
/** Creates the this-type symbol associated to this class. */
private final Symbol newThisType() {
return newTerm(pos, SYNTHETIC, Names.this_, IS_THISTYPE);
}
public Type thisType() {
Global global = Global.instance;
if (global.currentPhase.id > global.PHASE.ERASURE.id()) return type();
return thistp;
}
public Type typeOfThis() {
return thisSym.type();
}
public Symbol setTypeOfThis(Type tp) {
thisSym = newThisType();
thisSym.setInfo(tp);
return this;
}
/** Return the next enclosing class */
public Symbol enclClass() {
return this;
}
public Symbol caseFieldAccessor(int index) {
assert (flags & CASE) != 0 : this;
Scope.SymbolIterator it = info().members().iterator();
Symbol sym = null;
if ((flags & JAVA) == 0) {
for (int i = 0; i <= index; i++) {
do {
sym = it.next();
} while (sym.kind != VAL || (sym.flags & CASEACCESSOR) == 0 || !sym.isMethod());
}
//System.out.println(this + ", case field[" + index + "] = " + sym);//DEBUG
} else {
sym = it.next();
while ((sym.flags & SYNTHETIC) == 0) {
//System.out.println("skipping " + sym);
sym = it.next();
}
for (int i = 0; i < index; i++)
sym = it.next();
//System.out.println("field accessor = " + sym);//DEBUG
}
assert sym != null : this;
return sym;
}
public final Symbol rebindSym() {
return rebindSym;
}
public void reset(Type completer) {
super.reset(completer);
thisSym = this;
}
protected final TypeSymbol cloneTypeSymbolImpl(Symbol owner, int attrs) {
assert !isModuleClass(): Debug.show(this);
ClassSymbol clone = new ClassSymbol(owner, pos, flags, name, attrs);
if (thisSym != this) clone.setTypeOfThis(typeOfThis());
return clone;
}
}
/**
* A class for module class symbols
*
* @see Symbol#sourceModule()
*/
public final class ModuleClassSymbol extends ClassSymbol {
/** The source module */
private final ModuleSymbol module;
/** Initializes this instance. */
ModuleClassSymbol(ModuleSymbol module) {
super(module.owner(), module.pos,
(module.flags & MODULE2CLASSFLAGS) | MODUL | FINAL,
module.name.toTypeName(), 0);
primaryConstructor().flags |= PRIVATE;
primaryConstructor().setInfo(
Type.MethodType(Symbol.EMPTY_ARRAY, typeConstructor()));
this.module = module;
}
public ModuleSymbol sourceModule() {
return module;
}
}
/**
* A class for linked class symbols
*
* @see Symbol#linkedModule()
*/
final class LinkedClassSymbol extends ClassSymbol {
/** The linked module */
private final LinkedModuleSymbol module;
/** Initializes this instance. */
LinkedClassSymbol(Symbol owner, int flags, Name name) {
super(owner, Position.NOPOS, flags, name, 0);
this.module = new LinkedModuleSymbol(this);
}
public ModuleSymbol linkedModule() {
return module;
}
}
/** The class of Symbol.NONE
*/
final class NoSymbol extends Symbol {
/** Constructor */
public NoSymbol() {
super(Kinds.NONE, null, Position.NOPOS, 0, Names.NOSYMBOL, 0);
super.setInfo(Type.NoType);
}
/** Set type */
public Symbol setInfo(Type info) {
assert info == Type.NoType : info;
return this;
}
/** Return the next enclosing class */
public Symbol enclClass() {
return this;
}
/** Return the next enclosing method */
public Symbol enclMethod() {
return this;
}
public Symbol owner() {
throw new ApplicationError();
}
public Type thisType() {
return Type.NoPrefix;
}
public void reset(Type completer) {
}
protected Symbol cloneSymbolImpl(Symbol owner, int attrs) {
throw Debug.abort("illegal clone", this);
}
}
/** An exception for signalling cyclic references.
*/
public class CyclicReference extends Type.Error {
public Symbol sym;
public Type info;
public CyclicReference(Symbol sym, Type info) {
super("illegal cyclic reference involving " + sym);
this.sym = sym;
this.info = info;
}
}
/** A base class for values indexed by phases. */
abstract class IntervalList {
/** Interval starts at start of phase "start" (inclusive) */
public final Phase start;
/** Interval ends at start of phase "limit" (inclusive) */
private Phase limit;
public IntervalList(IntervalList prev, Phase start) {
this.start = start;
this.limit = start;
assert start != null && (prev == null || prev.limit.next == start) :
Global.instance.currentPhase + " - " + prev + " - " + start;
}
public Phase limit() {
return limit;
}
public void setLimit(Phase phase) {
assert phase != null && !phase.precedes(start) : start + " - " + phase;
limit = phase;
}
public String toString() {
return "[" + start + "->" + limit + "]";
}
}
/** A class for types indexed by phases. */
class TypeIntervalList extends IntervalList {
/** Previous interval */
public final TypeIntervalList prev;
/** Info valid during this interval */
public final Type info;
public TypeIntervalList(TypeIntervalList prev, Type info, Phase start) {
super(prev, start);
this.prev = prev;
this.info = info;
assert info != null;
}
}
| - Fixed and optimized isStatic and isStaticOwner
| sources/scalac/symtab/Symbol.java | - Fixed and optimized isStatic and isStaticOwner | <ide><path>ources/scalac/symtab/Symbol.java
<ide>
<ide> /** Is this symbol static (i.e. with no outer instance)? */
<ide> public final boolean isStatic() {
<del> return owner.isStaticOwner();
<add> return isRoot() || owner.isStaticOwner();
<ide> }
<ide>
<ide> /** Does this symbol denote a class that defines static symbols? */
<ide> public final boolean isStaticOwner() {
<del> return isRoot() || (isStatic() && isModuleClass()
<add> return isPackageClass() || (isStatic() && isModuleClass()
<ide> // !!! remove later? translation does not work (yet?)
<ide> && isJava());
<ide> } |
|
JavaScript | mit | 48c5399917bbde398c130c6a764deb0bcbd21d6f | 0 | exclude/kusaba-quickreply | function QuickReply() {
document.addEventListener('mousemove', this.mousePos, false);
this.addButtons();
this.createForm();
}
QuickReply.prototype.mousePos = function(e) {
window.pageX = e.pageX;
window.pageY = e.pageY;
}
QuickReply.prototype.addButtons = function() {
replies = document.getElementsByClassName('reply');
for (i = 0; i < replies.length; i++) {
reply = replies[i];
parentid = reply.parentNode.parentNode.parentNode.parentNode.id.split('replies')[1][0] // FUCK THE POLICE!!
postid = reply.id.split('reply')[1]
extrabtns = reply.getElementsByClassName('extrabtns')[0]
extrabtns.appendChild(this.createButton(parentid, postid));
}
}
QuickReply.prototype.createButton = function(parentid, postid) {
a = document.createElement('a');
a.href = '#';
a.onclick = this.formHandler;
img = document.createElement('img');
img.src = '/css/icons/blank.gif';
img.className = 'quickreply' // kusaba's default class
a.appendChild(img);
return a; // we need to return it because closures in javascript are awful
}
QuickReply.prototype.createForm = function() {
// Maybe, only maybe we can copy default form to a div and put this div
// under mouse cursor instead of creating it from zero
var quickform = document.getElementById('postform').cloneNode(true);
var container = document.createElement('div')
container.style.display = 'none';
container.style.position = 'absolute';
container.style.width = '450px';
container.style.background = '#fff';
container.id = 'quickreplyx';
var header = document.createElement('div');
header.innerHTML = '<h1>Quickreply</h1>';
var content = document.createElement('div');
content.appendChild(quickform)
container.appendChild(header);
container.appendChild(content);
document.body.appendChild(container);
}
QuickReply.prototype.formHandler = function(e) {
// try {
// document.getElementById('qr-name').value = getCookie("name");
// }
// catch (e) {
// // ALL GLORY TO HYPNOTOAD!!
// }
// document.getElementById('qr-em').value = getCookie("email");
// document.getElementById('qr-password').value = get_password("postpassword");
// document.getElementById('qr-parentid').value = parentid;
// document.getElementById('qr-info').innerHTML = 'Reply to: #' + postid + ' in: #' + parentid;
// var messagearea = document.getElementById('qr-message');
// messagearea.value = '>>' + postid + '\n';
// // messagearea.onfocus = function() {
// // this.value = this.value; // just to move cursor to the end
// // }
var qr = document.getElementById('quickreplyx');
qr.style.display = 'block';
qr.style.left = window.pageX + 'px';
qr.style.top = window.pageY + 'px';
// messagearea.focus();
e.preventDefault();
}
window.onload = function() {
new QuickReply();
}
| lib/javascript/quickreply.js | function QuickReply() {
document.addEventListener('mousemove', this.mousePos, false);
this.addButtons();
}
QuickReply.prototype.mousePos = function(e) {
window.pageX = e.pageX;
window.pageY = e.pageY;
}
QuickReply.prototype.addButtons = function() {
replies = document.getElementsByClassName('reply');
for (i = 0; i < replies.length; i++) {
reply = replies[i];
parent_id = reply.parentNode.parentNode.parentNode.parentNode.id.split('replies')[1][0] // this shit is serious?!?!!
post_id = reply.id.split('reply')[1]
extrabtns = reply.getElementsByClassName('extrabtns')[0]
extrabtns.appendChild(this.createButton(parent_id, post_id));
}
}
QuickReply.prototype.createButton = function(parent_id, post_id) {
a = document.createElement('a');
a.href = '#';
a.onclick = function(e) {
var qr = document.getElementById('quickreply');
// copy post password
// copy post name
// put thread id
// fill message box
qr.style.display = 'block';
qr.style.left = window.pageX;
qr.style.top = window.pageY;
e.preventDefault();
}
img = document.createElement('img');
img.src = '/css/icons/blank.gif';
img.className = 'quickreply' // kusaba's default class
a.appendChild(img);
return a
}
window.onload = function() {
new QuickReply();
}
| add progress
| lib/javascript/quickreply.js | add progress | <ide><path>ib/javascript/quickreply.js
<ide> document.addEventListener('mousemove', this.mousePos, false);
<ide>
<ide> this.addButtons();
<add> this.createForm();
<ide> }
<ide>
<ide> QuickReply.prototype.mousePos = function(e) {
<ide>
<ide> for (i = 0; i < replies.length; i++) {
<ide> reply = replies[i];
<del> parent_id = reply.parentNode.parentNode.parentNode.parentNode.id.split('replies')[1][0] // this shit is serious?!?!!
<del> post_id = reply.id.split('reply')[1]
<add> parentid = reply.parentNode.parentNode.parentNode.parentNode.id.split('replies')[1][0] // FUCK THE POLICE!!
<add> postid = reply.id.split('reply')[1]
<ide>
<ide> extrabtns = reply.getElementsByClassName('extrabtns')[0]
<del> extrabtns.appendChild(this.createButton(parent_id, post_id));
<add> extrabtns.appendChild(this.createButton(parentid, postid));
<ide> }
<ide> }
<ide>
<del>QuickReply.prototype.createButton = function(parent_id, post_id) {
<add>QuickReply.prototype.createButton = function(parentid, postid) {
<ide> a = document.createElement('a');
<ide> a.href = '#';
<del> a.onclick = function(e) {
<del> var qr = document.getElementById('quickreply');
<del>
<del> // copy post password
<del> // copy post name
<del> // put thread id
<del> // fill message box
<del>
<del> qr.style.display = 'block';
<del> qr.style.left = window.pageX;
<del> qr.style.top = window.pageY;
<del>
<del> e.preventDefault();
<del> }
<add> a.onclick = this.formHandler;
<ide>
<ide> img = document.createElement('img');
<ide> img.src = '/css/icons/blank.gif';
<ide>
<ide> a.appendChild(img);
<ide>
<del> return a
<add> return a; // we need to return it because closures in javascript are awful
<add>}
<add>
<add>QuickReply.prototype.createForm = function() {
<add> // Maybe, only maybe we can copy default form to a div and put this div
<add> // under mouse cursor instead of creating it from zero
<add>
<add> var quickform = document.getElementById('postform').cloneNode(true);
<add>
<add> var container = document.createElement('div')
<add> container.style.display = 'none';
<add> container.style.position = 'absolute';
<add> container.style.width = '450px';
<add> container.style.background = '#fff';
<add> container.id = 'quickreplyx';
<add>
<add> var header = document.createElement('div');
<add> header.innerHTML = '<h1>Quickreply</h1>';
<add>
<add> var content = document.createElement('div');
<add> content.appendChild(quickform)
<add>
<add> container.appendChild(header);
<add> container.appendChild(content);
<add>
<add> document.body.appendChild(container);
<add>}
<add>
<add>QuickReply.prototype.formHandler = function(e) {
<add> // try {
<add> // document.getElementById('qr-name').value = getCookie("name");
<add> // }
<add> // catch (e) {
<add> // // ALL GLORY TO HYPNOTOAD!!
<add> // }
<add> // document.getElementById('qr-em').value = getCookie("email");
<add> // document.getElementById('qr-password').value = get_password("postpassword");
<add> // document.getElementById('qr-parentid').value = parentid;
<add> // document.getElementById('qr-info').innerHTML = 'Reply to: #' + postid + ' in: #' + parentid;
<add>
<add> // var messagearea = document.getElementById('qr-message');
<add> // messagearea.value = '>>' + postid + '\n';
<add> // // messagearea.onfocus = function() {
<add> // // this.value = this.value; // just to move cursor to the end
<add> // // }
<add>
<add> var qr = document.getElementById('quickreplyx');
<add> qr.style.display = 'block';
<add> qr.style.left = window.pageX + 'px';
<add> qr.style.top = window.pageY + 'px';
<add>
<add> // messagearea.focus();
<add>
<add> e.preventDefault();
<ide> }
<ide>
<ide> window.onload = function() { |
|
Java | apache-2.0 | 78dabdf3fa2554fe1182331473064ae716ae6189 | 0 | esaunders/autopsy,rcordovano/autopsy,rcordovano/autopsy,wschaeferB/autopsy,rcordovano/autopsy,esaunders/autopsy,wschaeferB/autopsy,wschaeferB/autopsy,esaunders/autopsy,rcordovano/autopsy,wschaeferB/autopsy,esaunders/autopsy,rcordovano/autopsy,rcordovano/autopsy,esaunders/autopsy,wschaeferB/autopsy | /*
* Autopsy Forensic Browser
*
* Copyright 2013-2018 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sleuthkit.autopsy.imagegallery;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.EnumSet;
import java.util.Set;
import java.util.logging.Level;
import javafx.application.Platform;
import javax.annotation.concurrent.GuardedBy;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
import org.openide.util.NbBundle;
import org.sleuthkit.autopsy.casemodule.Case;
import org.sleuthkit.autopsy.casemodule.NoCurrentCaseException;
import org.sleuthkit.autopsy.casemodule.events.ContentTagAddedEvent;
import org.sleuthkit.autopsy.casemodule.events.ContentTagDeletedEvent;
import org.sleuthkit.autopsy.core.RuntimeProperties;
import org.sleuthkit.autopsy.coreutils.Logger;
import org.sleuthkit.autopsy.events.AutopsyEvent;
import org.sleuthkit.autopsy.imagegallery.datamodel.DrawableDB;
import org.sleuthkit.autopsy.ingest.IngestManager;
import static org.sleuthkit.autopsy.ingest.IngestManager.IngestModuleEvent.DATA_ADDED;
import static org.sleuthkit.autopsy.ingest.IngestManager.IngestModuleEvent.FILE_DONE;
import org.sleuthkit.autopsy.ingest.ModuleDataEvent;
import org.sleuthkit.autopsy.ingest.events.DataSourceAnalysisEvent;
import org.sleuthkit.autopsy.modules.filetypeid.FileTypeDetector;
import org.sleuthkit.datamodel.AbstractFile;
import org.sleuthkit.datamodel.BlackboardArtifact;
import org.sleuthkit.datamodel.BlackboardArtifact.ARTIFACT_TYPE;
import org.sleuthkit.datamodel.Content;
import org.sleuthkit.datamodel.TskCoreException;
import org.sleuthkit.datamodel.TskData;
/**
* This class is reponsible for handling selected application events for the
* image gallery module, managing the image gallery module's per case MVC
* controller and keeping track of the following state: the module name, the
* module output directory and whether or not the ingest gallery module is
* enabled for the current case.
*/
@NbBundle.Messages({"ImageGalleryModule.moduleName=Image Gallery"})
public class ImageGalleryModule {
private static final Logger logger = Logger.getLogger(ImageGalleryModule.class.getName());
private static final String MODULE_NAME = Bundle.ImageGalleryModule_moduleName();
private static final Set<Case.Events> CASE_EVENTS_OF_INTEREST = EnumSet.of(
Case.Events.CURRENT_CASE,
Case.Events.DATA_SOURCE_ADDED,
Case.Events.CONTENT_TAG_ADDED,
Case.Events.CONTENT_TAG_DELETED
);
private static final Object controllerLock = new Object();
@GuardedBy("controllerLock")
private static ImageGalleryController controller;
/**
* Gets the per case image gallery controller for the current case. The
* controller is changed in the case event listener.
*
* @return The image gallery controller for the current case.
*
* @throws TskCoreException If there is a problem creating the controller.
*/
public static ImageGalleryController getController() throws TskCoreException {
synchronized (controllerLock) {
if (controller == null) {
try {
Case currentCase = Case.getCurrentCaseThrows();
controller = new ImageGalleryController(currentCase);
} catch (NoCurrentCaseException ex) {
throw new TskCoreException("Failed to get ", ex);
}
}
return controller;
}
}
/**
* Sets the implicit exit property attribute of the JavaFX runtime to false
* and sets up listeners for application events. It is invoked at
* application start up by virtue of the OnStart annotation on the OnStart
* class in this package.
*/
static void onStart() {
Platform.setImplicitExit(false);
IngestManager.getInstance().addIngestJobEventListener(new IngestJobEventListener());
IngestManager.getInstance().addIngestModuleEventListener(new IngestModuleEventListener());
Case.addEventTypeSubscriber(CASE_EVENTS_OF_INTEREST, new CaseEventListener());
}
/**
* Gets the image gallery module name.
*
* @return The module name,
*/
static String getModuleName() {
return MODULE_NAME;
}
/**
* Gets the path to the image gallery module output folder for a given case.
*
* @param theCase The case.
*
* @return The path to the image gallery module output folder for the case.
*/
public static Path getModuleOutputDir(Case theCase) {
return Paths.get(theCase.getModuleDirectory(), getModuleName());
}
/**
* Prevents instantiation.
*/
private ImageGalleryModule() {
}
/**
* Indicates whether or not the image gallery module is enabled for a given
* case.
*
* @param theCase The case.
*
* @return True or false.
*/
static boolean isEnabledforCase(Case theCase) {
String enabledforCaseProp = new PerCaseProperties(theCase).getConfigSetting(ImageGalleryModule.MODULE_NAME, PerCaseProperties.ENABLED);
return isNotBlank(enabledforCaseProp) ? Boolean.valueOf(enabledforCaseProp) : ImageGalleryPreferences.isEnabledByDefault();
}
/**
* Indicates whether or not a given file is of interest to the image gallery
* module (is "drawable") and is not marked as a "known" file (e.g., is not
* a file in the NSRL hash set).
*
* @param file The file.
*
* @return True if the file is "drawable" and not "known", false otherwise.
*
* @throws FileTypeDetectorInitException If there is an error determining
* the type of the file.
*/
private static boolean isDrawableAndNotKnown(AbstractFile abstractFile) throws FileTypeDetector.FileTypeDetectorInitException {
return (abstractFile.getKnown() != TskData.FileKnown.KNOWN) && FileTypeUtils.isDrawable(abstractFile);
}
/**
* A listener for ingest module application events.
*/
static private class IngestModuleEventListener implements PropertyChangeListener {
@Override
public void propertyChange(PropertyChangeEvent event) {
/*
* Only process individual files and artifacts in "real time" on the
* node that is running the ingest job. On a remote node, image
* files are processed as a group when the ingest job is complete.
*/
if (((AutopsyEvent) event).getSourceType() != AutopsyEvent.SourceType.LOCAL) {
return;
}
ImageGalleryController currentController;
try {
currentController = getController();
// RJCTODO: If a closed controller had a method that could be
// queried to determine whether it was shut down, we could
// bail out here. The older code that used to try to check for
// a current case was flawed; there was no guarantee the current
// case was the same case associated with the event.
} catch (TskCoreException ex) {
logger.log(Level.SEVERE, String.format("Failed to handle %s event", event.getPropertyName()), ex); //NON-NLS
return;
}
String eventType = event.getPropertyName();
switch (IngestManager.IngestModuleEvent.valueOf(eventType)) {
case FILE_DONE:
AbstractFile file = (AbstractFile) event.getNewValue();
if (!file.isFile()) {
return;
}
if (currentController.isListeningEnabled()) {
try {
if (isDrawableAndNotKnown(file)) {
currentController.queueDBTask(new ImageGalleryController.UpdateFileTask(file, currentController.getDatabase()));
}
} catch (FileTypeDetector.FileTypeDetectorInitException ex) {
logger.log(Level.SEVERE, String.format("Failed to determine if file is of interest to the image gallery module, ignoring file (obj_id=%d)", file.getId()), ex); //NON-NLS
}
}
break;
case DATA_ADDED:
ModuleDataEvent artifactAddedEvent = (ModuleDataEvent) event.getOldValue();
if (artifactAddedEvent.getBlackboardArtifactType().getTypeID() == ARTIFACT_TYPE.TSK_METADATA_EXIF.getTypeID()) {
DrawableDB drawableDB = currentController.getDatabase();
if (artifactAddedEvent.getArtifacts() != null) {
for (BlackboardArtifact art : artifactAddedEvent.getArtifacts()) {
drawableDB.addExifCache(art.getObjectID());
}
}
} else if (artifactAddedEvent.getBlackboardArtifactType().getTypeID() == ARTIFACT_TYPE.TSK_HASHSET_HIT.getTypeID()) {
DrawableDB drawableDB = currentController.getDatabase();
if (artifactAddedEvent.getArtifacts() != null) {
for (BlackboardArtifact art : artifactAddedEvent.getArtifacts()) {
drawableDB.addHashSetCache(art.getObjectID());
}
}
}
break;
default:
break;
}
}
}
/**
* A listener for case application events.
*/
// RJCTODO: This code would be easier to read if there were two case event
// listeners, one that handled CURRENT_CASE events and one that handled
// the other events.
static private class CaseEventListener implements PropertyChangeListener {
@Override
public void propertyChange(PropertyChangeEvent event) {
Case.Events eventType = Case.Events.valueOf(event.getPropertyName());
if (eventType == Case.Events.CURRENT_CASE) {
synchronized (controllerLock) {
if (event.getNewValue() != null) {
/*
* CURRENT_CASE(_OPENED) event.
*/
Case newCase = (Case) event.getNewValue();
try {
controller = new ImageGalleryController(newCase);
} catch (TskCoreException ex) {
logger.log(Level.SEVERE, String.format("Failed to construct controller for new case %s (%s)", newCase.getDisplayName(), newCase.getName()), ex);
}
} else if (event.getOldValue() != null) {
/*
* CURRENT_CASE(_CLOSED) event.
*/
SwingUtilities.invokeLater(ImageGalleryTopComponent::closeTopComponent);
controller.shutDown();
}
}
} else {
ImageGalleryController currentController;
try {
currentController = getController();
// RJCTODO: If a closed controller had a method that could be
// queried to determine whether it was shut down, we could
// bail out here. The older code that used to try to check for
// a current case was flawed; there was no guarantee the current
// case was the same case associated with the event.
} catch (TskCoreException ex) {
logger.log(Level.SEVERE, String.format("Failed to handle %s event", event.getPropertyName()), ex); //NON-NLS
return;
}
switch (eventType) {
case DATA_SOURCE_ADDED:
if (((AutopsyEvent) event).getSourceType() == AutopsyEvent.SourceType.LOCAL) {
Content newDataSource = (Content) event.getNewValue();
if (currentController.isListeningEnabled()) {
currentController.getDatabase().insertOrUpdateDataSource(newDataSource.getId(), DrawableDB.DrawableDbBuildStatusEnum.UNKNOWN);
}
}
break;
case CONTENT_TAG_ADDED:
final ContentTagAddedEvent tagAddedEvent = (ContentTagAddedEvent) event;
long objId = tagAddedEvent.getAddedTag().getContent().getId();
DrawableDB drawableDB = currentController.getDatabase();
drawableDB.addTagCache(objId); // RJCTODO: Why add the tag to the cache before doing the in DB check?
if (drawableDB.isInDB(objId)) {
currentController.getTagsManager().fireTagAddedEvent(tagAddedEvent);
}
break;
case CONTENT_TAG_DELETED:
final ContentTagDeletedEvent tagDeletedEvent = (ContentTagDeletedEvent) event;
if (currentController.getDatabase().isInDB(tagDeletedEvent.getDeletedTagInfo().getContentID())) {
currentController.getTagsManager().fireTagDeletedEvent(tagDeletedEvent);
} // RJCTODO: Why not remove the tag from the cache?
break;
default:
logger.log(Level.SEVERE, String.format("Received %s event with no subscription", event.getPropertyName())); //NON-NLS
break;
}
}
}
}
/**
* A listener for ingest job application events.
*/
static private class IngestJobEventListener implements PropertyChangeListener {
@NbBundle.Messages({
"ImageGalleryController.dataSourceAnalyzed.confDlg.msg= A new data source was added and finished ingest.\n"
+ "The image / video database may be out of date. "
+ "Do you want to update the database with ingest results?\n",
"ImageGalleryController.dataSourceAnalyzed.confDlg.title=Image Gallery"
})
@Override
public void propertyChange(PropertyChangeEvent event) {
/*
* Only handling data source analysis events.
*/
if (!(event instanceof DataSourceAnalysisEvent)) {
return;
}
ImageGalleryController controller;
try {
controller = getController();
// RJCTODO: If a closed controller had a method that could be
// queried to determine whether it was shut down, we could
// bail out here. The older code that used to try to check for
// a current case was flawed; there was no guarantee the current
// case was the same case associated with the event.
} catch (TskCoreException ex) {
logger.log(Level.SEVERE, String.format("Failed to handle %s event", event.getPropertyName()), ex); //NON-NLS
return;
}
DataSourceAnalysisEvent dataSourceEvent = (DataSourceAnalysisEvent) event;
Content dataSource = dataSourceEvent.getDataSource();
long dataSourceObjId = dataSource.getId();
String eventType = dataSourceEvent.getPropertyName();
try {
switch (IngestManager.IngestJobEvent.valueOf(eventType)) {
case DATA_SOURCE_ANALYSIS_STARTED:
if (((AutopsyEvent) event).getSourceType() == AutopsyEvent.SourceType.LOCAL) {
if (controller.isListeningEnabled()) {
DrawableDB drawableDb = controller.getDatabase();
// Don't update status if it is is already marked as COMPLETE
if (drawableDb.getDataSourceDbBuildStatus(dataSourceObjId) != DrawableDB.DrawableDbBuildStatusEnum.COMPLETE) {
drawableDb.insertOrUpdateDataSource(dataSource.getId(), DrawableDB.DrawableDbBuildStatusEnum.IN_PROGRESS);
}
}
}
break;
case DATA_SOURCE_ANALYSIS_COMPLETED:
if (((AutopsyEvent) event).getSourceType() == AutopsyEvent.SourceType.LOCAL) {
/*
* This node just completed analysis of a data
* source. Set the state of the local drawables
* database.
*/
if (controller.isListeningEnabled()) {
DrawableDB drawableDb = controller.getDatabase();
if (drawableDb.getDataSourceDbBuildStatus(dataSourceObjId) == DrawableDB.DrawableDbBuildStatusEnum.IN_PROGRESS) {
// If at least one file in CaseDB has mime type, then set to COMPLETE
// Otherwise, back to UNKNOWN since we assume file type module was not run
DrawableDB.DrawableDbBuildStatusEnum datasourceDrawableDBStatus
= controller.hasFilesWithMimeType(dataSourceObjId)
? DrawableDB.DrawableDbBuildStatusEnum.COMPLETE
: DrawableDB.DrawableDbBuildStatusEnum.UNKNOWN;
controller.getDatabase().insertOrUpdateDataSource(dataSource.getId(), datasourceDrawableDBStatus);
}
}
} else if (((AutopsyEvent) event).getSourceType() == AutopsyEvent.SourceType.REMOTE) {
/*
* A remote node just completed analysis of a data
* source. The local drawables database is therefore
* stale. If the image gallery top component is
* open, give the user an opportunity to update the
* drawables database now.
*/
controller.setCaseStale(true);
if (controller.isListeningEnabled()) {
SwingUtilities.invokeLater(() -> {
if (ImageGalleryTopComponent.isImageGalleryOpen()) {
int showAnswer = JOptionPane.showConfirmDialog(ImageGalleryTopComponent.getTopComponent(),
Bundle.ImageGalleryController_dataSourceAnalyzed_confDlg_msg(),
Bundle.ImageGalleryController_dataSourceAnalyzed_confDlg_title(),
JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
switch (showAnswer) {
case JOptionPane.YES_OPTION:
controller.rebuildDB();
break;
case JOptionPane.NO_OPTION:
case JOptionPane.CANCEL_OPTION:
default:
break;
}
}
});
}
}
break;
default:
break;
}
} catch (TskCoreException ex) {
logger.log(Level.SEVERE, String.format("Failed to handle %s event for %s (objId=%d)", dataSourceEvent.getPropertyName(), dataSource.getName(), dataSourceObjId), ex);
}
}
}
}
| ImageGallery/src/org/sleuthkit/autopsy/imagegallery/ImageGalleryModule.java | /*
* Autopsy Forensic Browser
*
* Copyright 2013-2018 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sleuthkit.autopsy.imagegallery;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.EnumSet;
import java.util.Set;
import java.util.logging.Level;
import javafx.application.Platform;
import javax.annotation.concurrent.GuardedBy;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
import org.openide.util.NbBundle;
import org.sleuthkit.autopsy.casemodule.Case;
import org.sleuthkit.autopsy.casemodule.NoCurrentCaseException;
import org.sleuthkit.autopsy.casemodule.events.ContentTagAddedEvent;
import org.sleuthkit.autopsy.casemodule.events.ContentTagDeletedEvent;
import org.sleuthkit.autopsy.core.RuntimeProperties;
import org.sleuthkit.autopsy.coreutils.Logger;
import org.sleuthkit.autopsy.events.AutopsyEvent;
import org.sleuthkit.autopsy.imagegallery.datamodel.DrawableDB;
import org.sleuthkit.autopsy.ingest.IngestManager;
import static org.sleuthkit.autopsy.ingest.IngestManager.IngestModuleEvent.DATA_ADDED;
import static org.sleuthkit.autopsy.ingest.IngestManager.IngestModuleEvent.FILE_DONE;
import org.sleuthkit.autopsy.ingest.ModuleDataEvent;
import org.sleuthkit.autopsy.ingest.events.DataSourceAnalysisEvent;
import org.sleuthkit.autopsy.modules.filetypeid.FileTypeDetector;
import org.sleuthkit.datamodel.AbstractFile;
import org.sleuthkit.datamodel.BlackboardArtifact;
import org.sleuthkit.datamodel.BlackboardArtifact.ARTIFACT_TYPE;
import org.sleuthkit.datamodel.Content;
import org.sleuthkit.datamodel.TskCoreException;
import org.sleuthkit.datamodel.TskData;
/**
* This class is reponsible for handling selected application events for the
* image gallery module, managing the image gallery module's per case MVC
* controller and keeping track of the following state: the module name, the
* module output directory and whether or not the ingest gallery module is
* enabled for the current case.
*/
@NbBundle.Messages({"ImageGalleryModule.moduleName=Image Gallery"})
public class ImageGalleryModule {
private static final Logger logger = Logger.getLogger(ImageGalleryModule.class.getName());
private static final String MODULE_NAME = Bundle.ImageGalleryModule_moduleName();
private static final Set<Case.Events> CASE_EVENTS_OF_INTEREST = EnumSet.of(
Case.Events.CURRENT_CASE,
Case.Events.DATA_SOURCE_ADDED,
Case.Events.CONTENT_TAG_ADDED,
Case.Events.CONTENT_TAG_DELETED
);
private static final Object controllerLock = new Object();
@GuardedBy("controllerLock")
private static ImageGalleryController controller;
/**
* Gets the per case image gallery controller for the current case. The
* controller is changed in the case event listener.
*
* @return The image gallery controller for the current case.
*
* @throws TskCoreException If there is a problem creating the controller.
*/
public static ImageGalleryController getController() throws TskCoreException {
synchronized (controllerLock) {
if (controller == null) {
try {
Case currentCase = Case.getCurrentCaseThrows();
controller = new ImageGalleryController(currentCase);
} catch (NoCurrentCaseException ex) {
throw new TskCoreException("Failed to get ", ex);
}
}
return controller;
}
}
/**
* Sets the implicit exit property attribute of the JavaFX runtime to false
* and sets up listeners for application events. It is invoked at
* application start up by virtue of the OnStart annotation on the OnStart
* class in this package.
*/
static void onStart() {
Platform.setImplicitExit(false);
IngestManager.getInstance().addIngestJobEventListener(new IngestJobEventListener());
IngestManager.getInstance().addIngestModuleEventListener(new IngestModuleEventListener());
Case.addEventTypeSubscriber(CASE_EVENTS_OF_INTEREST, new CaseEventListener());
}
/**
* Gets the image gallery module name.
*
* @return The module name,
*/
static String getModuleName() {
return MODULE_NAME;
}
/**
* Gets the path to the image gallery module output folder for a given case.
*
* @param theCase The case.
*
* @return The path to the image gallery module output folder for the case.
*/
public static Path getModuleOutputDir(Case theCase) {
return Paths.get(theCase.getModuleDirectory(), getModuleName());
}
/**
* Prevents instantiation.
*/
private ImageGalleryModule() {
}
/**
* Indicates whether or not the image gallery module is enabled for a given
* case.
*
* @param theCase The case.
*
* @return True or false.
*/
static boolean isEnabledforCase(Case theCase) {
String enabledforCaseProp = new PerCaseProperties(theCase).getConfigSetting(ImageGalleryModule.MODULE_NAME, PerCaseProperties.ENABLED);
return isNotBlank(enabledforCaseProp) ? Boolean.valueOf(enabledforCaseProp) : ImageGalleryPreferences.isEnabledByDefault();
}
/**
* Indicates whether or not a given file is of interest to the image gallery
* module (is "drawable") and is not marked as a "known" file (e.g., is not
* a file in the NSRL hash set).
*
* @param file The file.
*
* @return True if the file is "drawable" and not "known", false otherwise.
*
* @throws FileTypeDetectorInitException If there is an error determining
* the type of the file.
*/
private static boolean isDrawableAndNotKnown(AbstractFile abstractFile) throws FileTypeDetector.FileTypeDetectorInitException {
return (abstractFile.getKnown() != TskData.FileKnown.KNOWN) && FileTypeUtils.isDrawable(abstractFile);
}
/**
* A listener for ingest module application events.
*/
static private class IngestModuleEventListener implements PropertyChangeListener {
@Override
public void propertyChange(PropertyChangeEvent event) {
/*
* Only process individual files and artifacts in "real time" on the
* node that is running the ingest job. On a remote node, image
* files are processed as a group when the ingest job is complete.
*/
if (((AutopsyEvent) event).getSourceType() != AutopsyEvent.SourceType.LOCAL) {
return;
}
ImageGalleryController currentController;
try {
currentController = getController();
} catch (TskCoreException ex) {
logger.log(Level.SEVERE, String.format("Failed to handle %s event", event.getPropertyName()), ex); //NON-NLS
return;
}
String eventType = event.getPropertyName();
switch (IngestManager.IngestModuleEvent.valueOf(eventType)) {
case FILE_DONE:
AbstractFile file = (AbstractFile) event.getNewValue();
if (!file.isFile()) {
return;
}
if (currentController.isListeningEnabled()) {
try {
if (isDrawableAndNotKnown(file)) {
currentController.queueDBTask(new ImageGalleryController.UpdateFileTask(file, currentController.getDatabase()));
}
} catch (FileTypeDetector.FileTypeDetectorInitException ex) {
logger.log(Level.SEVERE, String.format("Failed to determine if file is of interest to the image gallery module, ignoring file (obj_id=%d)", file.getId()), ex); //NON-NLS
}
}
break;
case DATA_ADDED:
ModuleDataEvent artifactAddedEvent = (ModuleDataEvent) event.getOldValue();
if (artifactAddedEvent.getBlackboardArtifactType().getTypeID() == ARTIFACT_TYPE.TSK_METADATA_EXIF.getTypeID()) {
DrawableDB drawableDB = currentController.getDatabase();
if (artifactAddedEvent.getArtifacts() != null) {
for (BlackboardArtifact art : artifactAddedEvent.getArtifacts()) {
drawableDB.addExifCache(art.getObjectID());
}
}
} else if (artifactAddedEvent.getBlackboardArtifactType().getTypeID() == ARTIFACT_TYPE.TSK_HASHSET_HIT.getTypeID()) {
DrawableDB drawableDB = currentController.getDatabase();
if (artifactAddedEvent.getArtifacts() != null) {
for (BlackboardArtifact art : artifactAddedEvent.getArtifacts()) {
drawableDB.addHashSetCache(art.getObjectID());
}
}
}
break;
default:
break;
}
}
}
/**
* A listener for case application events.
*/
static private class CaseEventListener implements PropertyChangeListener {
@Override
public void propertyChange(PropertyChangeEvent event) {
Case.Events eventType = Case.Events.valueOf(event.getPropertyName());
if (eventType == Case.Events.CURRENT_CASE) {
synchronized (controllerLock) {
if (event.getNewValue() != null) {
/*
* CURRENT_CASE(_OPENED) event.
*/
Case newCase = (Case) event.getNewValue();
try {
controller = new ImageGalleryController(newCase);
} catch (TskCoreException ex) {
logger.log(Level.SEVERE, String.format("Failed to construct controller for new case %s (%s)", newCase.getDisplayName(), newCase.getName()), ex);
}
} else if (event.getOldValue() != null) {
/*
* CURRENT_CASE(_CLOSED) event.
*/
SwingUtilities.invokeLater(ImageGalleryTopComponent::closeTopComponent);
controller.shutDown();
controller = null;
}
}
} else {
ImageGalleryController currentController;
try {
currentController = getController();
} catch (TskCoreException ex) {
logger.log(Level.SEVERE, String.format("Failed to handle %s event", event.getPropertyName()), ex); //NON-NLS
return;
}
switch (eventType) {
case DATA_SOURCE_ADDED:
if (((AutopsyEvent) event).getSourceType() == AutopsyEvent.SourceType.LOCAL) {
Content newDataSource = (Content) event.getNewValue();
if (currentController.isListeningEnabled()) {
currentController.getDatabase().insertOrUpdateDataSource(newDataSource.getId(), DrawableDB.DrawableDbBuildStatusEnum.UNKNOWN);
}
}
break;
case CONTENT_TAG_ADDED:
final ContentTagAddedEvent tagAddedEvent = (ContentTagAddedEvent) event;
long objId = tagAddedEvent.getAddedTag().getContent().getId();
DrawableDB drawableDB = currentController.getDatabase();
drawableDB.addTagCache(objId); // RJCTODO: Why add the tag to the cache before doing the in DB check?
if (drawableDB.isInDB(objId)) {
currentController.getTagsManager().fireTagAddedEvent(tagAddedEvent);
}
break;
case CONTENT_TAG_DELETED:
final ContentTagDeletedEvent tagDeletedEvent = (ContentTagDeletedEvent) event;
if (currentController.getDatabase().isInDB(tagDeletedEvent.getDeletedTagInfo().getContentID())) {
currentController.getTagsManager().fireTagDeletedEvent(tagDeletedEvent);
} // RJCTODO: Why not remove the tag from the cache?
break;
default:
logger.log(Level.SEVERE, String.format("Received %s event with no subscription", event.getPropertyName())); //NON-NLS
break;
}
}
}
}
/**
* A listener for ingest job application events.
*/
static private class IngestJobEventListener implements PropertyChangeListener {
@NbBundle.Messages({
"ImageGalleryController.dataSourceAnalyzed.confDlg.msg= A new data source was added and finished ingest.\n"
+ "The image / video database may be out of date. "
+ "Do you want to update the database with ingest results?\n",
"ImageGalleryController.dataSourceAnalyzed.confDlg.title=Image Gallery"
})
@Override
public void propertyChange(PropertyChangeEvent event) {
/*
* Only handling data source analysis events.
*/
if (!(event instanceof DataSourceAnalysisEvent)) {
return;
}
ImageGalleryController controller;
try {
controller = getController();
} catch (TskCoreException ex) {
logger.log(Level.SEVERE, String.format("Failed to handle %s event", event.getPropertyName()), ex); //NON-NLS
return;
}
DataSourceAnalysisEvent dataSourceEvent = (DataSourceAnalysisEvent) event;
Content dataSource = dataSourceEvent.getDataSource();
long dataSourceObjId = dataSource.getId();
String eventType = dataSourceEvent.getPropertyName();
try {
switch (IngestManager.IngestJobEvent.valueOf(eventType)) {
case DATA_SOURCE_ANALYSIS_STARTED:
if (((AutopsyEvent) event).getSourceType() == AutopsyEvent.SourceType.LOCAL) {
if (controller.isListeningEnabled()) {
DrawableDB drawableDb = controller.getDatabase();
// Don't update status if it is is already marked as COMPLETE
if (drawableDb.getDataSourceDbBuildStatus(dataSourceObjId) != DrawableDB.DrawableDbBuildStatusEnum.COMPLETE) {
drawableDb.insertOrUpdateDataSource(dataSource.getId(), DrawableDB.DrawableDbBuildStatusEnum.IN_PROGRESS);
}
}
}
break;
case DATA_SOURCE_ANALYSIS_COMPLETED:
if (((AutopsyEvent) event).getSourceType() == AutopsyEvent.SourceType.LOCAL) {
/*
* This node just completed analysis of a data
* source. Set the state of the local drawables
* database.
*/
if (controller.isListeningEnabled()) {
DrawableDB drawableDb = controller.getDatabase();
if (drawableDb.getDataSourceDbBuildStatus(dataSourceObjId) == DrawableDB.DrawableDbBuildStatusEnum.IN_PROGRESS) {
// If at least one file in CaseDB has mime type, then set to COMPLETE
// Otherwise, back to UNKNOWN since we assume file type module was not run
DrawableDB.DrawableDbBuildStatusEnum datasourceDrawableDBStatus
= controller.hasFilesWithMimeType(dataSourceObjId)
? DrawableDB.DrawableDbBuildStatusEnum.COMPLETE
: DrawableDB.DrawableDbBuildStatusEnum.UNKNOWN;
controller.getDatabase().insertOrUpdateDataSource(dataSource.getId(), datasourceDrawableDBStatus);
}
}
} else if (((AutopsyEvent) event).getSourceType() == AutopsyEvent.SourceType.REMOTE) {
/*
* A remote node just completed analysis of a data
* source. The local drawables database is therefore
* stale. If the image gallery top component is
* open, give the user an opportunity to update the
* drawables database now.
*/
controller.setCaseStale(true);
if (controller.isListeningEnabled()) {
SwingUtilities.invokeLater(() -> {
if (ImageGalleryTopComponent.isImageGalleryOpen()) {
int showAnswer = JOptionPane.showConfirmDialog(ImageGalleryTopComponent.getTopComponent(),
Bundle.ImageGalleryController_dataSourceAnalyzed_confDlg_msg(),
Bundle.ImageGalleryController_dataSourceAnalyzed_confDlg_title(),
JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
switch (showAnswer) {
case JOptionPane.YES_OPTION:
controller.rebuildDB();
break;
case JOptionPane.NO_OPTION:
case JOptionPane.CANCEL_OPTION:
default:
break;
}
}
});
}
}
break;
default:
break;
}
} catch (TskCoreException ex) {
logger.log(Level.SEVERE, String.format("Failed to handle %s event for %s (objId=%d)", dataSourceEvent.getPropertyName(), dataSource.getName(), dataSourceObjId), ex);
}
}
}
}
| Add comments TODOs ImageGalleryModule
| ImageGallery/src/org/sleuthkit/autopsy/imagegallery/ImageGalleryModule.java | Add comments TODOs ImageGalleryModule | <ide><path>mageGallery/src/org/sleuthkit/autopsy/imagegallery/ImageGalleryModule.java
<ide> ImageGalleryController currentController;
<ide> try {
<ide> currentController = getController();
<add> // RJCTODO: If a closed controller had a method that could be
<add> // queried to determine whether it was shut down, we could
<add> // bail out here. The older code that used to try to check for
<add> // a current case was flawed; there was no guarantee the current
<add> // case was the same case associated with the event.
<ide> } catch (TskCoreException ex) {
<ide> logger.log(Level.SEVERE, String.format("Failed to handle %s event", event.getPropertyName()), ex); //NON-NLS
<ide> return;
<ide> /**
<ide> * A listener for case application events.
<ide> */
<add> // RJCTODO: This code would be easier to read if there were two case event
<add> // listeners, one that handled CURRENT_CASE events and one that handled
<add> // the other events.
<ide> static private class CaseEventListener implements PropertyChangeListener {
<ide>
<ide> @Override
<ide> */
<ide> SwingUtilities.invokeLater(ImageGalleryTopComponent::closeTopComponent);
<ide> controller.shutDown();
<del> controller = null;
<ide> }
<ide> }
<ide> } else {
<ide> ImageGalleryController currentController;
<ide> try {
<ide> currentController = getController();
<add> // RJCTODO: If a closed controller had a method that could be
<add> // queried to determine whether it was shut down, we could
<add> // bail out here. The older code that used to try to check for
<add> // a current case was flawed; there was no guarantee the current
<add> // case was the same case associated with the event.
<ide> } catch (TskCoreException ex) {
<ide> logger.log(Level.SEVERE, String.format("Failed to handle %s event", event.getPropertyName()), ex); //NON-NLS
<ide> return;
<ide> ImageGalleryController controller;
<ide> try {
<ide> controller = getController();
<add> // RJCTODO: If a closed controller had a method that could be
<add> // queried to determine whether it was shut down, we could
<add> // bail out here. The older code that used to try to check for
<add> // a current case was flawed; there was no guarantee the current
<add> // case was the same case associated with the event.
<ide> } catch (TskCoreException ex) {
<ide> logger.log(Level.SEVERE, String.format("Failed to handle %s event", event.getPropertyName()), ex); //NON-NLS
<ide> return; |
|
Java | mit | 341c6729df9e726a05e37c20e23987ce1f90d108 | 0 | FIRST-Team-1699/autonomous-code | package org.usfirst.frc.team1699.utils.autonomous;
import java.util.ArrayList;
import org.usfirst.frc.team1699.utils.autonomous.Tokenizer.Token;
import org.usfirst.frc.team1699.utils.command.Command;
public class IfConditionalUtils {
private static final String[] validConditionalSymbols = {"<", ">", "==", "<=", ">="}; //Stores valid conditional symbols
/**
* Returns true if string is a conditional
*
* @param fileAsString
* @param startLine
* @param reader
* @return
*/
public static boolean ifConditional(ArrayList<String> fileAsString, int startLine, Tokenizer reader){
String[] conLine = fileAsString.get(startLine).split(" ");
String conditional = "";
int conditionalStart = 0;
int conditionalEnd = 0;
for(int i = 0; i < conLine.length; i++){
if(conLine[i].equals("if")){
conditionalStart = i + 1;
}
}
for(int i = 0; i < conLine.length; i++){
if(conLine[i].equals("then:")){
conditionalEnd = i;
}
}
for(int i = conditionalStart; i < conditionalEnd; i++){
conditional += conLine[i] + " ";
}
return evaluateConditional(conditional, reader);
}
/**
* Returns true if conditional string evaluates to true
*
* @param conditional
* @param tokenizer
* @return
*/
public static boolean evaluateConditional(String conditional, Tokenizer tokenizer){
String firstStatement = "";
String secondStatement = "";
String conditionalSymbol = "";
Type firstType;
Type secondType;
if(conditional.contains(">") || conditional.contains("<") || conditional.contains(">=") || conditional.contains("<=") || conditional.contains("==") || conditional.contains("!=")){
for(int i = 0; i < conditional.length(); i++){
if(conditional.substring(i, i + 1).equals(">") || conditional.substring(i, i + 1).equals("<") || conditional.substring(i, i + 1).equals(">=") || conditional.substring(i, i + 1).equals("<=") || conditional.substring(i, i + 1).equals("==") || conditional.substring(i, i + 1).equals("!=")){
conditionalSymbol = conditional.substring(i, i + 1);
firstStatement = conditional.substring(0, i);
secondStatement = conditional.substring(i + 1).trim();
}
}
}else{
//boolean
}
firstType = getType(firstStatement);
secondType = getType(secondStatement);
if((firstType.equals(Type.DOUBLE) || firstType.equals(Type.INTEGER)) && (secondType.equals(Type.DOUBLE) || secondType.equals(Type.INTEGER))){
tokenizer.tokenize(conditionalSymbol);
Token tok = tokenizer.getTokens().get(0);
switch(tok.token){
case 0: return AutoUtils.parseDouble(firstStatement) < AutoUtils.parseDouble(secondStatement);
case 1: return AutoUtils.parseDouble(firstStatement) > AutoUtils.parseDouble(secondStatement);
case 2: return AutoUtils.parseDouble(firstStatement) <= AutoUtils.parseDouble(secondStatement);
case 3: return AutoUtils.parseDouble(firstStatement) >= AutoUtils.parseDouble(secondStatement);
case 4: return AutoUtils.parseDouble(firstStatement) == AutoUtils.parseDouble(secondStatement);
case 5: return AutoUtils.parseDouble(firstStatement) != AutoUtils.parseDouble(secondStatement);
default: return false;
}
}else if(firstType.equals(Type.STRING) && secondType.equals(Type.STRING)){
return firstStatement.equals(secondStatement);
}else{
return false;
}
}
/**
* Gets Type of string
*
* @param str
* @return
*/
public static Type getType(String str){
if((!str.contains(".") && (!str.contains("\"")))){
return Type.INTEGER;
}else if((str.contains(".")) && (!str.contains("\""))){
return Type.DOUBLE;
}else{
return Type.STRING;
}
}
/**
* Gets length of if
*
* @param strArr
* @param currentLine
* @return
*/
public static int getIfLength(ArrayList<String> strArr, int currentLine){
for(int i = currentLine; i < strArr.size(); i++){
if(strArr.get(i).trim().equals("end")){
return i - currentLine;
}
}
return 0;
}
/**
* Returns true if string is a conditional symbol
*
* @param conditional
* @return
*/
public static boolean isConditional(String conditional){
for(String x: validConditionalSymbols){
return x.equals(conditional);
}
return false;
}
/**
* Returns conditional symbol from string
*
* @param conditional
* @return
*/
public static String getConditional(String conditional){
for(String x: validConditionalSymbols){
if(x.equals(conditional)){
return x;
}
}
return null;
}
/**
* Returns true if string contains a conditional
*
* @param string
* @return
*/
public static boolean containsIfConditional(String string){
String[] inp = string.split(" ");
for(int i = 0; i < inp.length; i++){
if(inp[i].equals("if")){
return true;
}
}
return false;
}
}
| src/org/usfirst/frc/team1699/utils/autonomous/IfConditionalUtils.java | package org.usfirst.frc.team1699.utils.autonomous;
import java.util.ArrayList;
import org.usfirst.frc.team1699.utils.autonomous.Tokenizer.Token;
import org.usfirst.frc.team1699.utils.command.Command;
public class IfConditionalUtils {
private static final String[] validConditionalSymbols = {"<", ">", "==", "<=", ">="}; //Stores valid conditional symbols
public static boolean ifConditional(ArrayList<String> fileAsString, int startLine, Tokenizer reader){
String[] conLine = fileAsString.get(startLine).split(" ");
String conditional = "";
int conditionalStart = 0;
int conditionalEnd = 0;
for(int i = 0; i < conLine.length; i++){
if(conLine[i].equals("if")){
conditionalStart = i + 1;
}
}
for(int i = 0; i < conLine.length; i++){
if(conLine[i].equals("then:")){
conditionalEnd = i;
}
}
for(int i = conditionalStart; i < conditionalEnd; i++){
conditional += conLine[i] + " ";
}
return evaluateConditional(conditional, reader);
}
public static boolean evaluateConditional(String conditional, Tokenizer tokenizer){
String firstStatement = "";
String secondStatement = "";
String conditionalSymbol = "";
Type firstType;
Type secondType;
if(conditional.contains(">") || conditional.contains("<") || conditional.contains(">=") || conditional.contains("<=") || conditional.contains("==") || conditional.contains("!=")){
for(int i = 0; i < conditional.length(); i++){
if(conditional.substring(i, i + 1).equals(">") || conditional.substring(i, i + 1).equals("<") || conditional.substring(i, i + 1).equals(">=") || conditional.substring(i, i + 1).equals("<=") || conditional.substring(i, i + 1).equals("==") || conditional.substring(i, i + 1).equals("!=")){
conditionalSymbol = conditional.substring(i, i + 1);
firstStatement = conditional.substring(0, i);
secondStatement = conditional.substring(i + 1).trim();
}
}
}else{
//boolean
}
firstType = getType(firstStatement);
secondType = getType(secondStatement);
if((firstType.equals(Type.DOUBLE) || firstType.equals(Type.INTEGER)) && (secondType.equals(Type.DOUBLE) || secondType.equals(Type.INTEGER))){
tokenizer.tokenize(conditionalSymbol);
Token tok = tokenizer.getTokens().get(0);
switch(tok.token){
case 0: return AutoUtils.parseDouble(firstStatement) < AutoUtils.parseDouble(secondStatement);
case 1: return AutoUtils.parseDouble(firstStatement) > AutoUtils.parseDouble(secondStatement);
case 2: return AutoUtils.parseDouble(firstStatement) <= AutoUtils.parseDouble(secondStatement);
case 3: return AutoUtils.parseDouble(firstStatement) >= AutoUtils.parseDouble(secondStatement);
case 4: return AutoUtils.parseDouble(firstStatement) == AutoUtils.parseDouble(secondStatement);
case 5: return AutoUtils.parseDouble(firstStatement) != AutoUtils.parseDouble(secondStatement);
default: return false;
}
}else if(firstType.equals(Type.STRING) && secondType.equals(Type.STRING)){
return firstStatement.equals(secondStatement);
}else{
return false;
}
}
public static Type getType(String str){
if((!str.contains(".") && (!str.contains("\"")))){
return Type.INTEGER;
}else if((str.contains(".")) && (!str.contains("\""))){
return Type.DOUBLE;
}else{
return Type.STRING;
}
}
public static int getIfLength(ArrayList<String> strArr, int currentLine){
for(int i = currentLine; i < strArr.size(); i++){
if(strArr.get(i).trim().equals("end")){
return i - currentLine;
}
}
return 0;
}
public static boolean isConditional(String conditional){
for(String x: validConditionalSymbols){
return x.equals(conditional);
}
return false;
}
public static String getConditional(String conditional){
for(String x: validConditionalSymbols){
if(x.equals(conditional)){
return x;
}
}
return null;
}
public static boolean containsIfConditional(String string){
String[] inp = string.split(" ");
for(int i = 0; i < inp.length; i++){
if(inp[i].equals("if")){
return true;
}
}
return false;
}
}
| JavaDocs | src/org/usfirst/frc/team1699/utils/autonomous/IfConditionalUtils.java | JavaDocs | <ide><path>rc/org/usfirst/frc/team1699/utils/autonomous/IfConditionalUtils.java
<ide> public class IfConditionalUtils {
<ide> private static final String[] validConditionalSymbols = {"<", ">", "==", "<=", ">="}; //Stores valid conditional symbols
<ide>
<del>
<del>
<add> /**
<add> * Returns true if string is a conditional
<add> *
<add> * @param fileAsString
<add> * @param startLine
<add> * @param reader
<add> * @return
<add> */
<ide> public static boolean ifConditional(ArrayList<String> fileAsString, int startLine, Tokenizer reader){
<ide> String[] conLine = fileAsString.get(startLine).split(" ");
<ide> String conditional = "";
<ide> return evaluateConditional(conditional, reader);
<ide> }
<ide>
<add> /**
<add> * Returns true if conditional string evaluates to true
<add> *
<add> * @param conditional
<add> * @param tokenizer
<add> * @return
<add> */
<ide> public static boolean evaluateConditional(String conditional, Tokenizer tokenizer){
<ide> String firstStatement = "";
<ide> String secondStatement = "";
<ide> }
<ide> }
<ide>
<add> /**
<add> * Gets Type of string
<add> *
<add> * @param str
<add> * @return
<add> */
<ide> public static Type getType(String str){
<ide> if((!str.contains(".") && (!str.contains("\"")))){
<ide> return Type.INTEGER;
<ide> }
<ide> }
<ide>
<add> /**
<add> * Gets length of if
<add> *
<add> * @param strArr
<add> * @param currentLine
<add> * @return
<add> */
<ide> public static int getIfLength(ArrayList<String> strArr, int currentLine){
<ide> for(int i = currentLine; i < strArr.size(); i++){
<ide> if(strArr.get(i).trim().equals("end")){
<ide> return 0;
<ide> }
<ide>
<add> /**
<add> * Returns true if string is a conditional symbol
<add> *
<add> * @param conditional
<add> * @return
<add> */
<ide> public static boolean isConditional(String conditional){
<ide> for(String x: validConditionalSymbols){
<ide> return x.equals(conditional);
<ide> return false;
<ide> }
<ide>
<add> /**
<add> * Returns conditional symbol from string
<add> *
<add> * @param conditional
<add> * @return
<add> */
<ide> public static String getConditional(String conditional){
<ide> for(String x: validConditionalSymbols){
<ide> if(x.equals(conditional)){
<ide> return null;
<ide> }
<ide>
<add> /**
<add> * Returns true if string contains a conditional
<add> *
<add> * @param string
<add> * @return
<add> */
<ide> public static boolean containsIfConditional(String string){
<ide> String[] inp = string.split(" ");
<ide> for(int i = 0; i < inp.length; i++){ |
|
Java | bsd-3-clause | f34d443059f61928439f703979d12314445c723c | 0 | terabyte/Jira-Commit-Acceptance-Plugin,terabyte/Jira-Commit-Acceptance-Plugin,terabyte/Jira-Commit-Acceptance-Plugin,terabyte/Jira-Commit-Acceptance-Plugin,terabyte/Jira-Commit-Acceptance-Plugin | package com.atlassian.jira.ext.commitacceptance.server.action;
import org.apache.commons.lang.builder.HashCodeBuilder;
/**
* Wraps the commit acceptance settings for one project
* or globally.
*
* @author <a href="mailto:[email protected]">Ferenc Kiss</a>
* @version $Id$
*/
public class AcceptanceSettings {
/**
* If <code>true</code> the global settings override
* the project-specific settings.
*/
private boolean useGlobalRules;
/**
* If <code>true</code> the commit message must contain
* at least valid issue key.
*/
private boolean mustHaveIssue;
/**
* If <code>true</code>, all the issues must be unresolved.
*/
private boolean mustBeUnresolved;
/**
* If <code>true</code>, all the issues must be assigned to
* the commiter.
*/
private boolean mustBeAssignedToCommiter;
public boolean getUseGlobalRules() {
return useGlobalRules;
}
public void setUseGlobalRules(boolean useGlobalRules) {
this.useGlobalRules = useGlobalRules;
}
public boolean isMustHaveIssue() {
return mustHaveIssue;
}
public void setMustHaveIssue(boolean mustHaveIssue) {
this.mustHaveIssue = mustHaveIssue;
}
public boolean isMustBeUnresolved() {
return mustBeUnresolved;
}
public void setMustBeUnresolved(boolean mustBeUnresolved) {
this.mustBeUnresolved = mustBeUnresolved;
}
public boolean isMustBeAssignedToCommiter() {
return mustBeAssignedToCommiter;
}
public void setMustBeAssignedToCommiter(boolean mustBeAssignedToCommiter) {
this.mustBeAssignedToCommiter = mustBeAssignedToCommiter;
}
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
AcceptanceSettings other = (AcceptanceSettings)obj;
return (useGlobalRules == other.getUseGlobalRules()) &&
(mustHaveIssue == other.isMustHaveIssue()) &&
(mustBeUnresolved == other.isMustBeUnresolved()) &&
(mustBeAssignedToCommiter == other.isMustBeAssignedToCommiter());
}
public int hashCode() {
return new HashCodeBuilder(79, 11).append(useGlobalRules).append(mustHaveIssue).append(mustBeUnresolved).append(mustBeAssignedToCommiter).hashCode();
}
}
| src/java/com/atlassian/jira/ext/commitacceptance/server/action/AcceptanceSettings.java | package com.atlassian.jira.ext.commitacceptance.server.action;
import org.apache.commons.lang.builder.HashCodeBuilder;
/**
* Wraps the commit acceptance settings for one project
* or globally.
*
* @author <a href="mailto:[email protected]">Ferenc Kiss</a>
* @version $Id$
*/
public class AcceptanceSettings {
/**
* If <code>true</code> the global settings override
* the project-specific settings.
*/
private boolean useGlobalRules;
/**
* If <code>true</code> the commit message must contain
* at least valid issue key.
*/
private boolean mustHaveIssue;
/**
* If <code>true</code>, all the issues must be assigned to
* the commiter.
*/
private boolean mustBeAssignedToCommiter;
/**
* If <code>true</code>, all the issues must be unresolved.
*/
private boolean mustBeUnresolved;
public boolean getUseGlobalRules() {
return useGlobalRules;
}
public void setUseGlobalRules(boolean useGlobalRules) {
this.useGlobalRules = useGlobalRules;
}
public boolean isMustHaveIssue() {
return mustHaveIssue;
}
public void setMustHaveIssue(boolean mustHaveIssue) {
this.mustHaveIssue = mustHaveIssue;
}
public boolean isMustBeUnresolved() {
return mustBeUnresolved;
}
public void setMustBeUnresolved(boolean mustBeUnresolved) {
this.mustBeUnresolved = mustBeUnresolved;
}
public boolean isMustBeAssignedToCommiter() {
return mustBeAssignedToCommiter;
}
public void setMustBeAssignedToCommiter(boolean mustBeAssignedToCommiter) {
this.mustBeAssignedToCommiter = mustBeAssignedToCommiter;
}
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
AcceptanceSettings other = (AcceptanceSettings)obj;
return (useGlobalRules == other.getUseGlobalRules()) &&
(mustHaveIssue == other.isMustHaveIssue()) &&
(mustBeUnresolved == other.isMustBeUnresolved()) &&
(mustBeAssignedToCommiter == other.isMustBeAssignedToCommiter());
}
public int hashCode() {
return new HashCodeBuilder(79, 11).append(useGlobalRules).append(mustHaveIssue).append(mustBeUnresolved).append(mustBeAssignedToCommiter).hashCode();
}
}
| Property declarations in consistent order
git-svn-id: d0eb299132fa1d4c22ea7ae7c6220ead72f92c2a@6642 2c54a935-e501-0410-bc05-97a93f6bca70
| src/java/com/atlassian/jira/ext/commitacceptance/server/action/AcceptanceSettings.java | Property declarations in consistent order | <ide><path>rc/java/com/atlassian/jira/ext/commitacceptance/server/action/AcceptanceSettings.java
<ide> * the project-specific settings.
<ide> */
<ide> private boolean useGlobalRules;
<del> /**
<add>
<add> /**
<ide> * If <code>true</code> the commit message must contain
<ide> * at least valid issue key.
<ide> */
<ide> private boolean mustHaveIssue;
<del>
<add> /**
<add> * If <code>true</code>, all the issues must be unresolved.
<add> */
<add> private boolean mustBeUnresolved;
<ide> /**
<ide> * If <code>true</code>, all the issues must be assigned to
<ide> * the commiter.
<ide> */
<ide> private boolean mustBeAssignedToCommiter;
<del>
<del> /**
<del> * If <code>true</code>, all the issues must be unresolved.
<del> */
<del> private boolean mustBeUnresolved;
<del>
<ide>
<ide> public boolean getUseGlobalRules() {
<ide> return useGlobalRules; |
|
Java | apache-2.0 | b206507178eaa6d780654120ce5f3bede01cdaeb | 0 | akamai-open/AkamaiOPEN-edgegrid-java,akamai-open/edgegrid-auth-java | /*
* Copyright 2016 Copyright 2016 Akamai Technologies, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.akamai.edgegrid.signer;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import org.apache.commons.lang3.Validate;
import org.apache.commons.lang3.builder.Builder;
import org.apache.commons.lang3.builder.CompareToBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.akamai.edgegrid.signer.exceptions.RequestSigningException;
/**
* Library-agnostic representation of an HTTP request. This object is immutable, so you probably
* want to build an instance using {@link RequestBuilder}. Extenders of
* {@link AbstractEdgeGridRequestSigner} will need to build one of these as part of their
* implementation.
*
* @author [email protected]
* @author [email protected]
*/
public class Request implements Comparable<Request> {
private final byte[] body;
private final String method;
private final URI uri;
private final Map<String, String> headers;
private Request(RequestBuilder b) {
this.body = b.body;
this.method = b.method;
this.headers = b.headers;
this.uri = b.uri;
}
/**
* Returns a new builder. The returned builder is equivalent to the builder
* generated by {@link RequestBuilder}.
*
* @return a fresh {@link RequestBuilder}
*/
public static RequestBuilder builder() {
return new RequestBuilder();
}
@Override
public int compareTo(Request that) {
return new CompareToBuilder()
.append(this.body, that.body)
.append(this.headers, that.headers)
.append(this.method, that.method)
.append(this.uri, that.uri)
.build();
}
@Override
public boolean equals(Object o) {
if (o == null) return false;
if (getClass() != o.getClass()) return false;
final Request that = (Request) o;
return compareTo(that) == 0;
}
@Override
public int hashCode() {
return Objects.hash(body, headers, method, uri);
}
@Override
public String toString() {
return new ToStringBuilder(this, ToStringStyle.JSON_STYLE)
.append("body", body)
.append("headers", headers)
.append("method", method)
.append("uri", uri)
.build();
}
byte[] getBody() {
return body;
}
Map<String, String> getHeaders() {
return Collections.unmodifiableMap(headers);
}
String getMethod() {
return method;
}
URI getUri() {
return uri;
}
/**
* Creates a new builder. The returned builder is equivalent to the builder
* generated by {@link Request#builder()}.
*/
public static class RequestBuilder implements Builder<Request> {
private byte[] body = new byte[]{};
private Map<String, String> headers = new HashMap<>();
private String method;
private URI uri;
/**
* Sets a content of HTTP request body. If not set, body is empty by default.
*
* @param requestBody a request body, in bytes
* @return reference back to this builder instance
*/
public RequestBuilder body(byte[] requestBody) {
Validate.notNull(body, "body cannot be blank");
this.body = Arrays.copyOf(requestBody, requestBody.length);
return this;
}
/**
* <p>
* Adds a single header for an HTTP request. This can be called multiple times to add as
* many headers as needed.
* </p>
* <p>
* <i>NOTE: All header names are lower-cased for storage. In HTTP, header names are
* case-insensitive anyway, and EdgeGrid does not support multiple headers with the same
* name. Forcing to lowercase here improves our chance of detecting bad requests early.</i>
* </p>
*
* @param headerName a header name
* @param value a header value
* @return reference back to this builder instance
* @throws RequestSigningException if a duplicate header name is encountered
*/
public RequestBuilder header(String headerName, String value) throws RequestSigningException {
Validate.notEmpty(headerName, "headerName cannot be empty");
Validate.notEmpty(value, "value cannot be empty");
headerName = headerName.toLowerCase();
if (this.headers.containsKey(headerName)) {
throw new RequestSigningException("Duplicate header found: " + headerName);
}
headers.put(headerName, value);
return this;
}
/**
* <p>
* Sets headers of HTTP request. The {@code headers} parameter is copied so that changes
* to the original {@link Map} will not impact the stored reference.
* </p>
* <p>
* <i>NOTE: All header names are lower-cased for storage. In HTTP, header names are
* case-insensitive anyway, and EdgeGrid does not support multiple headers with the same
* name. Forcing to lowercase here improves our chance of detecting bad requests early.</i>
* </p>
*
* @param headers a {@link Map} of headers
* @return reference back to this builder instance
* @throws RequestSigningException if a duplicate header name is encountered
*/
public RequestBuilder headers(Map<String, String> headers) throws RequestSigningException {
Validate.notNull(headers, "headers cannot be null");
for (Map.Entry<String, String> entry : headers.entrySet()) {
header(entry.getKey(), entry.getValue());
}
return this;
}
/**
* Sets HTTP method: GET, PUT, POST, DELETE. Mandatory to set.
*
* @param method an HTTP method
* @return reference back to this builder instance
*/
public RequestBuilder method(String method) {
Validate.notBlank(method, "method cannot be blank");
this.method = method;
return this;
}
/**
* <p>
* Sets the URI of the HTTP request. This URI <i>MUST</i> have the correct path and query
* segments set. Scheme is assumed to be "HTTPS" for the purpose of this library. Host is
* actually taken from a {@link ClientCredential} as signing time; any value in this URI is
* discarded. Fragments are not signed.
* </p>
* <p>
* A path and/or query string is required.
* </p>
*
* @param uri a {@link URI}
* @return reference back to this builder instance
*/
public RequestBuilder uri(String uri) {
Validate.notEmpty(uri, "uri cannot be blank");
return uri(URI.create(uri));
}
/**
* <p>
* Sets the URI of the HTTP request. This URI <i>MUST</i> have the correct path and query
* segments set. Scheme is assumed to be "HTTPS" for the purpose of this library. Host is
* actually taken from a {@link ClientCredential} as signing time; any value in this URI is
* discarded. Fragments are not signed.
* </p>
* <p>
* A path and/or query string is required.
* </p>
*
* @param uri a {@link URI}
* @return reference back to this builder instance
*/
public RequestBuilder uri(URI uri) {
Validate.notNull(uri, "uri cannot be null");
try {
this.uri = new URI(null, null, uri.getPath(), uri.getQuery(), null);
} catch (URISyntaxException e) {
throw new IllegalArgumentException("Error setting URI", e);
}
return this;
}
/**
* Returns a newly-created immutable HTTP request.
*/
@Override
public Request build() {
Validate.notNull(body, "body cannot be blank");
Validate.notBlank(method, "method cannot be blank");
Validate.notNull(uri, "uriWithQuery cannot be blank");
return new Request(this);
}
}
}
| edgegrid-signer-core/src/main/java/com/akamai/edgegrid/signer/Request.java | /*
* Copyright 2016 Copyright 2016 Akamai Technologies, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.akamai.edgegrid.signer;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import org.apache.commons.lang3.Validate;
import org.apache.commons.lang3.builder.Builder;
import org.apache.commons.lang3.builder.CompareToBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.akamai.edgegrid.signer.exceptions.RequestSigningException;
/**
* Library-agnostic representation of an HTTP request. This object is immutable, so you probably
* want to build an instance using {@link RequestBuilder}. Extenders of
* {@link AbstractEdgeGridRequestSigner} will need to build one of these as part of their
* implementation.
*
* @author [email protected]
* @author [email protected]
*/
public class Request implements Comparable<Request> {
private final byte[] body;
private final String method;
private final URI uri;
private final Map<String, String> headers;
private Request(RequestBuilder b) {
this.body = b.body;
this.method = b.method;
this.headers = b.headers;
this.uri = b.uri;
}
/**
* Returns a new builder. The returned builder is equivalent to the builder
* generated by {@link RequestBuilder}.
*
* @return a fresh {@link RequestBuilder}
*/
public static RequestBuilder builder() {
return new RequestBuilder();
}
@Override
public int compareTo(Request that) {
return new CompareToBuilder()
.append(this.body, that.body)
.append(this.headers, that.headers)
.append(this.method, that.method)
.append(this.uri, that.uri)
.build();
}
@Override
public boolean equals(Object o) {
if (o == null) return false;
if (getClass() != o.getClass()) return false;
final Request that = (Request) o;
return compareTo(that) == 0;
}
@Override
public int hashCode() {
return Objects.hash(body, headers, method, uri);
}
@Override
public String toString() {
return new ToStringBuilder(this, ToStringStyle.JSON_STYLE)
.append("body", body)
.append("headers", headers)
.append("method", method)
.append("uri", uri)
.build();
}
byte[] getBody() {
return body;
}
Map<String, String> getHeaders() {
return Collections.unmodifiableMap(headers);
}
String getMethod() {
return method;
}
URI getUri() {
return uri;
}
/**
* Creates a new builder. The returned builder is equivalent to the builder
* generated by {@link Request#builder()}.
*/
public static class RequestBuilder implements Builder<Request> {
private byte[] body = new byte[]{};
private Map<String, String> headers = new HashMap<>();
private String method;
private URI uri;
/**
* Sets a content of HTTP request body. If not set, body is empty by default.
*
* @param requestBody a request body, in bytes
* @return reference back to this builder instance
*/
public RequestBuilder body(byte[] requestBody) {
Validate.notNull(body, "body cannot be blank");
this.body = Arrays.copyOf(requestBody, requestBody.length);
return this;
}
/**
* <p>
* Adds a single header for an HTTP request. This can be called multiple times to add as
* many headers as needed.
* </p>
* <p>
* <i>NOTE: All header names are lower-cased for storage. In HTTP, header names are
* case-insensitive anyway, and EdgeGrid does not support multiple headers with the same
* name. Forcing to lowercase here improves our chance of detecting bad requests early.</i>
* </p>
*
* @param headerName a header name
* @param value a header value
* @return reference back to this builder instance
* @throws RequestSigningException if a duplicate header name is encountered
*/
public RequestBuilder header(String headerName, String value) throws RequestSigningException {
Validate.notEmpty(headerName, "headerName cannot be empty");
Validate.notEmpty(value, "value cannot be empty");
headerName = headerName.toLowerCase();
if (this.headers.containsKey(headerName)) {
throw new RequestSigningException("Duplicate header found: " + headerName);
}
headers.put(headerName, value);
return this;
}
/**
* <p>
* Sets headers of HTTP request. The {@code headers} parameter is copied so that changes
* to the original {@link Map} will not impact the stored reference.
* </p>
* <p>
* <i>NOTE: All header names are lower-cased for storage. In HTTP, header names are
* case-insensitive anyway, and EdgeGrid does not support multiple headers with the same
* name. Forcing to lowercase here improves our chance of detecting bad requests early.</i>
* </p>
*
* @param headers a {@link Map} of headers
* @return reference back to this builder instance
* @throws RequestSigningException if a duplicate header name is encountered
*/
public RequestBuilder headers(Map<String, String> headers) throws RequestSigningException {
Validate.notNull(headers, "headers cannot be null");
for (Map.Entry<String, String> entry : headers.entrySet()) {
header(entry.getKey(), entry.getValue());
}
return this;
}
/**
* Sets HTTP method: GET, PUT, POST, DELETE. Mandatory to set.
*
* @param method an HTTP method
* @return reference back to this builder instance
*/
public RequestBuilder method(String method) {
Validate.notBlank(method, "method cannot be blank");
this.method = method;
return this;
}
/**
* <p>
* Sets the URI of the HTTP request. This URI <i>MUST</i> have the correct path and query
* segments set. Scheme is assumed to be "HTTPS" for the purpose of this library. Host is
* actually taken from a {@link ClientCredential} as signing time; any value in this URI is
* discarded. Fragments are not signed.
* </p>
* <p>
* A path and/or query string is required.
* </p>
*
* @param uri a {@link URI}
* @return reference back to this builder instance
*/
public RequestBuilder uri(String uri) {
Validate.notEmpty(uri, "uri cannot be blank");
return uri(URI.create(uri));
}
/**
* <p>
* Sets the URI of the HTTP request. This URI <i>MUST</i> have the correct path and query
* segments set. Scheme is assumed to be "HTTPS" for the purpose of this library. Host is
* actually taken from a {@link ClientCredential} as signing time; any value in this URI is
* discarded. Fragments are not signed.
* </p>
* <p>
* A path and/or query string is required.
* </p>
*
* @param uri a {@link URI}
* @return reference back to this builder instance
*/
public RequestBuilder uri(URI uri) {
Validate.notNull(uri, "uri cannot be null");
try {
this.uri = new URI(null, null, uri.getPath(), uri.getQuery(), null);
} catch (URISyntaxException e) {
throw new IllegalArgumentException("Error setting URI", e);
}
return this;
}
/**
* Please use {@link #uri(URI)} instead.
*
* @param uri a {@link URI}
* @return reference back to this builder instance
* @deprecated
*/
@Deprecated
public RequestBuilder uriWithQuery(URI uri) {
return uri(uri);
}
/**
* Returns a newly-created immutable HTTP request.
*/
@Override
public Request build() {
Validate.notNull(body, "body cannot be blank");
Validate.notBlank(method, "method cannot be blank");
Validate.notNull(uri, "uriWithQuery cannot be blank");
return new Request(this);
}
}
}
| Remove deprecated method RequestBuilder#uriWithQuery
| edgegrid-signer-core/src/main/java/com/akamai/edgegrid/signer/Request.java | Remove deprecated method RequestBuilder#uriWithQuery | <ide><path>dgegrid-signer-core/src/main/java/com/akamai/edgegrid/signer/Request.java
<ide> return this;
<ide> }
<ide>
<del> /**
<del> * Please use {@link #uri(URI)} instead.
<del> *
<del> * @param uri a {@link URI}
<del> * @return reference back to this builder instance
<del> * @deprecated
<del> */
<del> @Deprecated
<del> public RequestBuilder uriWithQuery(URI uri) {
<del> return uri(uri);
<del> }
<ide>
<ide> /**
<ide> * Returns a newly-created immutable HTTP request. |
|
JavaScript | apache-2.0 | 789d0ba711d70fcc5715959840e43b8aee3b8cb7 | 0 | Undev/redmine_cut_tag,Undev/redmine_cut_tag,Undev/redmine_cut_tag | // due to this task http://www.redmine.org/issues/11445
// check which framework is installed
if (typeof(jQuery) == 'undefined') {
// using prototype
document.observe('click', function(event) {
var switchesSelector = '.cut_tag_show,.cut_tag_hide';
var contentSelector = '.cut_tag_content';
var switcher = event.findElement(switchesSelector);
if (switcher) {
var cutTagEl = switcher.parentNode;
var selector = switchesSelector + ',' + contentSelector;
Selector.matchElements(cutTagEl.childElements(), selector).map(Element.toggle);
Event.stop(event);
}
});
} else {
// using jquery
$(document).ready(function() {
var switchesSelector = '.cut_tag_show,.cut_tag_hide';
var contentSelector = '.cut_tag_content';
$(document).on('click', switchesSelector, function() {
var selector = switchesSelector + ',' + contentSelector;
$(this).parent().children(selector).toggle();
return false;
});
});
}
| assets/javascripts/redmine_cut_tag.js | // due to this task http://www.redmine.org/issues/11445
// check which framework is installed
if (typeof(jQuery) == 'undefined') {
// using prototype
document.observe('click', function(event) {
var switchesSelector = '.cut_tag_show,.cut_tag_hide';
var contentSelector = '.cut_tag_content';
var switcher = event.findElement(switchesSelector);
if (switcher) {
var cutTagEl = switcher.parentNode;
var selector = switchesSelector + ',' + contentSelector;
Selector.matchElements(cutTagEl.childElements(), selector).map(Element.toggle);
Event.stop(event);
}
});
} else {
// using jquery
// compatibility code to use 'live' method on jquery 1.9 (redmine 2.5+)
// borrowed from jQuery 1.8.3's source code
jQuery.fn.extend({
live: function( types, data, fn ) {
jQuery( this.context ).on( types, this.selector, data, fn );
return this;
}
});
$(document).ready(function() {
var switchesSelector = '.cut_tag_show,.cut_tag_hide';
var contentSelector = '.cut_tag_content';
$(switchesSelector).live('click', function() {
var selector = switchesSelector + ',' + contentSelector;
$(this).parent().children(selector).toggle();
return false;
});
});
}
| Compatibility with redmine 2.6+
Properly migrate from .live to .on as described on http://api.jquery.com/live/ instead of porting a deprecated function.
| assets/javascripts/redmine_cut_tag.js | Compatibility with redmine 2.6+ | <ide><path>ssets/javascripts/redmine_cut_tag.js
<ide> } else {
<ide> // using jquery
<ide>
<del> // compatibility code to use 'live' method on jquery 1.9 (redmine 2.5+)
<del> // borrowed from jQuery 1.8.3's source code
<del> jQuery.fn.extend({
<del> live: function( types, data, fn ) {
<del> jQuery( this.context ).on( types, this.selector, data, fn );
<del> return this;
<del> }
<del> });
<del>
<ide> $(document).ready(function() {
<ide>
<ide> var switchesSelector = '.cut_tag_show,.cut_tag_hide';
<ide> var contentSelector = '.cut_tag_content';
<ide>
<del> $(switchesSelector).live('click', function() {
<add> $(document).on('click', switchesSelector, function() {
<ide> var selector = switchesSelector + ',' + contentSelector;
<ide> $(this).parent().children(selector).toggle();
<ide> return false; |
|
Java | apache-2.0 | 445a12fbd808a5af95ec0aba31e31519839d1f29 | 0 | allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vfs.impl;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.util.text.StringUtilRt;
import com.intellij.openapi.vfs.*;
import com.intellij.openapi.vfs.newvfs.ArchiveFileSystem;
import com.intellij.openapi.vfs.newvfs.NewVirtualFileSystem;
import com.intellij.openapi.vfs.newvfs.impl.FileNameCache;
import com.intellij.openapi.vfs.newvfs.impl.VirtualFileSystemEntry;
import com.intellij.openapi.vfs.pointers.VirtualFilePointerListener;
import com.intellij.util.ArrayUtil;
import com.intellij.util.ObjectUtils;
import com.intellij.util.PathUtil;
import com.intellij.util.containers.MultiMap;
import com.intellij.util.io.URLUtil;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;
/**
* Trie data structure for succinct storage and fast retrieval of file pointers.
* File pointer "a/b/x.txt" is stored in the tree with nodes a->b->x.txt
*/
class FilePartNode {
private static final FilePartNode[] EMPTY_ARRAY = new FilePartNode[0];
static final int JAR_SEPARATOR_NAME_ID = -2;
private final int nameId; // name id of the VirtualFile corresponding to this node
FilePartNode @NotNull [] children = EMPTY_ARRAY; // sorted by this.getName(). elements never updated inplace
// file pointers for this exact path (i.e. concatenation of all getName() down from the root).
// Either VirtualFilePointerImpl or VirtualFilePointerImpl[] (when it so happened that several pointers merged into one node - e.g. after file rename onto existing pointer)
private Object leaves;
@NotNull
volatile Object myFileOrUrl;
final NewVirtualFileSystem myFS; // the file system of this particular component. E.g. for path "/x.jar!/foo.txt" the node "x.jar" fs is LocalFileSystem, the node "foo.txt" fs is JarFileSystem
FilePartNode(int nameId,
@NotNull Object fileOrUrl,
@NotNull NewVirtualFileSystem fs) {
myFS = fs;
assert nameId > 0 || nameId == JAR_SEPARATOR_NAME_ID : nameId + "; " + getClass();
this.nameId = nameId;
myFileOrUrl = fileOrUrl;
if (fileOrUrl instanceof VirtualFile) {
assert myFile().getFileSystem() == myFS : "myFs=" + myFS + "; myFile().getFileSystem()=" + myFile().getFileSystem() + "; " + fileOrUrl;
if (myFile().getParent() == null && fs instanceof ArchiveFileSystem) {
assert nameId == JAR_SEPARATOR_NAME_ID : nameId;
}
}
}
private VirtualFile myFile() {
return myFile(myFileOrUrl);
}
void addLeaf(@NotNull VirtualFilePointerImpl pointer) {
Object leaves = this.leaves;
Object newLeaves;
if (leaves == null) {
newLeaves = pointer;
}
else if (leaves instanceof VirtualFilePointerImpl) {
newLeaves = new VirtualFilePointerImpl[]{(VirtualFilePointerImpl)leaves, pointer};
}
else {
newLeaves = ArrayUtil.append((VirtualFilePointerImpl[])leaves, pointer);
}
associate(newLeaves);
}
// return remaining leaves number
int removeLeaf(@NotNull VirtualFilePointerImpl pointer) {
Object leaves = this.leaves;
if (leaves == null) {
return 0;
}
if (leaves instanceof VirtualFilePointerImpl) {
if (leaves == pointer) {
this.leaves = null;
return 0;
}
return 1;
}
VirtualFilePointerImpl[] newLeaves = ArrayUtil.remove((VirtualFilePointerImpl[])leaves, pointer);
if (newLeaves.length == 0) newLeaves = null;
this.leaves = newLeaves;
return newLeaves == null ? 0 : newLeaves.length;
}
static VirtualFile myFile(@NotNull Object fileOrUrl) {
return fileOrUrl instanceof VirtualFile ? (VirtualFile)fileOrUrl : null;
}
@NotNull
private String myUrl() {
return myUrl(myFileOrUrl);
}
@NotNull
static String myUrl(Object fileOrUrl) {
return fileOrUrl instanceof VirtualFile ? ((VirtualFile)fileOrUrl).getUrl() : (String)fileOrUrl;
}
// for creating fake root
FilePartNode(@NotNull NewVirtualFileSystem fs) {
nameId = -1;
myFileOrUrl = "";
myFS = fs;
}
@NotNull
static CharSequence fromNameId(int nameId) {
return nameId == JAR_SEPARATOR_NAME_ID ? JarFileSystem.JAR_SEPARATOR : FileNameCache.getVFileName(nameId);
}
@NotNull
CharSequence getName() {
return fromNameId(nameId);
}
@Override
public String toString() {
return getName() + (children.length == 0 ? "" : " -> "+children.length);
}
static int getNameId(@NotNull VirtualFile file) {
VirtualFileSystem fs = file.getFileSystem();
if (fs instanceof ArchiveFileSystem && file.getParent() == null) {
return JAR_SEPARATOR_NAME_ID;
}
return ((VirtualFileSystemEntry)file).getNameId();
}
@Contract("_, _, true, _ -> !null")
FilePartNode findChildByNameId(@Nullable VirtualFile file,
int nameId,
boolean createIfNotFound,
@NotNull NewVirtualFileSystem childFs) {
if (nameId <= 0 && nameId != JAR_SEPARATOR_NAME_ID) throw new IllegalArgumentException("invalid argument nameId: "+nameId);
for (FilePartNode child : children) {
if (child.nameEqualTo(nameId)) return child;
}
if (createIfNotFound) {
CharSequence name = fromNameId(nameId);
int index = children.length == 0 ? -1 : binarySearchChildByName(name);
FilePartNode child;
assert index < 0 : index + " : child= '" + (child = children[index]) + "'"
+ "; child.nameEqualTo(nameId)=" + child.nameEqualTo(nameId)
+ "; child.getClass()=" + child.getClass()
+ "; child.nameId=" + child.nameId
+ "; child.getName()='" + child.getName() + "'"
+ "; nameId=" + nameId
+ "; name='" + name + "'"
+ "; compare(child) = " + StringUtil.compare(child.getName(), name, !SystemInfo.isFileSystemCaseSensitive) + ";"
+ " UrlPart.nameEquals: " + FileUtil.PATH_CHAR_SEQUENCE_HASHING_STRATEGY.equals(child.getName(), fromNameId(nameId))
+ "; name.equals(child.getName())=" + child.getName().equals(name)
;
Object fileOrUrl = file;
if (fileOrUrl == null) {
fileOrUrl = this.nameId == -1 ? name.toString() : childUrl(myUrl(), name, childFs);
}
child = new FilePartNode(nameId, fileOrUrl, childFs);
children = ArrayUtil.insert(children, -index-1, child);
return child;
}
return null;
}
boolean nameEqualTo(int nameId) {
return this.nameId == nameId;
}
int binarySearchChildByName(@NotNull CharSequence name) {
return ObjectUtils.binarySearch(0, children.length, i -> {
FilePartNode child = children[i];
CharSequence childName = child.getName();
return StringUtil.compare(childName, name, !SystemInfo.isFileSystemCaseSensitive);
});
}
void addRecursiveDirectoryPtrTo(@NotNull MultiMap<? super VirtualFilePointerListener, ? super VirtualFilePointerImpl> toFirePointers) {
processPointers(pointer -> { if (pointer.isRecursive()) toFirePointers.putValue(pointer.myListener, pointer); });
}
void doCheckConsistency(@Nullable VirtualFile parent, @NotNull String pathFromRoot) {
String name = getName().toString();
VirtualFile myFile = myFile();
if (!(this instanceof FilePartNodeRoot)) {
if (myFile == null) {
String myUrl = myUrl();
String expectedUrl = VirtualFileManager.constructUrl(myFS.getProtocol(), pathFromRoot + (pathFromRoot.endsWith("/") ? "" : "/"));
String actualUrl = myUrl + (myUrl.endsWith("/") ? "" : "/");
assert FileUtil.PATH_HASHING_STRATEGY.equals(actualUrl, expectedUrl) : "Expected url: '" + expectedUrl + "' but got: '" + actualUrl + "'";
}
else {
assert Comparing.equal(getParentThroughJar(myFile, myFS), parent) : "parent: " + parent + "; myFile: " + myFile;
}
}
assert !"..".equals(name) && !".".equals(name) : "url must not contain '.' or '..' but got: " + this;
for (int i = 0; i < children.length; i++) {
FilePartNode child = children[i];
CharSequence childName = child.getName();
String childPathRoot = pathFromRoot +
(pathFromRoot.isEmpty() || pathFromRoot.endsWith("/") || childName.equals(JarFileSystem.JAR_SEPARATOR) ? "" : "/") +
childName;
child.doCheckConsistency(myFile, childPathRoot);
if (i != 0) {
assert !FileUtil.namesEqual(childName.toString(), children[i - 1].getName().toString()) : "child[" + i + "] = " + child + "; [-1] = " + children[i - 1];
}
}
int[] leafNumber = new int[1];
processPointers(p -> { assert p.myNode == this; leafNumber[0]++; });
int useCount = leafNumber[0];
assert (useCount == 0) == (leaves == null) : useCount + " - " + (leaves instanceof VirtualFilePointerImpl ? leaves : Arrays.toString((VirtualFilePointerImpl[])leaves));
if (myFileOrUrl instanceof String) {
String myPath = VfsUtilCore.urlToPath(myUrl());
String nameFromPath = nameId == JAR_SEPARATOR_NAME_ID || myPath.endsWith(JarFileSystem.JAR_SEPARATOR) ? JarFileSystem.JAR_SEPARATOR : PathUtil.getFileName(myPath);
if (!myPath.isEmpty() && nameFromPath.isEmpty()) {
nameFromPath = "/";
}
assert StringUtilRt.equal(nameFromPath, name, SystemInfo.isFileSystemCaseSensitive) : "fileAndUrl: " + myFileOrUrl + "; but this: " + this + "; nameFromPath: " + nameFromPath + "; name: " + name + "; myPath: " + myPath + "; url: " + myUrl() + ";";
if (myFile != null) {
String fileName = myFile.getParent() == null && myFile.getFileSystem() instanceof ArchiveFileSystem ? JarFileSystem.JAR_SEPARATOR : myFile.getName();
assert fileName.equals(name) : "fileAndUrl: " + myFileOrUrl + "; but this: " + this;
assert myFile.getFileSystem() == myFS;
}
}
}
// update myFileOrUrl to a VirtualFile and replace UrlPartNode with FilePartNode if the file exists, including all subnodes
void update(@NotNull FilePartNode parent, @NotNull FilePartNodeRoot root) {
Object fileOrUrl = myFileOrUrl;
VirtualFile file = myFile(fileOrUrl);
boolean changed = false;
boolean nameChanged = false;
boolean fileIsValid = false;
if (file != null) {
fileIsValid = file.isValid();
if (fileIsValid && file.getParent() == null && file.getFileSystem() instanceof ArchiveFileSystem) {
VirtualFile local = ((ArchiveFileSystem)file.getFileSystem()).getLocalByEntry(file);
fileIsValid = local != null;
}
if (!fileIsValid) {
file = null;
changed = true;
}
}
Object parentFileOrUrl;
parentFileOrUrl = parent.myFileOrUrl;
String myName = getName().toString();
String url = null;
String parentUrl = null;
VirtualFile parentFile = myFile(parentFileOrUrl);
if (file == null) {
file = parentFile == null || !parentFile.isValid() ? null : findChildThroughJar(parentFile, myName, myFS);
if (file == null) {
parentUrl = myUrl(parentFileOrUrl);
url = childUrl(parentUrl, myName, myFS);
changed |= nameChanged = !Comparing.strEqual(url, myUrl(fileOrUrl));
}
else {
changed = true;
}
fileIsValid = file != null && file.isValid();
}
if (parent.nameId != -1 && !(parentFileOrUrl instanceof VirtualFile) && file != null) {
// if parent file can't be found then the child is not valid too
file = null;
fileIsValid = false;
url = myUrl(fileOrUrl);
}
if (file != null) {
if (fileIsValid) {
changed |= nameChanged = !StringUtil.equals(file.getNameSequence(), myName);
}
else {
file = null; // can't find, try next time
changed = true;
url = myUrl(fileOrUrl);
}
}
Object result = file == null ? url : file;
changed |= !Objects.equals(fileOrUrl, result);
FilePartNode thisNode = this;
if (changed) {
myFileOrUrl = result;
if (file != null && (this instanceof UrlPartNode || nameChanged)) {
// replace with FPPN if the actual file's appeared on disk to save memory with nameIds
thisNode = replaceWithFPPN(file, parent);
}
}
if (file != null && !Objects.equals(getParentThroughJar(file, myFS), parentFile)) {
// this node file must be moved to the other dir. remove and re-insert from the root to the correct path, preserving all children
FilePartNode newNode = root.findOrCreateByFile(file).node;
processPointers(p-> newNode.addLeaf(p));
newNode.children = children;
children = EMPTY_ARRAY;
changed = true;
String myOldPath = VfsUtilCore.urlToPath(childUrl(parentUrl=myUrl(parentFileOrUrl), myName, myFS));
root.removeEmptyNodesByPath(FilePartNodeRoot.splitNames(myOldPath));
thisNode = newNode;
nameChanged = true;
}
if (nameChanged) {
String myOldPath = VfsUtilCore.urlToPath(childUrl(parentUrl == null ? myUrl(parentFileOrUrl) : parentUrl, myName, myFS));
String myNewPath = VfsUtilCore.urlToPath(myUrl(result));
// fix UrlPartNodes with (now) wrong url start
thisNode.fixUrlPartNodes(myOldPath, myNewPath);
}
if (changed) {
for (FilePartNode child : thisNode.children) {
child.update(thisNode, root);
}
}
}
private void fixUrlPartNodes(@NotNull String oldPath, @NotNull String newPath) {
if (this instanceof UrlPartNode) {
String protocol = myFS.getProtocol();
String myUrl = myUrl();
if (StringUtil.startsWith(myUrl, protocol.length()+URLUtil.SCHEME_SEPARATOR.length(), oldPath)) {
myFileOrUrl = protocol + URLUtil.SCHEME_SEPARATOR + newPath + myUrl.substring(protocol.length() + URLUtil.SCHEME_SEPARATOR.length()+oldPath.length());
}
}
for (FilePartNode child : children) {
child.fixUrlPartNodes(oldPath, newPath);
}
}
@NotNull
private FilePartNode replaceWithFPPN(@NotNull VirtualFile file, @NotNull FilePartNode parent) {
int nameId = getNameId(file);
parent.children = ArrayUtil.remove(parent.children, this);
FilePartNode newNode = parent.findChildByNameId(file, nameId, true, (NewVirtualFileSystem)file.getFileSystem());
newNode.children = children; // old children are destroyed when renamed onto their parent
processPointers(pointer-> newNode.addLeaf(pointer));
leaves = null;
return newNode;
}
@NotNull
static String childUrl(@NotNull String parentUrl, @NotNull CharSequence childName, @NotNull NewVirtualFileSystem fs) {
if (childName.equals(JarFileSystem.JAR_SEPARATOR) && fs instanceof ArchiveFileSystem) {
return VirtualFileManager.constructUrl(fs.getProtocol(), StringUtil.trimEnd(VfsUtilCore.urlToPath(parentUrl), '/')) + childName;
}
return parentUrl.isEmpty() ? VirtualFileManager.constructUrl(fs.getProtocol(), childName.toString()) :
VirtualFileManager.constructUrl(fs.getProtocol(), StringUtil.trimEnd(VfsUtilCore.urlToPath(parentUrl), '/')) + '/' + childName;
}
private void associate(@Nullable Object leaves) {
this.leaves = leaves;
if (leaves != null) {
if (leaves instanceof VirtualFilePointerImpl) {
((VirtualFilePointerImpl)leaves).myNode = this;
}
else {
for (VirtualFilePointerImpl pointer : (VirtualFilePointerImpl[])leaves) {
pointer.myNode = this;
}
}
}
}
VirtualFilePointerImpl getPointer(VirtualFilePointerListener listener) {
Object leaves = this.leaves;
if (leaves == null) {
return null;
}
if (leaves instanceof VirtualFilePointerImpl) {
VirtualFilePointerImpl leaf = (VirtualFilePointerImpl)leaves;
return leaf.myListener == listener ? leaf : null;
}
VirtualFilePointerImpl[] array = (VirtualFilePointerImpl[])leaves;
for (VirtualFilePointerImpl pointer : array) {
if (pointer.myListener == listener) return pointer;
}
return null;
}
void addAllPointersTo(@NotNull Collection<? super VirtualFilePointerImpl> outList) {
processPointers(p->{ if (p.myNode != null) outList.add(p); });
}
void processPointers(@NotNull Consumer<? super VirtualFilePointerImpl> processor) {
Object leaves = this.leaves;
if (leaves == null) {
return;
}
if (leaves instanceof VirtualFilePointerImpl) {
processor.accept((VirtualFilePointerImpl)leaves);
return;
}
VirtualFilePointerImpl[] pointers = (VirtualFilePointerImpl[])leaves;
for (VirtualFilePointerImpl pointer : pointers) {
processor.accept(pointer);
}
}
// for "file://a/b/c.txt" return "a/b", for "jar://a/b/j.jar!" return "file://a/b/j.jar"
static VirtualFile getParentThroughJar(@NotNull VirtualFile file, @NotNull NewVirtualFileSystem fs) {
VirtualFile parent = file.getParent();
if (parent == null && fs instanceof ArchiveFileSystem) {
parent = ((ArchiveFileSystem)fs).getLocalByEntry(file);
}
return parent;
}
static VirtualFile findChildThroughJar(@NotNull VirtualFile file, @NotNull String name, @NotNull NewVirtualFileSystem childFs) {
VirtualFile child;
if (name.equals(JarFileSystem.JAR_SEPARATOR) && childFs instanceof ArchiveFileSystem) {
child = ((ArchiveFileSystem)childFs).getRootByLocal(file);
}
else {
child = file.findChild(name);
}
return child;
}
boolean removeEmptyNodesByFile(@NotNull List<VirtualFile> parts) {
if (parts.isEmpty()) {
return children.length == 0;
}
VirtualFile file = parts.remove(parts.size()-1);
FilePartNode child = findChildByNameId(null, getNameId(file), false, (NewVirtualFileSystem)file.getFileSystem());
if (child == null) {
return false;
}
boolean toRemove = child.removeEmptyNodesByFile(parts);
if (toRemove) {
children = children.length == 1 ? EMPTY_ARRAY : ArrayUtil.remove(children, child);
return children.length == 0 && leaves == null;
}
return false;
}
boolean removeEmptyNodesByPath(@NotNull List<String> parts) {
if (parts.isEmpty()) {
return children.length == 0;
}
String name = parts.remove(parts.size()-1);
int index = binarySearchChildByName(name);
if (index < 0) {
return false;
}
FilePartNode child = children[index];
boolean toRemove = child.removeEmptyNodesByPath(parts);
if (toRemove) {
children = children.length == 1 ? EMPTY_ARRAY : ArrayUtil.remove(children, child);
return children.length == 0 && leaves == null;
}
return false;
}
}
| platform/platform-impl/src/com/intellij/openapi/vfs/impl/FilePartNode.java | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vfs.impl;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.util.text.StringUtilRt;
import com.intellij.openapi.vfs.*;
import com.intellij.openapi.vfs.newvfs.ArchiveFileSystem;
import com.intellij.openapi.vfs.newvfs.NewVirtualFileSystem;
import com.intellij.openapi.vfs.newvfs.impl.FileNameCache;
import com.intellij.openapi.vfs.newvfs.impl.VirtualFileSystemEntry;
import com.intellij.openapi.vfs.pointers.VirtualFilePointerListener;
import com.intellij.util.ArrayUtil;
import com.intellij.util.ObjectUtils;
import com.intellij.util.PathUtil;
import com.intellij.util.containers.MultiMap;
import com.intellij.util.io.URLUtil;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;
/**
* Trie data structure for succinct storage and fast retrieval of file pointers.
* File pointer "a/b/x.txt" is stored in the tree with nodes a->b->x.txt
*/
class FilePartNode {
private static final FilePartNode[] EMPTY_ARRAY = new FilePartNode[0];
static final int JAR_SEPARATOR_NAME_ID = -2;
private final int nameId; // name id of the VirtualFile corresponding to this node
FilePartNode @NotNull [] children = EMPTY_ARRAY; // sorted by this.getName(). elements never updated inplace
// file pointers for this exact path (i.e. concatenation of all getName() down from the root).
// Either VirtualFilePointerImpl or VirtualFilePointerImpl[] (when it so happened that several pointers merged into one node - e.g. after file rename onto existing pointer)
private Object leaves;
@NotNull
volatile Object myFileOrUrl;
final NewVirtualFileSystem myFS; // the file system of this particular component. E.g. for path "/x.jar!/foo.txt" the node "x.jar" fs is LocalFileSystem, the node "foo.txt" fs is JarFileSystem
FilePartNode(int nameId,
@NotNull Object fileOrUrl,
@NotNull NewVirtualFileSystem fs) {
myFS = fs;
assert nameId > 0 || nameId == JAR_SEPARATOR_NAME_ID : nameId + "; " + getClass();
this.nameId = nameId;
myFileOrUrl = fileOrUrl;
if (fileOrUrl instanceof VirtualFile) {
assert myFile().getFileSystem() == myFS : "myFs=" + myFS + "; myFile().getFileSystem()=" + myFile().getFileSystem() + "; " + fileOrUrl;
if (myFile().getParent() == null && fs instanceof ArchiveFileSystem) {
assert nameId == JAR_SEPARATOR_NAME_ID : nameId;
}
}
}
private VirtualFile myFile() {
return myFile(myFileOrUrl);
}
void addLeaf(@NotNull VirtualFilePointerImpl pointer) {
Object leaves = this.leaves;
Object newLeaves;
if (leaves == null) {
newLeaves = pointer;
}
else if (leaves instanceof VirtualFilePointerImpl) {
newLeaves = new VirtualFilePointerImpl[]{(VirtualFilePointerImpl)leaves, pointer};
}
else {
newLeaves = ArrayUtil.append((VirtualFilePointerImpl[])leaves, pointer);
}
associate(newLeaves);
}
// return remaining leaves number
int removeLeaf(@NotNull VirtualFilePointerImpl pointer) {
Object leaves = this.leaves;
if (leaves == null) {
return 0;
}
if (leaves instanceof VirtualFilePointerImpl) {
if (leaves == pointer) {
this.leaves = null;
return 0;
}
return 1;
}
VirtualFilePointerImpl[] newLeaves = ArrayUtil.remove((VirtualFilePointerImpl[])leaves, pointer);
if (newLeaves.length == 0) newLeaves = null;
this.leaves = newLeaves;
return newLeaves == null ? 0 : newLeaves.length;
}
static VirtualFile myFile(@NotNull Object fileOrUrl) {
return fileOrUrl instanceof VirtualFile ? (VirtualFile)fileOrUrl : null;
}
@NotNull
private String myUrl() {
return myUrl(myFileOrUrl);
}
@NotNull
static String myUrl(Object fileOrUrl) {
return fileOrUrl instanceof VirtualFile ? ((VirtualFile)fileOrUrl).getUrl() : (String)fileOrUrl;
}
// for creating fake root
FilePartNode(@NotNull NewVirtualFileSystem fs) {
nameId = -1;
myFileOrUrl = "";
myFS = fs;
}
@NotNull
static CharSequence fromNameId(int nameId) {
return nameId == JAR_SEPARATOR_NAME_ID ? JarFileSystem.JAR_SEPARATOR : FileNameCache.getVFileName(nameId);
}
@NotNull
CharSequence getName() {
return fromNameId(nameId);
}
@Override
public String toString() {
return getName() + (children.length == 0 ? "" : " -> "+children.length);
}
static int getNameId(@NotNull VirtualFile file) {
VirtualFileSystem fs = file.getFileSystem();
if (fs instanceof ArchiveFileSystem && file.getParent() == null) {
return JAR_SEPARATOR_NAME_ID;
}
return ((VirtualFileSystemEntry)file).getNameId();
}
@Contract("_, _, true, _ -> !null")
FilePartNode findChildByNameId(@Nullable VirtualFile file,
int nameId,
boolean createIfNotFound,
@NotNull NewVirtualFileSystem childFs) {
if (nameId <= 0 && nameId != JAR_SEPARATOR_NAME_ID) throw new IllegalArgumentException("invalid argument nameId: "+nameId);
for (FilePartNode child : children) {
if (child.nameEqualTo(nameId)) return child;
}
if (createIfNotFound) {
CharSequence name = fromNameId(nameId);
int index = children.length == 0 ? -1 : binarySearchChildByName(name);
FilePartNode child;
assert index < 0 : index + " : child= '" + (child = children[index]) + "'"
+ "; child.nameEqualTo(nameId)=" + child.nameEqualTo(nameId)
+ "; child.getClass()=" + child.getClass()
+ "; child.nameId=" + child.nameId
+ "; child.getName()='" + child.getName() + "'"
+ "; nameId=" + nameId
+ "; name='" + name + "'"
+ "; compare(child) = " + StringUtil.compare(child.getName(), name, !SystemInfo.isFileSystemCaseSensitive) + ";"
+ " UrlPart.nameEquals: " + FileUtil.PATH_CHAR_SEQUENCE_HASHING_STRATEGY.equals(child.getName(), fromNameId(nameId))
+ "; name.equals(child.getName())=" + child.getName().equals(name)
;
Object fileOrUrl = file;
if (fileOrUrl == null) {
fileOrUrl = this.nameId == -1 ? name.toString() : childUrl(myUrl(), name, childFs);
}
child = new FilePartNode(nameId, fileOrUrl, childFs);
children = ArrayUtil.insert(children, -index-1, child);
return child;
}
return null;
}
boolean nameEqualTo(int nameId) {
return this.nameId == nameId;
}
int binarySearchChildByName(@NotNull CharSequence name) {
return ObjectUtils.binarySearch(0, children.length, i -> {
FilePartNode child = children[i];
CharSequence childName = child.getName();
return StringUtil.compare(childName, name, !SystemInfo.isFileSystemCaseSensitive);
});
}
void addRecursiveDirectoryPtrTo(@NotNull MultiMap<? super VirtualFilePointerListener, ? super VirtualFilePointerImpl> toFirePointers) {
processPointers(pointer -> { if (pointer.isRecursive()) toFirePointers.putValue(pointer.myListener, pointer); });
}
void doCheckConsistency(@Nullable VirtualFile parent, @NotNull String pathFromRoot) {
String name = getName().toString();
VirtualFile myFile = myFile();
if (!(this instanceof FilePartNodeRoot)) {
if (myFile == null) {
String myUrl = myUrl();
String expectedUrl = VirtualFileManager.constructUrl(myFS.getProtocol(), pathFromRoot + (pathFromRoot.endsWith("/") ? "" : "/"));
String actualUrl = myUrl + (myUrl.endsWith("/") ? "" : "/");
assert actualUrl.equals(expectedUrl) : "Expected url: '" + expectedUrl + "' but got: '" + actualUrl + "'";
}
else {
assert Comparing.equal(getParentThroughJar(myFile, myFS), parent) : "parent: " + parent + "; myFile: " + myFile;
}
}
assert !"..".equals(name) && !".".equals(name) : "url must not contain '.' or '..' but got: " + this;
for (int i = 0; i < children.length; i++) {
FilePartNode child = children[i];
CharSequence childName = child.getName();
String childPathRoot = pathFromRoot +
(pathFromRoot.isEmpty() || pathFromRoot.endsWith("/") || childName.equals(JarFileSystem.JAR_SEPARATOR) ? "" : "/") +
childName;
child.doCheckConsistency(myFile, childPathRoot);
if (i != 0) {
assert !FileUtil.namesEqual(childName.toString(), children[i - 1].getName().toString()) : "child[" + i + "] = " + child + "; [-1] = " + children[i - 1];
}
}
int[] leafNumber = new int[1];
processPointers(p -> { assert p.myNode == this; leafNumber[0]++; });
int useCount = leafNumber[0];
assert (useCount == 0) == (leaves == null) : useCount + " - " + (leaves instanceof VirtualFilePointerImpl ? leaves : Arrays.toString((VirtualFilePointerImpl[])leaves));
if (myFileOrUrl instanceof String) {
String myPath = VfsUtilCore.urlToPath(myUrl());
String nameFromPath = nameId == JAR_SEPARATOR_NAME_ID || myPath.endsWith(JarFileSystem.JAR_SEPARATOR) ? JarFileSystem.JAR_SEPARATOR : PathUtil.getFileName(myPath);
if (!myPath.isEmpty() && nameFromPath.isEmpty()) {
nameFromPath = "/";
}
assert StringUtilRt.equal(nameFromPath, name, SystemInfo.isFileSystemCaseSensitive) : "fileAndUrl: " + myFileOrUrl + "; but this: " + this + "; nameFromPath: " + nameFromPath + "; name: " + name + "; myPath: " + myPath + "; url: " + myUrl() + ";";
if (myFile != null) {
String fileName = myFile.getParent() == null && myFile.getFileSystem() instanceof ArchiveFileSystem ? JarFileSystem.JAR_SEPARATOR : myFile.getName();
assert fileName.equals(name) : "fileAndUrl: " + myFileOrUrl + "; but this: " + this;
assert myFile.getFileSystem() == myFS;
}
}
}
// update myFileOrUrl to a VirtualFile and replace UrlPartNode with FilePartNode if the file exists, including all subnodes
void update(@NotNull FilePartNode parent, @NotNull FilePartNodeRoot root) {
Object fileOrUrl = myFileOrUrl;
VirtualFile file = myFile(fileOrUrl);
boolean changed = false;
boolean nameChanged = false;
boolean fileIsValid = false;
if (file != null) {
fileIsValid = file.isValid();
if (fileIsValid && file.getParent() == null && file.getFileSystem() instanceof ArchiveFileSystem) {
VirtualFile local = ((ArchiveFileSystem)file.getFileSystem()).getLocalByEntry(file);
fileIsValid = local != null;
}
if (!fileIsValid) {
file = null;
changed = true;
}
}
Object parentFileOrUrl;
parentFileOrUrl = parent.myFileOrUrl;
String myName = getName().toString();
String url = null;
String parentUrl = null;
VirtualFile parentFile = myFile(parentFileOrUrl);
if (file == null) {
file = parentFile == null || !parentFile.isValid() ? null : findChildThroughJar(parentFile, myName, myFS);
if (file == null) {
parentUrl = myUrl(parentFileOrUrl);
url = childUrl(parentUrl, myName, myFS);
changed |= nameChanged = !Comparing.strEqual(url, myUrl(fileOrUrl));
}
else {
changed = true;
}
fileIsValid = file != null && file.isValid();
}
if (parent.nameId != -1 && !(parentFileOrUrl instanceof VirtualFile) && file != null) {
// if parent file can't be found then the child is not valid too
file = null;
fileIsValid = false;
url = myUrl(fileOrUrl);
}
if (file != null) {
if (fileIsValid) {
changed |= nameChanged = !StringUtil.equals(file.getNameSequence(), myName);
}
else {
file = null; // can't find, try next time
changed = true;
url = myUrl(fileOrUrl);
}
}
Object result = file == null ? url : file;
changed |= !Objects.equals(fileOrUrl, result);
FilePartNode thisNode = this;
if (changed) {
myFileOrUrl = result;
if (file != null && (this instanceof UrlPartNode || nameChanged)) {
// replace with FPPN if the actual file's appeared on disk to save memory with nameIds
thisNode = replaceWithFPPN(file, parent);
}
}
if (file != null && !Objects.equals(getParentThroughJar(file, myFS), parentFile)) {
// this node file must be moved to the other dir. remove and re-insert from the root to the correct path, preserving all children
FilePartNode newNode = root.findOrCreateByFile(file).node;
processPointers(p-> newNode.addLeaf(p));
newNode.children = children;
children = EMPTY_ARRAY;
changed = true;
String myOldPath = VfsUtilCore.urlToPath(childUrl(parentUrl=myUrl(parentFileOrUrl), myName, myFS));
root.removeEmptyNodesByPath(FilePartNodeRoot.splitNames(myOldPath));
thisNode = newNode;
nameChanged = true;
}
if (nameChanged) {
String myOldPath = VfsUtilCore.urlToPath(childUrl(parentUrl == null ? myUrl(parentFileOrUrl) : parentUrl, myName, myFS));
String myNewPath = VfsUtilCore.urlToPath(myUrl(result));
// fix UrlPartNodes with (now) wrong url start
thisNode.fixUrlPartNodes(myOldPath, myNewPath);
}
if (changed) {
for (FilePartNode child : thisNode.children) {
child.update(thisNode, root);
}
}
}
private void fixUrlPartNodes(@NotNull String oldPath, @NotNull String newPath) {
if (this instanceof UrlPartNode) {
String protocol = myFS.getProtocol();
String myUrl = myUrl();
if (StringUtil.startsWith(myUrl, protocol.length()+URLUtil.SCHEME_SEPARATOR.length(), oldPath)) {
myFileOrUrl = protocol + URLUtil.SCHEME_SEPARATOR + newPath + myUrl.substring(protocol.length() + URLUtil.SCHEME_SEPARATOR.length()+oldPath.length());
}
}
for (FilePartNode child : children) {
child.fixUrlPartNodes(oldPath, newPath);
}
}
@NotNull
private FilePartNode replaceWithFPPN(@NotNull VirtualFile file, @NotNull FilePartNode parent) {
int nameId = getNameId(file);
parent.children = ArrayUtil.remove(parent.children, this);
FilePartNode newNode = parent.findChildByNameId(file, nameId, true, (NewVirtualFileSystem)file.getFileSystem());
newNode.children = children; // old children are destroyed when renamed onto their parent
processPointers(pointer-> newNode.addLeaf(pointer));
leaves = null;
return newNode;
}
@NotNull
static String childUrl(@NotNull String parentUrl, @NotNull CharSequence childName, @NotNull NewVirtualFileSystem fs) {
if (childName.equals(JarFileSystem.JAR_SEPARATOR) && fs instanceof ArchiveFileSystem) {
return VirtualFileManager.constructUrl(fs.getProtocol(), StringUtil.trimEnd(VfsUtilCore.urlToPath(parentUrl), '/')) + childName;
}
return parentUrl.isEmpty() ? VirtualFileManager.constructUrl(fs.getProtocol(), childName.toString()) :
VirtualFileManager.constructUrl(fs.getProtocol(), StringUtil.trimEnd(VfsUtilCore.urlToPath(parentUrl), '/')) + '/' + childName;
}
private void associate(@Nullable Object leaves) {
this.leaves = leaves;
if (leaves != null) {
if (leaves instanceof VirtualFilePointerImpl) {
((VirtualFilePointerImpl)leaves).myNode = this;
}
else {
for (VirtualFilePointerImpl pointer : (VirtualFilePointerImpl[])leaves) {
pointer.myNode = this;
}
}
}
}
VirtualFilePointerImpl getPointer(VirtualFilePointerListener listener) {
Object leaves = this.leaves;
if (leaves == null) {
return null;
}
if (leaves instanceof VirtualFilePointerImpl) {
VirtualFilePointerImpl leaf = (VirtualFilePointerImpl)leaves;
return leaf.myListener == listener ? leaf : null;
}
VirtualFilePointerImpl[] array = (VirtualFilePointerImpl[])leaves;
for (VirtualFilePointerImpl pointer : array) {
if (pointer.myListener == listener) return pointer;
}
return null;
}
void addAllPointersTo(@NotNull Collection<? super VirtualFilePointerImpl> outList) {
processPointers(p->{ if (p.myNode != null) outList.add(p); });
}
void processPointers(@NotNull Consumer<? super VirtualFilePointerImpl> processor) {
Object leaves = this.leaves;
if (leaves == null) {
return;
}
if (leaves instanceof VirtualFilePointerImpl) {
processor.accept((VirtualFilePointerImpl)leaves);
return;
}
VirtualFilePointerImpl[] pointers = (VirtualFilePointerImpl[])leaves;
for (VirtualFilePointerImpl pointer : pointers) {
processor.accept(pointer);
}
}
// for "file://a/b/c.txt" return "a/b", for "jar://a/b/j.jar!" return "file://a/b/j.jar"
static VirtualFile getParentThroughJar(@NotNull VirtualFile file, @NotNull NewVirtualFileSystem fs) {
VirtualFile parent = file.getParent();
if (parent == null && fs instanceof ArchiveFileSystem) {
parent = ((ArchiveFileSystem)fs).getLocalByEntry(file);
}
return parent;
}
static VirtualFile findChildThroughJar(@NotNull VirtualFile file, @NotNull String name, @NotNull NewVirtualFileSystem childFs) {
VirtualFile child;
if (name.equals(JarFileSystem.JAR_SEPARATOR) && childFs instanceof ArchiveFileSystem) {
child = ((ArchiveFileSystem)childFs).getRootByLocal(file);
}
else {
child = file.findChild(name);
}
return child;
}
boolean removeEmptyNodesByFile(@NotNull List<VirtualFile> parts) {
if (parts.isEmpty()) {
return children.length == 0;
}
VirtualFile file = parts.remove(parts.size()-1);
FilePartNode child = findChildByNameId(null, getNameId(file), false, (NewVirtualFileSystem)file.getFileSystem());
if (child == null) {
return false;
}
boolean toRemove = child.removeEmptyNodesByFile(parts);
if (toRemove) {
children = children.length == 1 ? EMPTY_ARRAY : ArrayUtil.remove(children, child);
return children.length == 0 && leaves == null;
}
return false;
}
boolean removeEmptyNodesByPath(@NotNull List<String> parts) {
if (parts.isEmpty()) {
return children.length == 0;
}
String name = parts.remove(parts.size()-1);
int index = binarySearchChildByName(name);
if (index < 0) {
return false;
}
FilePartNode child = children[index];
boolean toRemove = child.removeEmptyNodesByPath(parts);
if (toRemove) {
children = children.length == 1 ? EMPTY_ARRAY : ArrayUtil.remove(children, child);
return children.length == 0 && leaves == null;
}
return false;
}
}
| fix CMake tests
GitOrigin-RevId: d910b0321e0703cc2c0330d2d811043f01489131 | platform/platform-impl/src/com/intellij/openapi/vfs/impl/FilePartNode.java | fix CMake tests | <ide><path>latform/platform-impl/src/com/intellij/openapi/vfs/impl/FilePartNode.java
<ide> String myUrl = myUrl();
<ide> String expectedUrl = VirtualFileManager.constructUrl(myFS.getProtocol(), pathFromRoot + (pathFromRoot.endsWith("/") ? "" : "/"));
<ide> String actualUrl = myUrl + (myUrl.endsWith("/") ? "" : "/");
<del> assert actualUrl.equals(expectedUrl) : "Expected url: '" + expectedUrl + "' but got: '" + actualUrl + "'";
<add> assert FileUtil.PATH_HASHING_STRATEGY.equals(actualUrl, expectedUrl) : "Expected url: '" + expectedUrl + "' but got: '" + actualUrl + "'";
<ide> }
<ide> else {
<ide> assert Comparing.equal(getParentThroughJar(myFile, myFS), parent) : "parent: " + parent + "; myFile: " + myFile; |
|
Java | apache-2.0 | 685a2435fa898d6e7e5e96ea222022afc0494577 | 0 | ibinti/intellij-community,akosyakov/intellij-community,idea4bsd/idea4bsd,diorcety/intellij-community,hurricup/intellij-community,ahb0327/intellij-community,suncycheng/intellij-community,slisson/intellij-community,orekyuu/intellij-community,joewalnes/idea-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,retomerz/intellij-community,amith01994/intellij-community,signed/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,dslomov/intellij-community,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,amith01994/intellij-community,semonte/intellij-community,Lekanich/intellij-community,petteyg/intellij-community,gnuhub/intellij-community,nicolargo/intellij-community,semonte/intellij-community,TangHao1987/intellij-community,ibinti/intellij-community,Distrotech/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,kool79/intellij-community,holmes/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,xfournet/intellij-community,semonte/intellij-community,signed/intellij-community,clumsy/intellij-community,fitermay/intellij-community,xfournet/intellij-community,petteyg/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,diorcety/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,ernestp/consulo,jexp/idea2,consulo/consulo,xfournet/intellij-community,Distrotech/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,da1z/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,caot/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,caot/intellij-community,amith01994/intellij-community,fnouama/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,dslomov/intellij-community,MER-GROUP/intellij-community,supersven/intellij-community,diorcety/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,adedayo/intellij-community,consulo/consulo,ol-loginov/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,MichaelNedzelsky/intellij-community,blademainer/intellij-community,xfournet/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,blademainer/intellij-community,supersven/intellij-community,retomerz/intellij-community,ryano144/intellij-community,ol-loginov/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,apixandru/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,fnouama/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,ernestp/consulo,wreckJ/intellij-community,robovm/robovm-studio,robovm/robovm-studio,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,tmpgit/intellij-community,petteyg/intellij-community,jagguli/intellij-community,adedayo/intellij-community,suncycheng/intellij-community,SerCeMan/intellij-community,holmes/intellij-community,supersven/intellij-community,holmes/intellij-community,TangHao1987/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,SerCeMan/intellij-community,ibinti/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,samthor/intellij-community,clumsy/intellij-community,fitermay/intellij-community,Distrotech/intellij-community,diorcety/intellij-community,adedayo/intellij-community,vvv1559/intellij-community,petteyg/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,fengbaicanhe/intellij-community,orekyuu/intellij-community,signed/intellij-community,TangHao1987/intellij-community,ol-loginov/intellij-community,allotria/intellij-community,izonder/intellij-community,allotria/intellij-community,supersven/intellij-community,vladmm/intellij-community,samthor/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,diorcety/intellij-community,jagguli/intellij-community,signed/intellij-community,amith01994/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,caot/intellij-community,Distrotech/intellij-community,amith01994/intellij-community,ahb0327/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,amith01994/intellij-community,ol-loginov/intellij-community,muntasirsyed/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,orekyuu/intellij-community,jagguli/intellij-community,akosyakov/intellij-community,ftomassetti/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,vladmm/intellij-community,kool79/intellij-community,kdwink/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,ol-loginov/intellij-community,clumsy/intellij-community,FHannes/intellij-community,ibinti/intellij-community,ftomassetti/intellij-community,consulo/consulo,salguarnieri/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,orekyuu/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,akosyakov/intellij-community,robovm/robovm-studio,joewalnes/idea-community,Lekanich/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,adedayo/intellij-community,ol-loginov/intellij-community,amith01994/intellij-community,jexp/idea2,wreckJ/intellij-community,suncycheng/intellij-community,izonder/intellij-community,tmpgit/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,ivan-fedorov/intellij-community,semonte/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,hurricup/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,robovm/robovm-studio,jexp/idea2,slisson/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,petteyg/intellij-community,amith01994/intellij-community,FHannes/intellij-community,slisson/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,alphafoobar/intellij-community,suncycheng/intellij-community,izonder/intellij-community,semonte/intellij-community,FHannes/intellij-community,ibinti/intellij-community,clumsy/intellij-community,tmpgit/intellij-community,muntasirsyed/intellij-community,wreckJ/intellij-community,amith01994/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,ryano144/intellij-community,petteyg/intellij-community,ibinti/intellij-community,kool79/intellij-community,ftomassetti/intellij-community,ahb0327/intellij-community,salguarnieri/intellij-community,orekyuu/intellij-community,Distrotech/intellij-community,ernestp/consulo,akosyakov/intellij-community,robovm/robovm-studio,gnuhub/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,allotria/intellij-community,clumsy/intellij-community,kdwink/intellij-community,gnuhub/intellij-community,supersven/intellij-community,robovm/robovm-studio,SerCeMan/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,izonder/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,izonder/intellij-community,wreckJ/intellij-community,pwoodworth/intellij-community,ftomassetti/intellij-community,akosyakov/intellij-community,allotria/intellij-community,asedunov/intellij-community,SerCeMan/intellij-community,SerCeMan/intellij-community,ernestp/consulo,adedayo/intellij-community,Lekanich/intellij-community,allotria/intellij-community,ahb0327/intellij-community,tmpgit/intellij-community,joewalnes/idea-community,asedunov/intellij-community,holmes/intellij-community,ryano144/intellij-community,blademainer/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,tmpgit/intellij-community,dslomov/intellij-community,da1z/intellij-community,hurricup/intellij-community,tmpgit/intellij-community,xfournet/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,joewalnes/idea-community,salguarnieri/intellij-community,supersven/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,fitermay/intellij-community,adedayo/intellij-community,apixandru/intellij-community,kdwink/intellij-community,supersven/intellij-community,wreckJ/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,blademainer/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,vladmm/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,wreckJ/intellij-community,asedunov/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,nicolargo/intellij-community,orekyuu/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,samthor/intellij-community,clumsy/intellij-community,retomerz/intellij-community,adedayo/intellij-community,fnouama/intellij-community,supersven/intellij-community,wreckJ/intellij-community,tmpgit/intellij-community,kool79/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,ivan-fedorov/intellij-community,ryano144/intellij-community,youdonghai/intellij-community,diorcety/intellij-community,TangHao1987/intellij-community,jexp/idea2,mglukhikh/intellij-community,kool79/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,caot/intellij-community,samthor/intellij-community,youdonghai/intellij-community,gnuhub/intellij-community,samthor/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,TangHao1987/intellij-community,dslomov/intellij-community,asedunov/intellij-community,signed/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,consulo/consulo,ol-loginov/intellij-community,supersven/intellij-community,slisson/intellij-community,vladmm/intellij-community,signed/intellij-community,apixandru/intellij-community,fengbaicanhe/intellij-community,petteyg/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,joewalnes/idea-community,ahb0327/intellij-community,caot/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,pwoodworth/intellij-community,caot/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,TangHao1987/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,pwoodworth/intellij-community,fengbaicanhe/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,pwoodworth/intellij-community,joewalnes/idea-community,da1z/intellij-community,pwoodworth/intellij-community,MER-GROUP/intellij-community,MER-GROUP/intellij-community,robovm/robovm-studio,xfournet/intellij-community,ernestp/consulo,suncycheng/intellij-community,tmpgit/intellij-community,asedunov/intellij-community,fitermay/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,holmes/intellij-community,dslomov/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,izonder/intellij-community,MER-GROUP/intellij-community,semonte/intellij-community,da1z/intellij-community,suncycheng/intellij-community,alphafoobar/intellij-community,supersven/intellij-community,jexp/idea2,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,fengbaicanhe/intellij-community,lucafavatella/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,vladmm/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,jagguli/intellij-community,izonder/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,blademainer/intellij-community,pwoodworth/intellij-community,da1z/intellij-community,nicolargo/intellij-community,dslomov/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,SerCeMan/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,slisson/intellij-community,tmpgit/intellij-community,jexp/idea2,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,signed/intellij-community,adedayo/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,fnouama/intellij-community,fnouama/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,signed/intellij-community,caot/intellij-community,da1z/intellij-community,fitermay/intellij-community,slisson/intellij-community,caot/intellij-community,salguarnieri/intellij-community,jexp/idea2,ftomassetti/intellij-community,retomerz/intellij-community,kdwink/intellij-community,nicolargo/intellij-community,jexp/idea2,kool79/intellij-community,apixandru/intellij-community,caot/intellij-community,dslomov/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,tmpgit/intellij-community,SerCeMan/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,allotria/intellij-community,pwoodworth/intellij-community,joewalnes/idea-community,petteyg/intellij-community,Distrotech/intellij-community,ernestp/consulo,izonder/intellij-community,samthor/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,vladmm/intellij-community,FHannes/intellij-community,blademainer/intellij-community,ivan-fedorov/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,ftomassetti/intellij-community,orekyuu/intellij-community,fnouama/intellij-community,asedunov/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,jagguli/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,youdonghai/intellij-community,Lekanich/intellij-community,holmes/intellij-community,da1z/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,petteyg/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,TangHao1987/intellij-community,hurricup/intellij-community,diorcety/intellij-community,fnouama/intellij-community,kool79/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,amith01994/intellij-community,MER-GROUP/intellij-community,idea4bsd/idea4bsd,fnouama/intellij-community,blademainer/intellij-community,allotria/intellij-community,kool79/intellij-community,kdwink/intellij-community,holmes/intellij-community,jagguli/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,joewalnes/idea-community,youdonghai/intellij-community,jagguli/intellij-community,MichaelNedzelsky/intellij-community,diorcety/intellij-community,nicolargo/intellij-community,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,semonte/intellij-community,clumsy/intellij-community,asedunov/intellij-community,retomerz/intellij-community,kdwink/intellij-community,jagguli/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,ol-loginov/intellij-community,supersven/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,ol-loginov/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,gnuhub/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,Lekanich/intellij-community,diorcety/intellij-community,nicolargo/intellij-community,izonder/intellij-community,caot/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,ahb0327/intellij-community,alphafoobar/intellij-community,Lekanich/intellij-community,ahb0327/intellij-community,da1z/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,alphafoobar/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,gnuhub/intellij-community,blademainer/intellij-community,fnouama/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,ryano144/intellij-community,kool79/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,fnouama/intellij-community,vladmm/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,tmpgit/intellij-community,ivan-fedorov/intellij-community,jagguli/intellij-community,diorcety/intellij-community,wreckJ/intellij-community,gnuhub/intellij-community,FHannes/intellij-community,signed/intellij-community,apixandru/intellij-community,semonte/intellij-community,Lekanich/intellij-community,kdwink/intellij-community,izonder/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,petteyg/intellij-community,clumsy/intellij-community,retomerz/intellij-community,holmes/intellij-community,FHannes/intellij-community,fengbaicanhe/intellij-community,pwoodworth/intellij-community,robovm/robovm-studio,kdwink/intellij-community,MichaelNedzelsky/intellij-community,vladmm/intellij-community,akosyakov/intellij-community,dslomov/intellij-community,da1z/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,slisson/intellij-community,SerCeMan/intellij-community,robovm/robovm-studio,ryano144/intellij-community,asedunov/intellij-community,MichaelNedzelsky/intellij-community,blademainer/intellij-community,holmes/intellij-community,ryano144/intellij-community,robovm/robovm-studio,supersven/intellij-community,MER-GROUP/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,ahb0327/intellij-community,caot/intellij-community,ryano144/intellij-community,da1z/intellij-community,allotria/intellij-community,robovm/robovm-studio,pwoodworth/intellij-community,ryano144/intellij-community,adedayo/intellij-community,Lekanich/intellij-community,Lekanich/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,joewalnes/idea-community,alphafoobar/intellij-community,petteyg/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,ryano144/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,dslomov/intellij-community,vladmm/intellij-community,Distrotech/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,alphafoobar/intellij-community,suncycheng/intellij-community,fengbaicanhe/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,robovm/robovm-studio,jagguli/intellij-community,Lekanich/intellij-community,asedunov/intellij-community,xfournet/intellij-community,hurricup/intellij-community,allotria/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,da1z/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,muntasirsyed/intellij-community,consulo/consulo,lucafavatella/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,asedunov/intellij-community,fitermay/intellij-community,fengbaicanhe/intellij-community,alphafoobar/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,samthor/intellij-community,ftomassetti/intellij-community,consulo/consulo,idea4bsd/idea4bsd,amith01994/intellij-community,asedunov/intellij-community,ftomassetti/intellij-community,akosyakov/intellij-community,slisson/intellij-community,kool79/intellij-community,kdwink/intellij-community,fnouama/intellij-community,nicolargo/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,izonder/intellij-community,mglukhikh/intellij-community,gnuhub/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,ol-loginov/intellij-community,holmes/intellij-community,jagguli/intellij-community,SerCeMan/intellij-community,vladmm/intellij-community,youdonghai/intellij-community,caot/intellij-community,diorcety/intellij-community,muntasirsyed/intellij-community,fengbaicanhe/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,ol-loginov/intellij-community,akosyakov/intellij-community,adedayo/intellij-community,salguarnieri/intellij-community,nicolargo/intellij-community | package com.intellij.openapi.vfs.impl.local;
import com.intellij.Patches;
import com.intellij.ide.ui.UISettings;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.*;
import com.intellij.openapi.vfs.ex.ProvidedContent;
import com.intellij.util.LocalTimeCounter;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.awt.*;
import java.io.*;
public class VirtualFileImpl extends VirtualFile {
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.vfs.impl.local.VirtualFileImpl");
private static final LocalFileSystemImpl ourFileSystem = (LocalFileSystemImpl)LocalFileSystem.getInstance();
private static char[] myBuffer = new char[1024];
private VirtualFileImpl myParent;
private String myName;
private VirtualFileImpl[] myChildren = null; // null, if not defined yet
private boolean myDirectoryFlag;
private Boolean myWritableFlag = null; // null, if not defined yet
private long myModificationStamp = LocalTimeCounter.currentTime();
private long myTimeStamp = -1; // -1, if file content has not been requested yet
private static final VirtualFileImpl[] EMPTY_VIRTUAL_FILE_ARRAY = new VirtualFileImpl[0];
// used by tests
public void setTimeStamp(long timeStamp) {
myTimeStamp = timeStamp;
}
VirtualFileImpl(
VirtualFileImpl parent,
PhysicalFile file,
boolean isDirectory
) {
myParent = parent;
setName(file.getName());
if (myName.length() == 0) {
LOG.error("file:" + file.getPath());
}
myDirectoryFlag = isDirectory;
if (!myDirectoryFlag) {
myTimeStamp = file.lastModified();
}
}
//for constructing roots
VirtualFileImpl(String path) {
int lastSlash = path.lastIndexOf('/');
LOG.assertTrue(lastSlash >= 0);
if (lastSlash == path.length() - 1) { // 'c:/' or '/'
setName(path);
myDirectoryFlag = true;
}
else {
setName(path.substring(lastSlash + 1));
String systemPath = path.replace('/', File.separatorChar);
myDirectoryFlag = new IoFile(systemPath).isDirectory();
}
LOG.assertTrue(myName.length() > 0);
}
boolean areChildrenCached() {
synchronized (ourFileSystem.LOCK) {
return myChildren != null;
}
}
void setParent(VirtualFileImpl parent) {
synchronized (ourFileSystem.LOCK) {
myParent = parent;
}
}
PhysicalFile getPhysicalFile() {
String path = getPath(File.separatorChar);
return new IoFile(path);
}
@NotNull
public VirtualFileSystem getFileSystem() {
return ourFileSystem;
}
public String getPath() {
return getPath('/');
}
private String getPath(char separatorChar) {
//ApplicationManager.getApplication().assertReadAccessAllowed();
synchronized (ourFileSystem.LOCK) {
try {
int length = appendPath(myBuffer, separatorChar);
return new String(myBuffer, 0, length);
}
catch (ArrayIndexOutOfBoundsException aiob) {
myBuffer = new char[myBuffer.length * 2];
return getPath(separatorChar);
}
}
}
private int appendPath(char[] buffer, char separatorChar) {
int currentLength = myParent == null ? 0 : myParent.appendPath(buffer, separatorChar);
if (currentLength > 0 && buffer[currentLength - 1] != separatorChar) {
buffer[currentLength++] = separatorChar;
}
String name = myName;
final int nameLength = name.length();
name.getChars(0, nameLength, buffer, currentLength);
int newLength = currentLength + nameLength;
if (currentLength == 0 && separatorChar != '/' ) {
StringUtil.replaceChar(buffer, '/', separatorChar, currentLength, newLength); // root may contain '/' char
}
return newLength;
}
@NotNull
public String getName() {
return myName;
}
public String getPresentableName() {
if (UISettings.getInstance().HIDE_KNOWN_EXTENSION_IN_TABS) {
final String nameWithoutExtension = getNameWithoutExtension();
return nameWithoutExtension.length() == 0 ? getName() : nameWithoutExtension;
}
return getName();
}
public boolean isWritable() {
synchronized (ourFileSystem.LOCK) {
if (myWritableFlag == null) {
myWritableFlag = isWritable(getPhysicalFile(), isDirectory()) ? Boolean.TRUE : Boolean.FALSE;
}
}
return myWritableFlag.booleanValue();
}
private static boolean isWritable(PhysicalFile physicalFile, boolean isDirectory) {
if (Patches.ALL_FOLDERS_ARE_WRITABLE && isDirectory) {
return true;
}
else {
return physicalFile.canWrite();
}
}
public boolean isDirectory() {
return myDirectoryFlag;
}
public boolean isValid() {
synchronized (ourFileSystem.LOCK) {
if (myParent == null) {
return ourFileSystem.isRoot(this);
}
return myParent.isValid();
}
}
@Nullable
public VirtualFileImpl getParent() {
synchronized (ourFileSystem.LOCK) {
return myParent;
}
}
public VirtualFile[] getChildren() {
if (!isDirectory()) return null;
synchronized (ourFileSystem.LOCK) {
if (myChildren == null) {
PhysicalFile file = getPhysicalFile();
PhysicalFile[] files = file.listFiles();
final int length = files.length;
if (length == 0) {
myChildren = EMPTY_VIRTUAL_FILE_ARRAY;
}
else {
myChildren = new VirtualFileImpl[ length ];
for (int i = 0; i < length; ++i) {
PhysicalFile f = files[i];
myChildren[i] = new VirtualFileImpl(this, f, f.isDirectory());
}
}
}
}
return myChildren;
}
void replaceChild(VirtualFileImpl oldChild, VirtualFileImpl newChild) {
for (int i = 0; i < myChildren.length; i++) {
VirtualFileImpl child = myChildren[i];
if (child == oldChild) {
myChildren[i] = newChild;
return;
}
}
}
public InputStream getInputStream() throws IOException {
return getProvidedContent().getInputStream();
}
public long getLength() {
LOG.assertTrue(!isDirectory());
ProvidedContent content;
try {
content = getProvidedContent();
}
catch (IOException e) {
throw new RuntimeException(e);
}
return content.getLength();
}
private ProvidedContent getProvidedContent() throws IOException {
ApplicationManager.getApplication().assertReadAccessAllowed();
if (isDirectory()) {
throw new IOException(VfsBundle.message("file.read.error", getPhysicalFile().getPath()));
}
if (myTimeStamp < 0) return physicalContent();
ProvidedContent content = ourFileSystem.getManager().getProvidedContent(this);
return content == null ? physicalContent() : content;
}
private ProvidedContent physicalContent() {
return new ProvidedContent() {
public InputStream getInputStream() throws IOException {
return new BufferedInputStream(getPhysicalFileInputStream());
}
public int getLength() {
return getPhysicalFileLength();
}
};
}
protected InputStream getPhysicalFileInputStream() throws IOException {
getTimeStamp();
return getPhysicalFile().createInputStream();
}
public OutputStream getOutputStream(final Object requestor,
final long newModificationStamp,
final long newTimeStamp) throws IOException {
ApplicationManager.getApplication().assertWriteAccessAllowed();
PhysicalFile physicalFile = getPhysicalFile();
if (isDirectory()) {
throw new IOException(VfsBundle.message("file.write.error", physicalFile.getPath()));
}
ourFileSystem.fireBeforeContentsChange(requestor, this);
final OutputStream out = new BufferedOutputStream(physicalFile.createOutputStream());
if (getBOM() != null) {
out.write(getBOM());
}
return new OutputStream() {
public void write(int b) throws IOException {
out.write(b);
}
public void write(byte[] b) throws IOException {
out.write(b);
}
public void write(byte[] b, int off, int len) throws IOException {
out.write(b, off, len);
}
public void flush() throws IOException {
out.flush();
}
public void close() throws IOException {
out.close();
long oldModificationStamp = getModificationStamp();
myModificationStamp = newModificationStamp >= 0 ? newModificationStamp : LocalTimeCounter.currentTime();
if (newTimeStamp >= 0) {
getPhysicalFile().setLastModified(newTimeStamp);
}
myTimeStamp = getPhysicalFile().lastModified();
ourFileSystem.fireContentsChanged(requestor, VirtualFileImpl.this, oldModificationStamp);
}
};
}
public byte[] contentsToByteArray() throws IOException {
InputStream in = getInputStream();
byte[] bytes = new byte[(int)getLength()];
try {
int count = 0;
while (true) {
int n = in.read(bytes, count, bytes.length - count);
if (n <= 0) break;
count += n;
}
}
finally {
in.close();
}
return bytes;
}
public long getModificationStamp() {
return myModificationStamp;
}
public long getTimeStamp() {
if (myTimeStamp < 0) {
myTimeStamp = getPhysicalFile().lastModified();
}
return myTimeStamp;
}
public long getActualTimeStamp() {
return getPhysicalFile().lastModified();
}
public void refresh(final boolean asynchronous, final boolean recursive, final Runnable postRunnable) {
if (!asynchronous) {
ApplicationManager.getApplication().assertWriteAccessAllowed();
}
final ModalityState modalityState = EventQueue.isDispatchThread() ? ModalityState.current() : ModalityState.NON_MMODAL;
if (LOG.isDebugEnabled()) {
LOG.debug("VirtualFile.refresh():" + getPresentableUrl() + ", recursive = " + recursive + ", modalityState = " + modalityState);
}
final Runnable runnable = new Runnable() {
public void run() {
ourFileSystem.getManager().beforeRefreshStart(asynchronous, modalityState, postRunnable);
PhysicalFile physicalFile = getPhysicalFile();
if (!physicalFile.exists()) {
Runnable runnable = new Runnable() {
public void run() {
if (!isValid()) return;
VirtualFileImpl parent = (VirtualFileImpl)getParent();
if (parent != null) {
ourFileSystem.fireBeforeFileDeletion(null, VirtualFileImpl.this);
parent.removeChild(VirtualFileImpl.this);
ourFileSystem.fireFileDeleted(null, VirtualFileImpl.this, myName, myDirectoryFlag, parent);
}
}
};
ourFileSystem.getManager().addEventToFireByRefresh(runnable, asynchronous, modalityState);
}
else {
ourFileSystem.refresh(VirtualFileImpl.this, recursive, true, modalityState, asynchronous, false);
}
}
};
final Runnable endTask = new Runnable() {
public void run() {
ourFileSystem.getManager().afterRefreshFinish(asynchronous, modalityState);
}
};
if (asynchronous) {
Runnable runnable1 = new Runnable() {
public void run() {
LOG.info("Executing request:" + this);
final ProgressIndicator indicator = ourFileSystem.getManager().getRefreshIndicator();
indicator.start();
indicator.setText(VfsBundle.message("file.synchronize.progress"));
ApplicationManager.getApplication().runReadAction(runnable);
indicator.stop();
endTask.run();
}
};
ourFileSystem.getSynchronizeExecutor().submit(runnable1);
}
else {
runnable.run();
endTask.run();
}
}
public boolean nameEquals(String name) {
return SystemInfo.isFileSystemCaseSensitive ? getName().equals(name) : getName().equalsIgnoreCase(name);
}
public int getPhysicalFileLength() {
return (int)getPhysicalFile().length();
}
void refreshInternal(final boolean recursive,
final ModalityState modalityState,
final boolean forceRefresh,
final boolean asynchronous) {
if (!asynchronous) {
ApplicationManager.getApplication().assertWriteAccessAllowed();
}
if (!isValid()) return;
if (LOG.isDebugEnabled()) {
LOG.debug("refreshInternal recursive = " + recursive + " asynchronous = " + asynchronous + " file = " + myName);
}
PhysicalFile physicalFile = getPhysicalFile();
final boolean isDirectory = physicalFile.isDirectory();
if (isDirectory != myDirectoryFlag) {
final PhysicalFile _physicalFile = physicalFile;
ourFileSystem.getManager().addEventToFireByRefresh(
new Runnable() {
public void run() {
if (!isValid()) return;
VirtualFileImpl parent = (VirtualFileImpl)getParent();
if (parent == null) return;
ourFileSystem.fireBeforeFileDeletion(null, VirtualFileImpl.this);
parent.removeChild(VirtualFileImpl.this);
ourFileSystem.fireFileDeleted(null, VirtualFileImpl.this, myName, myDirectoryFlag, parent);
VirtualFileImpl newChild = new VirtualFileImpl(parent, _physicalFile, isDirectory);
parent.addChild(newChild);
ourFileSystem.fireFileCreated(null, newChild);
}
},
asynchronous,
modalityState
);
return;
}
if (isDirectory) {
if (myChildren == null) return;
PhysicalFile[] files = physicalFile.listFiles();
final boolean[] found = new boolean[myChildren.length];
VirtualFileImpl[] children = myChildren;
for (int i = 0; i < files.length; i++) {
final PhysicalFile file = files[i];
final String name = file.getName();
int index = -1;
if (i < children.length && children[i].myName.equals(name)) {
index = i;
}
else {
for (int j = 0; j < children.length; j++) {
VirtualFileImpl child = myChildren[j];
if (child.myName.equals(name)) index = j;
}
}
if (index < 0) {
ourFileSystem.getManager().addEventToFireByRefresh(
new Runnable() {
public void run() {
if (VirtualFileImpl.this.isValid()) {
if (findChild(file.getName()) != null) return; // was already created
VirtualFileImpl newChild = new VirtualFileImpl(
VirtualFileImpl.this,
file,
file.isDirectory()
);
addChild(newChild);
ourFileSystem.fireFileCreated(null, newChild);
}
}
},
asynchronous,
modalityState
);
}
else {
found[index] = true;
}
}
for (int i = 0; i < children.length; i++) {
final VirtualFileImpl child = children[i];
if (found[i]) {
if (recursive) {
child.refreshInternal(recursive, modalityState, false, asynchronous);
}
}
else {
ourFileSystem.getManager().addEventToFireByRefresh(
new Runnable() {
public void run() {
if (child.isValid()) {
ourFileSystem.fireBeforeFileDeletion(null, child);
removeChild(child);
ourFileSystem.fireFileDeleted(null, child, child.myName, child.myDirectoryFlag, VirtualFileImpl.this);
}
}
},
asynchronous,
modalityState
);
}
}
}
else {
if (myTimeStamp > 0) {
final long timeStamp = physicalFile.lastModified();
if (timeStamp != myTimeStamp || forceRefresh) {
ourFileSystem.getManager().addEventToFireByRefresh(
new Runnable() {
public void run() {
if (!isValid()) return;
ourFileSystem.fireBeforeContentsChange(null, VirtualFileImpl.this);
long oldModificationStamp = getModificationStamp();
myTimeStamp = timeStamp;
myModificationStamp = LocalTimeCounter.currentTime();
ourFileSystem.fireContentsChanged(null, VirtualFileImpl.this, oldModificationStamp);
}
},
asynchronous,
modalityState
);
}
}
}
if (myWritableFlag != null) {
final boolean isWritable = isWritable(physicalFile, isDirectory());
if (isWritable != myWritableFlag.booleanValue()) {
ourFileSystem.getManager().addEventToFireByRefresh(
new Runnable() {
public void run() {
if (!isValid()) return;
ourFileSystem.fireBeforePropertyChange(
null, VirtualFileImpl.this, PROP_WRITABLE,
myWritableFlag, isWritable ? Boolean.TRUE : Boolean.FALSE
);
myWritableFlag = isWritable ? Boolean.TRUE : Boolean.FALSE;
ourFileSystem.firePropertyChanged(
null, VirtualFileImpl.this, PROP_WRITABLE,
isWritable ? Boolean.FALSE : Boolean.TRUE, myWritableFlag
);
}
},
asynchronous,
modalityState
);
}
}
}
void addChild(VirtualFileImpl child) {
getChildren(); // to initialize myChildren
synchronized (ourFileSystem.LOCK) {
VirtualFileImpl[] newChildren = new VirtualFileImpl[myChildren.length + 1];
System.arraycopy(myChildren, 0, newChildren, 0, myChildren.length);
newChildren[myChildren.length] = child;
myChildren = newChildren;
child.setParent(this);
}
}
void removeChild(VirtualFileImpl child) {
getChildren(); // to initialize myChildren
synchronized (ourFileSystem.LOCK) {
for (int i = 0; i < myChildren.length; i++) {
if (myChildren[i] == child) {
VirtualFileImpl[] newChildren = new VirtualFileImpl[myChildren.length - 1];
System.arraycopy(myChildren, 0, newChildren, 0, i);
System.arraycopy(myChildren, i + 1, newChildren, i, newChildren.length - i);
myChildren = newChildren;
child.myParent = null;
return;
}
}
}
}
@NonNls
public String toString() {
return "VirtualFile: " + getPresentableUrl();
}
void setName(String name) {
myName = name;
}
}
| source/com/intellij/openapi/vfs/impl/local/VirtualFileImpl.java | package com.intellij.openapi.vfs.impl.local;
import com.intellij.Patches;
import com.intellij.ide.ui.UISettings;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.*;
import com.intellij.openapi.vfs.ex.ProvidedContent;
import com.intellij.util.LocalTimeCounter;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.awt.*;
import java.io.*;
public class VirtualFileImpl extends VirtualFile {
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.vfs.impl.local.VirtualFileImpl");
private static final LocalFileSystemImpl ourFileSystem = (LocalFileSystemImpl)LocalFileSystem.getInstance();
private VirtualFileImpl myParent;
private String myName;
private VirtualFileImpl[] myChildren = null; // null, if not defined yet
private boolean myDirectoryFlag;
private Boolean myWritableFlag = null; // null, if not defined yet
private long myModificationStamp = LocalTimeCounter.currentTime();
private long myTimeStamp = -1; // -1, if file content has not been requested yet
private static final VirtualFileImpl[] EMPTY_VIRTUAL_FILE_ARRAY = new VirtualFileImpl[0];
// used by tests
public void setTimeStamp(long timeStamp) {
myTimeStamp = timeStamp;
}
VirtualFileImpl(
VirtualFileImpl parent,
PhysicalFile file,
boolean isDirectory
) {
myParent = parent;
setName(file.getName());
if (myName.length() == 0) {
LOG.error("file:" + file.getPath());
}
myDirectoryFlag = isDirectory;
if (!myDirectoryFlag) {
myTimeStamp = file.lastModified();
}
}
//for constructing roots
VirtualFileImpl(String path) {
int lastSlash = path.lastIndexOf('/');
LOG.assertTrue(lastSlash >= 0);
if (lastSlash == path.length() - 1) { // 'c:/' or '/'
setName(path);
myDirectoryFlag = true;
}
else {
setName(path.substring(lastSlash + 1));
String systemPath = path.replace('/', File.separatorChar);
myDirectoryFlag = new IoFile(systemPath).isDirectory();
}
LOG.assertTrue(myName.length() > 0);
}
boolean areChildrenCached() {
synchronized (ourFileSystem.LOCK) {
return myChildren != null;
}
}
void setParent(VirtualFileImpl parent) {
synchronized (ourFileSystem.LOCK) {
myParent = parent;
}
}
PhysicalFile getPhysicalFile() {
String path = getPath(File.separatorChar, 1024);
return new IoFile(path);
}
@NotNull
public VirtualFileSystem getFileSystem() {
return ourFileSystem;
}
public String getPath() {
return getPath('/', 1024);
}
private String getPath(char separatorChar, int bufferLength) {
//ApplicationManager.getApplication().assertReadAccessAllowed();
try {
char[] buffer = new char[bufferLength];
int length;
synchronized (ourFileSystem.LOCK) {
length = appendPath(buffer, separatorChar);
}
return StringFactory.createStringFromConstantArray(buffer, 0, length);
}
catch(ArrayIndexOutOfBoundsException aiob) {
return getPath(separatorChar, bufferLength * 2);
}
}
private int appendPath(char[] buffer, char separatorChar) {
int currentLength = myParent == null ? 0 : myParent.appendPath(buffer, separatorChar);
if (currentLength > 0 && buffer[currentLength - 1] != separatorChar) {
buffer[currentLength++] = separatorChar;
}
String name = myName;
final int nameLength = name.length();
name.getChars(0, nameLength, buffer, currentLength);
int newLength = currentLength + nameLength;
if (currentLength == 0) {
StringUtil.replaceChar(buffer, '/', separatorChar, currentLength, newLength); // root may contain '/' char
}
return newLength;
}
@NotNull
public String getName() {
return myName;
}
public String getPresentableName() {
if (UISettings.getInstance().HIDE_KNOWN_EXTENSION_IN_TABS) {
final String nameWithoutExtension = getNameWithoutExtension();
return nameWithoutExtension.length() == 0 ? getName() : nameWithoutExtension;
}
return getName();
}
public boolean isWritable() {
synchronized (ourFileSystem.LOCK) {
if (myWritableFlag == null) {
myWritableFlag = isWritable(getPhysicalFile(), isDirectory()) ? Boolean.TRUE : Boolean.FALSE;
}
}
return myWritableFlag.booleanValue();
}
private static boolean isWritable(PhysicalFile physicalFile, boolean isDirectory) {
if (Patches.ALL_FOLDERS_ARE_WRITABLE && isDirectory) {
return true;
}
else {
return physicalFile.canWrite();
}
}
public boolean isDirectory() {
return myDirectoryFlag;
}
public boolean isValid() {
synchronized (ourFileSystem.LOCK) {
if (myParent == null) {
return ourFileSystem.isRoot(this);
}
return myParent.isValid();
}
}
@Nullable
public VirtualFileImpl getParent() {
synchronized (ourFileSystem.LOCK) {
return myParent;
}
}
public VirtualFile[] getChildren() {
if (!isDirectory()) return null;
synchronized (ourFileSystem.LOCK) {
if (myChildren == null) {
PhysicalFile file = getPhysicalFile();
PhysicalFile[] files = file.listFiles();
final int length = files.length;
if (length == 0) {
myChildren = EMPTY_VIRTUAL_FILE_ARRAY;
}
else {
myChildren = new VirtualFileImpl[ length ];
for (int i = 0; i < length; ++i) {
PhysicalFile f = files[i];
myChildren[i] = new VirtualFileImpl(this, f, f.isDirectory());
}
}
}
}
return myChildren;
}
void replaceChild(VirtualFileImpl oldChild, VirtualFileImpl newChild) {
for (int i = 0; i < myChildren.length; i++) {
VirtualFileImpl child = myChildren[i];
if (child == oldChild) {
myChildren[i] = newChild;
return;
}
}
}
public InputStream getInputStream() throws IOException {
return getProvidedContent().getInputStream();
}
public long getLength() {
LOG.assertTrue(!isDirectory());
ProvidedContent content;
try {
content = getProvidedContent();
}
catch (IOException e) {
throw new RuntimeException(e);
}
return content.getLength();
}
private ProvidedContent getProvidedContent() throws IOException {
ApplicationManager.getApplication().assertReadAccessAllowed();
if (isDirectory()) {
throw new IOException(VfsBundle.message("file.read.error", getPhysicalFile().getPath()));
}
if (myTimeStamp < 0) return physicalContent();
ProvidedContent content = ourFileSystem.getManager().getProvidedContent(this);
return content == null ? physicalContent() : content;
}
private ProvidedContent physicalContent() {
return new ProvidedContent() {
public InputStream getInputStream() throws IOException {
return new BufferedInputStream(getPhysicalFileInputStream());
}
public int getLength() {
return getPhysicalFileLength();
}
};
}
protected InputStream getPhysicalFileInputStream() throws IOException {
getTimeStamp();
return getPhysicalFile().createInputStream();
}
public OutputStream getOutputStream(final Object requestor,
final long newModificationStamp,
final long newTimeStamp) throws IOException {
ApplicationManager.getApplication().assertWriteAccessAllowed();
PhysicalFile physicalFile = getPhysicalFile();
if (isDirectory()) {
throw new IOException(VfsBundle.message("file.write.error", physicalFile.getPath()));
}
ourFileSystem.fireBeforeContentsChange(requestor, this);
final OutputStream out = new BufferedOutputStream(physicalFile.createOutputStream());
if (getBOM() != null) {
out.write(getBOM());
}
return new OutputStream() {
public void write(int b) throws IOException {
out.write(b);
}
public void write(byte[] b) throws IOException {
out.write(b);
}
public void write(byte[] b, int off, int len) throws IOException {
out.write(b, off, len);
}
public void flush() throws IOException {
out.flush();
}
public void close() throws IOException {
out.close();
long oldModificationStamp = getModificationStamp();
myModificationStamp = newModificationStamp >= 0 ? newModificationStamp : LocalTimeCounter.currentTime();
if (newTimeStamp >= 0) {
getPhysicalFile().setLastModified(newTimeStamp);
}
myTimeStamp = getPhysicalFile().lastModified();
ourFileSystem.fireContentsChanged(requestor, VirtualFileImpl.this, oldModificationStamp);
}
};
}
public byte[] contentsToByteArray() throws IOException {
InputStream in = getInputStream();
byte[] bytes = new byte[(int)getLength()];
try {
int count = 0;
while (true) {
int n = in.read(bytes, count, bytes.length - count);
if (n <= 0) break;
count += n;
}
}
finally {
in.close();
}
return bytes;
}
public long getModificationStamp() {
return myModificationStamp;
}
public long getTimeStamp() {
if (myTimeStamp < 0) {
myTimeStamp = getPhysicalFile().lastModified();
}
return myTimeStamp;
}
public long getActualTimeStamp() {
return getPhysicalFile().lastModified();
}
public void refresh(final boolean asynchronous, final boolean recursive, final Runnable postRunnable) {
if (!asynchronous) {
ApplicationManager.getApplication().assertWriteAccessAllowed();
}
final ModalityState modalityState = EventQueue.isDispatchThread() ? ModalityState.current() : ModalityState.NON_MMODAL;
if (LOG.isDebugEnabled()) {
LOG.debug("VirtualFile.refresh():" + getPresentableUrl() + ", recursive = " + recursive + ", modalityState = " + modalityState);
}
final Runnable runnable = new Runnable() {
public void run() {
ourFileSystem.getManager().beforeRefreshStart(asynchronous, modalityState, postRunnable);
PhysicalFile physicalFile = getPhysicalFile();
if (!physicalFile.exists()) {
Runnable runnable = new Runnable() {
public void run() {
if (!isValid()) return;
VirtualFileImpl parent = (VirtualFileImpl)getParent();
if (parent != null) {
ourFileSystem.fireBeforeFileDeletion(null, VirtualFileImpl.this);
parent.removeChild(VirtualFileImpl.this);
ourFileSystem.fireFileDeleted(null, VirtualFileImpl.this, myName, myDirectoryFlag, parent);
}
}
};
ourFileSystem.getManager().addEventToFireByRefresh(runnable, asynchronous, modalityState);
}
else {
ourFileSystem.refresh(VirtualFileImpl.this, recursive, true, modalityState, asynchronous, false);
}
}
};
final Runnable endTask = new Runnable() {
public void run() {
ourFileSystem.getManager().afterRefreshFinish(asynchronous, modalityState);
}
};
if (asynchronous) {
Runnable runnable1 = new Runnable() {
public void run() {
LOG.info("Executing request:" + this);
final ProgressIndicator indicator = ourFileSystem.getManager().getRefreshIndicator();
indicator.start();
indicator.setText(VfsBundle.message("file.synchronize.progress"));
ApplicationManager.getApplication().runReadAction(runnable);
indicator.stop();
endTask.run();
}
};
ourFileSystem.getSynchronizeExecutor().submit(runnable1);
}
else {
runnable.run();
endTask.run();
}
}
public boolean nameEquals(String name) {
return SystemInfo.isFileSystemCaseSensitive ? getName().equals(name) : getName().equalsIgnoreCase(name);
}
public int getPhysicalFileLength() {
return (int)getPhysicalFile().length();
}
void refreshInternal(final boolean recursive,
final ModalityState modalityState,
final boolean forceRefresh,
final boolean asynchronous) {
if (!asynchronous) {
ApplicationManager.getApplication().assertWriteAccessAllowed();
}
if (!isValid()) return;
if (LOG.isDebugEnabled()) {
LOG.debug("refreshInternal recursive = " + recursive + " asynchronous = " + asynchronous + " file = " + myName);
}
PhysicalFile physicalFile = getPhysicalFile();
final boolean isDirectory = physicalFile.isDirectory();
if (isDirectory != myDirectoryFlag) {
final PhysicalFile _physicalFile = physicalFile;
ourFileSystem.getManager().addEventToFireByRefresh(
new Runnable() {
public void run() {
if (!isValid()) return;
VirtualFileImpl parent = (VirtualFileImpl)getParent();
if (parent == null) return;
ourFileSystem.fireBeforeFileDeletion(null, VirtualFileImpl.this);
parent.removeChild(VirtualFileImpl.this);
ourFileSystem.fireFileDeleted(null, VirtualFileImpl.this, myName, myDirectoryFlag, parent);
VirtualFileImpl newChild = new VirtualFileImpl(parent, _physicalFile, isDirectory);
parent.addChild(newChild);
ourFileSystem.fireFileCreated(null, newChild);
}
},
asynchronous,
modalityState
);
return;
}
if (isDirectory) {
if (myChildren == null) return;
PhysicalFile[] files = physicalFile.listFiles();
final boolean[] found = new boolean[myChildren.length];
VirtualFileImpl[] children = myChildren;
for (int i = 0; i < files.length; i++) {
final PhysicalFile file = files[i];
final String name = file.getName();
int index = -1;
if (i < children.length && children[i].myName.equals(name)) {
index = i;
} else {
for (int j = 0; j < children.length; j++) {
VirtualFileImpl child = myChildren[j];
if (child.myName.equals(name)) index = j;
}
}
if (index < 0) {
ourFileSystem.getManager().addEventToFireByRefresh(
new Runnable() {
public void run() {
if (VirtualFileImpl.this.isValid()) {
if (findChild(file.getName()) != null) return; // was already created
VirtualFileImpl newChild = new VirtualFileImpl(
VirtualFileImpl.this,
file,
file.isDirectory()
);
addChild(newChild);
ourFileSystem.fireFileCreated(null, newChild);
}
}
},
asynchronous,
modalityState
);
}
else {
found[index] = true;
}
}
for (int i = 0; i < children.length; i++) {
final VirtualFileImpl child = children[i];
if (found[i]) {
if (recursive) {
child.refreshInternal(recursive, modalityState, false, asynchronous);
}
}
else {
ourFileSystem.getManager().addEventToFireByRefresh(
new Runnable() {
public void run() {
if (child.isValid()) {
ourFileSystem.fireBeforeFileDeletion(null, child);
removeChild(child);
ourFileSystem.fireFileDeleted(null, child, child.myName, child.myDirectoryFlag, VirtualFileImpl.this);
}
}
},
asynchronous,
modalityState
);
}
}
}
else {
if (myTimeStamp > 0) {
final long timeStamp = physicalFile.lastModified();
if (timeStamp != myTimeStamp || forceRefresh) {
ourFileSystem.getManager().addEventToFireByRefresh(
new Runnable() {
public void run() {
if (!isValid()) return;
ourFileSystem.fireBeforeContentsChange(null, VirtualFileImpl.this);
long oldModificationStamp = getModificationStamp();
myTimeStamp = timeStamp;
myModificationStamp = LocalTimeCounter.currentTime();
ourFileSystem.fireContentsChanged(null, VirtualFileImpl.this, oldModificationStamp);
}
},
asynchronous,
modalityState
);
}
}
}
if (myWritableFlag != null) {
final boolean isWritable = isWritable(physicalFile, isDirectory());
if (isWritable != myWritableFlag.booleanValue()) {
ourFileSystem.getManager().addEventToFireByRefresh(
new Runnable() {
public void run() {
if (!isValid()) return;
ourFileSystem.fireBeforePropertyChange(
null, VirtualFileImpl.this, PROP_WRITABLE,
myWritableFlag, isWritable ? Boolean.TRUE : Boolean.FALSE
);
myWritableFlag = isWritable ? Boolean.TRUE : Boolean.FALSE;
ourFileSystem.firePropertyChanged(
null, VirtualFileImpl.this, PROP_WRITABLE,
isWritable ? Boolean.FALSE : Boolean.TRUE, myWritableFlag
);
}
},
asynchronous,
modalityState
);
}
}
}
void addChild(VirtualFileImpl child) {
getChildren(); // to initialize myChildren
synchronized (ourFileSystem.LOCK) {
VirtualFileImpl[] newChildren = new VirtualFileImpl[myChildren.length + 1];
System.arraycopy(myChildren, 0, newChildren, 0, myChildren.length);
newChildren[myChildren.length] = child;
myChildren = newChildren;
child.setParent(this);
}
}
void removeChild(VirtualFileImpl child) {
getChildren(); // to initialize myChildren
synchronized (ourFileSystem.LOCK) {
for (int i = 0; i < myChildren.length; i++) {
if (myChildren[i] == child) {
VirtualFileImpl[] newChildren = new VirtualFileImpl[myChildren.length - 1];
System.arraycopy(myChildren, 0, newChildren, 0, i);
System.arraycopy(myChildren, i + 1, newChildren, i, newChildren.length - i);
myChildren = newChildren;
child.myParent = null;
return;
}
}
}
}
@NonNls
public String toString() {
return "VirtualFile: " + getPresentableUrl();
}
void setName(String name) {
myName = name;
}
}
| optimization: getPath() uses static char buffer
| source/com/intellij/openapi/vfs/impl/local/VirtualFileImpl.java | optimization: getPath() uses static char buffer | <ide><path>ource/com/intellij/openapi/vfs/impl/local/VirtualFileImpl.java
<ide>
<ide> private static final LocalFileSystemImpl ourFileSystem = (LocalFileSystemImpl)LocalFileSystem.getInstance();
<ide>
<add> private static char[] myBuffer = new char[1024];
<add>
<ide> private VirtualFileImpl myParent;
<ide> private String myName;
<ide> private VirtualFileImpl[] myChildren = null; // null, if not defined yet
<ide> }
<ide>
<ide> PhysicalFile getPhysicalFile() {
<del> String path = getPath(File.separatorChar, 1024);
<add> String path = getPath(File.separatorChar);
<ide> return new IoFile(path);
<ide> }
<ide>
<ide> }
<ide>
<ide> public String getPath() {
<del> return getPath('/', 1024);
<del> }
<del>
<del> private String getPath(char separatorChar, int bufferLength) {
<add> return getPath('/');
<add> }
<add>
<add> private String getPath(char separatorChar) {
<ide> //ApplicationManager.getApplication().assertReadAccessAllowed();
<del> try {
<del> char[] buffer = new char[bufferLength];
<del> int length;
<del> synchronized (ourFileSystem.LOCK) {
<del> length = appendPath(buffer, separatorChar);
<del> }
<del> return StringFactory.createStringFromConstantArray(buffer, 0, length);
<del> }
<del> catch(ArrayIndexOutOfBoundsException aiob) {
<del> return getPath(separatorChar, bufferLength * 2);
<add> synchronized (ourFileSystem.LOCK) {
<add> try {
<add> int length = appendPath(myBuffer, separatorChar);
<add> return new String(myBuffer, 0, length);
<add> }
<add> catch (ArrayIndexOutOfBoundsException aiob) {
<add> myBuffer = new char[myBuffer.length * 2];
<add> return getPath(separatorChar);
<add> }
<ide> }
<ide> }
<ide>
<ide>
<ide> name.getChars(0, nameLength, buffer, currentLength);
<ide> int newLength = currentLength + nameLength;
<del> if (currentLength == 0) {
<add> if (currentLength == 0 && separatorChar != '/' ) {
<ide> StringUtil.replaceChar(buffer, '/', separatorChar, currentLength, newLength); // root may contain '/' char
<ide> }
<ide> return newLength;
<ide> int index = -1;
<ide> if (i < children.length && children[i].myName.equals(name)) {
<ide> index = i;
<del> } else {
<add> }
<add> else {
<ide> for (int j = 0; j < children.length; j++) {
<ide> VirtualFileImpl child = myChildren[j];
<ide> if (child.myName.equals(name)) index = j; |
|
JavaScript | mit | 30faf46f0acf9c7777bae99ba401dbf32efbca5c | 0 | alpertuna/react-metismenu,alpertuna/react-metismenu | import React, {Component} from 'react'
import {render} from 'react-dom'
import MetisMenu from '../src/main.js'
import '../less/style.less'
class App extends Component{
render(){
var menu=[
{
icon: 'dashboard',
label: 'Menu 1',
href: '#menu-1'
},
{
icon: 'bell',
label: 'Menu 2',
href: '#menu-2'
},
{
icon: 'bolt',
label: 'Menu 3',
content: [
{
icon: 'bolt',
label: 'Test',
href: '#test'
}
]
},
{
icon: 'bars',
label: 'Menu 4',
content: [
{
icon: 'bold',
label: 'Sub Menu 1',
href: '#sub-menu-1'
},
{
icon: 'italic',
label: 'Sub Menu 2',
content: [
{
icon: 'cog',
label: 'Level 3 Menu 1',
href: '#level-3-menu-1'
},
{
icon: 'group',
label: 'Level 3 Menu 2',
href: '#level-3-menu-2'
}
]
},
{
icon: 'image',
label: 'Sub Menu 3',
content: [
{
icon: 'cog',
label: 'Level 3 Menu 1',
href: '#level-3-menu-1'
},
{
icon: 'group',
label: 'Level 3 Menu 2',
href: '#level-3-menu-2'
}
]
},
{
icon: 'check',
label: 'Sub Menu 4',
href: '#sub-menu-4'
}
]
},
{
icon: 'user',
label: 'Menu 5',
href: '#menu-5'
}
];
return <div>
<MetisMenu
content={menu}
/>
</div>
}
}
render(<App />, document.getElementById('root'));
| dev/App.js | import React, {Component} from 'react'
import {render} from 'react-dom'
import MetisMenu from '../src/main.js'
import '../less/style.less'
class App extends Component{
render(){
var menu=[
{
icon: 'dashboard',
label: 'Menu 1',
href: '#menu-1'
},
{
icon: 'bell',
label: 'Menu 2',
href: '#menu-2'
},
{
icon: 'bolt',
label: 'Menu 3',
content: [
{
icon: 'bolt',
label: 'Test',
href: '#test'
}
]
},
{
icon: 'bars',
label: 'Menu 4',
content: [
{
icon: 'bold',
label: 'Sub Menu 1',
href: '#sub-menu-1'
},
{
icon: 'italic',
label: 'Sub Menu 2',
content: [
{
icon: 'cog',
label: 'Level 3 Menu 1',
href: '#level-3-menu-1'
},
{
icon: 'group',
label: 'Level 3 Menu 2',
href: '#level-3-menu-2'
}
]
},
{
icon: 'image',
label: 'Sub Menu 3',
content: [
{
icon: 'cog',
label: 'Level 3 Menu 1',
href: '#level-3-menu-1'
},
{
icon: 'group',
label: 'Level 3 Menu 2',
href: '#level-3-menu-2'
}
]
},
{
icon: 'check',
label: 'Sub Menu 4',
href: '#sub-menu-4'
}
]
},
{
icon: 'user',
label: 'Menu 5',
href: '#menu-5'
}
];
return <div>
<MetisMenu
iconClassPrefix="fa fa-"
iconLevelDown="arrow-down"
iconLevelUp="arrow-up"
content={menu}
/>
</div>
}
}
render(<App />, document.getElementById('root'));
| Update dev/App.js
| dev/App.js | Update dev/App.js | <ide><path>ev/App.js
<ide>
<ide> return <div>
<ide> <MetisMenu
<del> iconClassPrefix="fa fa-"
<del> iconLevelDown="arrow-down"
<del> iconLevelUp="arrow-up"
<ide> content={menu}
<ide> />
<ide> </div> |
|
Java | bsd-3-clause | 5cc0cd6ae5a66d1a2e1a7d1033b297309547e269 | 0 | jCoderZ/fawkez-old,jCoderZ/fawkez-old,jCoderZ/fawkez-old | /*
* $Id: LogMessageGenerator.java 1 2006-11-25 14:41:52Z amandel $
*
* Copyright 2006, The jCoderZ.org Project. 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 jCoderZ.org Project 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 REGENTS 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 REGENTS AND 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 org.jcoderz.commons.taskdefs;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;
import com.caucho.hessian.client.HessianProxyFactory;
import com.luntsys.luntbuild.facades.BuildParams;
import com.luntsys.luntbuild.facades.Constants;
import com.luntsys.luntbuild.facades.ILuntbuild;
import com.luntsys.luntbuild.facades.lb12.BuildFacade;
import com.luntsys.luntbuild.facades.lb12.ScheduleFacade;
/**
* Ant task to trigger a build on the Luntbuild system and download results
* afterwards.
*
* @author Albrecht Messner
*/
public class LuntBuildTask
extends Task
{
/**
* Schedule start policy: allows multiple schedules to be running
* simultaneously.
*/
public static final String START_MULTIPLE = "startMultiple";
/**
* Schedule start policy: skips execution if schedule is currently running.
*/
public static final String SKIP_IF_RUNNING = "skipIfRunning";
/**
* Schedule start policy: fails this task if schedule is currently running.
*/
public static final String FAIL_IF_RUNNING = "failIfRunning";
private static final List POLICY_LIST = new ArrayList();
static
{
POLICY_LIST.add(START_MULTIPLE);
POLICY_LIST.add(SKIP_IF_RUNNING);
POLICY_LIST.add(FAIL_IF_RUNNING);
}
/** Wait time between kicking off schedule and start polling status
* and between schedule termination and log retrieval. */
private static final int WAIT_PERIOD = 5000;
/** Interval to poll build server. */
private static final int POLL_INTERVAL = 2000;
/** Buffer size to read from HTTP stream when retrieving artifacts. */
private static final int BUFFER_SIZE = 512;
private String mLuntUrl;
private String mUserName;
private String mPassword;
private String mProjectName;
private String mScheduleName;
private String mStartPolicy = FAIL_IF_RUNNING;
private boolean mWaitForSchedule = true;
private String mToDir;
private final List mArtifacts = new ArrayList();
private ILuntbuild mLuntServer;
/**
* @param luntUrl The luntUrl to set.
*/
public void setLuntUrl (String luntUrl)
{
mLuntUrl = luntUrl;
}
/**
* @param userName The userName to set.
*/
public void setUserName (String userName)
{
mUserName = userName;
}
/**
* @param password The password to set.
*/
public void setPassword (String password)
{
mPassword = password;
}
/**
* @param projectName The projectName to set.
*/
public void setProjectName (String projectName)
{
mProjectName = projectName;
}
/**
* @param scheduleName The scheduleName to set.
*/
public void setScheduleName (String scheduleName)
{
mScheduleName = scheduleName;
}
/**
* @param startPolicy The startPolicy to set.
*/
public void setStartPolicy (String startPolicy)
{
if (!POLICY_LIST.contains(startPolicy))
{
throw new BuildException("Invalid start policy " + startPolicy
+ ", must be one of " + POLICY_LIST);
}
mStartPolicy = startPolicy;
}
/**
* @param waitForSchedule The waitForSchedule to set.
*/
public void setWaitForSchedule (boolean waitForSchedule)
{
mWaitForSchedule = waitForSchedule;
}
/**
* @param toDir The toDir to set.
*/
public void setToDir (String toDir)
{
mToDir = toDir;
}
/**
* Adds an artifact for retrieval.
* @param artifact
*/
public void addArtifact (Artifact artifact)
{
mArtifacts.add(artifact);
}
public void execute () throws BuildException
{
checkParameters();
try
{
final ScheduleFacade schedule = getSchedule();
final boolean startSchedule;
if (schedule.getStatus() == Constants.SCHEDULE_STATUS_RUNNING)
{
if (mStartPolicy.equals(START_MULTIPLE))
{
startSchedule = true;
}
else if (mStartPolicy.equals(SKIP_IF_RUNNING))
{
startSchedule = false;
}
else
{
throw new BuildException(
"Can't start build because schedule is already running");
}
}
else
{
startSchedule = true;
}
if (startSchedule)
{
startSchedule();
}
}
catch (BuildException x)
{
throw x;
}
catch (Exception x)
{
throw new BuildException(x);
}
}
private void startSchedule () throws InterruptedException, IOException
{
log("Starting build for " + mProjectName + "/" + mScheduleName
+ " on server " + mLuntUrl, Project.MSG_INFO);
getLuntServer().triggerBuild(mProjectName, mScheduleName, getBuildParams());
if (mWaitForSchedule)
{
waitForSchedule();
}
}
private void waitForSchedule () throws InterruptedException, IOException
{
Thread.sleep(WAIT_PERIOD);
log("Waiting for build "
+ getLuntServer().getLastBuild(mProjectName, mScheduleName).getVersion()
+ " to finish");
while (getSchedule().getStatus() == Constants.SCHEDULE_STATUS_RUNNING)
{
log("Schedule running", Project.MSG_VERBOSE);
Thread.sleep(POLL_INTERVAL);
}
final int termStatus = getSchedule().getStatus();
switch (termStatus)
{
case Constants.SCHEDULE_STATUS_SUCCESS:
log("LuntBuild schedule " + mProjectName + "/" + mScheduleName
+ " succeeded");
dumpLogFile();
retrieveArtifacts();
break;
case Constants.SCHEDULE_STATUS_FAILED:
log("LuntBuild schedule " + mProjectName + "/" + mScheduleName
+ " FAILED");
dumpLogFile();
throw new BuildException("LuntBuild schedule " + mProjectName + "/"
+ mScheduleName + " FAILED");
default:
throw new BuildException("Unexpected status for schedule "
+ mProjectName + "/" + mScheduleName + ": " + termStatus);
}
}
private ScheduleFacade getSchedule () throws MalformedURLException
{
return getLuntServer().getScheduleByName(mProjectName, mScheduleName);
}
/**
* @throws IOException
*
*/
private void retrieveArtifacts () throws IOException
{
final BuildFacade currentBuild
= getLuntServer().getLastBuild(mProjectName, mScheduleName);
final String buildLogUrl = currentBuild.getBuildLogUrl();
final String path = buildLogUrl.substring(0, buildLogUrl.lastIndexOf('/'));
final String artifactsBaseUrl = path + "/artifacts/";
log("Artifacts base URL: " + artifactsBaseUrl, Project.MSG_VERBOSE);
HttpURLConnection.setFollowRedirects(true);
for (final Iterator it = mArtifacts.iterator(); it.hasNext(); )
{
final String artifactName = ((Artifact)it.next()).getName();
final File outputFile = new File(new File(mToDir), artifactName);
if (outputFile.exists())
{
throw new BuildException("Output file " + outputFile
+ " already exists");
}
final String artifactUrl = artifactsBaseUrl + artifactName;
log("Retrieving artifact " + artifactName);
log("Retrieving from URL: " + artifactUrl, Project.MSG_VERBOSE);
log("Writing to file: " + mToDir + File.separator + outputFile,
Project.MSG_VERBOSE);
final HttpURLConnection con
= (HttpURLConnection)new URL(artifactUrl).openConnection();
con.setDoOutput(true);
con.addRequestProperty("Keep-alive", "false");
con.connect();
if (con.getResponseCode() != HttpURLConnection.HTTP_OK)
{
throw new BuildException("Failed while retrieving artifact "
+ artifactUrl + ": " + con.getResponseMessage());
}
writeArtifactToFile(outputFile, con);
}
}
private void writeArtifactToFile (
final File outputFile, final HttpURLConnection con)
throws IOException, FileNotFoundException
{
int read = 0;
final byte[] buf = new byte[BUFFER_SIZE];
InputStream artifactInput = null;
OutputStream artifactOutput = null;
try
{
artifactInput = con.getInputStream();
artifactOutput = new FileOutputStream(outputFile);
while ((read = artifactInput.read(buf)) > 0)
{
artifactOutput.write(buf, 0, read);
}
}
finally
{
close(artifactInput);
close(artifactOutput);
}
}
private void close (InputStream inputStream)
{
if (inputStream != null)
{
try
{
inputStream.close();
}
catch (IOException x)
{
log("Failed to close java.io.InputStream: " + x.getMessage(),
Project.MSG_WARN);
}
}
}
private void close (OutputStream outputStream)
{
if (outputStream != null)
{
try
{
outputStream.close();
}
catch (IOException x)
{
log("Failed to close java.io.OutputStream: " + x.getMessage(),
Project.MSG_WARN);
}
}
}
/**
* @throws InterruptedException
* @throws IOException
*
*/
private void dumpLogFile () throws InterruptedException, IOException
{
Thread.sleep(WAIT_PERIOD);
final BuildFacade currentBuild
= getLuntServer().getLastBuild(mProjectName, mScheduleName);
final String buildLogUrlHtml = currentBuild.getBuildLogUrl();
log("Build log URL (HTML format): " + buildLogUrlHtml, Project.MSG_VERBOSE);
final String buildLogUrlTxt = buildLogUrlHtml.substring(0,
buildLogUrlHtml.lastIndexOf(".html")) + ".txt";
log("Build log URL (Text format): " + buildLogUrlTxt, Project.MSG_VERBOSE);
final URL buildLog = new URL(buildLogUrlTxt);
final HttpURLConnection con = (HttpURLConnection)buildLog.openConnection();
log("Got HTTP code " + con.getResponseCode(), Project.MSG_VERBOSE);
final InputStream is = con.getInputStream();
int read = 0;
final byte[] buf = new byte[256];
final ByteArrayOutputStream bout = new ByteArrayOutputStream();
while ((read = is.read(buf)) > 0)
{
bout.write(buf, 0, read);
}
final String buildLogData = new String(bout.toByteArray());
log("===== START Build log =====", Project.MSG_INFO);
log(buildLogData, Project.MSG_INFO);
log("===== END Build log =====", Project.MSG_INFO);
}
private BuildParams getBuildParams ()
{
final BuildParams params = new BuildParams();
params.setBuildNecessaryCondition("always");
params.setBuildType(Constants.BUILD_TYPE_CLEAN);
params.setLabelStrategy(Constants.LABEL_NONE);
params.setNotifyStrategy(Constants.NOTIFY_NONE);
params.setPostbuildStrategy(Constants.POSTBUILD_NONE);
// params.setScheduleId()
params.setTriggerDependencyStrategy(
Constants.TRIGGER_NONE_DEPENDENT_SCHEDULES);
return params;
}
/**
* @param luntUrl
*/
private void checkNotNull (Object obj, String name)
{
if (obj == null)
{
throw new BuildException("Parameter " + name + " missing");
}
}
/**
*
*/
private void checkParameters ()
{
checkNotNull(mLuntUrl, "luntUrl");
checkNotNull(mUserName, "userName");
checkNotNull(mPassword, "password");
checkNotNull(mProjectName, "projectName");
checkNotNull(mScheduleName, "scheduleName");
if (mArtifacts.size() > 0)
{
if (mToDir == null)
{
throw new BuildException("'toDir' must be set if artifacts are set");
}
else
{
AntTaskUtil.ensureDirectory(new File(mToDir));
}
if (!mWaitForSchedule)
{
throw new BuildException(
"Can't retrieve artifacts when waitForBuild == false");
}
}
}
private ILuntbuild getLuntServer () throws MalformedURLException
{
if (mLuntServer == null)
{
HessianProxyFactory factory = new HessianProxyFactory();
factory.setUser(mUserName);
factory.setPassword(mPassword);
mLuntServer = (ILuntbuild)factory.create(ILuntbuild.class, mLuntUrl);
}
return mLuntServer;
}
public static final class Artifact
{
private String mName;
/**
* @param name The name to set.
*/
public void setName (String name)
{
mName = name;
}
/**
* @return Returns the name.
*/
public String getName ()
{
return mName;
}
}
}
| src/java/org/jcoderz/commons/taskdefs/LuntBuildTask.java | //
// Copyright (C) 2006 Media Saturn Systemzentrale. All rights reserved.
//
// $Project: Inventory$
// $Revision:$
// $Date:$
// $Log[10]$
//
package org.jcoderz.commons.taskdefs;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DefaultLogger;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;
import com.caucho.hessian.client.HessianProxyFactory;
import com.luntsys.luntbuild.facades.BuildParams;
import com.luntsys.luntbuild.facades.Constants;
import com.luntsys.luntbuild.facades.ILuntbuild;
import com.luntsys.luntbuild.facades.lb12.BuildFacade;
import com.luntsys.luntbuild.facades.lb12.ScheduleFacade;
/**
*
*/
public class LuntBuildTask
extends Task
{
/** Schedule start policy: allows multiple schedules to be running simultaneously. */
public static final String START_MULTIPLE = "startMultiple";
/** Schedule start policy: skips execution if schedule is currently running. */
public static final String SKIP_IF_RUNNING = "skipIfRunning";
/** Schedule start policy: fails this task if schedule is currently running. */
public static final String FAIL_IF_RUNNING = "failIfRunning";
private static final List POLICY_LIST = new ArrayList();
static
{
POLICY_LIST.add(START_MULTIPLE);
POLICY_LIST.add(SKIP_IF_RUNNING);
POLICY_LIST.add(FAIL_IF_RUNNING);
}
/** Wait time between kicking off schedule and start polling status
* and between schedule termination and log retrieval. */
private static final int WAIT_PERIOD = 5000;
/** Interval to poll build server. */
private static final int POLL_INTERVAL = 2000;
/** Buffer size to read from HTTP stream when retrieving artifacts. */
private static final int BUFFER_SIZE = 512;
private String mLuntUrl;
private String mUserName;
private String mPassword;
private String mProjectName;
private String mScheduleName;
private String mStartPolicy = FAIL_IF_RUNNING;
private boolean mWaitForSchedule = true;
private String mToDir;
private List mArtifacts = new ArrayList();
private ILuntbuild mLuntServer;
/**
* @param luntUrl The luntUrl to set.
*/
public void setLuntUrl(String luntUrl)
{
mLuntUrl = luntUrl;
}
/**
* @param userName The userName to set.
*/
public void setUserName(String userName)
{
mUserName = userName;
}
/**
* @param password The password to set.
*/
public void setPassword(String password)
{
mPassword = password;
}
/**
* @param projectName The projectName to set.
*/
public void setProjectName(String projectName)
{
mProjectName = projectName;
}
/**
* @param scheduleName The scheduleName to set.
*/
public void setScheduleName(String scheduleName)
{
mScheduleName = scheduleName;
}
/**
* @param startPolicy The startPolicy to set.
*/
public void setStartPolicy(String startPolicy)
{
if (!POLICY_LIST.contains(startPolicy))
{
throw new BuildException("Invalid start policy " + startPolicy + ", must be one of " + POLICY_LIST);
}
mStartPolicy = startPolicy;
}
/**
* @param waitForSchedule The waitForSchedule to set.
*/
public void setWaitForSchedule(boolean waitForSchedule)
{
mWaitForSchedule = waitForSchedule;
}
/**
* @param toDir The toDir to set.
*/
public void setToDir(String toDir)
{
mToDir = toDir;
}
/**
* Adds an artifact for retrieval.
* @param artifact
*/
public void addArtifact(Artifact artifact)
{
mArtifacts.add(artifact);
}
public void execute() throws BuildException
{
checkParameters();
try
{
final ScheduleFacade schedule = getSchedule();
final boolean startSchedule;
if (schedule.getStatus() == Constants.SCHEDULE_STATUS_RUNNING)
{
if (mStartPolicy.equals(START_MULTIPLE))
{
startSchedule = true;
}
else if (mStartPolicy.equals(SKIP_IF_RUNNING))
{
startSchedule = false;
}
else
{
throw new BuildException("Can't start build because schedule is already running");
}
}
else
{
startSchedule = true;
}
if (startSchedule)
{
startSchedule();
}
}
catch (BuildException x)
{
throw x;
}
catch (Exception x)
{
throw new BuildException(x);
}
}
private void startSchedule() throws InterruptedException, IOException
{
log("Starting build for " + mProjectName + "/" + mScheduleName + " on server " + mLuntUrl, Project.MSG_INFO);
getLuntServer().triggerBuild(mProjectName, mScheduleName, getBuildParams());
if (mWaitForSchedule)
{
waitForSchedule();
}
}
private void waitForSchedule() throws InterruptedException, IOException
{
Thread.sleep(WAIT_PERIOD);
log("Waiting for build " + getLuntServer().getLastBuild(mProjectName, mScheduleName).getVersion() + " to finish");
while (getSchedule().getStatus() == Constants.SCHEDULE_STATUS_RUNNING)
{
log("Schedule running", Project.MSG_VERBOSE);
Thread.sleep(POLL_INTERVAL);
}
final int termStatus = getSchedule().getStatus();
switch (termStatus)
{
case Constants.SCHEDULE_STATUS_SUCCESS:
log("LuntBuild schedule " + mProjectName + "/" + mScheduleName + " succeeded");
dumpLogFile();
retrieveArtifacts();
break;
case Constants.SCHEDULE_STATUS_FAILED:
log("LuntBuild schedule " + mProjectName + "/" + mScheduleName + " FAILED");
dumpLogFile();
throw new BuildException("LuntBuild schedule " + mProjectName + "/" + mScheduleName + " FAILED");
default:
throw new BuildException("Unexpected status for schedule " + mProjectName + "/" + mScheduleName + ": " + termStatus);
}
}
private ScheduleFacade getSchedule() throws MalformedURLException
{
return getLuntServer().getScheduleByName(mProjectName, mScheduleName);
}
/**
* @throws IOException
*
*/
private void retrieveArtifacts() throws IOException
{
final BuildFacade currentBuild = getLuntServer().getLastBuild(mProjectName, mScheduleName);
final String buildLogUrl = currentBuild.getBuildLogUrl();
final String path = buildLogUrl.substring(0, buildLogUrl.lastIndexOf('/'));
final String artifactsBaseUrl = path + "/artifacts/";
log("Artifacts base URL: " + artifactsBaseUrl, Project.MSG_VERBOSE);
HttpURLConnection.setFollowRedirects(true);
for (final Iterator it = mArtifacts.iterator(); it.hasNext(); )
{
final String artifactName = ((Artifact)it.next()).getName();
final File outputFile = new File(new File(mToDir), artifactName);
if (outputFile.exists())
{
throw new BuildException("Output file " + outputFile + " already exists");
}
final String artifactUrl = artifactsBaseUrl + artifactName;
log("Retrieving artifact " + artifactName);
log("Retrieving from URL: " + artifactUrl, Project.MSG_VERBOSE);
log("Writing to file: " + mToDir + File.separator + outputFile, Project.MSG_VERBOSE);
final HttpURLConnection con = (HttpURLConnection)new URL(artifactUrl).openConnection();
con.setDoOutput(true);
con.addRequestProperty("Keep-alive", "false");
con.connect();
if (con.getResponseCode() != HttpURLConnection.HTTP_OK)
{
throw new BuildException("Failed while retrieving artifact " + artifactUrl + ": " + con.getResponseMessage());
}
writeArtifactToFile(outputFile, con);
}
}
private void writeArtifactToFile(final File outputFile, final HttpURLConnection con) throws IOException, FileNotFoundException
{
int read = 0;
final byte[] buf = new byte[BUFFER_SIZE];
InputStream artifactInput = null;
OutputStream artifactOutput = null;
try
{
artifactInput = con.getInputStream();
artifactOutput = new FileOutputStream(outputFile);
while ((read = artifactInput.read(buf)) > 0)
{
artifactOutput.write(buf, 0, read);
}
}
finally
{
close(artifactInput);
close(artifactOutput);
}
}
private void close(InputStream inputStream)
{
if (inputStream != null)
{
try
{
inputStream.close();
}
catch (IOException x)
{
log("Failed to close java.io.InputStream: " + x.getMessage(), Project.MSG_WARN);
}
}
}
private void close(OutputStream outputStream)
{
if (outputStream != null)
{
try
{
outputStream.close();
}
catch (IOException x)
{
log("Failed to close java.io.OutputStream: " + x.getMessage(), Project.MSG_WARN);
}
}
}
/**
* @throws InterruptedException
* @throws IOException
*
*/
private void dumpLogFile() throws InterruptedException, IOException
{
Thread.sleep(WAIT_PERIOD);
final BuildFacade currentBuild = getLuntServer().getLastBuild(mProjectName, mScheduleName);
final String buildLogUrlHtml = currentBuild.getBuildLogUrl();
log("Build log URL (HTML format): " + buildLogUrlHtml, Project.MSG_VERBOSE);
final String buildLogUrlTxt = buildLogUrlHtml.substring(0, buildLogUrlHtml.lastIndexOf(".html")) + ".txt";
log("Build log URL (Text format): " + buildLogUrlTxt, Project.MSG_VERBOSE);
final URL buildLog = new URL(buildLogUrlTxt);
final HttpURLConnection con = (HttpURLConnection)buildLog.openConnection();
log("Got HTTP code " + con.getResponseCode(), Project.MSG_VERBOSE);
final InputStream is = con.getInputStream();
int read = 0;
final byte[] buf = new byte[256];
final ByteArrayOutputStream bout = new ByteArrayOutputStream();
while ((read = is.read(buf)) > 0)
{
bout.write(buf, 0, read);
}
final String buildLogData = new String(bout.toByteArray());
log("===== START Build log =====", Project.MSG_INFO);
log(buildLogData, Project.MSG_INFO);
log("===== END Build log =====", Project.MSG_INFO);
}
private BuildParams getBuildParams()
{
final BuildParams params = new BuildParams();
params.setBuildNecessaryCondition("always");
params.setBuildType(Constants.BUILD_TYPE_CLEAN);
params.setLabelStrategy(Constants.LABEL_NONE);
params.setNotifyStrategy(Constants.NOTIFY_NONE);
params.setPostbuildStrategy(Constants.POSTBUILD_NONE);
// params.setScheduleId()
params.setTriggerDependencyStrategy(Constants.TRIGGER_NONE_DEPENDENT_SCHEDULES);
return params;
}
/**
* @param luntUrl
*/
private void checkNotNull(Object obj, String name)
{
if (obj == null)
{
throw new BuildException("Parameter " + name + " missing");
}
}
/**
*
*/
private void checkParameters()
{
checkNotNull(mLuntUrl, "luntUrl");
checkNotNull(mUserName, "userName");
checkNotNull(mPassword, "password");
checkNotNull(mProjectName, "projectName");
checkNotNull(mScheduleName, "scheduleName");
if (mArtifacts.size() > 0)
{
if (mToDir == null)
{
throw new BuildException("'toDir' must be set if artifacts are set");
}
else
{
AntTaskUtil.ensureDirectory(new File(mToDir));
}
if (!mWaitForSchedule)
{
throw new BuildException("Can't retrieve artifacts when waitForBuild == false");
}
}
}
private ILuntbuild getLuntServer() throws MalformedURLException
{
if (mLuntServer == null)
{
HessianProxyFactory factory = new HessianProxyFactory();
factory.setUser(mUserName);
factory.setPassword(mPassword);
mLuntServer = (ILuntbuild)factory.create(ILuntbuild.class, mLuntUrl);
}
return mLuntServer;
}
public static final class Artifact
{
private String mName;
/**
* @param name The name to set.
*/
public void setName(String name)
{
mName = name;
}
/**
* @return Returns the name.
*/
public String getName()
{
return mName;
}
}
public static void main(String[] args)
{
final Project dummy = new Project();
DefaultLogger logger = new DefaultLogger();
logger.setMessageOutputLevel(Project.MSG_INFO);
logger.setOutputPrintStream(System.out);
logger.setErrorPrintStream(System.err);
dummy.addBuildListener(logger);
final LuntBuildTask lbr = new LuntBuildTask();
lbr.setProject(dummy);
lbr.setProjectName("test");
lbr.setScheduleName("on-demand");
lbr.setLuntUrl("http://dev130wks0007:8080/luntbuild/app.do?service=hessian");
lbr.setUserName("luntbuild");
lbr.setPassword("geheim42");
final Artifact a1 = new Artifact();
a1.setName("artifact1.txt");
lbr.addArtifact(a1);
final Artifact a2 = new Artifact();
a2.setName("artifact2.txt");
lbr.addArtifact(a2);
lbr.setToDir("C:\\temp");
lbr.execute();
}
}
| code cleanup
| src/java/org/jcoderz/commons/taskdefs/LuntBuildTask.java | code cleanup | <ide><path>rc/java/org/jcoderz/commons/taskdefs/LuntBuildTask.java
<del>//
<del>// Copyright (C) 2006 Media Saturn Systemzentrale. All rights reserved.
<del>//
<del>// $Project: Inventory$
<del>// $Revision:$
<del>// $Date:$
<del>// $Log[10]$
<del>//
<add>/*
<add> * $Id: LogMessageGenerator.java 1 2006-11-25 14:41:52Z amandel $
<add> *
<add> * Copyright 2006, The jCoderZ.org Project. 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 are
<add> * met:
<add> *
<add> * * Redistributions of source code must retain the above copyright
<add> * notice, this list of conditions and the following disclaimer.
<add> * * Redistributions in binary form must reproduce the above
<add> * copyright notice, this list of conditions and the following
<add> * disclaimer in the documentation and/or other materials
<add> * provided with the distribution.
<add> * * Neither the name of the jCoderZ.org Project nor the names of
<add> * its contributors may be used to endorse or promote products
<add> * derived from this software without specific prior written
<add> * permission.
<add> *
<add> * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS" AND
<add> * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
<add> * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
<add> * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS
<add> * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
<add> * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
<add> * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
<add> * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
<add> * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
<add> * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
<add> * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
<add> */
<ide>
<ide> package org.jcoderz.commons.taskdefs;
<ide>
<ide> import java.util.List;
<ide>
<ide> import org.apache.tools.ant.BuildException;
<del>import org.apache.tools.ant.DefaultLogger;
<ide> import org.apache.tools.ant.Project;
<ide> import org.apache.tools.ant.Task;
<ide>
<ide> import com.luntsys.luntbuild.facades.lb12.ScheduleFacade;
<ide>
<ide> /**
<del> *
<add> * Ant task to trigger a build on the Luntbuild system and download results
<add> * afterwards.
<add> *
<add> * @author Albrecht Messner
<ide> */
<ide> public class LuntBuildTask
<ide> extends Task
<ide> {
<del> /** Schedule start policy: allows multiple schedules to be running simultaneously. */
<add> /**
<add> * Schedule start policy: allows multiple schedules to be running
<add> * simultaneously.
<add> */
<ide> public static final String START_MULTIPLE = "startMultiple";
<del> /** Schedule start policy: skips execution if schedule is currently running. */
<add> /**
<add> * Schedule start policy: skips execution if schedule is currently running.
<add> */
<ide> public static final String SKIP_IF_RUNNING = "skipIfRunning";
<del> /** Schedule start policy: fails this task if schedule is currently running. */
<add> /**
<add> * Schedule start policy: fails this task if schedule is currently running.
<add> */
<ide> public static final String FAIL_IF_RUNNING = "failIfRunning";
<ide>
<ide> private static final List POLICY_LIST = new ArrayList();
<ide> private String mStartPolicy = FAIL_IF_RUNNING;
<ide> private boolean mWaitForSchedule = true;
<ide> private String mToDir;
<del> private List mArtifacts = new ArrayList();
<add> private final List mArtifacts = new ArrayList();
<ide>
<ide> private ILuntbuild mLuntServer;
<ide>
<ide> /**
<ide> * @param luntUrl The luntUrl to set.
<ide> */
<del> public void setLuntUrl(String luntUrl)
<add> public void setLuntUrl (String luntUrl)
<ide> {
<ide> mLuntUrl = luntUrl;
<ide> }
<ide> /**
<ide> * @param userName The userName to set.
<ide> */
<del> public void setUserName(String userName)
<add> public void setUserName (String userName)
<ide> {
<ide> mUserName = userName;
<ide> }
<ide> /**
<ide> * @param password The password to set.
<ide> */
<del> public void setPassword(String password)
<add> public void setPassword (String password)
<ide> {
<ide> mPassword = password;
<ide> }
<ide> /**
<ide> * @param projectName The projectName to set.
<ide> */
<del> public void setProjectName(String projectName)
<add> public void setProjectName (String projectName)
<ide> {
<ide> mProjectName = projectName;
<ide> }
<ide> /**
<ide> * @param scheduleName The scheduleName to set.
<ide> */
<del> public void setScheduleName(String scheduleName)
<add> public void setScheduleName (String scheduleName)
<ide> {
<ide> mScheduleName = scheduleName;
<ide> }
<ide> /**
<ide> * @param startPolicy The startPolicy to set.
<ide> */
<del> public void setStartPolicy(String startPolicy)
<add> public void setStartPolicy (String startPolicy)
<ide> {
<ide> if (!POLICY_LIST.contains(startPolicy))
<ide> {
<del> throw new BuildException("Invalid start policy " + startPolicy + ", must be one of " + POLICY_LIST);
<add> throw new BuildException("Invalid start policy " + startPolicy
<add> + ", must be one of " + POLICY_LIST);
<ide> }
<ide> mStartPolicy = startPolicy;
<ide> }
<ide> /**
<ide> * @param waitForSchedule The waitForSchedule to set.
<ide> */
<del> public void setWaitForSchedule(boolean waitForSchedule)
<add> public void setWaitForSchedule (boolean waitForSchedule)
<ide> {
<ide> mWaitForSchedule = waitForSchedule;
<ide> }
<ide> /**
<ide> * @param toDir The toDir to set.
<ide> */
<del> public void setToDir(String toDir)
<add> public void setToDir (String toDir)
<ide> {
<ide> mToDir = toDir;
<ide> }
<ide> * Adds an artifact for retrieval.
<ide> * @param artifact
<ide> */
<del> public void addArtifact(Artifact artifact)
<add> public void addArtifact (Artifact artifact)
<ide> {
<ide> mArtifacts.add(artifact);
<ide> }
<ide>
<del> public void execute() throws BuildException
<add> public void execute () throws BuildException
<ide> {
<ide> checkParameters();
<ide> try
<ide> }
<ide> else
<ide> {
<del> throw new BuildException("Can't start build because schedule is already running");
<add> throw new BuildException(
<add> "Can't start build because schedule is already running");
<ide> }
<ide> }
<ide> else
<ide> }
<ide> }
<ide>
<del> private void startSchedule() throws InterruptedException, IOException
<del> {
<del> log("Starting build for " + mProjectName + "/" + mScheduleName + " on server " + mLuntUrl, Project.MSG_INFO);
<add> private void startSchedule () throws InterruptedException, IOException
<add> {
<add> log("Starting build for " + mProjectName + "/" + mScheduleName
<add> + " on server " + mLuntUrl, Project.MSG_INFO);
<ide> getLuntServer().triggerBuild(mProjectName, mScheduleName, getBuildParams());
<ide>
<ide> if (mWaitForSchedule)
<ide> }
<ide> }
<ide>
<del> private void waitForSchedule() throws InterruptedException, IOException
<add> private void waitForSchedule () throws InterruptedException, IOException
<ide> {
<ide> Thread.sleep(WAIT_PERIOD);
<del> log("Waiting for build " + getLuntServer().getLastBuild(mProjectName, mScheduleName).getVersion() + " to finish");
<add> log("Waiting for build "
<add> + getLuntServer().getLastBuild(mProjectName, mScheduleName).getVersion()
<add> + " to finish");
<ide>
<ide> while (getSchedule().getStatus() == Constants.SCHEDULE_STATUS_RUNNING)
<ide> {
<ide> switch (termStatus)
<ide> {
<ide> case Constants.SCHEDULE_STATUS_SUCCESS:
<del> log("LuntBuild schedule " + mProjectName + "/" + mScheduleName + " succeeded");
<add> log("LuntBuild schedule " + mProjectName + "/" + mScheduleName
<add> + " succeeded");
<ide> dumpLogFile();
<ide> retrieveArtifacts();
<ide> break;
<ide> case Constants.SCHEDULE_STATUS_FAILED:
<del> log("LuntBuild schedule " + mProjectName + "/" + mScheduleName + " FAILED");
<add> log("LuntBuild schedule " + mProjectName + "/" + mScheduleName
<add> + " FAILED");
<ide> dumpLogFile();
<del> throw new BuildException("LuntBuild schedule " + mProjectName + "/" + mScheduleName + " FAILED");
<add> throw new BuildException("LuntBuild schedule " + mProjectName + "/"
<add> + mScheduleName + " FAILED");
<ide> default:
<del> throw new BuildException("Unexpected status for schedule " + mProjectName + "/" + mScheduleName + ": " + termStatus);
<del> }
<del> }
<del>
<del> private ScheduleFacade getSchedule() throws MalformedURLException
<add> throw new BuildException("Unexpected status for schedule "
<add> + mProjectName + "/" + mScheduleName + ": " + termStatus);
<add> }
<add> }
<add>
<add> private ScheduleFacade getSchedule () throws MalformedURLException
<ide> {
<ide> return getLuntServer().getScheduleByName(mProjectName, mScheduleName);
<ide> }
<ide> * @throws IOException
<ide> *
<ide> */
<del> private void retrieveArtifacts() throws IOException
<del> {
<del> final BuildFacade currentBuild = getLuntServer().getLastBuild(mProjectName, mScheduleName);
<add> private void retrieveArtifacts () throws IOException
<add> {
<add> final BuildFacade currentBuild
<add> = getLuntServer().getLastBuild(mProjectName, mScheduleName);
<ide> final String buildLogUrl = currentBuild.getBuildLogUrl();
<ide> final String path = buildLogUrl.substring(0, buildLogUrl.lastIndexOf('/'));
<ide> final String artifactsBaseUrl = path + "/artifacts/";
<ide> final File outputFile = new File(new File(mToDir), artifactName);
<ide> if (outputFile.exists())
<ide> {
<del> throw new BuildException("Output file " + outputFile + " already exists");
<add> throw new BuildException("Output file " + outputFile
<add> + " already exists");
<ide> }
<ide> final String artifactUrl = artifactsBaseUrl + artifactName;
<ide> log("Retrieving artifact " + artifactName);
<ide> log("Retrieving from URL: " + artifactUrl, Project.MSG_VERBOSE);
<del> log("Writing to file: " + mToDir + File.separator + outputFile, Project.MSG_VERBOSE);
<del> final HttpURLConnection con = (HttpURLConnection)new URL(artifactUrl).openConnection();
<add> log("Writing to file: " + mToDir + File.separator + outputFile,
<add> Project.MSG_VERBOSE);
<add> final HttpURLConnection con
<add> = (HttpURLConnection)new URL(artifactUrl).openConnection();
<ide> con.setDoOutput(true);
<ide> con.addRequestProperty("Keep-alive", "false");
<ide>
<ide> con.connect();
<ide> if (con.getResponseCode() != HttpURLConnection.HTTP_OK)
<ide> {
<del> throw new BuildException("Failed while retrieving artifact " + artifactUrl + ": " + con.getResponseMessage());
<add> throw new BuildException("Failed while retrieving artifact "
<add> + artifactUrl + ": " + con.getResponseMessage());
<ide> }
<ide>
<ide> writeArtifactToFile(outputFile, con);
<ide> }
<ide> }
<ide>
<del> private void writeArtifactToFile(final File outputFile, final HttpURLConnection con) throws IOException, FileNotFoundException
<add> private void writeArtifactToFile (
<add> final File outputFile, final HttpURLConnection con)
<add> throws IOException, FileNotFoundException
<ide> {
<ide> int read = 0;
<ide> final byte[] buf = new byte[BUFFER_SIZE];
<ide> }
<ide> }
<ide>
<del> private void close(InputStream inputStream)
<add> private void close (InputStream inputStream)
<ide> {
<ide> if (inputStream != null)
<ide> {
<ide> }
<ide> catch (IOException x)
<ide> {
<del> log("Failed to close java.io.InputStream: " + x.getMessage(), Project.MSG_WARN);
<del> }
<del> }
<del> }
<del>
<del> private void close(OutputStream outputStream)
<add> log("Failed to close java.io.InputStream: " + x.getMessage(),
<add> Project.MSG_WARN);
<add> }
<add> }
<add> }
<add>
<add> private void close (OutputStream outputStream)
<ide> {
<ide> if (outputStream != null)
<ide> {
<ide> }
<ide> catch (IOException x)
<ide> {
<del> log("Failed to close java.io.OutputStream: " + x.getMessage(), Project.MSG_WARN);
<add> log("Failed to close java.io.OutputStream: " + x.getMessage(),
<add> Project.MSG_WARN);
<ide> }
<ide> }
<ide> }
<ide> * @throws IOException
<ide> *
<ide> */
<del> private void dumpLogFile() throws InterruptedException, IOException
<add> private void dumpLogFile () throws InterruptedException, IOException
<ide> {
<ide> Thread.sleep(WAIT_PERIOD);
<del> final BuildFacade currentBuild = getLuntServer().getLastBuild(mProjectName, mScheduleName);
<add> final BuildFacade currentBuild
<add> = getLuntServer().getLastBuild(mProjectName, mScheduleName);
<ide>
<ide> final String buildLogUrlHtml = currentBuild.getBuildLogUrl();
<ide> log("Build log URL (HTML format): " + buildLogUrlHtml, Project.MSG_VERBOSE);
<del> final String buildLogUrlTxt = buildLogUrlHtml.substring(0, buildLogUrlHtml.lastIndexOf(".html")) + ".txt";
<add> final String buildLogUrlTxt = buildLogUrlHtml.substring(0,
<add> buildLogUrlHtml.lastIndexOf(".html")) + ".txt";
<ide> log("Build log URL (Text format): " + buildLogUrlTxt, Project.MSG_VERBOSE);
<ide>
<ide> final URL buildLog = new URL(buildLogUrlTxt);
<ide> log("===== END Build log =====", Project.MSG_INFO);
<ide> }
<ide>
<del> private BuildParams getBuildParams()
<add> private BuildParams getBuildParams ()
<ide> {
<ide> final BuildParams params = new BuildParams();
<ide>
<ide> params.setNotifyStrategy(Constants.NOTIFY_NONE);
<ide> params.setPostbuildStrategy(Constants.POSTBUILD_NONE);
<ide> // params.setScheduleId()
<del> params.setTriggerDependencyStrategy(Constants.TRIGGER_NONE_DEPENDENT_SCHEDULES);
<add> params.setTriggerDependencyStrategy(
<add> Constants.TRIGGER_NONE_DEPENDENT_SCHEDULES);
<ide>
<ide> return params;
<ide> }
<ide> /**
<ide> * @param luntUrl
<ide> */
<del> private void checkNotNull(Object obj, String name)
<add> private void checkNotNull (Object obj, String name)
<ide> {
<ide> if (obj == null)
<ide> {
<ide> /**
<ide> *
<ide> */
<del> private void checkParameters()
<add> private void checkParameters ()
<ide> {
<ide> checkNotNull(mLuntUrl, "luntUrl");
<ide> checkNotNull(mUserName, "userName");
<ide> }
<ide> if (!mWaitForSchedule)
<ide> {
<del> throw new BuildException("Can't retrieve artifacts when waitForBuild == false");
<del> }
<del> }
<del> }
<del>
<del> private ILuntbuild getLuntServer() throws MalformedURLException
<add> throw new BuildException(
<add> "Can't retrieve artifacts when waitForBuild == false");
<add> }
<add> }
<add> }
<add>
<add> private ILuntbuild getLuntServer () throws MalformedURLException
<ide> {
<ide> if (mLuntServer == null)
<ide> {
<ide> /**
<ide> * @param name The name to set.
<ide> */
<del> public void setName(String name)
<add> public void setName (String name)
<ide> {
<ide> mName = name;
<ide> }
<ide> /**
<ide> * @return Returns the name.
<ide> */
<del> public String getName()
<add> public String getName ()
<ide> {
<ide> return mName;
<ide> }
<ide> }
<del>
<del> public static void main(String[] args)
<del> {
<del> final Project dummy = new Project();
<del> DefaultLogger logger = new DefaultLogger();
<del>
<del> logger.setMessageOutputLevel(Project.MSG_INFO);
<del> logger.setOutputPrintStream(System.out);
<del> logger.setErrorPrintStream(System.err);
<del> dummy.addBuildListener(logger);
<del>
<del> final LuntBuildTask lbr = new LuntBuildTask();
<del> lbr.setProject(dummy);
<del> lbr.setProjectName("test");
<del> lbr.setScheduleName("on-demand");
<del> lbr.setLuntUrl("http://dev130wks0007:8080/luntbuild/app.do?service=hessian");
<del> lbr.setUserName("luntbuild");
<del> lbr.setPassword("geheim42");
<del>
<del> final Artifact a1 = new Artifact();
<del> a1.setName("artifact1.txt");
<del> lbr.addArtifact(a1);
<del> final Artifact a2 = new Artifact();
<del> a2.setName("artifact2.txt");
<del> lbr.addArtifact(a2);
<del>
<del> lbr.setToDir("C:\\temp");
<del> lbr.execute();
<del> }
<ide> } |
|
JavaScript | mit | 59f49a94651d9884aac8f26b70bd6edd72e4e26b | 0 | Revionics/SlickGrid,Revionics/SlickGrid | /**
* @license
* (c) 2009-2013 Michael Leibman
* michael{dot}leibman{at}gmail{dot}com
* http://github.com/mleibman/slickgrid
*
* Distributed under MIT license.
* All rights reserved.
*
* SlickGrid v2.2
*
* NOTES:
* Cell/row DOM manipulations are done directly bypassing jQuery's DOM manipulation methods.
* This increases the speed dramatically, but can only be done safely because there are no event handlers
* or data associated with any cell/row DOM nodes. Cell editors must make sure they implement .destroy()
* and do proper cleanup.
*
*/
// make sure required JavaScript modules are loaded
if (typeof jQuery === "undefined") {
throw "SlickGrid requires jquery module to be loaded";
}
if (!jQuery.fn.drag) {
throw "SlickGrid requires jquery.event.drag module to be loaded";
}
if (typeof Slick === "undefined") {
throw "slick.core.js not loaded";
}
(function ($) {
// Slick.Grid
$.extend(true, window, {
Slick: {
Grid: SlickGrid
}
});
// shared across all grids on the page
var scrollbarDimensions;
var maxSupportedCssHeight; // browser's breaking point
// ////////////////////////////////////////////////////////////////////////////////////////////
// SlickGrid class implementation (available as Slick.Grid)
/**
* Creates a new instance of the grid.
* @class SlickGrid
* @constructor
* @param {Node} container Container node to create the grid in.
* @param {Array,Object} data An array of objects for databinding.
* @param {Array} columns An array of column definitions.
* @param {Object} options Grid options.
**/
function SlickGrid(container, data, columns, options) {
// settings
var defaults = {
explicitInitialization: false,
rowHeight: 25,
defaultColumnWidth: 80,
enableAddRow: false,
leaveSpaceForNewRows: false,
editable: false,
autoEdit: true,
enableCellNavigation: true,
enableColumnReorder: true,
asyncEditorLoading: false,
asyncEditorLoadDelay: 100,
forceFitColumns: false,
enableAsyncPostRender: false,
asyncPostRenderDelay: 50,
autoHeight: false,
editorLock: Slick.GlobalEditorLock,
showHeaderRow: false,
headerRowHeight: 25,
showTopPanel: false,
topPanelHeight: 25,
formatterFactory: null,
editorFactory: null,
cellFlashingCssClass: "flashing",
selectedCellCssClass: "selected",
multiSelect: true,
enableTextSelectionOnCells: false,
dataItemColumnValueExtractor: null,
frozenBottom: false,
frozenColumn: -1,
frozenRow: -1,
fullWidthRows: false,
multiColumnSort: false,
defaultFormatter: defaultFormatter,
forceSyncScrolling: false
};
var columnDefaults = {
name: "",
resizable: true,
sortable: false,
minWidth: 30,
rerenderOnResize: false,
headerCssClass: null,
defaultSortAsc: true,
focusable: true,
selectable: true
};
// scroller
var th; // virtual height
var h; // real scrollable height
var ph; // page height
var n; // number of pages
var cj; // "jumpiness" coefficient
var page = 0; // current page
var offset = 0; // current page offset
var vScrollDir = 1;
// private
var initialized = false;
var $container;
var uid = "slickgrid_" + Math.round(1000000 * Math.random());
var self = this;
var $focusSink, $focusSink2;
var $headerScroller;
var $headers;
var $headerRow, $headerRowScroller, $headerRowSpacerL, $headerRowSpacerR;
var $topPanelScroller;
var $topPanel;
var $viewport;
var $canvas;
var $style;
var $boundAncestors;
var stylesheet, columnCssRulesL, columnCssRulesR;
var viewportH, viewportW;
var canvasWidth, canvasWidthL, canvasWidthR;
var headersWidth, headersWidthL, headersWidthR;
var viewportHasHScroll, viewportHasVScroll;
var headerColumnWidthDiff = 0,
headerColumnHeightDiff = 0,
// border+padding
cellWidthDiff = 0,
cellHeightDiff = 0;
var absoluteColumnMinWidth;
var hasFrozenRows = false;
var frozenRowsHeight = 0;
var actualFrozenRow = -1;
var paneTopH = 0;
var paneBottomH = 0;
var viewportTopH = 0;
var viewportBottomH = 0;
var topPanelH = 0;
var headerRowH = 0;
var tabbingDirection = 1;
var $activeCanvasNode;
var $activeViewportNode;
var activePosX;
var activeRow, activeCell;
var activeCellNode = null;
var currentEditor = null;
var serializedEditorValue;
var editController;
var rowsCache = {};
var renderedRows = 0;
var numVisibleRows = 0;
var prevScrollTop = 0;
var scrollTop = 0;
var lastRenderedScrollTop = 0;
var lastRenderedScrollLeft = 0;
var prevScrollLeft = 0;
var scrollLeft = 0;
var selectionModel;
var selectedRows = [];
var plugins = [];
var cellCssClasses = {};
var columnsById = {};
var sortColumns = [];
var columnPosLeft = [];
var columnPosRight = [];
// async call handles
var h_editorLoader = null;
var h_render = null;
var h_postrender = null;
var postProcessedRows = {};
var postProcessToRow = null;
var postProcessFromRow = null;
// perf counters
var counter_rows_rendered = 0;
var counter_rows_removed = 0;
var $paneHeaderL;
var $paneHeaderR;
var $paneTopL;
var $paneTopR;
var $paneBottomL;
var $paneBottomR;
var $headerScrollerL;
var $headerScrollerR;
var $headerL;
var $headerR;
var $headerRowScrollerL;
var $headerRowScrollerR;
var $headerRowL;
var $headerRowR;
var $topPanelScrollerL;
var $topPanelScrollerR;
var $topPanelL;
var $topPanelR;
var $viewportTopL;
var $viewportTopR;
var $viewportBottomL;
var $viewportBottomR;
var $canvasTopL;
var $canvasTopR;
var $canvasBottomL;
var $canvasBottomR;
var $viewportScrollContainerX;
var $viewportScrollContainerY;
var $headerScrollContainer;
var $headerRowScrollContainer;
// ////////////////////////////////////////////////////////////////////////////////////////////
// Initialization
function init() {
$container = $(container);
if ($container.length < 1) {
throw new Error("SlickGrid requires a valid container, " + container + " does not exist in the DOM.");
}
// calculate these only once and share between grid instances
maxSupportedCssHeight = maxSupportedCssHeight || getMaxSupportedCssHeight();
scrollbarDimensions = scrollbarDimensions || measureScrollbar();
options = $.extend({}, defaults, options);
validateAndEnforceOptions();
columnDefaults.width = options.defaultColumnWidth;
columnsById = {};
for (var i = 0; i < columns.length; i++) {
var m = columns[i] = $.extend({}, columnDefaults, columns[i]);
columnsById[m.id] = i;
if (m.minWidth && m.width < m.minWidth) {
m.width = m.minWidth;
}
if (m.maxWidth && m.width > m.maxWidth) {
m.width = m.maxWidth;
}
}
// validate loaded JavaScript modules against requested options
if (options.enableColumnReorder && !$.fn.sortable) {
throw new Error("SlickGrid's 'enableColumnReorder = true' option requires jquery-ui.sortable module to be loaded");
}
editController = {
"commitCurrentEdit": commitCurrentEdit,
"cancelCurrentEdit": cancelCurrentEdit
};
$container
.empty()
.css("overflow", "hidden")
.css("outline", 0)
.addClass(uid)
.addClass("ui-widget");
// set up a positioning container if needed
if (!/relative|absolute|fixed/.test($container.css("position"))) {
$container.css("position", "relative");
}
$focusSink = $("<div tabIndex='0' hideFocus style='position:fixed;width:0;height:0;top:0;left:0;outline:0;'></div>").appendTo($container);
// Containers used for scrolling frozen columns and rows
$paneHeaderL = $("<div class='slick-pane slick-pane-header slick-pane-left' tabIndex='0' />").appendTo($container);
$paneHeaderR = $("<div class='slick-pane slick-pane-header slick-pane-right' tabIndex='0' />").appendTo($container);
$paneTopL = $("<div class='slick-pane slick-pane-top slick-pane-left' tabIndex='0' />").appendTo($container);
$paneTopR = $("<div class='slick-pane slick-pane-top slick-pane-right' tabIndex='0' />").appendTo($container);
$paneBottomL = $("<div class='slick-pane slick-pane-bottom slick-pane-left' tabIndex='0' />").appendTo($container);
$paneBottomR = $("<div class='slick-pane slick-pane-bottom slick-pane-right' tabIndex='0' />").appendTo($container);
// Append the header scroller containers
$headerScrollerL = $("<div class='ui-state-default slick-header slick-header-left' />").appendTo($paneHeaderL);
$headerScrollerR = $("<div class='ui-state-default slick-header slick-header-right' />").appendTo($paneHeaderR);
// Cache the header scroller containers
$headerScroller = $().add($headerScrollerL).add($headerScrollerR);
// Append the columnn containers to the headers
$headerL = $("<div class='slick-header-columns slick-header-columns-left' style='left:-1000px' />").appendTo($headerScrollerL);
$headerR = $("<div class='slick-header-columns slick-header-columns-right' style='left:-1000px' />").appendTo($headerScrollerR);
// Cache the header columns
$headers = $().add($headerL).add($headerR);
$headerRowScrollerL = $("<div class='ui-state-default slick-headerrow' />").appendTo($paneTopL);
$headerRowScrollerR = $("<div class='ui-state-default slick-headerrow' />").appendTo($paneTopR);
$headerRowScroller = $().add($headerRowScrollerL).add($headerRowScrollerR);
$headerRowSpacerL = $("<div style='display:block;height:1px;position:absolute;top:0;left:0;'></div>")
.css("width", getCanvasWidth() + scrollbarDimensions.width + "px")
.appendTo($headerRowScrollerL);
$headerRowSpacerR = $("<div style='display:block;height:1px;position:absolute;top:0;left:0;'></div>")
.css("width", getCanvasWidth() + scrollbarDimensions.width + "px")
.appendTo($headerRowScrollerR);
$headerRowL = $("<div class='slick-headerrow-columns slick-headerrow-columns-left' />").appendTo($headerRowScrollerL);
$headerRowR = $("<div class='slick-headerrow-columns slick-headerrow-columns-right' />").appendTo($headerRowScrollerR);
$headerRow = $().add($headerRowL).add($headerRowR);
// Append the top panel scroller
$topPanelScrollerL = $("<div class='ui-state-default slick-top-panel-scroller' />").appendTo($paneTopL);
$topPanelScrollerR = $("<div class='ui-state-default slick-top-panel-scroller' />").appendTo($paneTopR);
$topPanelScroller = $().add($topPanelScrollerL).add($topPanelScrollerR);
// Append the top panel
$topPanelL = $("<div class='slick-top-panel' style='width:10000px' />").appendTo($topPanelScrollerL);
$topPanelR = $("<div class='slick-top-panel' style='width:10000px' />").appendTo($topPanelScrollerR);
$topPanel = $().add($topPanelL).add($topPanelR);
if (!options.showTopPanel) {
$topPanelScroller.hide();
}
if (!options.showHeaderRow) {
$headerRowScroller.hide();
}
// Append the viewport containers
$viewportTopL = $("<div class='slick-viewport slick-viewport-top slick-viewport-left' tabIndex='0' hideFocus />").appendTo($paneTopL);
$viewportTopR = $("<div class='slick-viewport slick-viewport-top slick-viewport-right' tabIndex='0' hideFocus />").appendTo($paneTopR);
$viewportBottomL = $("<div class='slick-viewport slick-viewport-bottom slick-viewport-left' tabIndex='0' hideFocus />").appendTo($paneBottomL);
$viewportBottomR = $("<div class='slick-viewport slick-viewport-bottom slick-viewport-right' tabIndex='0' hideFocus />").appendTo($paneBottomR);
// Cache the viewports
$viewport = $().add($viewportTopL).add($viewportTopR).add($viewportBottomL).add($viewportBottomR);
// Default the active viewport to the top left
$activeViewportNode = $viewportTopL;
// Append the canvas containers
$canvasTopL = $("<div class='grid-canvas grid-canvas-top grid-canvas-left' tabIndex='0' hideFocus />").appendTo($viewportTopL);
$canvasTopR = $("<div class='grid-canvas grid-canvas-top grid-canvas-right' tabIndex='0' hideFocus />").appendTo($viewportTopR);
$canvasBottomL = $("<div class='grid-canvas grid-canvas-bottom grid-canvas-left' tabIndex='0' hideFocus />").appendTo($viewportBottomL);
$canvasBottomR = $("<div class='grid-canvas grid-canvas-bottom grid-canvas-right' tabIndex='0' hideFocus />").appendTo($viewportBottomR);
// Cache the canvases
$canvas = $().add($canvasTopL).add($canvasTopR).add($canvasBottomL).add($canvasBottomR);
// Default the active canvas to the top left
$activeCanvasNode = $canvasTopL;
$focusSink2 = $focusSink.clone().appendTo($container);
if (!options.explicitInitialization) {
finishInitialization();
}
}
function finishInitialization() {
if (!initialized) {
initialized = true;
getViewportWidth();
getViewportHeight();
// header columns and cells may have different padding/border
// skewing width calculations (box-sizing, hello?)
// calculate the diff so we can set consistent sizes
measureCellPaddingAndBorder();
// for usability reasons, all text selection in SlickGrid is
// disabled with the exception of input and textarea elements (selection
// must be enabled there so that editors work as expected); note that
// selection in grid cells (grid body) is already unavailable in
// all browsers except IE
disableSelection($headers); // disable all text selection in header (including input and textarea)
if (!options.enableTextSelectionOnCells) {
// disable text selection in grid cells except in input and textarea elements
// (this is IE-specific, because selectstart event will only fire in IE)
$viewport.bind("selectstart.ui", function (event) {
return $(event.target).is("input,textarea");
});
}
setFrozenOptions();
setPaneVisibility();
setScroller();
setOverflow();
updateColumnCaches();
createColumnHeaders();
setupColumnSort();
createCssRules();
resizeCanvas();
bindAncestorScrollEvents();
$container
.bind("resize.slickgrid", resizeCanvas);
$viewport
//.bind("click", handleClick)
.bind("scroll", handleScroll);
if (jQuery.fn.mousewheel && ( options.frozenColumn > -1 || hasFrozenRows )) {
$viewport
.bind("mousewheel", handleMouseWheel);
}
$headerScroller
.bind("contextmenu", handleHeaderContextMenu)
.bind("click", handleHeaderClick)
.delegate(".slick-header-column", "mouseenter", handleHeaderMouseEnter)
.delegate(".slick-header-column", "mouseleave", handleHeaderMouseLeave);
$headerRowScroller
.bind("scroll", handleHeaderRowScroll);
$focusSink.add($focusSink2)
.bind("keydown", handleKeyDown);
$canvas
.bind("keydown", handleKeyDown)
.bind("click", handleClick)
.bind("dblclick", handleDblClick)
.bind("contextmenu", handleContextMenu)
.bind("draginit", handleDragInit)
.bind("dragstart", {distance: 3}, handleDragStart)
.bind("drag", handleDrag)
.bind("dragend", handleDragEnd)
.delegate(".slick-cell", "mouseenter", handleMouseEnter)
.delegate(".slick-cell", "mouseleave", handleMouseLeave);
}
}
function registerPlugin(plugin) {
plugins.unshift(plugin);
plugin.init(self);
}
function unregisterPlugin(plugin) {
for (var i = plugins.length; i >= 0; i--) {
if (plugins[i] === plugin) {
if (plugins[i].destroy) {
plugins[i].destroy();
}
plugins.splice(i, 1);
break;
}
}
}
function setSelectionModel(model) {
if (selectionModel) {
selectionModel.onSelectedRangesChanged.unsubscribe(handleSelectedRangesChanged);
if (selectionModel.destroy) {
selectionModel.destroy();
}
}
selectionModel = model;
if (selectionModel) {
selectionModel.init(self);
selectionModel.onSelectedRangesChanged.subscribe(handleSelectedRangesChanged);
}
}
function getSelectionModel() {
return selectionModel;
}
function getCanvasNode() {
return $canvas[0];
}
function getActiveCanvasNode(element) {
setActiveCanvasNode(element);
return $activeCanvasNode[0];
}
function getCanvases() {
return $canvas;
}
function setActiveCanvasNode(element) {
if (element) {
$activeCanvasNode = $(element.target).closest('.grid-canvas');
}
}
function getViewportNode() {
return $viewport[0];
}
function getActiveViewportNode(element) {
setActiveViewPortNode(element);
return $activeViewportNode[0];
}
function setActiveViewportNode(element) {
if (element) {
$activeViewportNode = $(element.target).closest('.slick-viewport');
}
}
function measureScrollbar() {
var $c = $("<div style='position:absolute; top:-10000px; left:-10000px; width:100px; height:100px; overflow:scroll;'></div>").appendTo("body");
var dim = {
width: $c.width() - $c[0].clientWidth,
height: $c.height() - $c[0].clientHeight
};
$c.remove();
return dim;
}
function getHeadersWidth() {
headersWidth = headersWidthL = headersWidthR = 0;
for (var i = 0, ii = columns.length; i < ii; i++) {
var width = columns[ i ].width;
if (( options.frozenColumn ) > -1 && ( i > options.frozenColumn )) {
headersWidthR += width;
} else {
headersWidthL += width;
}
}
if (options.frozenColumn > -1) {
headersWidthL = headersWidthL + 1000;
headersWidthR = Math.max(headersWidthR, viewportW) + headersWidthL;
headersWidthR += scrollbarDimensions.width;
} else {
headersWidthL += scrollbarDimensions.width;
headersWidthL = Math.max(headersWidthL, viewportW) + 1000;
}
headersWidth = headersWidthL + headersWidthR;
}
function getCanvasWidth() {
var availableWidth = viewportHasVScroll ? viewportW - scrollbarDimensions.width : viewportW;
var i = columns.length;
canvasWidthL = canvasWidthR = 0;
while (i--) {
if ((options.frozenColumn > -1) && (i > options.frozenColumn)) {
canvasWidthR += columns[i].width;
} else {
canvasWidthL += columns[i].width;
}
}
var totalRowWidth = canvasWidthL + canvasWidthR;
return options.fullWidthRows ? Math.max(totalRowWidth, availableWidth) : totalRowWidth;
}
function updateCanvasWidth(forceColumnWidthsUpdate) {
var oldCanvasWidth = canvasWidth;
var oldCanvasWidthL = canvasWidthL;
var oldCanvasWidthR = canvasWidthR;
var widthChanged;
canvasWidth = getCanvasWidth();
widthChanged = canvasWidth !== oldCanvasWidth || canvasWidthL !== oldCanvasWidthL || canvasWidthR !== oldCanvasWidthR;
if (widthChanged || options.frozenColumn > -1 || hasFrozenRows) {
$canvasTopL.width(canvasWidthL);
getHeadersWidth();
$headerL.width(headersWidthL);
$headerR.width(headersWidthR);
if (options.frozenColumn > -1) {
$canvasTopR.width(canvasWidthR);
$paneHeaderL.width(canvasWidthL);
$paneHeaderR.css('left', canvasWidthL);
$paneHeaderR.css('width', viewportW - canvasWidthL);
$paneTopL.width(canvasWidthL);
$paneTopR.css('left', canvasWidthL);
$paneTopR.css('width', viewportW - canvasWidthL);
$headerRowScrollerL.width(canvasWidthL);
$headerRowScrollerR.width(viewportW - canvasWidthL);
$headerRowL.width(canvasWidthL);
$headerRowR.width(canvasWidthR);
$viewportTopL.width(canvasWidthL);
$viewportTopR.width(viewportW - canvasWidthL);
if (hasFrozenRows) {
$paneBottomL.width(canvasWidthL);
$paneBottomR.css('left', canvasWidthL);
$viewportBottomL.width(canvasWidthL);
$viewportBottomR.width(viewportW - canvasWidthL);
$canvasBottomL.width(canvasWidthL);
$canvasBottomR.width(canvasWidthR);
}
} else {
$paneHeaderL.width('100%');
$paneTopL.width('100%');
$headerRowScrollerL.width('100%');
$headerRowL.width(canvasWidth);
$viewportTopL.width('100%');
if (hasFrozenRows) {
$viewportBottomL.width('100%');
$canvasBottomL.width(canvasWidthL);
}
}
viewportHasHScroll = (canvasWidth > viewportW - scrollbarDimensions.width);
}
$headerRowSpacerL.width(canvasWidth + (viewportHasVScroll ? scrollbarDimensions.width : 0));
$headerRowSpacerR.width(canvasWidth + (viewportHasVScroll ? scrollbarDimensions.width : 0));
if (widthChanged || forceColumnWidthsUpdate) {
applyColumnWidths();
}
}
function disableSelection($target) {
if ($target && $target.jquery) {
$target.attr("unselectable", "on").css("MozUserSelect", "none").bind("selectstart.ui", function () {
return false;
}); // from jquery:ui.core.js 1.7.2
}
}
function getMaxSupportedCssHeight() {
var supportedHeight = 1000000;
// FF reports the height back but still renders blank after ~6M px
var testUpTo = navigator.userAgent.toLowerCase().match(/firefox/) ? 6000000 : 1000000000;
var div = $("<div style='display:none' />").appendTo(document.body);
while (true) {
var test = supportedHeight * 2;
div.css("height", test);
if (test > testUpTo || div.height() !== test) {
break;
} else {
supportedHeight = test;
}
}
div.remove();
return supportedHeight;
}
// TODO: this is static. need to handle page mutation.
function bindAncestorScrollEvents() {
var elem = (hasFrozenRows && !options.frozenBottom) ? $canvasBottomL[0] : $canvasTopL[0];
while ((elem = elem.parentNode) != document.body && elem != null) {
// bind to scroll containers only
if (elem == $viewportTopL[0] || elem.scrollWidth != elem.clientWidth || elem.scrollHeight != elem.clientHeight) {
var $elem = $(elem);
if (!$boundAncestors) {
$boundAncestors = $elem;
} else {
$boundAncestors = $boundAncestors.add($elem);
}
$elem.bind("scroll." + uid, handleActiveCellPositionChange);
}
}
}
function unbindAncestorScrollEvents() {
if (!$boundAncestors) {
return;
}
$boundAncestors.unbind("scroll." + uid);
$boundAncestors = null;
}
function updateColumnHeader(columnId, title, toolTip) {
if (!initialized) {
return;
}
var idx = getColumnIndex(columnId);
if (idx == null) {
return;
}
var columnDef = columns[idx];
var $header = $headers.children().eq(idx);
if ($header) {
if (title !== undefined) {
columns[idx].name = title;
}
if (toolTip !== undefined) {
columns[idx].toolTip = toolTip;
}
trigger(self.onBeforeHeaderCellDestroy, {
"node": $header[0],
"column": columnDef
});
$header.attr("title", toolTip || "").children().eq(0).html(title);
trigger(self.onHeaderCellRendered, {
"node": $header[0],
"column": columnDef
});
}
}
function getHeaderRow() {
return (options.frozenColumn > -1) ? $headerRow : $headerRow[0];
}
function getHeaderRowColumn(columnId) {
var idx = getColumnIndex(columnId);
var $headerRowTarget;
if (options.frozenColumn > -1) {
if (idx <= options.frozenColumn) {
$headerRowTarget = $headerRowL;
} else {
$headerRowTarget = $headerRowR;
idx -= options.frozenColumn + 1;
}
} else {
$headerRowTarget = $headerRowL;
}
var $header = $headerRowTarget.children().eq(idx);
return $header && $header[0];
}
function createColumnHeaders() {
function onMouseEnter() {
$(this).addClass("ui-state-hover");
}
function onMouseLeave() {
$(this).removeClass("ui-state-hover");
}
$headers.find(".slick-header-column")
.each(function () {
var columnDef = $(this).data("column");
if (columnDef) {
trigger(self.onBeforeHeaderCellDestroy, {
"node": this,
"column": columnDef
});
}
});
$headerL.empty();
$headerR.empty();
getHeadersWidth();
$headerL.width(headersWidthL);
$headerR.width(headersWidthR);
$headerRow.find(".slick-headerrow-column")
.each(function () {
var columnDef = $(this).data("column");
if (columnDef) {
trigger(self.onBeforeHeaderRowCellDestroy, {
"node": this,
"column": columnDef
});
}
});
$headerRowL.empty();
$headerRowR.empty();
for (var i = 0; i < columns.length; i++) {
var m = columns[i];
var $headerTarget = (options.frozenColumn > -1) ? ((i <= options.frozenColumn) ? $headerL : $headerR) : $headerL;
var $headerRowTarget = (options.frozenColumn > -1) ? ((i <= options.frozenColumn) ? $headerRowL : $headerRowR) : $headerRowL;
var header = $("<div class='ui-state-default slick-header-column' />")
.html("<span class='slick-column-name'>" + m.name + "</span>")
.width(m.width - headerColumnWidthDiff)
.attr("id", "" + uid + m.id)
.attr("title", m.toolTip || "")
.data("column", m)
.addClass(m.headerCssClass || "")
.appendTo($headerTarget);
if (options.enableColumnReorder || m.sortable) {
header
.on('mouseenter', onMouseEnter)
.on('mouseleave', onMouseLeave);
}
if (m.sortable) {
header.addClass("slick-header-sortable");
header.append("<span class='slick-sort-indicator' />");
}
trigger(self.onHeaderCellRendered, {
"node": header[0],
"column": m
});
if (options.showHeaderRow) {
var headerRowCell = $("<div class='ui-state-default slick-headerrow-column l" + i + " r" + i + "'></div>")
.data("column", m)
.appendTo($headerRowTarget);
trigger(self.onHeaderRowCellRendered, {
"node": headerRowCell[0],
"column": m
});
}
}
setSortColumns(sortColumns);
setupColumnResize();
if (options.enableColumnReorder) {
setupColumnReorder();
}
}
function setupColumnSort() {
$headers.click(function (e) {
// temporary workaround for a bug in jQuery 1.7.1
// (http://bugs.jquery.com/ticket/11328)
e.metaKey = e.metaKey || e.ctrlKey;
if ($(e.target).hasClass("slick-resizable-handle")) {
return;
}
var $col = $(e.target).closest(".slick-header-column");
if (!$col.length) {
return;
}
var column = $col.data("column");
if (column.sortable) {
if (!getEditorLock().commitCurrentEdit()) {
return;
}
var sortOpts = null;
var i = 0;
for (; i < sortColumns.length; i++) {
if (sortColumns[i].columnId == column.id) {
sortOpts = sortColumns[i];
sortOpts.sortAsc = !sortOpts.sortAsc;
break;
}
}
if (e.metaKey && options.multiColumnSort) {
if (sortOpts) {
sortColumns.splice(i, 1);
}
} else {
if ((!e.shiftKey && !e.metaKey) || !options.multiColumnSort) {
sortColumns = [];
}
if (!sortOpts) {
sortOpts = {
columnId: column.id,
sortAsc: true
};
sortColumns.push(sortOpts);
} else if (sortColumns.length == 0) {
sortColumns.push(sortOpts);
}
}
setSortColumns(sortColumns);
if (!options.multiColumnSort) {
trigger(self.onSort, {
multiColumnSort: false,
sortCol: column,
sortAsc: sortOpts.sortAsc
}, e);
} else {
trigger(
self.onSort, {
multiColumnSort: true,
sortCols: $.map(
sortColumns, function (col) {
return {
sortCol: columns[getColumnIndex(col.columnId)],
sortAsc: col.sortAsc
};
})
}, e);
}
}
});
}
function setupColumnReorder() {
$headers.filter(":ui-sortable").sortable("destroy");
var columnScrollTimer = null;
function scrollColumnsRight() {
$viewportScrollContainerX[0].scrollLeft = $viewportScrollContainerX[0].scrollLeft + 10;
}
function scrollColumnsLeft() {
$viewportScrollContainerX[0].scrollLeft = $viewportScrollContainerX[0].scrollLeft - 10;
}
$headers.sortable({
containment: "parent",
distance: 3,
axis: "x",
cursor: "default",
tolerance: "intersection",
helper: "clone",
placeholder: "slick-sortable-placeholder ui-state-default slick-header-column",
start: function (e, ui) {
ui.placeholder.width(ui.helper.outerWidth() - headerColumnWidthDiff);
$(ui.helper).addClass("slick-header-column-active");
},
beforeStop: function (e, ui) {
$(ui.helper).removeClass("slick-header-column-active");
},
sort: function (e, ui) {
if (e.originalEvent.pageX > $container[0].clientWidth) {
if (!(columnScrollTimer)) {
columnScrollTimer = setInterval(
scrollColumnsRight, 100);
}
} else if (e.originalEvent.pageX < $viewportScrollContainerX.offset().left) {
if (!(columnScrollTimer)) {
columnScrollTimer = setInterval(
scrollColumnsLeft, 100);
}
} else {
clearInterval(columnScrollTimer);
columnScrollTimer = null;
}
},
stop: function (e) {
clearInterval(columnScrollTimer);
columnScrollTimer = null;
if (!getEditorLock().commitCurrentEdit()) {
$(this).sortable("cancel");
return;
}
var reorderedIds = $headerL.sortable("toArray");
reorderedIds = reorderedIds.concat($headerR.sortable("toArray"));
var reorderedColumns = [];
for (var i = 0; i < reorderedIds.length; i++) {
reorderedColumns.push(columns[getColumnIndex(reorderedIds[i].replace(uid, ""))]);
}
setColumns(reorderedColumns);
trigger(self.onColumnsReordered, {});
e.stopPropagation();
setupColumnResize();
}
});
}
function setupColumnResize() {
var $col, j, c, pageX, columnElements, minPageX, maxPageX, firstResizable, lastResizable;
columnElements = $headers.children();
columnElements.find(".slick-resizable-handle").remove();
columnElements.each(function (i, e) {
if (columns[i].resizable) {
if (firstResizable === undefined) {
firstResizable = i;
}
lastResizable = i;
}
});
if (firstResizable === undefined) {
return;
}
columnElements.each(function (i, e) {
if (i < firstResizable || (options.forceFitColumns && i >= lastResizable)) {
return;
}
$col = $(e);
$("<div class='slick-resizable-handle' />")
.appendTo(e)
.bind("dragstart",function (e, dd) {
if (!getEditorLock().commitCurrentEdit()) {
return false;
}
pageX = e.pageX;
$(this).parent().addClass("slick-header-column-active");
var shrinkLeewayOnRight = null,
stretchLeewayOnRight = null;
// lock each column's width option to current width
columnElements.each(function (i, e) {
columns[i].previousWidth = $(e).outerWidth();
});
if (options.forceFitColumns) {
shrinkLeewayOnRight = 0;
stretchLeewayOnRight = 0;
// colums on right affect maxPageX/minPageX
for (j = i + 1; j < columnElements.length; j++) {
c = columns[j];
if (c.resizable) {
if (stretchLeewayOnRight !== null) {
if (c.maxWidth) {
stretchLeewayOnRight += c.maxWidth - c.previousWidth;
} else {
stretchLeewayOnRight = null;
}
}
shrinkLeewayOnRight += c.previousWidth - Math.max(c.minWidth || 0, absoluteColumnMinWidth);
}
}
}
var shrinkLeewayOnLeft = 0,
stretchLeewayOnLeft = 0;
for (j = 0; j <= i; j++) {
// columns on left only affect minPageX
c = columns[j];
if (c.resizable) {
if (stretchLeewayOnLeft !== null) {
if (c.maxWidth) {
stretchLeewayOnLeft += c.maxWidth - c.previousWidth;
} else {
stretchLeewayOnLeft = null;
}
}
shrinkLeewayOnLeft += c.previousWidth - Math.max(c.minWidth || 0, absoluteColumnMinWidth);
}
}
if (shrinkLeewayOnRight === null) {
shrinkLeewayOnRight = 100000;
}
if (shrinkLeewayOnLeft === null) {
shrinkLeewayOnLeft = 100000;
}
if (stretchLeewayOnRight === null) {
stretchLeewayOnRight = 100000;
}
if (stretchLeewayOnLeft === null) {
stretchLeewayOnLeft = 100000;
}
maxPageX = pageX + Math.min(shrinkLeewayOnRight, stretchLeewayOnLeft);
minPageX = pageX - Math.min(shrinkLeewayOnLeft, stretchLeewayOnRight);
}).bind("drag",function (e, dd) {
var actualMinWidth, d = Math.min(maxPageX, Math.max(minPageX, e.pageX)) - pageX,
x;
if (d < 0) { // shrink column
x = d;
var newCanvasWidthL = 0, newCanvasWidthR = 0;
for (j = i; j >= 0; j--) {
c = columns[j];
if (c.resizable) {
actualMinWidth = Math.max(c.minWidth || 0, absoluteColumnMinWidth);
if (x && c.previousWidth + x < actualMinWidth) {
x += c.previousWidth - actualMinWidth;
c.width = actualMinWidth;
} else {
c.width = c.previousWidth + x;
x = 0;
}
}
}
for (k = 0; k <= i; k++) {
c = columns[k];
if ((options.frozenColumn > -1) && (k > options.frozenColumn)) {
newCanvasWidthR += c.width;
} else {
newCanvasWidthL += c.width;
}
}
if (options.forceFitColumns) {
x = -d;
for (j = i + 1; j < columnElements.length; j++) {
c = columns[j];
if (c.resizable) {
if (x && c.maxWidth && (c.maxWidth - c.previousWidth < x)) {
x -= c.maxWidth - c.previousWidth;
c.width = c.maxWidth;
} else {
c.width = c.previousWidth + x;
x = 0;
}
if ((options.frozenColumn > -1) && (j > options.frozenColumn)) {
newCanvasWidthR += c.width;
} else {
newCanvasWidthL += c.width;
}
}
}
} else {
for (j = i + 1; j < columnElements.length; j++) {
c = columns[j];
if ((options.frozenColumn > -1) && (j > options.frozenColumn)) {
newCanvasWidthR += c.width;
} else {
newCanvasWidthL += c.width;
}
}
}
} else { // stretch column
x = d;
var newCanvasWidthL = 0, newCanvasWidthR = 0;
for (j = i; j >= 0; j--) {
c = columns[j];
if (c.resizable) {
if (x && c.maxWidth && (c.maxWidth - c.previousWidth < x)) {
x -= c.maxWidth - c.previousWidth;
c.width = c.maxWidth;
} else {
c.width = c.previousWidth + x;
x = 0;
}
}
}
for (k = 0; k <= i; k++) {
c = columns[k];
if ((options.frozenColumn > -1) && (k > options.frozenColumn)) {
newCanvasWidthR += c.width;
} else {
newCanvasWidthL += c.width;
}
}
if (options.forceFitColumns) {
x = -d;
for (j = i + 1; j < columnElements.length; j++) {
c = columns[j];
if (c.resizable) {
actualMinWidth = Math.max(c.minWidth || 0, absoluteColumnMinWidth);
if (x && c.previousWidth + x < actualMinWidth) {
x += c.previousWidth - actualMinWidth;
c.width = actualMinWidth;
} else {
c.width = c.previousWidth + x;
x = 0;
}
if ((options.frozenColumn > -1) && (j > options.frozenColumn)) {
newCanvasWidthR += c.width;
} else {
newCanvasWidthL += c.width;
}
}
}
} else {
for (j = i + 1; j < columnElements.length; j++) {
c = columns[j];
if ((options.frozenColumn > -1) && (j > options.frozenColumn)) {
newCanvasWidthR += c.width;
} else {
newCanvasWidthL += c.width;
}
}
}
}
if (options.frozenColumn > -1 && newCanvasWidthL != canvasWidthL) {
$headerL.width(newCanvasWidthL + 1000);
$paneHeaderR.css('left', newCanvasWidthL);
}
applyColumnHeaderWidths();
if (options.syncColumnCellResize) {
updateCanvasWidth();
applyColumnWidths();
}
}).bind("dragend", function (e, dd) {
var newWidth;
$(this).parent().removeClass("slick-header-column-active");
for (j = 0; j < columnElements.length; j++) {
c = columns[j];
newWidth = $(columnElements[j]).outerWidth();
if (c.previousWidth !== newWidth && c.rerenderOnResize) {
invalidateAllRows();
}
}
updateCanvasWidth(true);
render();
trigger(self.onColumnsResized, {});
});
});
}
function getVBoxDelta($el) {
var p = ["borderTopWidth", "borderBottomWidth", "paddingTop", "paddingBottom"];
var delta = 0;
$.each(p, function (n, val) {
delta += parseFloat($el.css(val)) || 0;
});
return delta;
}
function setFrozenOptions() {
options.frozenColumn = ( options.frozenColumn >= 0
&& options.frozenColumn < columns.length
)
? parseInt(options.frozenColumn)
: -1;
options.frozenRow = ( options.frozenRow >= 0
&& options.frozenRow < numVisibleRows
)
? parseInt(options.frozenRow)
: -1;
if (options.frozenRow > -1) {
hasFrozenRows = true;
frozenRowsHeight = ( options.frozenRow ) * options.rowHeight;
var dataLength = getDataLength() || this.data.length;
actualFrozenRow = ( options.frozenBottom )
? ( dataLength - options.frozenRow )
: options.frozenRow;
} else {
hasFrozenRows = false;
}
}
function setPaneVisibility() {
if (options.frozenColumn > -1) {
$paneHeaderR.show();
$paneTopR.show();
if (hasFrozenRows) {
$paneBottomL.show();
$paneBottomR.show();
} else {
$paneBottomR.hide();
$paneBottomL.hide();
}
} else {
$paneHeaderR.hide();
$paneTopR.hide();
$paneBottomR.hide();
if (hasFrozenRows) {
$paneBottomL.show();
} else {
$paneBottomR.hide();
$paneBottomL.hide();
}
}
}
function setOverflow() {
$viewportTopL.css({
'overflow-x': ( options.frozenColumn > -1 ) ? ( hasFrozenRows ) ? 'hidden' : 'scroll' : ( hasFrozenRows ) ? 'hidden' : 'auto',
'overflow-y': ( options.frozenColumn > -1 ) ? ( hasFrozenRows ) ? 'hidden' : 'hidden' : ( hasFrozenRows ) ? 'scroll' : 'auto'
});
$viewportTopR.css({
'overflow-x': ( options.frozenColumn > -1 ) ? ( hasFrozenRows ) ? 'hidden' : 'scroll' : ( hasFrozenRows ) ? 'hidden' : 'auto',
'overflow-y': ( options.frozenColumn > -1 ) ? ( hasFrozenRows ) ? 'scroll' : 'auto' : ( hasFrozenRows ) ? 'scroll' : 'auto'
});
$viewportBottomL.css({
'overflow-x': ( options.frozenColumn > -1 ) ? ( hasFrozenRows ) ? 'scroll' : 'auto' : ( hasFrozenRows ) ? 'auto' : 'auto',
'overflow-y': ( options.frozenColumn > -1 ) ? ( hasFrozenRows ) ? 'hidden' : 'hidden' : ( hasFrozenRows ) ? 'scroll' : 'auto'
});
$viewportBottomR.css({
'overflow-x': ( options.frozenColumn > -1 ) ? ( hasFrozenRows ) ? 'scroll' : 'auto' : ( hasFrozenRows ) ? 'auto' : 'auto',
'overflow-y': ( options.frozenColumn > -1 ) ? ( hasFrozenRows ) ? 'auto' : 'auto' : ( hasFrozenRows ) ? 'auto' : 'auto'
});
}
function setScroller() {
if (options.frozenColumn > -1) {
$headerScrollContainer = $headerScrollerR;
$headerRowScrollContainer = $headerRowScrollerR;
if (hasFrozenRows) {
if (options.frozenBottom) {
$viewportScrollContainerX = $viewportBottomR;
$viewportScrollContainerY = $viewportTopR;
} else {
$viewportScrollContainerX = $viewportScrollContainerY = $viewportBottomR;
}
} else {
$viewportScrollContainerX = $viewportScrollContainerY = $viewportTopR;
}
} else {
$headerScrollContainer = $headerScrollerL;
$headerRowScrollContainer = $headerRowScrollerL;
if (hasFrozenRows) {
if (options.frozenBottom) {
$viewportScrollContainerX = $viewportBottomL;
$viewportScrollContainerY = $viewportTopL;
} else {
$viewportScrollContainerX = $viewportScrollContainerY = $viewportBottomL;
}
} else {
$viewportScrollContainerX = $viewportScrollContainerY = $viewportTopL;
}
}
}
function measureCellPaddingAndBorder() {
var el;
var h = ["borderLeftWidth", "borderRightWidth", "paddingLeft", "paddingRight"];
var v = ["borderTopWidth", "borderBottomWidth", "paddingTop", "paddingBottom"];
el = $("<div class='ui-state-default slick-header-column' style='visibility:hidden'>-</div>").appendTo($headers);
headerColumnWidthDiff = headerColumnHeightDiff = 0;
if (el.css("box-sizing") != "border-box" && el.css("-moz-box-sizing") != "border-box" && el.css("-webkit-box-sizing") != "border-box") {
$.each(h, function (n, val) {
headerColumnWidthDiff += parseFloat(el.css(val)) || 0;
});
$.each(v, function (n, val) {
headerColumnHeightDiff += parseFloat(el.css(val)) || 0;
});
}
el.remove();
var r = $("<div class='slick-row' />").appendTo($canvas);
el = $("<div class='slick-cell' id='' style='visibility:hidden'>-</div>").appendTo(r);
cellWidthDiff = cellHeightDiff = 0;
if (el.css("box-sizing") != "border-box" && el.css("-moz-box-sizing") != "border-box" && el.css("-webkit-box-sizing") != "border-box") {
$.each(h, function (n, val) {
cellWidthDiff += parseFloat(el.css(val)) || 0;
});
$.each(v, function (n, val) {
cellHeightDiff += parseFloat(el.css(val)) || 0;
});
}
r.remove();
absoluteColumnMinWidth = Math.max(headerColumnWidthDiff, cellWidthDiff);
}
function createCssRules() {
$style = $("<style type='text/css' rel='stylesheet' />").appendTo($("head"));
var rowHeight = (options.rowHeight - cellHeightDiff);
var rules = [
"." + uid + " .slick-header-column { left: 1000px; }",
"." + uid + " .slick-top-panel { height:" + options.topPanelHeight + "px; }",
"." + uid + " .slick-headerrow-columns { height:" + options.headerRowHeight + "px; }",
"." + uid + " .slick-cell { height:" + rowHeight + "px; }",
"." + uid + " .slick-row { height:" + options.rowHeight + "px; }"
];
for (var i = 0; i < columns.length; i++) {
rules.push("." + uid + " .l" + i + " { }");
rules.push("." + uid + " .r" + i + " { }");
}
if ($style[0].styleSheet) { // IE
$style[0].styleSheet.cssText = rules.join(" ");
} else {
$style[0].appendChild(document.createTextNode(rules.join(" ")));
}
}
function getColumnCssRules(idx) {
if (!stylesheet) {
var sheets = document.styleSheets;
for (var i = 0; i < sheets.length; i++) {
if ((sheets[i].ownerNode || sheets[i].owningElement) == $style[0]) {
stylesheet = sheets[i];
break;
}
}
if (!stylesheet) {
throw new Error("Cannot find stylesheet.");
}
// find and cache column CSS rules
columnCssRulesL = [];
columnCssRulesR = [];
var cssRules = (stylesheet.cssRules || stylesheet.rules);
var matches, columnIdx;
for (var i = 0; i < cssRules.length; i++) {
var selector = cssRules[i].selectorText;
if (matches = /\.l\d+/.exec(selector)) {
columnIdx = parseInt(matches[0].substr(2, matches[0].length - 2), 10);
columnCssRulesL[columnIdx] = cssRules[i];
} else if (matches = /\.r\d+/.exec(selector)) {
columnIdx = parseInt(matches[0].substr(2, matches[0].length - 2), 10);
columnCssRulesR[columnIdx] = cssRules[i];
}
}
}
return {
"left": columnCssRulesL[idx],
"right": columnCssRulesR[idx]
};
}
function removeCssRules() {
$style.remove();
stylesheet = null;
}
function destroy() {
getEditorLock().cancelCurrentEdit();
trigger(self.onBeforeDestroy, {});
var i = plugins.length;
while (i--) {
unregisterPlugin(plugins[i]);
}
if (options.enableColumnReorder) {
$headers.filter(":ui-sortable").sortable("destroy");
}
unbindAncestorScrollEvents();
$container.unbind(".slickgrid");
removeCssRules();
$canvas.unbind("draginit dragstart dragend drag");
$container.empty().removeClass(uid);
}
// ////////////////////////////////////////////////////////////////////////////////////////////
// General
function trigger(evt, args, e) {
e = e || new Slick.EventData();
args = args || {};
args.grid = self;
return evt.notify(args, e, self);
}
function getEditorLock() {
return options.editorLock;
}
function getEditController() {
return editController;
}
function getColumnIndex(id) {
return columnsById[id];
}
function autosizeColumns() {
var i, c, widths = [],
shrinkLeeway = 0,
total = 0,
prevTotal, availWidth = viewportHasVScroll ? viewportW - scrollbarDimensions.width : viewportW;
for (i = 0; i < columns.length; i++) {
c = columns[i];
widths.push(c.width);
total += c.width;
if (c.resizable) {
shrinkLeeway += c.width - Math.max(c.minWidth, absoluteColumnMinWidth);
}
}
// shrink
prevTotal = total;
while (total > availWidth && shrinkLeeway) {
var shrinkProportion = (total - availWidth) / shrinkLeeway;
for (i = 0; i < columns.length && total > availWidth; i++) {
c = columns[i];
var width = widths[i];
if (!c.resizable || width <= c.minWidth || width <= absoluteColumnMinWidth) {
continue;
}
var absMinWidth = Math.max(c.minWidth, absoluteColumnMinWidth);
var shrinkSize = Math.floor(shrinkProportion * (width - absMinWidth)) || 1;
shrinkSize = Math.min(shrinkSize, width - absMinWidth);
total -= shrinkSize;
shrinkLeeway -= shrinkSize;
widths[i] -= shrinkSize;
}
if (prevTotal == total) { // avoid infinite loop
break;
}
prevTotal = total;
}
// grow
prevTotal = total;
while (total < availWidth) {
var growProportion = availWidth / total;
for (i = 0; i < columns.length && total < availWidth; i++) {
c = columns[i];
if (!c.resizable || c.maxWidth <= c.width) {
continue;
}
var growSize = Math.min(Math.floor(growProportion * c.width) - c.width, (c.maxWidth - c.width) || 1000000) || 1;
total += growSize;
widths[i] += growSize;
}
if (prevTotal == total) { // avoid infinite loop
break;
}
prevTotal = total;
}
var reRender = false;
for (i = 0; i < columns.length; i++) {
if (columns[i].rerenderOnResize && columns[i].width != widths[i]) {
reRender = true;
}
columns[i].width = widths[i];
}
applyColumnHeaderWidths();
updateCanvasWidth(true);
if (reRender) {
invalidateAllRows();
render();
}
}
function applyColumnHeaderWidths() {
if (!initialized) {
return;
}
var h;
for (var i = 0, headers = $headers.children(), ii = headers.length; i < ii; i++) {
h = $(headers[i]);
if (h.width() !== columns[i].width - headerColumnWidthDiff) {
h.width(columns[i].width - headerColumnWidthDiff);
}
}
updateColumnCaches();
}
function applyColumnWidths() {
var x = 0,
w, rule;
for (var i = 0; i < columns.length; i++) {
w = columns[i].width;
rule = getColumnCssRules(i);
rule.left.style.left = x + "px";
rule.right.style.right = (((options.frozenColumn != -1 && i > options.frozenColumn) ? canvasWidthR : canvasWidthL) - x - w) + "px";
// If this column is frozen, reset the css left value since the
// column starts in a new viewport.
if (options.frozenColumn == i) {
x = 0;
} else {
x += columns[i].width;
}
}
}
function setSortColumn(columnId, ascending) {
setSortColumns([
{
columnId: columnId,
sortAsc: ascending
}
]);
}
function setSortColumns(cols) {
sortColumns = cols;
var headerColumnEls = $headers.children();
headerColumnEls.removeClass("slick-header-column-sorted").find(".slick-sort-indicator").removeClass("slick-sort-indicator-asc slick-sort-indicator-desc");
$.each(sortColumns, function (i, col) {
if (col.sortAsc == null) {
col.sortAsc = true;
}
var columnIndex = getColumnIndex(col.columnId);
if (columnIndex != null) {
headerColumnEls.eq(columnIndex).addClass("slick-header-column-sorted").find(".slick-sort-indicator").addClass(
col.sortAsc ? "slick-sort-indicator-asc" : "slick-sort-indicator-desc");
}
});
}
function getSortColumns() {
return sortColumns;
}
function handleSelectedRangesChanged(e, ranges) {
selectedRows = [];
var hash = {};
for (var i = 0; i < ranges.length; i++) {
for (var j = ranges[i].fromRow; j <= ranges[i].toRow; j++) {
if (!hash[j]) { // prevent duplicates
selectedRows.push(j);
hash[j] = {};
}
for (var k = ranges[i].fromCell; k <= ranges[i].toCell; k++) {
if (canCellBeSelected(j, k)) {
hash[j][columns[k].id] = options.selectedCellCssClass;
}
}
}
}
setCellCssStyles(options.selectedCellCssClass, hash);
trigger(self.onSelectedRowsChanged, {
rows: getSelectedRows()
}, e);
}
function getColumns() {
return columns;
}
function updateColumnCaches() {
// Pre-calculate cell boundaries.
columnPosLeft = [];
columnPosRight = [];
var x = 0;
for (var i = 0, ii = columns.length; i < ii; i++) {
columnPosLeft[i] = x;
columnPosRight[i] = x + columns[i].width;
if (options.frozenColumn == i) {
x = 0;
} else {
x += columns[i].width;
}
}
}
function setColumns(columnDefinitions) {
columns = columnDefinitions;
columnsById = {};
for (var i = 0; i < columns.length; i++) {
var m = columns[i] = $.extend({}, columnDefaults, columns[i]);
columnsById[m.id] = i;
if (m.minWidth && m.width < m.minWidth) {
m.width = m.minWidth;
}
if (m.maxWidth && m.width > m.maxWidth) {
m.width = m.maxWidth;
}
}
updateColumnCaches();
if (initialized) {
setPaneVisibility();
setOverflow();
invalidateAllRows();
createColumnHeaders();
removeCssRules();
createCssRules();
resizeCanvas();
updateCanvasWidth();
applyColumnWidths();
handleScroll();
}
}
function getOptions() {
return options;
}
function setOptions(args) {
if (!getEditorLock().commitCurrentEdit()) {
return;
}
makeActiveCellNormal();
if (options.enableAddRow !== args.enableAddRow) {
invalidateRow(getDataLength());
}
options = $.extend(options, args);
validateAndEnforceOptions();
setFrozenOptions();
setScroller();
setColumns(columns); // TODO: Is this necessary?
render();
}
function validateAndEnforceOptions() {
if (options.autoHeight) {
options.leaveSpaceForNewRows = false;
}
}
function setData(newData, scrollToTop) {
data = newData;
invalidateAllRows();
updateRowCount();
if (scrollToTop) {
scrollTo(0);
}
}
function getData() {
return data;
}
function getDataLength() {
if (data.getLength) {
return data.getLength();
} else {
return data.length;
}
}
function getDataLengthIncludingAddNew() {
return getDataLength() + (options.enableAddRow ? 1 : 0);
}
function getDataItem(i) {
if (data.getItem) {
return data.getItem(i);
} else {
return data[i];
}
}
function getTopPanel() {
return $topPanel[0];
}
function setTopPanelVisibility(visible) {
if (options.showTopPanel != visible) {
options.showTopPanel = visible;
if (visible) {
$topPanelScroller.slideDown("fast", resizeCanvas);
} else {
$topPanelScroller.slideUp("fast", resizeCanvas);
}
}
}
function setHeaderRowVisibility(visible) {
if (options.showHeaderRow != visible) {
options.showHeaderRow = visible;
if (visible) {
$headerRowScroller.slideDown("fast", resizeCanvas);
} else {
$headerRowScroller.slideUp("fast", resizeCanvas);
}
}
}
function getContainerNode() {
return $container.get(0);
}
// ////////////////////////////////////////////////////////////////////////////////////////////
// Rendering / Scrolling
function getRowTop(row) {
return options.rowHeight * row - offset;
}
function getRowFromPosition(y) {
return Math.floor((y + offset) / options.rowHeight);
}
function scrollTo(y) {
y = Math.max(y, 0);
y = Math.min(y, th - $viewportScrollContainerY.height() + ((viewportHasHScroll || options.frozenColumn > -1) ? scrollbarDimensions.height : 0));
var oldOffset = offset;
page = Math.min(n - 1, Math.floor(y / ph));
offset = Math.round(page * cj);
var newScrollTop = y - offset;
if (offset != oldOffset) {
var range = getVisibleRange(newScrollTop);
cleanupRows(range);
updateRowPositions();
}
if (prevScrollTop != newScrollTop) {
vScrollDir = (prevScrollTop + oldOffset < newScrollTop + offset) ? 1 : -1;
lastRenderedScrollTop = ( scrollTop = prevScrollTop = newScrollTop );
if (options.frozenColumn > -1) {
$viewportTopL[0].scrollTop = newScrollTop;
}
if (hasFrozenRows) {
$viewportBottomL[0].scrollTop = $viewportBottomR[0].scrollTop = newScrollTop;
}
$viewportScrollContainerY[0].scrollTop = newScrollTop;
trigger(self.onViewportChanged, {});
}
}
function defaultFormatter(row, cell, value, columnDef, dataContext) {
if (value == null) {
return "";
} else {
return (value + "").replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
}
}
function getFormatter(row, column) {
var rowMetadata = data.getItemMetadata && data.getItemMetadata(row);
// look up by id, then index
var columnOverrides = rowMetadata && rowMetadata.columns && (rowMetadata.columns[column.id] || rowMetadata.columns[getColumnIndex(column.id)]);
return (columnOverrides && columnOverrides.formatter) || (rowMetadata && rowMetadata.formatter) || column.formatter || (options.formatterFactory && options.formatterFactory.getFormatter(column)) || options.defaultFormatter;
}
function getEditor(row, cell) {
var column = columns[cell];
var rowMetadata = data.getItemMetadata && data.getItemMetadata(row);
var columnMetadata = rowMetadata && rowMetadata.columns;
if (columnMetadata && columnMetadata[column.id] && columnMetadata[column.id].editor !== undefined) {
return columnMetadata[column.id].editor;
}
if (columnMetadata && columnMetadata[cell] && columnMetadata[cell].editor !== undefined) {
return columnMetadata[cell].editor;
}
return column.editor || (options.editorFactory && options.editorFactory.getEditor(column));
}
function getDataItemValueForColumn(item, columnDef) {
if (options.dataItemColumnValueExtractor) {
return options.dataItemColumnValueExtractor(item, columnDef);
}
return item[columnDef.field];
}
function appendRowHtml(stringArrayL, stringArrayR, row, range, dataLength) {
var d = getDataItem(row);
var dataLoading = row < dataLength && !d;
var rowCss = "slick-row" +
(dataLoading ? " loading" : "") +
(row === activeRow ? " active" : "") +
(row % 2 == 1 ? " odd" : " even");
var metadata = data.getItemMetadata && data.getItemMetadata(row);
if (metadata && metadata.cssClasses) {
rowCss += " " + metadata.cssClasses;
}
var frozenRowOffset = getFrozenRowOffset(row);
var rowHtml = "<div class='ui-widget-content " + rowCss + "' style='top:"
+ (getRowTop(row) - frozenRowOffset )
+ "px'>";
stringArrayL.push(rowHtml);
if (options.frozenColumn > -1) {
stringArrayR.push(rowHtml);
}
var colspan, m;
for (var i = 0, ii = columns.length; i < ii; i++) {
m = columns[i];
colspan = 1;
if (metadata && metadata.columns) {
var columnData = metadata.columns[m.id] || metadata.columns[i];
colspan = (columnData && columnData.colspan) || 1;
if (colspan === "*") {
colspan = ii - i;
}
}
// Do not render cells outside of the viewport.
if (columnPosRight[Math.min(ii - 1, i + colspan - 1)] > range.leftPx) {
if (columnPosLeft[i] > range.rightPx) {
// All columns to the right are outside the range.
break;
}
if (( options.frozenColumn > -1 ) && ( i > options.frozenColumn )) {
appendCellHtml(stringArrayR, row, i, colspan, d);
} else {
appendCellHtml(stringArrayL, row, i, colspan, d);
}
} else if (( options.frozenColumn > -1 ) && ( i <= options.frozenColumn )) {
appendCellHtml(stringArrayL, row, i, colspan, d);
}
if (colspan > 1) {
i += (colspan - 1);
}
}
stringArrayL.push("</div>");
if (options.frozenColumn > -1) {
stringArrayR.push("</div>");
}
}
function appendCellHtml(stringArray, row, cell, colspan, item) {
var m = columns[cell];
var cellCss = "slick-cell l" + cell + " r" + Math.min(columns.length - 1, cell + colspan - 1)
+ (m.cssClass ? " " + m.cssClass : "");
if (row === activeRow && cell === activeCell) {
cellCss += (" active");
}
// TODO: merge them together in the setter
for (var key in cellCssClasses) {
if (cellCssClasses[key][row] && cellCssClasses[key][row][m.id]) {
cellCss += (" " + cellCssClasses[key][row][m.id]);
}
}
stringArray.push("<div class='" + cellCss + "'>");
// if there is a corresponding row (if not, this is the Add New row or this data hasn't been loaded yet)
if (item) {
var value = getDataItemValueForColumn(item, m);
stringArray.push(getFormatter(row, m)(row, cell, value, m, item));
}
stringArray.push("</div>");
rowsCache[row].cellRenderQueue.push(cell);
rowsCache[row].cellColSpans[cell] = colspan;
}
function cleanupRows(rangeToKeep) {
for (var i in rowsCache) {
var removeFrozenRow = true;
if (hasFrozenRows
&& ( ( options.frozenBottom && i >= actualFrozenRow ) // Frozen bottom rows
|| ( !options.frozenBottom && i <= actualFrozenRow ) // Frozen top rows
)
) {
removeFrozenRow = false;
}
if (( ( i = parseInt(i, 10)) !== activeRow )
&& ( i < rangeToKeep.top || i > rangeToKeep.bottom )
&& ( removeFrozenRow )
) {
removeRowFromCache(i);
}
}
}
function invalidate() {
updateRowCount();
invalidateAllRows();
render();
}
function invalidateAllRows() {
if (currentEditor) {
makeActiveCellNormal();
}
for (var row in rowsCache) {
removeRowFromCache(row);
}
}
function removeRowFromCache(row) {
var cacheEntry = rowsCache[row];
if (!cacheEntry) {
return;
}
cacheEntry.rowNode[0].parentElement.removeChild(cacheEntry.rowNode[0]);
// Remove the row from the right viewport
if (cacheEntry.rowNode[1]) {
cacheEntry.rowNode[1].parentElement.removeChild(cacheEntry.rowNode[1]);
}
delete rowsCache[row];
delete postProcessedRows[row];
renderedRows--;
counter_rows_removed++;
}
function invalidateRows(rows) {
var i, rl;
if (!rows || !rows.length) {
return;
}
vScrollDir = 0;
for (i = 0, rl = rows.length; i < rl; i++) {
if (currentEditor && activeRow === rows[i]) {
makeActiveCellNormal();
}
if (rowsCache[rows[i]]) {
removeRowFromCache(rows[i]);
}
}
}
function invalidateRow(row) {
invalidateRows([row]);
}
function updateCell(row, cell) {
var cellNode = getCellNode(row, cell);
if (!cellNode) {
return;
}
var m = columns[cell],
d = getDataItem(row);
if (currentEditor && activeRow === row && activeCell === cell) {
currentEditor.loadValue(d);
} else {
cellNode.innerHTML = d ? getFormatter(row, m)(row, cell, getDataItemValueForColumn(d, m), m, d) : "";
invalidatePostProcessingResults(row);
}
}
function updateRow(row) {
var cacheEntry = rowsCache[row];
if (!cacheEntry) {
return;
}
ensureCellNodesInRowsCache(row);
var d = getDataItem(row);
for (var columnIdx in cacheEntry.cellNodesByColumnIdx) {
if (!cacheEntry.cellNodesByColumnIdx.hasOwnProperty(columnIdx)) {
continue;
}
columnIdx = columnIdx | 0;
var m = columns[columnIdx],
node = cacheEntry.cellNodesByColumnIdx[columnIdx][0];
if (row === activeRow && columnIdx === activeCell && currentEditor) {
currentEditor.loadValue(d);
} else if (d) {
node.innerHTML = getFormatter(row, m)(row, columnIdx, getDataItemValueForColumn(d, m), m, d);
} else {
node.innerHTML = "";
}
}
invalidatePostProcessingResults(row);
}
function getViewportHeight() {
if (options.autoHeight) {
viewportH = options.rowHeight
* getDataLengthIncludingAddNew()
+ ( ( options.frozenColumn == -1 ) ? $headers.outerHeight() : 0 );
} else {
topPanelH = ( options.showTopPanel )
? options.topPanelHeight + getVBoxDelta($topPanelScroller)
: 0;
headerRowH = ( options.showHeaderRow )
? options.headerRowHeight + getVBoxDelta($headerRowScroller)
: 0;
viewportH = parseFloat($.css($container[0], "height", true))
- parseFloat($.css($container[0], "paddingTop", true))
- parseFloat($.css($container[0], "paddingBottom", true))
- parseFloat($.css($headerScroller[0], "height"))
- getVBoxDelta($headerScroller)
- topPanelH
- headerRowH;
}
numVisibleRows = Math.ceil(viewportH / options.rowHeight);
}
function getViewportWidth() {
viewportW = parseFloat($.css($container[0], "width", true));
}
function resizeCanvas() {
if (!initialized) {
return;
}
paneTopH = 0
paneBottomH = 0
viewportTopH = 0
viewportBottomH = 0;
getViewportWidth();
getViewportHeight();
// Account for Frozen Rows
if (hasFrozenRows) {
if (options.frozenBottom) {
paneTopH = viewportH - frozenRowsHeight - scrollbarDimensions.height;
paneBottomH = frozenRowsHeight + scrollbarDimensions.height;
} else {
paneTopH = frozenRowsHeight;
paneBottomH = viewportH - frozenRowsHeight;
}
} else {
paneTopH = viewportH;
}
// The top pane includes the top panel and the header row
paneTopH += topPanelH + headerRowH;
if (options.frozenColumn > -1 && options.autoHeight) {
paneTopH += scrollbarDimensions.height;
}
// The top viewport does not contain the top panel or header row
viewportTopH = paneTopH - topPanelH - headerRowH
if (options.autoHeight) {
if (options.frozenColumn > -1) {
$container.height(
paneTopH
+ parseFloat($.css($headerScrollerL[0], "height"))
);
}
$paneTopL.css('position', 'relative');
}
$paneTopL.css({
'top': $paneHeaderL.height(), 'height': paneTopH
});
var paneBottomTop = $paneTopL.position().top
+ paneTopH;
$viewportTopL.height(viewportTopH);
if (options.frozenColumn > -1) {
$paneTopR.css({
'top': $paneHeaderL.height(), 'height': paneTopH
});
$viewportTopR.height(viewportTopH);
if (hasFrozenRows) {
$paneBottomL.css({
'top': paneBottomTop, 'height': paneBottomH
});
$paneBottomR.css({
'top': paneBottomTop, 'height': paneBottomH
});
$viewportBottomR.height(paneBottomH);
}
} else {
if (hasFrozenRows) {
$paneBottomL.css({
'width': '100%', 'height': paneBottomH
});
$paneBottomL.css('top', paneBottomTop);
}
}
if (hasFrozenRows) {
$viewportBottomL.height(paneBottomH);
if (options.frozenBottom) {
$canvasBottomL.height(frozenRowsHeight);
if (options.frozenColumn > -1) {
$canvasBottomR.height(frozenRowsHeight);
}
} else {
$canvasTopL.height(frozenRowsHeight);
if (options.frozenColumn > -1) {
$canvasTopR.height(frozenRowsHeight);
}
}
} else {
$viewportTopR.height(viewportTopH);
}
if (options.forceFitColumns) {
autosizeColumns();
}
updateRowCount();
handleScroll();
// Since the width has changed, force the render() to reevaluate virtually rendered cells.
lastRenderedScrollLeft = -1;
render();
}
function updateRowCount() {
if (!initialized) {
return;
}
var dataLengthIncludingAddNew = getDataLengthIncludingAddNew();
var numberOfRows = 0;
var oldH = ( hasFrozenRows && !options.frozenBottom ) ? $canvasBottomL.height() : $canvasTopL.height();
if (hasFrozenRows && options.frozenBottom) {
var numberOfRows = getDataLength() - options.frozenRow;
} else {
var numberOfRows = dataLengthIncludingAddNew + (options.leaveSpaceForNewRows ? numVisibleRows - 1 : 0);
}
var tempViewportH = $viewportScrollContainerY.height();
var oldViewportHasVScroll = viewportHasVScroll;
// with autoHeight, we do not need to accommodate the vertical scroll bar
viewportHasVScroll = !options.autoHeight && (numberOfRows * options.rowHeight > tempViewportH);
// remove the rows that are now outside of the data range
// this helps avoid redundant calls to .removeRow() when the size of
// the data decreased by thousands of rows
var l = dataLengthIncludingAddNew - 1;
for (var i in rowsCache) {
if (i >= l) {
removeRowFromCache(i);
}
}
th = Math.max(options.rowHeight * numberOfRows, tempViewportH - scrollbarDimensions.height);
if (activeCellNode && activeRow > l) {
resetActiveCell();
}
if (th < maxSupportedCssHeight) {
// just one page
h = ph = th;
n = 1;
cj = 0;
} else {
// break into pages
h = maxSupportedCssHeight;
ph = h / 100;
n = Math.floor(th / ph);
cj = (th - h) / (n - 1);
}
if (h !== oldH) {
if (hasFrozenRows && !options.frozenBottom) {
$canvasBottomL.css("height", h);
if (options.frozenColumn > -1) {
$canvasBottomR.css("height", h);
}
} else {
$canvasTopL.css("height", h);
$canvasTopR.css("height", h);
}
scrollTop = $viewportScrollContainerY[0].scrollTop;
}
var oldScrollTopInRange = (scrollTop + offset <= th - tempViewportH);
if (th == 0 || scrollTop == 0) {
page = offset = 0;
} else if (oldScrollTopInRange) {
// maintain virtual position
scrollTo(scrollTop + offset);
} else {
// scroll to bottom
scrollTo(th - tempViewportH);
}
if (h != oldH && options.autoHeight) {
resizeCanvas();
}
if (options.forceFitColumns && oldViewportHasVScroll != viewportHasVScroll) {
autosizeColumns();
}
updateCanvasWidth(false);
}
function getVisibleRange(viewportTop, viewportLeft) {
if (viewportTop == null) {
viewportTop = scrollTop;
}
if (viewportLeft == null) {
viewportLeft = scrollLeft;
}
return {
top: getRowFromPosition(viewportTop),
bottom: getRowFromPosition(viewportTop + viewportH) + 1,
leftPx: viewportLeft,
rightPx: viewportLeft + viewportW
};
}
function getRenderedRange(viewportTop, viewportLeft) {
var range = getVisibleRange(viewportTop, viewportLeft);
var buffer = Math.round(viewportH / options.rowHeight);
var minBuffer = 3;
if (vScrollDir == -1) {
range.top -= buffer;
range.bottom += minBuffer;
} else if (vScrollDir == 1) {
range.top -= minBuffer;
range.bottom += buffer;
} else {
range.top -= minBuffer;
range.bottom += minBuffer;
}
range.top = Math.max(0, range.top);
range.bottom = Math.min(getDataLengthIncludingAddNew() - 1, range.bottom);
range.leftPx -= viewportW;
range.rightPx += viewportW;
range.leftPx = Math.max(0, range.leftPx);
range.rightPx = Math.min(canvasWidth, range.rightPx);
return range;
}
function ensureCellNodesInRowsCache(row) {
var cacheEntry = rowsCache[row];
if (cacheEntry) {
if (cacheEntry.cellRenderQueue.length) {
var $lastNode = cacheEntry.rowNode.children().last();
while (cacheEntry.cellRenderQueue.length) {
var columnIdx = cacheEntry.cellRenderQueue.pop();
cacheEntry.cellNodesByColumnIdx[columnIdx] = $lastNode;
$lastNode = $lastNode.prev();
// Hack to retrieve the frozen columns because
if ($lastNode.length == 0) {
$lastNode = $(cacheEntry.rowNode[0]).children().last();
}
}
}
}
}
function cleanUpCells(range, row) {
// Ignore frozen rows
if (hasFrozenRows
&& ( ( options.frozenBottom && row > actualFrozenRow ) // Frozen bottom rows
|| ( row <= actualFrozenRow ) // Frozen top rows
)
) {
return;
}
var totalCellsRemoved = 0;
var cacheEntry = rowsCache[row];
// Remove cells outside the range.
var cellsToRemove = [];
for (var i in cacheEntry.cellNodesByColumnIdx) {
// I really hate it when people mess with Array.prototype.
if (!cacheEntry.cellNodesByColumnIdx.hasOwnProperty(i)) {
continue;
}
// This is a string, so it needs to be cast back to a number.
i = i | 0;
// Ignore frozen columns
if (i <= options.frozenColumn) {
continue;
}
var colspan = cacheEntry.cellColSpans[i];
if (columnPosLeft[i] > range.rightPx || columnPosRight[Math.min(columns.length - 1, i + colspan - 1)] < range.leftPx) {
if (!(row == activeRow && i == activeCell)) {
cellsToRemove.push(i);
}
}
}
var cellToRemove;
while ((cellToRemove = cellsToRemove.pop()) != null) {
cacheEntry.cellNodesByColumnIdx[cellToRemove][0].parentElement.removeChild(cacheEntry.cellNodesByColumnIdx[cellToRemove][0]);
delete cacheEntry.cellColSpans[cellToRemove];
delete cacheEntry.cellNodesByColumnIdx[cellToRemove];
if (postProcessedRows[row]) {
delete postProcessedRows[row][cellToRemove];
}
totalCellsRemoved++;
}
}
function cleanUpAndRenderCells(range) {
var cacheEntry;
var stringArray = [];
var processedRows = [];
var cellsAdded;
var totalCellsAdded = 0;
var colspan;
for (var row = range.top, btm = range.bottom; row <= btm; row++) {
cacheEntry = rowsCache[row];
if (!cacheEntry) {
continue;
}
// cellRenderQueue populated in renderRows() needs to be cleared first
ensureCellNodesInRowsCache(row);
cleanUpCells(range, row);
// Render missing cells.
cellsAdded = 0;
var metadata = data.getItemMetadata && data.getItemMetadata(row);
metadata = metadata && metadata.columns;
var d = getDataItem(row);
// TODO: shorten this loop (index? heuristics? binary search?)
for (var i = 0, ii = columns.length; i < ii; i++) {
// Cells to the right are outside the range.
if (columnPosLeft[i] > range.rightPx) {
break;
}
// Already rendered.
if ((colspan = cacheEntry.cellColSpans[i]) != null) {
i += (colspan > 1 ? colspan - 1 : 0);
continue;
}
colspan = 1;
if (metadata) {
var columnData = metadata[columns[i].id] || metadata[i];
colspan = (columnData && columnData.colspan) || 1;
if (colspan === "*") {
colspan = ii - i;
}
}
if (columnPosRight[Math.min(ii - 1, i + colspan - 1)] > range.leftPx) {
appendCellHtml(stringArray, row, i, colspan, d);
cellsAdded++;
}
i += (colspan > 1 ? colspan - 1 : 0);
}
if (cellsAdded) {
totalCellsAdded += cellsAdded;
processedRows.push(row);
}
}
if (!stringArray.length) {
return;
}
var x = document.createElement("div");
x.innerHTML = stringArray.join("");
var processedRow;
var $node;
while ((processedRow = processedRows.pop()) != null) {
cacheEntry = rowsCache[processedRow];
var columnIdx;
while ((columnIdx = cacheEntry.cellRenderQueue.pop()) != null) {
$node = $(x).children().last();
if (( options.frozenColumn > -1 ) && ( columnIdx > options.frozenColumn )) {
$(cacheEntry.rowNode[1]).append($node);
} else {
$(cacheEntry.rowNode[0]).append($node);
}
cacheEntry.cellNodesByColumnIdx[columnIdx] = $node;
}
}
}
function renderRows(range) {
var stringArrayL = [],
stringArrayR = [],
rows = [],
needToReselectCell = false,
dataLength = getDataLength();
for (var i = range.top, ii = range.bottom; i <= ii; i++) {
if (rowsCache[i] || ( hasFrozenRows && options.frozenBottom && i == getDataLength() )) {
continue;
}
renderedRows++;
rows.push(i);
// Create an entry right away so that appendRowHtml() can
// start populatating it.
rowsCache[i] = {
"rowNode": null,
// ColSpans of rendered cells (by column idx).
// Can also be used for checking whether a cell has been rendered.
"cellColSpans": [],
// Cell nodes (by column idx). Lazy-populated by ensureCellNodesInRowsCache().
"cellNodesByColumnIdx": [],
// Column indices of cell nodes that have been rendered, but not yet indexed in
// cellNodesByColumnIdx. These are in the same order as cell nodes added at the
// end of the row.
"cellRenderQueue": []
};
appendRowHtml(stringArrayL, stringArrayR, i, range, dataLength);
if (activeCellNode && activeRow === i) {
needToReselectCell = true;
}
counter_rows_rendered++;
}
if (!rows.length) {
return;
}
var x = document.createElement("div"),
xRight = document.createElement("div");
x.innerHTML = stringArrayL.join("");
xRight.innerHTML = stringArrayR.join("");
for (var i = 0, ii = rows.length; i < ii; i++) {
if (( hasFrozenRows ) && ( rows[i] >= actualFrozenRow )) {
if (options.frozenColumn > -1) {
rowsCache[rows[i]].rowNode = $()
.add($(x.firstChild).appendTo($canvasBottomL))
.add($(xRight.firstChild).appendTo($canvasBottomR));
} else {
rowsCache[rows[i]].rowNode = $()
.add($(x.firstChild).appendTo($canvasBottomL));
}
} else if (options.frozenColumn > -1) {
rowsCache[rows[i]].rowNode = $()
.add($(x.firstChild).appendTo($canvasTopL))
.add($(xRight.firstChild).appendTo($canvasTopR));
} else {
rowsCache[rows[i]].rowNode = $()
.add($(x.firstChild).appendTo($canvasTopL));
}
}
if (needToReselectCell) {
activeCellNode = getCellNode(activeRow, activeCell);
}
}
function startPostProcessing() {
if (!options.enableAsyncPostRender) {
return;
}
clearTimeout(h_postrender);
h_postrender = setTimeout(asyncPostProcessRows, options.asyncPostRenderDelay);
}
function invalidatePostProcessingResults(row) {
delete postProcessedRows[row];
postProcessFromRow = Math.min(postProcessFromRow, row);
postProcessToRow = Math.max(postProcessToRow, row);
startPostProcessing();
}
function updateRowPositions() {
for (var row in rowsCache) {
rowsCache[row].rowNode.css('top', getRowTop(row) + "px");
}
}
function render() {
if (!initialized) {
return;
}
var visible = getVisibleRange();
var rendered = getRenderedRange();
// remove rows no longer in the viewport
cleanupRows(rendered);
// add new rows & missing cells in existing rows
if (lastRenderedScrollLeft != scrollLeft) {
cleanUpAndRenderCells(rendered);
}
// render missing rows
renderRows(rendered);
// Render frozen bottom rows
if (options.frozenBottom) {
renderRows({
top: actualFrozenRow, bottom: getDataLength() - 1, leftPx: rendered.leftPx, rightPx: rendered.rightPx
});
}
postProcessFromRow = visible.top;
postProcessToRow = Math.min(getDataLengthIncludingAddNew() - 1, visible.bottom);
startPostProcessing();
lastRenderedScrollTop = scrollTop;
lastRenderedScrollLeft = scrollLeft;
h_render = null;
}
function handleHeaderRowScroll() {
var scrollLeft = $headerRowScrollContainer[0].scrollLeft;
if (scrollLeft != $viewportScrollContainerX[0].scrollLeft) {
$viewportScrollContainerX[0].scrollLeft = scrollLeft;
}
}
function handleMouseWheel(event, delta, deltaX, deltaY) {
scrollTop = Math.max(0, $viewportScrollContainerY[0].scrollTop - (deltaY * options.rowHeight));
scrollLeft = $viewportScrollContainerX[0].scrollLeft + (deltaX * 10);
_handleScroll(true);
event.preventDefault();
}
function handleScroll() {
scrollTop = $viewportScrollContainerY[0].scrollTop;
scrollLeft = $viewportScrollContainerX[0].scrollLeft;
_handleScroll(false);
}
function _handleScroll(isMouseWheel) {
var maxScrollDistanceY = $viewportScrollContainerY[0].scrollHeight - $viewportScrollContainerY[0].clientHeight;
var maxScrollDistanceX = $viewportScrollContainerY[0].scrollWidth - $viewportScrollContainerY[0].clientWidth;
// Ceiling the max scroll values
if (scrollTop > maxScrollDistanceY) {
scrollTop = maxScrollDistanceY;
}
if (scrollLeft > maxScrollDistanceX) {
scrollLeft = maxScrollDistanceX;
}
var vScrollDist = Math.abs(scrollTop - prevScrollTop);
var hScrollDist = Math.abs(scrollLeft - prevScrollLeft);
if (hScrollDist) {
prevScrollLeft = scrollLeft;
$viewportScrollContainerX[0].scrollLeft = scrollLeft;
$headerScrollContainer[0].scrollLeft = scrollLeft;
$topPanelScroller[0].scrollLeft = scrollLeft;
$headerRowScrollContainer[0].scrollLeft = scrollLeft;
if (options.frozenColumn > -1) {
if (hasFrozenRows) {
$viewportTopR[0].scrollLeft = scrollLeft;
}
} else {
if (hasFrozenRows) {
$viewportTopL[0].scrollLeft = scrollLeft;
}
}
}
if (vScrollDist) {
vScrollDir = prevScrollTop < scrollTop ? 1 : -1;
prevScrollTop = scrollTop
if (isMouseWheel) {
$viewportScrollContainerY[0].scrollTop = scrollTop;
}
if (options.frozenColumn > -1) {
if (hasFrozenRows && !options.frozenBottom) {
$viewportBottomL[0].scrollTop = scrollTop;
} else {
$viewportTopL[0].scrollTop = scrollTop;
}
}
// switch virtual pages if needed
if (vScrollDist < viewportH) {
scrollTo(scrollTop + offset);
} else {
var oldOffset = offset;
if (h == viewportH) {
page = 0;
} else {
page = Math.min(n - 1, Math.floor(scrollTop * ((th - viewportH) / (h - viewportH)) * (1 / ph)));
}
offset = Math.round(page * cj);
if (oldOffset != offset) {
invalidateAllRows();
}
}
}
if (hScrollDist || vScrollDist) {
if (h_render) {
clearTimeout(h_render);
}
if (Math.abs(lastRenderedScrollTop - scrollTop) > 20 ||
Math.abs(lastRenderedScrollLeft - scrollLeft) > 20) {
if (options.forceSyncScrolling || (
Math.abs(lastRenderedScrollTop - scrollTop) < viewportH &&
Math.abs(lastRenderedScrollLeft - scrollLeft) < viewportW)) {
render();
} else {
h_render = setTimeout(render, 50);
}
trigger(self.onViewportChanged, {});
}
}
trigger(self.onScroll, {
scrollLeft: scrollLeft,
scrollTop: scrollTop
});
}
function asyncPostProcessRows() {
var dataLength = getDataLength();
while (postProcessFromRow <= postProcessToRow) {
var row = (vScrollDir >= 0) ? postProcessFromRow++ : postProcessToRow--;
var cacheEntry = rowsCache[row];
if (!cacheEntry || row >= dataLength) {
continue;
}
if (!postProcessedRows[row]) {
postProcessedRows[row] = {};
}
ensureCellNodesInRowsCache(row);
for (var columnIdx in cacheEntry.cellNodesByColumnIdx) {
if (!cacheEntry.cellNodesByColumnIdx.hasOwnProperty(columnIdx)) {
continue;
}
columnIdx = columnIdx | 0;
var m = columns[columnIdx];
if (m.asyncPostRender && !postProcessedRows[row][columnIdx]) {
var node = cacheEntry.cellNodesByColumnIdx[columnIdx];
if (node) {
m.asyncPostRender(node, row, getDataItem(row), m);
}
postProcessedRows[row][columnIdx] = true;
}
}
h_postrender = setTimeout(asyncPostProcessRows, options.asyncPostRenderDelay);
return;
}
}
function updateCellCssStylesOnRenderedRows(addedHash, removedHash) {
var node, columnId, addedRowHash, removedRowHash;
for (var row in rowsCache) {
removedRowHash = removedHash && removedHash[row];
addedRowHash = addedHash && addedHash[row];
if (removedRowHash) {
for (columnId in removedRowHash) {
if (!addedRowHash || removedRowHash[columnId] != addedRowHash[columnId]) {
node = getCellNode(row, getColumnIndex(columnId));
if (node) {
$(node).removeClass(removedRowHash[columnId]);
}
}
}
}
if (addedRowHash) {
for (columnId in addedRowHash) {
if (!removedRowHash || removedRowHash[columnId] != addedRowHash[columnId]) {
node = getCellNode(row, getColumnIndex(columnId));
if (node) {
$(node).addClass(addedRowHash[columnId]);
}
}
}
}
}
}
function addCellCssStyles(key, hash) {
if (cellCssClasses[key]) {
throw "addCellCssStyles: cell CSS hash with key '" + key + "' already exists.";
}
cellCssClasses[key] = hash;
updateCellCssStylesOnRenderedRows(hash, null);
trigger(self.onCellCssStylesChanged, {
"key": key,
"hash": hash
});
}
function removeCellCssStyles(key) {
if (!cellCssClasses[key]) {
return;
}
updateCellCssStylesOnRenderedRows(null, cellCssClasses[key]);
delete cellCssClasses[key];
trigger(self.onCellCssStylesChanged, {
"key": key,
"hash": null
});
}
function setCellCssStyles(key, hash) {
var prevHash = cellCssClasses[key];
cellCssClasses[key] = hash;
updateCellCssStylesOnRenderedRows(hash, prevHash);
trigger(self.onCellCssStylesChanged, {
"key": key,
"hash": hash
});
}
function getCellCssStyles(key) {
return cellCssClasses[key];
}
function flashCell(row, cell, speed) {
speed = speed || 100;
if (rowsCache[row]) {
var $cell = $(getCellNode(row, cell));
function toggleCellClass(times) {
if (!times) {
return;
}
setTimeout(function () {
$cell.queue(function () {
$cell.toggleClass(options.cellFlashingCssClass).dequeue();
toggleCellClass(times - 1);
});
}, speed);
}
toggleCellClass(4);
}
}
// ////////////////////////////////////////////////////////////////////////////////////////////
// Interactivity
function handleDragInit(e, dd) {
var cell = getCellFromEvent(e);
if (!cell || !cellExists(cell.row, cell.cell)) {
return false;
}
var retval = trigger(self.onDragInit, dd, e);
if (e.isImmediatePropagationStopped()) {
return retval;
}
// if nobody claims to be handling drag'n'drop by stopping immediate
// propagation, cancel out of it
return false;
}
function handleDragStart(e, dd) {
var cell = getCellFromEvent(e);
if (!cell || !cellExists(cell.row, cell.cell)) {
return false;
}
var retval = trigger(self.onDragStart, dd, e);
if (e.isImmediatePropagationStopped()) {
return retval;
}
return false;
}
function handleDrag(e, dd) {
return trigger(self.onDrag, dd, e);
}
function handleDragEnd(e, dd) {
trigger(self.onDragEnd, dd, e);
}
function handleKeyDown(e) {
trigger(self.onKeyDown, {
row: activeRow,
cell: activeCell
}, e);
var handled = e.isImmediatePropagationStopped();
if (!handled) {
if (!e.shiftKey && !e.altKey && !e.ctrlKey) {
if (e.which == 27) {
if (!getEditorLock().isActive()) {
return; // no editing mode to cancel, allow bubbling and default processing (exit without cancelling the event)
}
cancelEditAndSetFocus();
} else if (e.which == 34) {
navigatePageDown();
handled = true;
} else if (e.which == 33) {
navigatePageUp();
handled = true;
} else if (e.which == 37) {
handled = navigateLeft();
} else if (e.which == 39) {
handled = navigateRight();
} else if (e.which == 38) {
handled = navigateUp();
} else if (e.which == 40) {
handled = navigateDown();
} else if (e.which == 9) {
handled = navigateNext();
} else if (e.which == 13) {
if (options.editable) {
if (currentEditor) {
// adding new row
if (activeRow === getDataLength()) {
navigateDown();
} else {
commitEditAndSetFocus();
}
} else {
if (getEditorLock().commitCurrentEdit()) {
makeActiveCellEditable();
}
}
}
handled = true;
}
} else if (e.which == 9 && e.shiftKey && !e.ctrlKey && !e.altKey) {
handled = navigatePrev();
}
}
if (handled) {
// the event has been handled so don't let parent element (bubbling/propagation) or browser (default) handle it
e.stopPropagation();
e.preventDefault();
try {
e.originalEvent.keyCode = 0; // prevent default behaviour for special keys in IE browsers (F3, F5, etc.)
}
// ignore exceptions - setting the original event's keycode throws
// access denied exception for "Ctrl" (hitting control key only, nothing else), "Shift" (maybe others)
catch (error) {
}
}
}
function handleClick(e) {
if (!currentEditor) {
// if this click resulted in some cell child node getting focus,
// don't steal it back - keyboard events will still bubble up
// IE9+ seems to default DIVs to tabIndex=0 instead of -1, so check for cell clicks directly.
if (e.target != document.activeElement || $(e.target).hasClass("slick-cell")) {
setFocus();
}
}
var cell = getCellFromEvent(e);
if (!cell || (currentEditor !== null && activeRow == cell.row && activeCell == cell.cell)) {
return;
}
trigger(self.onClick, {
row: cell.row,
cell: cell.cell
}, e);
if (e.isImmediatePropagationStopped()) {
return;
}
if ((activeCell != cell.cell || activeRow != cell.row) && canCellBeActive(cell.row, cell.cell)) {
if (!getEditorLock().isActive() || getEditorLock().commitCurrentEdit()) {
if (hasFrozenRows) {
if (( !( options.frozenBottom ) && ( cell.row >= actualFrozenRow ) )
|| ( options.frozenBottom && ( cell.row < actualFrozenRow ) )
) {
scrollRowIntoView(cell.row, false);
}
setActiveCellInternal(getCellNode(cell.row, cell.cell));
}
}
}
}
function handleContextMenu(e) {
var $cell = $(e.target).closest(".slick-cell", $canvas);
if ($cell.length === 0) {
return;
}
// are we editing this cell?
if (activeCellNode === $cell[0] && currentEditor !== null) {
return;
}
trigger(self.onContextMenu, {}, e);
}
function handleDblClick(e) {
var cell = getCellFromEvent(e);
if (!cell || (currentEditor !== null && activeRow == cell.row && activeCell == cell.cell)) {
return;
}
trigger(self.onDblClick, {
row: cell.row,
cell: cell.cell
}, e);
if (e.isImmediatePropagationStopped()) {
return;
}
if (options.editable) {
gotoCell(cell.row, cell.cell, true);
}
}
function handleHeaderMouseEnter(e) {
trigger(self.onHeaderMouseEnter, {
"column": $(this).data("column")
}, e);
}
function handleHeaderMouseLeave(e) {
trigger(self.onHeaderMouseLeave, {
"column": $(this).data("column")
}, e);
}
function handleHeaderContextMenu(e) {
var $header = $(e.target).closest(".slick-header-column", ".slick-header-columns");
var column = $header && $header.data("column");
trigger(self.onHeaderContextMenu, {
column: column
}, e);
}
function handleHeaderClick(e) {
var $header = $(e.target).closest(".slick-header-column", ".slick-header-columns");
var column = $header && $header.data("column");
if (column) {
trigger(self.onHeaderClick, {
column: column
}, e);
}
}
function handleMouseEnter(e) {
trigger(self.onMouseEnter, {}, e);
}
function handleMouseLeave(e) {
trigger(self.onMouseLeave, {}, e);
}
function cellExists(row, cell) {
return !(row < 0 || row >= getDataLength() || cell < 0 || cell >= columns.length);
}
function getCellFromPoint(x, y) {
var row = getRowFromPosition(y);
var cell = 0;
var w = 0;
for (var i = 0; i < columns.length && w < x; i++) {
w += columns[i].width;
cell++;
}
if (cell < 0) {
cell = 0;
}
return {
row: row,
cell: cell - 1
};
}
function getCellFromNode(cellNode) {
// read column number from .l<columnNumber> CSS class
var cls = /l\d+/.exec(cellNode.className);
if (!cls) {
throw "getCellFromNode: cannot get cell - " + cellNode.className;
}
return parseInt(cls[0].substr(1, cls[0].length - 1), 10);
}
function getRowFromNode(rowNode) {
for (var row in rowsCache) {
if (rowsCache[row].rowNode[0] === rowNode[0]) {
return row | 0;
}
}
return null;
}
function getFrozenRowOffset(row) {
var offset =
( hasFrozenRows )
? ( options.frozenBottom )
? ( row >= actualFrozenRow )
? ( h < viewportTopH )
? ( actualFrozenRow * options.rowHeight )
: h
: 0
: ( row >= actualFrozenRow )
? frozenRowsHeight
: 0
: 0;
return offset;
}
function getCellFromEvent(e) {
var $cell = $(e.target).closest(".slick-cell", $canvas);
if (!$cell.length) {
return null;
}
// TODO: This change eliminates the need for getCellFromEvent since
// we're ultimately calling getCellFromPoint. Need to further analyze
// if getCellFromEvent can work with frozen columns
var c = $cell.parents('.grid-canvas').offset();
var rowOffset = 0;
var isBottom = $cell.parents('.grid-canvas-bottom').length;
if (hasFrozenRows && isBottom) {
rowOffset = ( options.frozenBottom ) ? $canvasTopL.height() : frozenRowsHeight;
}
var row = getCellFromPoint(e.clientX - c.left, e.clientY - c.top + rowOffset + $(document).scrollTop()).row;
var cell = getCellFromNode($cell[0]);
if (row == null || cell == null) {
return null;
} else {
return {
"row": row,
"cell": cell
};
}
}
function getCellNodeBox(row, cell) {
if (!cellExists(row, cell)) {
return null;
}
var frozenRowOffset = getFrozenRowOffset(row);
var y1 = getRowTop(row) - frozenRowOffset;
var y2 = y1 + options.rowHeight - 1;
var x1 = 0;
for (var i = 0; i < cell; i++) {
x1 += columns[i].width;
if (options.frozenColumn == i) {
x1 = 0;
}
}
var x2 = x1 + columns[cell].width;
return {
top: y1,
left: x1,
bottom: y2,
right: x2
};
}
// ////////////////////////////////////////////////////////////////////////////////////////////
// Cell switching
function resetActiveCell() {
setActiveCellInternal(null, false);
}
function setFocus() {
if (tabbingDirection == -1) {
$focusSink[0].focus();
} else {
$focusSink2[0].focus();
}
}
function scrollCellIntoView(row, cell, doPaging) {
// Don't scroll to frozen cells
if (cell <= options.frozenColumn) {
return;
}
if (row < actualFrozenRow) {
scrollRowIntoView(row, doPaging);
}
var colspan = getColspan(row, cell);
var left = columnPosLeft[cell],
right = columnPosRight[cell + (colspan > 1 ? colspan - 1 : 0)],
scrollRight = scrollLeft + $viewportScrollContainerX.width();
if (left < scrollLeft) {
$viewportScrollContainerX.scrollLeft(left);
handleScroll();
render();
} else if (right > scrollRight) {
$viewportScrollContainerX.scrollLeft(Math.min(left, right - $viewportScrollContainerX[0].clientWidth));
handleScroll();
render();
}
}
function setActiveCellInternal(newCell, opt_editMode) {
if (activeCellNode !== null) {
makeActiveCellNormal();
$(activeCellNode).removeClass("active");
if (rowsCache[activeRow]) {
$(rowsCache[activeRow].rowNode).removeClass("active");
}
}
var activeCellChanged = (activeCellNode !== newCell);
activeCellNode = newCell;
if (activeCellNode != null) {
var $activeCellNode = $(activeCellNode);
var $activeCellOffset = $activeCellNode.offset();
var rowOffset = Math.floor($activeCellNode.parents('.grid-canvas').offset().top);
var isBottom = $activeCellNode.parents('.grid-canvas-bottom').length;
if (hasFrozenRows && isBottom) {
rowOffset -= ( options.frozenBottom )
? $canvasTopL.height()
: frozenRowsHeight;
}
cell = getCellFromPoint($activeCellOffset.left, Math.ceil($activeCellOffset.top) - rowOffset);
activeRow = cell.row;
activeCell = activePosX = activeCell = activePosX = getCellFromNode(activeCellNode[0]);
$activeCellNode.addClass("active");
if (rowsCache[activeRow]) {
$(rowsCache[activeRow].rowNode).addClass('active');
}
if (opt_editMode == null) {
opt_editMode = (activeRow == getDataLength()) || options.autoEdit;
}
if (options.editable && opt_editMode && isCellPotentiallyEditable(activeRow, activeCell)) {
clearTimeout(h_editorLoader);
if (options.asyncEditorLoading) {
h_editorLoader = setTimeout(function () {
makeActiveCellEditable();
}, options.asyncEditorLoadDelay);
} else {
makeActiveCellEditable();
}
}
} else {
activeRow = activeCell = null;
}
if (activeCellChanged) {
setTimeout(scrollActiveCellIntoView, 50);
trigger(self.onActiveCellChanged, getActiveCell());
}
}
function clearTextSelection() {
if (document.selection && document.selection.empty) {
try {
//IE fails here if selected element is not in dom
document.selection.empty();
} catch (e) {
}
} else if (window.getSelection) {
var sel = window.getSelection();
if (sel && sel.removeAllRanges) {
sel.removeAllRanges();
}
}
}
function isCellPotentiallyEditable(row, cell) {
var dataLength = getDataLength();
// is the data for this row loaded?
if (row < dataLength && !getDataItem(row)) {
return false;
}
// are we in the Add New row? can we create new from this cell?
if (columns[cell].cannotTriggerInsert && row >= dataLength) {
return false;
}
// does this cell have an editor?
if (!getEditor(row, cell)) {
return false;
}
return true;
}
function makeActiveCellNormal() {
if (!currentEditor) {
return;
}
trigger(self.onBeforeCellEditorDestroy, {
editor: currentEditor
});
currentEditor.destroy();
currentEditor = null;
if (activeCellNode) {
var d = getDataItem(activeRow);
$(activeCellNode).removeClass("editable invalid");
if (d) {
var column = columns[activeCell];
var formatter = getFormatter(activeRow, column);
activeCellNode[0].innerHTML = formatter(activeRow, activeCell, getDataItemValueForColumn(d, column), column, d);
invalidatePostProcessingResults(activeRow);
}
}
// if there previously was text selected on a page (such as selected
// text in the edit cell just removed),
// IE can't set focus to anything else correctly
if (navigator.userAgent.toLowerCase().match(/msie/)) {
clearTextSelection();
}
getEditorLock().deactivate(editController);
}
function makeActiveCellEditable(editor) {
if (!activeCellNode) {
return;
}
if (!options.editable) {
throw "Grid : makeActiveCellEditable : should never get called when options.editable is false";
}
// cancel pending async call if there is one
clearTimeout(h_editorLoader);
if (!isCellPotentiallyEditable(activeRow, activeCell)) {
return;
}
var columnDef = columns[activeCell];
var item = getDataItem(activeRow);
if (trigger(self.onBeforeEditCell, {
row: activeRow,
cell: activeCell,
item: item,
column: columnDef
}) === false) {
setFocus();
return;
}
getEditorLock().activate(editController);
$(activeCellNode).addClass("editable");
// don't clear the cell if a custom editor is passed through
if (!editor) {
activeCellNode[0].innerHTML = "";
}
currentEditor = new (editor || getEditor(activeRow, activeCell))({
grid: self,
gridPosition: absBox($container[0]),
position: absBox(activeCellNode[0]),
container: activeCellNode,
column: columnDef,
item: item || {},
commitChanges: commitEditAndSetFocus,
cancelChanges: cancelEditAndSetFocus
});
if (item) {
currentEditor.loadValue(item);
}
serializedEditorValue = currentEditor.serializeValue();
if (currentEditor.position) {
handleActiveCellPositionChange();
}
}
function commitEditAndSetFocus() {
// if the commit fails, it would do so due to a validation error
// if so, do not steal the focus from the editor
if (getEditorLock().commitCurrentEdit()) {
setFocus();
if (options.autoEdit) {
navigateDown();
}
}
}
function cancelEditAndSetFocus() {
if (getEditorLock().cancelCurrentEdit()) {
setFocus();
}
}
function absBox(elem) {
var box = {
top: elem.offsetTop,
left: elem.offsetLeft,
bottom: 0,
right: 0,
width: $(elem).outerWidth(),
height: $(elem).outerHeight(),
visible: true
};
box.bottom = box.top + box.height;
box.right = box.left + box.width;
// walk up the tree
var offsetParent = elem.offsetParent;
while ((elem = elem.parentNode) != document.body) {
if (box.visible && elem.scrollHeight != elem.offsetHeight && $(elem).css("overflowY") != "visible") {
box.visible = box.bottom > elem.scrollTop && box.top < elem.scrollTop + elem.clientHeight;
}
if (box.visible && elem.scrollWidth != elem.offsetWidth && $(elem).css("overflowX") != "visible") {
box.visible = box.right > elem.scrollLeft && box.left < elem.scrollLeft + elem.clientWidth;
}
box.left -= elem.scrollLeft;
box.top -= elem.scrollTop;
if (elem === offsetParent) {
box.left += elem.offsetLeft;
box.top += elem.offsetTop;
offsetParent = elem.offsetParent;
}
box.bottom = box.top + box.height;
box.right = box.left + box.width;
}
return box;
}
function getActiveCellPosition() {
return absBox(activeCellNode[0]);
}
function getGridPosition() {
return absBox($container[0]);
}
function handleActiveCellPositionChange() {
if (!activeCellNode) {
return;
}
trigger(self.onActiveCellPositionChanged, {});
if (currentEditor) {
var cellBox = getActiveCellPosition();
if (currentEditor.show && currentEditor.hide) {
if (!cellBox.visible) {
currentEditor.hide();
} else {
currentEditor.show();
}
}
if (currentEditor.position) {
currentEditor.position(cellBox);
}
}
}
function getCellEditor() {
return currentEditor;
}
function getActiveCell() {
if (!activeCellNode) {
return null;
} else {
return {
row: activeRow,
cell: activeCell
};
}
}
function getActiveCellNode() {
return activeCellNode;
}
function scrollActiveCellIntoView() {
if (activeRow != null && activeCell != null) {
scrollCellIntoView(activeRow, activeCell);
}
}
function scrollRowIntoView(row, doPaging) {
if (hasFrozenRows && !options.frozenBottom) {
row -= actualFrozenRow;
}
var viewportScrollH = $viewportScrollContainerY.height();
var rowAtTop = row * options.rowHeight;
var rowAtBottom = (row + 1) * options.rowHeight
- viewportScrollH
+ (viewportHasHScroll ? scrollbarDimensions.height : 0);
// need to page down?
if ((row + 1) * options.rowHeight > scrollTop + viewportScrollH + offset) {
scrollTo(doPaging ? rowAtTop : rowAtBottom);
render();
}
// or page up?
else if (row * options.rowHeight < scrollTop + offset) {
scrollTo(doPaging ? rowAtBottom : rowAtTop);
render();
}
}
function scrollRowToTop(row) {
scrollTo(row * options.rowHeight);
render();
}
function scrollPage(dir) {
var deltaRows = dir * numVisibleRows;
scrollTo((getRowFromPosition(scrollTop) + deltaRows) * options.rowHeight);
render();
if (options.enableCellNavigation && activeRow != null) {
var row = activeRow + deltaRows;
var dataLengthIncludingAddNew = getDataLengthIncludingAddNew();
if (row >= dataLengthIncludingAddNew) {
row = dataLengthIncludingAddNew - 1;
}
if (row < 0) {
row = 0;
}
var cell = 0, prevCell = null;
var prevActivePosX = activePosX;
while (cell <= activePosX) {
if (canCellBeActive(row, cell)) {
prevCell = cell;
}
cell += getColspan(row, cell);
}
if (prevCell !== null) {
setActiveCellInternal(getCellNode(row, prevCell));
activePosX = prevActivePosX;
} else {
resetActiveCell();
}
}
}
function navigatePageDown() {
scrollPage(1);
}
function navigatePageUp() {
scrollPage(-1);
}
function getColspan(row, cell) {
var metadata = data.getItemMetadata && data.getItemMetadata(row);
if (!metadata || !metadata.columns) {
return 1;
}
var columnData = metadata.columns[columns[cell].id] || metadata.columns[cell];
var colspan = (columnData && columnData.colspan);
if (colspan === "*") {
colspan = columns.length - cell;
} else {
colspan = colspan || 1;
}
return (colspan || 1);
}
function findFirstFocusableCell(row) {
var cell = 0;
while (cell < columns.length) {
if (canCellBeActive(row, cell)) {
return cell;
}
cell += getColspan(row, cell);
}
return null;
}
function findLastFocusableCell(row) {
var cell = 0;
var lastFocusableCell = null;
while (cell < columns.length) {
if (canCellBeActive(row, cell)) {
lastFocusableCell = cell;
}
cell += getColspan(row, cell);
}
return lastFocusableCell;
}
function gotoRight(row, cell, posX) {
if (cell >= columns.length) {
return null;
}
do {
cell += getColspan(row, cell);
} while (cell < columns.length && !canCellBeActive(row, cell));
if (cell < columns.length) {
return {
"row": row,
"cell": cell,
"posX": cell
};
}
return null;
}
function gotoLeft(row, cell, posX) {
if (cell <= 0) {
return null;
}
var firstFocusableCell = findFirstFocusableCell(row);
if (firstFocusableCell === null || firstFocusableCell >= cell) {
return null;
}
var prev = {
"row": row,
"cell": firstFocusableCell,
"posX": firstFocusableCell
};
var pos;
while (true) {
pos = gotoRight(prev.row, prev.cell, prev.posX);
if (!pos) {
return null;
}
if (pos.cell >= cell) {
return prev;
}
prev = pos;
}
}
function gotoDown(row, cell, posX) {
var prevCell;
var dataLengthIncludingAddNew = getDataLengthIncludingAddNew();
while (true) {
if (++row >= dataLengthIncludingAddNew) {
return null;
}
prevCell = cell = 0;
while (cell <= posX) {
prevCell = cell;
cell += getColspan(row, cell);
}
if (canCellBeActive(row, prevCell)) {
return {
"row": row,
"cell": prevCell,
"posX": posX
};
}
}
}
function gotoUp(row, cell, posX) {
var prevCell;
while (true) {
if (--row < 0) {
return null;
}
prevCell = cell = 0;
while (cell <= posX) {
prevCell = cell;
cell += getColspan(row, cell);
}
if (canCellBeActive(row, prevCell)) {
return {
"row": row,
"cell": prevCell,
"posX": posX
};
}
}
}
function gotoNext(row, cell, posX) {
if (row == null && cell == null) {
row = cell = posX = 0;
if (canCellBeActive(row, cell)) {
return {
"row": row,
"cell": cell,
"posX": cell
};
}
}
var pos = gotoRight(row, cell, posX);
if (pos) {
return pos;
}
var firstFocusableCell = null;
var dataLengthIncludingAddNew = getDataLengthIncludingAddNew();
while (++row < dataLengthIncludingAddNew) {
firstFocusableCell = findFirstFocusableCell(row);
if (firstFocusableCell !== null) {
return {
"row": row,
"cell": firstFocusableCell,
"posX": firstFocusableCell
};
}
}
return null;
}
function gotoPrev(row, cell, posX) {
if (row == null && cell == null) {
row = getDataLengthIncludingAddNew() - 1;
cell = posX = columns.length - 1;
if (canCellBeActive(row, cell)) {
return {
"row": row,
"cell": cell,
"posX": cell
};
}
}
var pos;
var lastSelectableCell;
while (!pos) {
pos = gotoLeft(row, cell, posX);
if (pos) {
break;
}
if (--row < 0) {
return null;
}
cell = 0;
lastSelectableCell = findLastFocusableCell(row);
if (lastSelectableCell !== null) {
pos = {
"row": row,
"cell": lastSelectableCell,
"posX": lastSelectableCell
};
}
}
return pos;
}
function navigateRight() {
return navigate("right");
}
function navigateLeft() {
return navigate("left");
}
function navigateDown() {
return navigate("down");
}
function navigateUp() {
return navigate("up");
}
function navigateNext() {
return navigate("next");
}
function navigatePrev() {
return navigate("prev");
}
/**
* @param {string} dir Navigation direction.
* @return {boolean} Whether navigation resulted in a change of active cell.
*/
function navigate(dir) {
if (!options.enableCellNavigation) {
return false;
}
if (!activeCellNode && dir != "prev" && dir != "next") {
return false;
}
if (!getEditorLock().commitCurrentEdit()) {
return true;
}
setFocus();
var tabbingDirections = {
"up": -1,
"down": 1,
"left": -1,
"right": 1,
"prev": -1,
"next": 1
};
tabbingDirection = tabbingDirections[dir];
var stepFunctions = {
"up": gotoUp,
"down": gotoDown,
"left": gotoLeft,
"right": gotoRight,
"prev": gotoPrev,
"next": gotoNext
};
var stepFn = stepFunctions[dir];
var pos = stepFn(activeRow, activeCell, activePosX);
if (pos) {
if (hasFrozenRows && options.frozenBottom & pos.row == getDataLength()) {
return;
}
var isAddNewRow = (pos.row == getDataLength());
if (( !options.frozenBottom && pos.row >= actualFrozenRow )
|| ( options.frozenBottom && pos.row < actualFrozenRow )
) {
scrollCellIntoView(pos.row, pos.cell, !isAddNewRow);
}
setActiveCellInternal(getCellNode(pos.row, pos.cell))
activePosX = pos.posX;
return true;
} else {
setActiveCellInternal(getCellNode(activeRow, activeCell));
return false;
}
}
function getCellNode(row, cell) {
if (rowsCache[row]) {
ensureCellNodesInRowsCache(row);
return rowsCache[row].cellNodesByColumnIdx[cell];
}
return null;
}
function setActiveCell(row, cell) {
if (!initialized) {
return;
}
if (row > getDataLength() || row < 0 || cell >= columns.length || cell < 0) {
return;
}
if (!options.enableCellNavigation) {
return;
}
scrollCellIntoView(row, cell, false);
setActiveCellInternal(getCellNode(row, cell), false);
}
function canCellBeActive(row, cell) {
if (!options.enableCellNavigation || row >= getDataLengthIncludingAddNew() ||
row < 0 || cell >= columns.length || cell < 0) {
return false;
}
var rowMetadata = data.getItemMetadata && data.getItemMetadata(row);
if (rowMetadata && typeof rowMetadata.focusable === "boolean") {
return rowMetadata.focusable;
}
var columnMetadata = rowMetadata && rowMetadata.columns;
if (columnMetadata && columnMetadata[columns[cell].id] && typeof columnMetadata[columns[cell].id].focusable === "boolean") {
return columnMetadata[columns[cell].id].focusable;
}
if (columnMetadata && columnMetadata[cell] && typeof columnMetadata[cell].focusable === "boolean") {
return columnMetadata[cell].focusable;
}
return columns[cell].focusable;
}
function canCellBeSelected(row, cell) {
if (row >= getDataLength() || row < 0 || cell >= columns.length || cell < 0) {
return false;
}
var rowMetadata = data.getItemMetadata && data.getItemMetadata(row);
if (rowMetadata && typeof rowMetadata.selectable === "boolean") {
return rowMetadata.selectable;
}
var columnMetadata = rowMetadata && rowMetadata.columns && (rowMetadata.columns[columns[cell].id] || rowMetadata.columns[cell]);
if (columnMetadata && typeof columnMetadata.selectable === "boolean") {
return columnMetadata.selectable;
}
return columns[cell].selectable;
}
function gotoCell(row, cell, forceEdit) {
if (!initialized) {
return;
}
if (!canCellBeActive(row, cell)) {
return;
}
if (!getEditorLock().commitCurrentEdit()) {
return;
}
scrollCellIntoView(row, cell, false);
var newCell = getCellNode(row, cell);
// if selecting the 'add new' row, start editing right away
setActiveCellInternal(newCell, forceEdit || (row === getDataLength()) || options.autoEdit);
// if no editor was created, set the focus back on the grid
if (!currentEditor) {
setFocus();
}
}
// ////////////////////////////////////////////////////////////////////////////////////////////
// IEditor implementation for the editor lock
function commitCurrentEdit() {
var item = getDataItem(activeRow);
var column = columns[activeCell];
if (currentEditor) {
if (currentEditor.isValueChanged()) {
var validationResults = currentEditor.validate();
if (validationResults.valid) {
if (activeRow < getDataLength()) {
var editCommand = {
row: activeRow,
cell: activeCell,
editor: currentEditor,
serializedValue: currentEditor.serializeValue(),
prevSerializedValue: serializedEditorValue,
execute: function () {
this.editor.applyValue(item, this.serializedValue);
updateRow(this.row);
},
undo: function () {
this.editor.applyValue(item, this.prevSerializedValue);
updateRow(this.row);
}
};
if (options.editCommandHandler) {
makeActiveCellNormal();
options.editCommandHandler(item, column, editCommand);
} else {
editCommand.execute();
makeActiveCellNormal();
}
trigger(self.onCellChange, {
row: activeRow,
cell: activeCell,
item: item
});
} else {
var newItem = {};
currentEditor.applyValue(newItem, currentEditor.serializeValue());
makeActiveCellNormal();
trigger(self.onAddNewRow, {
item: newItem,
column: column
});
}
// check whether the lock has been re-acquired by event handlers
return !getEditorLock().isActive();
} else {
// Re-add the CSS class to trigger transitions, if any.
$(activeCellNode).removeClass("invalid");
$(activeCellNode).width(); // force layout
$(activeCellNode).addClass("invalid");
trigger(self.onValidationError, {
editor: currentEditor,
cellNode: activeCellNode,
validationResults: validationResults,
row: activeRow,
cell: activeCell,
column: column
});
currentEditor.focus();
return false;
}
}
makeActiveCellNormal();
}
return true;
}
function cancelCurrentEdit() {
makeActiveCellNormal();
return true;
}
function rowsToRanges(rows) {
var ranges = [];
var lastCell = columns.length - 1;
for (var i = 0; i < rows.length; i++) {
ranges.push(new Slick.Range(rows[i], 0, rows[i], lastCell));
}
return ranges;
}
function getSelectedRows() {
if (!selectionModel) {
throw "Selection model is not set";
}
return selectedRows;
}
function setSelectedRows(rows) {
if (!selectionModel) {
throw "Selection model is not set";
}
selectionModel.setSelectedRanges(rowsToRanges(rows));
}
// ////////////////////////////////////////////////////////////////////////////////////////////
// Debug
this.debug = function () {
var s = "";
s += ("\n" + "counter_rows_rendered: " + counter_rows_rendered);
s += ("\n" + "counter_rows_removed: " + counter_rows_removed);
s += ("\n" + "renderedRows: " + renderedRows);
s += ("\n" + "numVisibleRows: " + numVisibleRows);
s += ("\n" + "maxSupportedCssHeight: " + maxSupportedCssHeight);
s += ("\n" + "n(umber of pages): " + n);
s += ("\n" + "(current) page: " + page);
s += ("\n" + "page height (ph): " + ph);
s += ("\n" + "vScrollDir: " + vScrollDir);
alert(s);
};
// a debug helper to be able to access private members
this.eval = function (expr) {
return eval(expr);
};
// ////////////////////////////////////////////////////////////////////////////////////////////
// Public API
$.extend(this, {
"slickGridVersion": "2.1",
// Events
"onScroll": new Slick.Event(),
"onSort": new Slick.Event(),
"onHeaderMouseEnter": new Slick.Event(),
"onHeaderMouseLeave": new Slick.Event(),
"onHeaderContextMenu": new Slick.Event(),
"onHeaderClick": new Slick.Event(),
"onHeaderCellRendered": new Slick.Event(),
"onBeforeHeaderCellDestroy": new Slick.Event(),
"onHeaderRowCellRendered": new Slick.Event(),
"onBeforeHeaderRowCellDestroy": new Slick.Event(),
"onMouseEnter": new Slick.Event(),
"onMouseLeave": new Slick.Event(),
"onClick": new Slick.Event(),
"onDblClick": new Slick.Event(),
"onContextMenu": new Slick.Event(),
"onKeyDown": new Slick.Event(),
"onAddNewRow": new Slick.Event(),
"onValidationError": new Slick.Event(),
"onViewportChanged": new Slick.Event(),
"onColumnsReordered": new Slick.Event(),
"onColumnsResized": new Slick.Event(),
"onCellChange": new Slick.Event(),
"onBeforeEditCell": new Slick.Event(),
"onBeforeCellEditorDestroy": new Slick.Event(),
"onBeforeDestroy": new Slick.Event(),
"onActiveCellChanged": new Slick.Event(),
"onActiveCellPositionChanged": new Slick.Event(),
"onDragInit": new Slick.Event(),
"onDragStart": new Slick.Event(),
"onDrag": new Slick.Event(),
"onDragEnd": new Slick.Event(),
"onSelectedRowsChanged": new Slick.Event(),
"onCellCssStylesChanged": new Slick.Event(),
// Methods
"registerPlugin": registerPlugin,
"unregisterPlugin": unregisterPlugin,
"getColumns": getColumns,
"setColumns": setColumns,
"getColumnIndex": getColumnIndex,
"updateColumnHeader": updateColumnHeader,
"setSortColumn": setSortColumn,
"setSortColumns": setSortColumns,
"getSortColumns": getSortColumns,
"autosizeColumns": autosizeColumns,
"getOptions": getOptions,
"setOptions": setOptions,
"getData": getData,
"getDataLength": getDataLength,
"getDataItem": getDataItem,
"setData": setData,
"getSelectionModel": getSelectionModel,
"setSelectionModel": setSelectionModel,
"getSelectedRows": getSelectedRows,
"setSelectedRows": setSelectedRows,
"getContainerNode": getContainerNode,
"render": render,
"invalidate": invalidate,
"invalidateRow": invalidateRow,
"invalidateRows": invalidateRows,
"invalidateAllRows": invalidateAllRows,
"updateCell": updateCell,
"updateRow": updateRow,
"getViewport": getVisibleRange,
"getRenderedRange": getRenderedRange,
"resizeCanvas": resizeCanvas,
"updateRowCount": updateRowCount,
"scrollRowIntoView": scrollRowIntoView,
"scrollRowToTop": scrollRowToTop,
"scrollCellIntoView": scrollCellIntoView,
"getCanvasNode": getCanvasNode,
"getCanvases": getCanvases,
"getActiveCanvasNode": getActiveCanvasNode,
"setActiveCanvasNode": setActiveCanvasNode,
"getViewportNode": getViewportNode,
"getActiveViewportNode": getActiveViewportNode,
"setActiveViewportNode": setActiveViewportNode,
"focus": setFocus,
"getCellFromPoint": getCellFromPoint,
"getCellFromEvent": getCellFromEvent,
"getActiveCell": getActiveCell,
"setActiveCell": setActiveCell,
"getActiveCellNode": getActiveCellNode,
"getActiveCellPosition": getActiveCellPosition,
"resetActiveCell": resetActiveCell,
"editActiveCell": makeActiveCellEditable,
"getCellEditor": getCellEditor,
"getCellNode": getCellNode,
"getCellNodeBox": getCellNodeBox,
"canCellBeSelected": canCellBeSelected,
"canCellBeActive": canCellBeActive,
"navigatePrev": navigatePrev,
"navigateNext": navigateNext,
"navigateUp": navigateUp,
"navigateDown": navigateDown,
"navigateLeft": navigateLeft,
"navigateRight": navigateRight,
"navigatePageUp": navigatePageUp,
"navigatePageDown": navigatePageDown,
"gotoCell": gotoCell,
"getTopPanel": getTopPanel,
"setTopPanelVisibility": setTopPanelVisibility,
"setHeaderRowVisibility": setHeaderRowVisibility,
"getHeaderRow": getHeaderRow,
"getHeaderRowColumn": getHeaderRowColumn,
"getGridPosition": getGridPosition,
"flashCell": flashCell,
"addCellCssStyles": addCellCssStyles,
"setCellCssStyles": setCellCssStyles,
"removeCellCssStyles": removeCellCssStyles,
"getCellCssStyles": getCellCssStyles,
"getFrozenRowOffset": getFrozenRowOffset,
"init": finishInitialization,
"destroy": destroy,
// IEditor implementation
"getEditorLock": getEditorLock,
"getEditController": getEditController
});
init();
}
}(jQuery));
| slick.grid.js | /**
* @license
* (c) 2009-2013 Michael Leibman
* michael{dot}leibman{at}gmail{dot}com
* http://github.com/mleibman/slickgrid
*
* Distributed under MIT license.
* All rights reserved.
*
* SlickGrid v2.2
*
* NOTES:
* Cell/row DOM manipulations are done directly bypassing jQuery's DOM manipulation methods.
* This increases the speed dramatically, but can only be done safely because there are no event handlers
* or data associated with any cell/row DOM nodes. Cell editors must make sure they implement .destroy()
* and do proper cleanup.
*
*/
// make sure required JavaScript modules are loaded
if (typeof jQuery === "undefined") {
throw "SlickGrid requires jquery module to be loaded";
}
if (!jQuery.fn.drag) {
throw "SlickGrid requires jquery.event.drag module to be loaded";
}
if (typeof Slick === "undefined") {
throw "slick.core.js not loaded";
}
(function ($) {
// Slick.Grid
$.extend(true, window, {
Slick: {
Grid: SlickGrid
}
});
// shared across all grids on the page
var scrollbarDimensions;
var maxSupportedCssHeight; // browser's breaking point
// ////////////////////////////////////////////////////////////////////////////////////////////
// SlickGrid class implementation (available as Slick.Grid)
/**
* Creates a new instance of the grid.
* @class SlickGrid
* @constructor
* @param {Node} container Container node to create the grid in.
* @param {Array,Object} data An array of objects for databinding.
* @param {Array} columns An array of column definitions.
* @param {Object} options Grid options.
**/
function SlickGrid(container, data, columns, options) {
// settings
var defaults = {
explicitInitialization: false,
rowHeight: 25,
defaultColumnWidth: 80,
enableAddRow: false,
leaveSpaceForNewRows: false,
editable: false,
autoEdit: true,
enableCellNavigation: true,
enableColumnReorder: true,
asyncEditorLoading: false,
asyncEditorLoadDelay: 100,
forceFitColumns: false,
enableAsyncPostRender: false,
asyncPostRenderDelay: 50,
autoHeight: false,
editorLock: Slick.GlobalEditorLock,
showHeaderRow: false,
headerRowHeight: 25,
showTopPanel: false,
topPanelHeight: 25,
formatterFactory: null,
editorFactory: null,
cellFlashingCssClass: "flashing",
selectedCellCssClass: "selected",
multiSelect: true,
enableTextSelectionOnCells: false,
dataItemColumnValueExtractor: null,
frozenBottom: false,
frozenColumn: -1,
frozenRow: -1,
fullWidthRows: false,
multiColumnSort: false,
defaultFormatter: defaultFormatter,
forceSyncScrolling: false
};
var columnDefaults = {
name: "",
resizable: true,
sortable: false,
minWidth: 30,
rerenderOnResize: false,
headerCssClass: null,
defaultSortAsc: true,
focusable: true,
selectable: true
};
// scroller
var th; // virtual height
var h; // real scrollable height
var ph; // page height
var n; // number of pages
var cj; // "jumpiness" coefficient
var page = 0; // current page
var offset = 0; // current page offset
var vScrollDir = 1;
// private
var initialized = false;
var $container;
var uid = "slickgrid_" + Math.round(1000000 * Math.random());
var self = this;
var $focusSink, $focusSink2;
var $headerScroller;
var $headers;
var $headerRow, $headerRowScroller, $headerRowSpacerL, $headerRowSpacerR;
var $topPanelScroller;
var $topPanel;
var $viewport;
var $canvas;
var $style;
var $boundAncestors;
var stylesheet, columnCssRulesL, columnCssRulesR;
var viewportH, viewportW;
var canvasWidth, canvasWidthL, canvasWidthR;
var headersWidth, headersWidthL, headersWidthR;
var viewportHasHScroll, viewportHasVScroll;
var headerColumnWidthDiff = 0,
headerColumnHeightDiff = 0,
// border+padding
cellWidthDiff = 0,
cellHeightDiff = 0;
var absoluteColumnMinWidth;
var hasFrozenRows = false;
var frozenRowsHeight = 0;
var actualFrozenRow = -1;
var paneTopH = 0;
var paneBottomH = 0;
var viewportTopH = 0;
var viewportBottomH = 0;
var topPanelH = 0;
var headerRowH = 0;
var tabbingDirection = 1;
var $activeCanvasNode;
var $activeViewportNode;
var activePosX;
var activeRow, activeCell;
var activeCellNode = null;
var currentEditor = null;
var serializedEditorValue;
var editController;
var rowsCache = {};
var renderedRows = 0;
var numVisibleRows = 0;
var prevScrollTop = 0;
var scrollTop = 0;
var lastRenderedScrollTop = 0;
var lastRenderedScrollLeft = 0;
var prevScrollLeft = 0;
var scrollLeft = 0;
var selectionModel;
var selectedRows = [];
var plugins = [];
var cellCssClasses = {};
var columnsById = {};
var sortColumns = [];
var columnPosLeft = [];
var columnPosRight = [];
// async call handles
var h_editorLoader = null;
var h_render = null;
var h_postrender = null;
var postProcessedRows = {};
var postProcessToRow = null;
var postProcessFromRow = null;
// perf counters
var counter_rows_rendered = 0;
var counter_rows_removed = 0;
var $paneHeaderL;
var $paneHeaderR;
var $paneTopL;
var $paneTopR;
var $paneBottomL;
var $paneBottomR;
var $headerScrollerL;
var $headerScrollerR;
var $headerL;
var $headerR;
var $headerRowScrollerL;
var $headerRowScrollerR;
var $headerRowL;
var $headerRowR;
var $topPanelScrollerL;
var $topPanelScrollerR;
var $topPanelL;
var $topPanelR;
var $viewportTopL;
var $viewportTopR;
var $viewportBottomL;
var $viewportBottomR;
var $canvasTopL;
var $canvasTopR;
var $canvasBottomL;
var $canvasBottomR;
var $viewportScrollContainerX;
var $viewportScrollContainerY;
var $headerScrollContainer;
var $headerRowScrollContainer;
// ////////////////////////////////////////////////////////////////////////////////////////////
// Initialization
function init() {
$container = $(container);
if ($container.length < 1) {
throw new Error("SlickGrid requires a valid container, " + container + " does not exist in the DOM.");
}
// calculate these only once and share between grid instances
maxSupportedCssHeight = maxSupportedCssHeight || getMaxSupportedCssHeight();
scrollbarDimensions = scrollbarDimensions || measureScrollbar();
options = $.extend({}, defaults, options);
validateAndEnforceOptions();
columnDefaults.width = options.defaultColumnWidth;
columnsById = {};
for (var i = 0; i < columns.length; i++) {
var m = columns[i] = $.extend({}, columnDefaults, columns[i]);
columnsById[m.id] = i;
if (m.minWidth && m.width < m.minWidth) {
m.width = m.minWidth;
}
if (m.maxWidth && m.width > m.maxWidth) {
m.width = m.maxWidth;
}
}
// validate loaded JavaScript modules against requested options
if (options.enableColumnReorder && !$.fn.sortable) {
throw new Error("SlickGrid's 'enableColumnReorder = true' option requires jquery-ui.sortable module to be loaded");
}
editController = {
"commitCurrentEdit": commitCurrentEdit,
"cancelCurrentEdit": cancelCurrentEdit
};
$container
.empty()
.css("overflow", "hidden")
.css("outline", 0)
.addClass(uid)
.addClass("ui-widget");
// set up a positioning container if needed
if (!/relative|absolute|fixed/.test($container.css("position"))) {
$container.css("position", "relative");
}
$focusSink = $("<div tabIndex='0' hideFocus style='position:fixed;width:0;height:0;top:0;left:0;outline:0;'></div>").appendTo($container);
// Containers used for scrolling frozen columns and rows
$paneHeaderL = $("<div class='slick-pane slick-pane-header slick-pane-left' tabIndex='0' />").appendTo($container);
$paneHeaderR = $("<div class='slick-pane slick-pane-header slick-pane-right' tabIndex='0' />").appendTo($container);
$paneTopL = $("<div class='slick-pane slick-pane-top slick-pane-left' tabIndex='0' />").appendTo($container);
$paneTopR = $("<div class='slick-pane slick-pane-top slick-pane-right' tabIndex='0' />").appendTo($container);
$paneBottomL = $("<div class='slick-pane slick-pane-bottom slick-pane-left' tabIndex='0' />").appendTo($container);
$paneBottomR = $("<div class='slick-pane slick-pane-bottom slick-pane-right' tabIndex='0' />").appendTo($container);
// Append the header scroller containers
$headerScrollerL = $("<div class='ui-state-default slick-header slick-header-left' />").appendTo($paneHeaderL);
$headerScrollerR = $("<div class='ui-state-default slick-header slick-header-right' />").appendTo($paneHeaderR);
// Cache the header scroller containers
$headerScroller = $().add($headerScrollerL).add($headerScrollerR);
// Append the columnn containers to the headers
$headerL = $("<div class='slick-header-columns slick-header-columns-left' style='left:-1000px' />").appendTo($headerScrollerL);
$headerR = $("<div class='slick-header-columns slick-header-columns-right' style='left:-1000px' />").appendTo($headerScrollerR);
// Cache the header columns
$headers = $().add($headerL).add($headerR);
$headerRowScrollerL = $("<div class='ui-state-default slick-headerrow' />").appendTo($paneTopL);
$headerRowScrollerR = $("<div class='ui-state-default slick-headerrow' />").appendTo($paneTopR);
$headerRowScroller = $().add($headerRowScrollerL).add($headerRowScrollerR);
$headerRowSpacerL = $("<div style='display:block;height:1px;position:absolute;top:0;left:0;'></div>")
.css("width", getCanvasWidth() + scrollbarDimensions.width + "px")
.appendTo($headerRowScrollerL);
$headerRowSpacerR = $("<div style='display:block;height:1px;position:absolute;top:0;left:0;'></div>")
.css("width", getCanvasWidth() + scrollbarDimensions.width + "px")
.appendTo($headerRowScrollerR);
$headerRowL = $("<div class='slick-headerrow-columns slick-headerrow-columns-left' />").appendTo($headerRowScrollerL);
$headerRowR = $("<div class='slick-headerrow-columns slick-headerrow-columns-right' />").appendTo($headerRowScrollerR);
$headerRow = $().add($headerRowL).add($headerRowR);
// Append the top panel scroller
$topPanelScrollerL = $("<div class='ui-state-default slick-top-panel-scroller' />").appendTo($paneTopL);
$topPanelScrollerR = $("<div class='ui-state-default slick-top-panel-scroller' />").appendTo($paneTopR);
$topPanelScroller = $().add($topPanelScrollerL).add($topPanelScrollerR);
// Append the top panel
$topPanelL = $("<div class='slick-top-panel' style='width:10000px' />").appendTo($topPanelScrollerL);
$topPanelR = $("<div class='slick-top-panel' style='width:10000px' />").appendTo($topPanelScrollerR);
$topPanel = $().add($topPanelL).add($topPanelR);
if (!options.showTopPanel) {
$topPanelScroller.hide();
}
if (!options.showHeaderRow) {
$headerRowScroller.hide();
}
// Append the viewport containers
$viewportTopL = $("<div class='slick-viewport slick-viewport-top slick-viewport-left' tabIndex='0' hideFocus />").appendTo($paneTopL);
$viewportTopR = $("<div class='slick-viewport slick-viewport-top slick-viewport-right' tabIndex='0' hideFocus />").appendTo($paneTopR);
$viewportBottomL = $("<div class='slick-viewport slick-viewport-bottom slick-viewport-left' tabIndex='0' hideFocus />").appendTo($paneBottomL);
$viewportBottomR = $("<div class='slick-viewport slick-viewport-bottom slick-viewport-right' tabIndex='0' hideFocus />").appendTo($paneBottomR);
// Cache the viewports
$viewport = $().add($viewportTopL).add($viewportTopR).add($viewportBottomL).add($viewportBottomR);
// Default the active viewport to the top left
$activeViewportNode = $viewportTopL;
// Append the canvas containers
$canvasTopL = $("<div class='grid-canvas grid-canvas-top grid-canvas-left' tabIndex='0' hideFocus />").appendTo($viewportTopL);
$canvasTopR = $("<div class='grid-canvas grid-canvas-top grid-canvas-right' tabIndex='0' hideFocus />").appendTo($viewportTopR);
$canvasBottomL = $("<div class='grid-canvas grid-canvas-bottom grid-canvas-left' tabIndex='0' hideFocus />").appendTo($viewportBottomL);
$canvasBottomR = $("<div class='grid-canvas grid-canvas-bottom grid-canvas-right' tabIndex='0' hideFocus />").appendTo($viewportBottomR);
// Cache the canvases
$canvas = $().add($canvasTopL).add($canvasTopR).add($canvasBottomL).add($canvasBottomR);
// Default the active canvas to the top left
$activeCanvasNode = $canvasTopL;
$focusSink2 = $focusSink.clone().appendTo($container);
if (!options.explicitInitialization) {
finishInitialization();
}
}
function finishInitialization() {
if (!initialized) {
initialized = true;
getViewportWidth();
getViewportHeight();
// header columns and cells may have different padding/border
// skewing width calculations (box-sizing, hello?)
// calculate the diff so we can set consistent sizes
measureCellPaddingAndBorder();
// for usability reasons, all text selection in SlickGrid is
// disabled with the exception of input and textarea elements (selection
// must be enabled there so that editors work as expected); note that
// selection in grid cells (grid body) is already unavailable in
// all browsers except IE
disableSelection($headers); // disable all text selection in header (including input and textarea)
if (!options.enableTextSelectionOnCells) {
// disable text selection in grid cells except in input and textarea elements
// (this is IE-specific, because selectstart event will only fire in IE)
$viewport.bind("selectstart.ui", function (event) {
return $(event.target).is("input,textarea");
});
}
setFrozenOptions();
setPaneVisibility();
setScroller();
setOverflow();
updateColumnCaches();
createColumnHeaders();
setupColumnSort();
createCssRules();
resizeCanvas();
bindAncestorScrollEvents();
$container
.bind("resize.slickgrid", resizeCanvas);
$viewport
//.bind("click", handleClick)
.bind("scroll", handleScroll);
if (jQuery.fn.mousewheel && ( options.frozenColumn > -1 || hasFrozenRows )) {
$viewport
.bind("mousewheel", handleMouseWheel);
}
$headerScroller
.bind("contextmenu", handleHeaderContextMenu)
.bind("click", handleHeaderClick)
.delegate(".slick-header-column", "mouseenter", handleHeaderMouseEnter)
.delegate(".slick-header-column", "mouseleave", handleHeaderMouseLeave);
$headerRowScroller
.bind("scroll", handleHeaderRowScroll);
$focusSink.add($focusSink2)
.bind("keydown", handleKeyDown);
$canvas
.bind("keydown", handleKeyDown)
.bind("click", handleClick)
.bind("dblclick", handleDblClick)
.bind("contextmenu", handleContextMenu)
.bind("draginit", handleDragInit)
.bind("dragstart", {distance: 3}, handleDragStart)
.bind("drag", handleDrag)
.bind("dragend", handleDragEnd)
.delegate(".slick-cell", "mouseenter", handleMouseEnter)
.delegate(".slick-cell", "mouseleave", handleMouseLeave);
}
}
function registerPlugin(plugin) {
plugins.unshift(plugin);
plugin.init(self);
}
function unregisterPlugin(plugin) {
for (var i = plugins.length; i >= 0; i--) {
if (plugins[i] === plugin) {
if (plugins[i].destroy) {
plugins[i].destroy();
}
plugins.splice(i, 1);
break;
}
}
}
function setSelectionModel(model) {
if (selectionModel) {
selectionModel.onSelectedRangesChanged.unsubscribe(handleSelectedRangesChanged);
if (selectionModel.destroy) {
selectionModel.destroy();
}
}
selectionModel = model;
if (selectionModel) {
selectionModel.init(self);
selectionModel.onSelectedRangesChanged.subscribe(handleSelectedRangesChanged);
}
}
function getSelectionModel() {
return selectionModel;
}
function getCanvasNode() {
return $canvas[0];
}
function getActiveCanvasNode(element) {
setActiveCanvasNode(element);
return $activeCanvasNode[0];
}
function getCanvases() {
return $canvas;
}
function setActiveCanvasNode(element) {
if (element) {
$activeCanvasNode = $(element.target).closest('.grid-canvas');
}
}
function getViewportNode() {
return $viewport[0];
}
function getActiveViewportNode(element) {
setActiveViewPortNode(element);
return $activeViewportNode[0];
}
function setActiveViewportNode(element) {
if (element) {
$activeViewportNode = $(element.target).closest('.slick-viewport');
}
}
function measureScrollbar() {
var $c = $("<div style='position:absolute; top:-10000px; left:-10000px; width:100px; height:100px; overflow:scroll;'></div>").appendTo("body");
var dim = {
width: $c.width() - $c[0].clientWidth,
height: $c.height() - $c[0].clientHeight
};
$c.remove();
return dim;
}
function getHeadersWidth() {
headersWidth = headersWidthL = headersWidthR = 0;
for (var i = 0, ii = columns.length; i < ii; i++) {
var width = columns[ i ].width;
if (( options.frozenColumn ) > -1 && ( i > options.frozenColumn )) {
headersWidthR += width;
} else {
headersWidthL += width;
}
}
if (options.frozenColumn > -1) {
headersWidthL = headersWidthL + 1000;
headersWidthR = Math.max(headersWidthR, viewportW) + headersWidthL;
headersWidthR += scrollbarDimensions.width;
} else {
headersWidthL += scrollbarDimensions.width;
headersWidthL = Math.max(headersWidthL, viewportW) + 1000;
}
headersWidth = headersWidthL + headersWidthR;
}
function getCanvasWidth() {
var availableWidth = viewportHasVScroll ? viewportW - scrollbarDimensions.width : viewportW;
var i = columns.length;
canvasWidthL = canvasWidthR = 0;
while (i--) {
if ((options.frozenColumn > -1) && (i > options.frozenColumn)) {
canvasWidthR += columns[i].width;
} else {
canvasWidthL += columns[i].width;
}
}
var totalRowWidth = canvasWidthL + canvasWidthR;
return options.fullWidthRows ? Math.max(totalRowWidth, availableWidth) : totalRowWidth;
}
function updateCanvasWidth(forceColumnWidthsUpdate) {
var oldCanvasWidth = canvasWidth;
var oldCanvasWidthL = canvasWidthL;
var oldCanvasWidthR = canvasWidthR;
var widthChanged;
canvasWidth = getCanvasWidth();
widthChanged = canvasWidth !== oldCanvasWidth || canvasWidthL !== oldCanvasWidthL || canvasWidthR !== oldCanvasWidthR;
if (widthChanged || options.frozenColumn > -1 || hasFrozenRows) {
$canvasTopL.width(canvasWidthL);
getHeadersWidth();
$headerL.width(headersWidthL);
$headerR.width(headersWidthR);
if (options.frozenColumn > -1) {
$canvasTopR.width(canvasWidthR);
$paneHeaderL.width(canvasWidthL);
$paneHeaderR.css('left', canvasWidthL);
$paneHeaderR.css('width', viewportW - canvasWidthL);
$paneTopL.width(canvasWidthL);
$paneTopR.css('left', canvasWidthL);
$paneTopR.css('width', viewportW - canvasWidthL);
$headerRowScrollerL.width(canvasWidthL);
$headerRowScrollerR.width(viewportW - canvasWidthL);
$headerRowL.width(canvasWidthL);
$headerRowR.width(canvasWidthR);
$viewportTopL.width(canvasWidthL);
$viewportTopR.width(viewportW - canvasWidthL);
if (hasFrozenRows) {
$paneBottomL.width(canvasWidthL);
$paneBottomR.css('left', canvasWidthL);
$viewportBottomL.width(canvasWidthL);
$viewportBottomR.width(viewportW - canvasWidthL);
$canvasBottomL.width(canvasWidthL);
$canvasBottomR.width(canvasWidthR);
}
} else {
$paneHeaderL.width('100%');
$paneTopL.width('100%');
$headerRowScrollerL.width('100%');
$headerRowL.width(canvasWidth);
$viewportTopL.width('100%');
if (hasFrozenRows) {
$viewportBottomL.width('100%');
$canvasBottomL.width(canvasWidthL);
}
}
viewportHasHScroll = (canvasWidth > viewportW - scrollbarDimensions.width);
}
$headerRowSpacerL.width(canvasWidth + (viewportHasVScroll ? scrollbarDimensions.width : 0));
$headerRowSpacerR.width(canvasWidth + (viewportHasVScroll ? scrollbarDimensions.width : 0));
if (widthChanged || forceColumnWidthsUpdate) {
applyColumnWidths();
}
}
function disableSelection($target) {
if ($target && $target.jquery) {
$target.attr("unselectable", "on").css("MozUserSelect", "none").bind("selectstart.ui", function () {
return false;
}); // from jquery:ui.core.js 1.7.2
}
}
function getMaxSupportedCssHeight() {
var supportedHeight = 1000000;
// FF reports the height back but still renders blank after ~6M px
var testUpTo = navigator.userAgent.toLowerCase().match(/firefox/) ? 6000000 : 1000000000;
var div = $("<div style='display:none' />").appendTo(document.body);
while (true) {
var test = supportedHeight * 2;
div.css("height", test);
if (test > testUpTo || div.height() !== test) {
break;
} else {
supportedHeight = test;
}
}
div.remove();
return supportedHeight;
}
// TODO: this is static. need to handle page mutation.
function bindAncestorScrollEvents() {
var elem = (hasFrozenRows && !options.frozenBottom) ? $canvasBottomL[0] : $canvasTopL[0];
while ((elem = elem.parentNode) != document.body && elem != null) {
// bind to scroll containers only
if (elem == $viewportTopL[0] || elem.scrollWidth != elem.clientWidth || elem.scrollHeight != elem.clientHeight) {
var $elem = $(elem);
if (!$boundAncestors) {
$boundAncestors = $elem;
} else {
$boundAncestors = $boundAncestors.add($elem);
}
$elem.bind("scroll." + uid, handleActiveCellPositionChange);
}
}
}
function unbindAncestorScrollEvents() {
if (!$boundAncestors) {
return;
}
$boundAncestors.unbind("scroll." + uid);
$boundAncestors = null;
}
function updateColumnHeader(columnId, title, toolTip) {
if (!initialized) {
return;
}
var idx = getColumnIndex(columnId);
if (idx == null) {
return;
}
var columnDef = columns[idx];
var $header = $headers.children().eq(idx);
if ($header) {
if (title !== undefined) {
columns[idx].name = title;
}
if (toolTip !== undefined) {
columns[idx].toolTip = toolTip;
}
trigger(self.onBeforeHeaderCellDestroy, {
"node": $header[0],
"column": columnDef
});
$header.attr("title", toolTip || "").children().eq(0).html(title);
trigger(self.onHeaderCellRendered, {
"node": $header[0],
"column": columnDef
});
}
}
function getHeaderRow() {
return (options.frozenColumn > -1) ? $headerRow : $headerRow[0];
}
function getHeaderRowColumn(columnId) {
var idx = getColumnIndex(columnId);
var $headerRowTarget;
if (options.frozenColumn > -1) {
if (idx <= options.frozenColumn) {
$headerRowTarget = $headerRowL;
} else {
$headerRowTarget = $headerRowR;
idx -= options.frozenColumn + 1;
}
} else {
$headerRowTarget = $headerRowL;
}
var $header = $headerRowTarget.children().eq(idx);
return $header && $header[0];
}
function createColumnHeaders() {
function onMouseEnter() {
$(this).addClass("ui-state-hover");
}
function onMouseLeave() {
$(this).removeClass("ui-state-hover");
}
$headers.find(".slick-header-column")
.each(function () {
var columnDef = $(this).data("column");
if (columnDef) {
trigger(self.onBeforeHeaderCellDestroy, {
"node": this,
"column": columnDef
});
}
});
$headerL.empty();
$headerR.empty();
getHeadersWidth();
$headerL.width(headersWidthL);
$headerR.width(headersWidthR);
$headerRow.find(".slick-headerrow-column")
.each(function () {
var columnDef = $(this).data("column");
if (columnDef) {
trigger(self.onBeforeHeaderRowCellDestroy, {
"node": this,
"column": columnDef
});
}
});
$headerRowL.empty();
$headerRowR.empty();
for (var i = 0; i < columns.length; i++) {
var m = columns[i];
var $headerTarget = (options.frozenColumn > -1) ? ((i <= options.frozenColumn) ? $headerL : $headerR) : $headerL;
var $headerRowTarget = (options.frozenColumn > -1) ? ((i <= options.frozenColumn) ? $headerRowL : $headerRowR) : $headerRowL;
var header = $("<div class='ui-state-default slick-header-column' />")
.html("<span class='slick-column-name'>" + m.name + "</span>")
.width(m.width - headerColumnWidthDiff)
.attr("id", "" + uid + m.id)
.attr("title", m.toolTip || "")
.data("column", m)
.addClass(m.headerCssClass || "")
.appendTo($headerTarget);
if (options.enableColumnReorder || m.sortable) {
header
.on('mouseenter', onMouseEnter)
.on('mouseleave', onMouseLeave);
}
if (m.sortable) {
header.addClass("slick-header-sortable");
header.append("<span class='slick-sort-indicator' />");
}
trigger(self.onHeaderCellRendered, {
"node": header[0],
"column": m
});
if (options.showHeaderRow) {
var headerRowCell = $("<div class='ui-state-default slick-headerrow-column l" + i + " r" + i + "'></div>")
.data("column", m)
.appendTo($headerRowTarget);
trigger(self.onHeaderRowCellRendered, {
"node": headerRowCell[0],
"column": m
});
}
}
setSortColumns(sortColumns);
setupColumnResize();
if (options.enableColumnReorder) {
setupColumnReorder();
}
}
function setupColumnSort() {
$headers.click(function (e) {
// temporary workaround for a bug in jQuery 1.7.1
// (http://bugs.jquery.com/ticket/11328)
e.metaKey = e.metaKey || e.ctrlKey;
if ($(e.target).hasClass("slick-resizable-handle")) {
return;
}
var $col = $(e.target).closest(".slick-header-column");
if (!$col.length) {
return;
}
var column = $col.data("column");
if (column.sortable) {
if (!getEditorLock().commitCurrentEdit()) {
return;
}
var sortOpts = null;
var i = 0;
for (; i < sortColumns.length; i++) {
if (sortColumns[i].columnId == column.id) {
sortOpts = sortColumns[i];
sortOpts.sortAsc = !sortOpts.sortAsc;
break;
}
}
if (e.metaKey && options.multiColumnSort) {
if (sortOpts) {
sortColumns.splice(i, 1);
}
} else {
if ((!e.shiftKey && !e.metaKey) || !options.multiColumnSort) {
sortColumns = [];
}
if (!sortOpts) {
sortOpts = {
columnId: column.id,
sortAsc: true
};
sortColumns.push(sortOpts);
} else if (sortColumns.length == 0) {
sortColumns.push(sortOpts);
}
}
setSortColumns(sortColumns);
if (!options.multiColumnSort) {
trigger(self.onSort, {
multiColumnSort: false,
sortCol: column,
sortAsc: sortOpts.sortAsc
}, e);
} else {
trigger(
self.onSort, {
multiColumnSort: true,
sortCols: $.map(
sortColumns, function (col) {
return {
sortCol: columns[getColumnIndex(col.columnId)],
sortAsc: col.sortAsc
};
})
}, e);
}
}
});
}
function setupColumnReorder() {
$headers.filter(":ui-sortable").sortable("destroy");
var columnScrollTimer = null;
function scrollColumnsRight() {
$viewportScrollContainerX[0].scrollLeft = $viewportScrollContainerX[0].scrollLeft + 10;
}
function scrollColumnsLeft() {
$viewportScrollContainerX[0].scrollLeft = $viewportScrollContainerX[0].scrollLeft - 10;
}
$headers.sortable({
containment: "parent",
distance: 3,
axis: "x",
cursor: "default",
tolerance: "intersection",
helper: "clone",
placeholder: "slick-sortable-placeholder ui-state-default slick-header-column",
start: function (e, ui) {
ui.placeholder.width(ui.helper.outerWidth() - headerColumnWidthDiff);
$(ui.helper).addClass("slick-header-column-active");
},
beforeStop: function (e, ui) {
$(ui.helper).removeClass("slick-header-column-active");
},
sort: function (e, ui) {
if (e.originalEvent.pageX > $container[0].clientWidth) {
if (!(columnScrollTimer)) {
columnScrollTimer = setInterval(
scrollColumnsRight, 100);
}
} else if (e.originalEvent.pageX < $viewportScrollContainerX.offset().left) {
if (!(columnScrollTimer)) {
columnScrollTimer = setInterval(
scrollColumnsLeft, 100);
}
} else {
clearInterval(columnScrollTimer);
columnScrollTimer = null;
}
},
stop: function (e) {
clearInterval(columnScrollTimer);
columnScrollTimer = null;
if (!getEditorLock().commitCurrentEdit()) {
$(this).sortable("cancel");
return;
}
var reorderedIds = $headerL.sortable("toArray");
reorderedIds = reorderedIds.concat($headerR.sortable("toArray"));
var reorderedColumns = [];
for (var i = 0; i < reorderedIds.length; i++) {
reorderedColumns.push(columns[getColumnIndex(reorderedIds[i].replace(uid, ""))]);
}
setColumns(reorderedColumns);
trigger(self.onColumnsReordered, {});
e.stopPropagation();
setupColumnResize();
}
});
}
function setupColumnResize() {
var $col, j, c, pageX, columnElements, minPageX, maxPageX, firstResizable, lastResizable;
columnElements = $headers.children();
columnElements.find(".slick-resizable-handle").remove();
columnElements.each(function (i, e) {
if (columns[i].resizable) {
if (firstResizable === undefined) {
firstResizable = i;
}
lastResizable = i;
}
});
if (firstResizable === undefined) {
return;
}
columnElements.each(function (i, e) {
if (i < firstResizable || (options.forceFitColumns && i >= lastResizable)) {
return;
}
$col = $(e);
$("<div class='slick-resizable-handle' />")
.appendTo(e)
.bind("dragstart",function (e, dd) {
if (!getEditorLock().commitCurrentEdit()) {
return false;
}
pageX = e.pageX;
$(this).parent().addClass("slick-header-column-active");
var shrinkLeewayOnRight = null,
stretchLeewayOnRight = null;
// lock each column's width option to current width
columnElements.each(function (i, e) {
columns[i].previousWidth = $(e).outerWidth();
});
if (options.forceFitColumns) {
shrinkLeewayOnRight = 0;
stretchLeewayOnRight = 0;
// colums on right affect maxPageX/minPageX
for (j = i + 1; j < columnElements.length; j++) {
c = columns[j];
if (c.resizable) {
if (stretchLeewayOnRight !== null) {
if (c.maxWidth) {
stretchLeewayOnRight += c.maxWidth - c.previousWidth;
} else {
stretchLeewayOnRight = null;
}
}
shrinkLeewayOnRight += c.previousWidth - Math.max(c.minWidth || 0, absoluteColumnMinWidth);
}
}
}
var shrinkLeewayOnLeft = 0,
stretchLeewayOnLeft = 0;
for (j = 0; j <= i; j++) {
// columns on left only affect minPageX
c = columns[j];
if (c.resizable) {
if (stretchLeewayOnLeft !== null) {
if (c.maxWidth) {
stretchLeewayOnLeft += c.maxWidth - c.previousWidth;
} else {
stretchLeewayOnLeft = null;
}
}
shrinkLeewayOnLeft += c.previousWidth - Math.max(c.minWidth || 0, absoluteColumnMinWidth);
}
}
if (shrinkLeewayOnRight === null) {
shrinkLeewayOnRight = 100000;
}
if (shrinkLeewayOnLeft === null) {
shrinkLeewayOnLeft = 100000;
}
if (stretchLeewayOnRight === null) {
stretchLeewayOnRight = 100000;
}
if (stretchLeewayOnLeft === null) {
stretchLeewayOnLeft = 100000;
}
maxPageX = pageX + Math.min(shrinkLeewayOnRight, stretchLeewayOnLeft);
minPageX = pageX - Math.min(shrinkLeewayOnLeft, stretchLeewayOnRight);
}).bind("drag",function (e, dd) {
var actualMinWidth, d = Math.min(maxPageX, Math.max(minPageX, e.pageX)) - pageX,
x;
if (d < 0) { // shrink column
x = d;
var newCanvasWidthL = 0, newCanvasWidthR = 0;
for (j = i; j >= 0; j--) {
c = columns[j];
if (c.resizable) {
actualMinWidth = Math.max(c.minWidth || 0, absoluteColumnMinWidth);
if (x && c.previousWidth + x < actualMinWidth) {
x += c.previousWidth - actualMinWidth;
c.width = actualMinWidth;
} else {
c.width = c.previousWidth + x;
x = 0;
}
}
}
for (k = 0; k <= i; k++) {
c = columns[k];
if ((options.frozenColumn > -1) && (k > options.frozenColumn)) {
newCanvasWidthR += c.width;
} else {
newCanvasWidthL += c.width;
}
}
if (options.forceFitColumns) {
x = -d;
for (j = i + 1; j < columnElements.length; j++) {
c = columns[j];
if (c.resizable) {
if (x && c.maxWidth && (c.maxWidth - c.previousWidth < x)) {
x -= c.maxWidth - c.previousWidth;
c.width = c.maxWidth;
} else {
c.width = c.previousWidth + x;
x = 0;
}
if ((options.frozenColumn > -1) && (j > options.frozenColumn)) {
newCanvasWidthR += c.width;
} else {
newCanvasWidthL += c.width;
}
}
}
} else {
for (j = i + 1; j < columnElements.length; j++) {
c = columns[j];
if ((options.frozenColumn > -1) && (j > options.frozenColumn)) {
newCanvasWidthR += c.width;
} else {
newCanvasWidthL += c.width;
}
}
}
} else { // stretch column
x = d;
var newCanvasWidthL = 0, newCanvasWidthR = 0;
for (j = i; j >= 0; j--) {
c = columns[j];
if (c.resizable) {
if (x && c.maxWidth && (c.maxWidth - c.previousWidth < x)) {
x -= c.maxWidth - c.previousWidth;
c.width = c.maxWidth;
} else {
c.width = c.previousWidth + x;
x = 0;
}
}
}
for (k = 0; k <= i; k++) {
c = columns[k];
if ((options.frozenColumn > -1) && (k > options.frozenColumn)) {
newCanvasWidthR += c.width;
} else {
newCanvasWidthL += c.width;
}
}
if (options.forceFitColumns) {
x = -d;
for (j = i + 1; j < columnElements.length; j++) {
c = columns[j];
if (c.resizable) {
actualMinWidth = Math.max(c.minWidth || 0, absoluteColumnMinWidth);
if (x && c.previousWidth + x < actualMinWidth) {
x += c.previousWidth - actualMinWidth;
c.width = actualMinWidth;
} else {
c.width = c.previousWidth + x;
x = 0;
}
if ((options.frozenColumn > -1) && (j > options.frozenColumn)) {
newCanvasWidthR += c.width;
} else {
newCanvasWidthL += c.width;
}
}
}
} else {
for (j = i + 1; j < columnElements.length; j++) {
c = columns[j];
if ((options.frozenColumn > -1) && (j > options.frozenColumn)) {
newCanvasWidthR += c.width;
} else {
newCanvasWidthL += c.width;
}
}
}
}
if (options.frozenColumn > -1 && newCanvasWidthL != canvasWidthL) {
$headerL.width(newCanvasWidthL + 1000);
$paneHeaderR.css('left', newCanvasWidthL);
}
applyColumnHeaderWidths();
if (options.syncColumnCellResize) {
updateCanvasWidth();
applyColumnWidths();
}
}).bind("dragend", function (e, dd) {
var newWidth;
$(this).parent().removeClass("slick-header-column-active");
for (j = 0; j < columnElements.length; j++) {
c = columns[j];
newWidth = $(columnElements[j]).outerWidth();
if (c.previousWidth !== newWidth && c.rerenderOnResize) {
invalidateAllRows();
}
}
updateCanvasWidth(true);
render();
trigger(self.onColumnsResized, {});
});
});
}
function getVBoxDelta($el) {
var p = ["borderTopWidth", "borderBottomWidth", "paddingTop", "paddingBottom"];
var delta = 0;
$.each(p, function (n, val) {
delta += parseFloat($el.css(val)) || 0;
});
return delta;
}
function setFrozenOptions() {
options.frozenColumn = ( options.frozenColumn >= 0
&& options.frozenColumn < columns.length
)
? parseInt(options.frozenColumn)
: -1;
options.frozenRow = ( options.frozenRow >= 0
&& options.frozenRow < numVisibleRows
)
? parseInt(options.frozenRow)
: -1;
if (options.frozenRow > -1) {
hasFrozenRows = true;
frozenRowsHeight = ( options.frozenRow ) * options.rowHeight;
var dataLength = getDataLength() || this.data.length;
actualFrozenRow = ( options.frozenBottom )
? ( dataLength - options.frozenRow )
: options.frozenRow;
} else {
hasFrozenRows = false;
}
}
function setPaneVisibility() {
if (options.frozenColumn > -1) {
$paneHeaderR.show();
$paneTopR.show();
if (hasFrozenRows) {
$paneBottomL.show();
$paneBottomR.show();
} else {
$paneBottomR.hide();
$paneBottomL.hide();
}
} else {
$paneHeaderR.hide();
$paneTopR.hide();
$paneBottomR.hide();
if (hasFrozenRows) {
$paneBottomL.show();
} else {
$paneBottomR.hide();
$paneBottomL.hide();
}
}
}
function setOverflow() {
$viewportTopL.css({
'overflow-x': ( options.frozenColumn > -1 ) ? ( hasFrozenRows ) ? 'hidden' : 'scroll' : ( hasFrozenRows ) ? 'hidden' : 'auto',
'overflow-y': ( options.frozenColumn > -1 ) ? ( hasFrozenRows ) ? 'hidden' : 'hidden' : ( hasFrozenRows ) ? 'scroll' : 'auto'
});
$viewportTopR.css({
'overflow-x': ( options.frozenColumn > -1 ) ? ( hasFrozenRows ) ? 'hidden' : 'scroll' : ( hasFrozenRows ) ? 'hidden' : 'auto',
'overflow-y': ( options.frozenColumn > -1 ) ? ( hasFrozenRows ) ? 'scroll' : 'auto' : ( hasFrozenRows ) ? 'scroll' : 'auto'
});
$viewportBottomL.css({
'overflow-x': ( options.frozenColumn > -1 ) ? ( hasFrozenRows ) ? 'scroll' : 'auto' : ( hasFrozenRows ) ? 'auto' : 'auto',
'overflow-y': ( options.frozenColumn > -1 ) ? ( hasFrozenRows ) ? 'hidden' : 'hidden' : ( hasFrozenRows ) ? 'scroll' : 'auto'
});
$viewportBottomR.css({
'overflow-x': ( options.frozenColumn > -1 ) ? ( hasFrozenRows ) ? 'scroll' : 'auto' : ( hasFrozenRows ) ? 'auto' : 'auto',
'overflow-y': ( options.frozenColumn > -1 ) ? ( hasFrozenRows ) ? 'auto' : 'auto' : ( hasFrozenRows ) ? 'auto' : 'auto'
});
}
function setScroller() {
if (options.frozenColumn > -1) {
$headerScrollContainer = $headerScrollerR;
$headerRowScrollContainer = $headerRowScrollerR;
if (hasFrozenRows) {
if (options.frozenBottom) {
$viewportScrollContainerX = $viewportBottomR;
$viewportScrollContainerY = $viewportTopR;
} else {
$viewportScrollContainerX = $viewportScrollContainerY = $viewportBottomR;
}
} else {
$viewportScrollContainerX = $viewportScrollContainerY = $viewportTopR;
}
} else {
$headerScrollContainer = $headerScrollerL;
$headerRowScrollContainer = $headerRowScrollerL;
if (hasFrozenRows) {
if (options.frozenBottom) {
$viewportScrollContainerX = $viewportBottomL;
$viewportScrollContainerY = $viewportTopL;
} else {
$viewportScrollContainerX = $viewportScrollContainerY = $viewportBottomL;
}
} else {
$viewportScrollContainerX = $viewportScrollContainerY = $viewportTopL;
}
}
}
function measureCellPaddingAndBorder() {
var el;
var h = ["borderLeftWidth", "borderRightWidth", "paddingLeft", "paddingRight"];
var v = ["borderTopWidth", "borderBottomWidth", "paddingTop", "paddingBottom"];
el = $("<div class='ui-state-default slick-header-column' style='visibility:hidden'>-</div>").appendTo($headers);
headerColumnWidthDiff = headerColumnHeightDiff = 0;
if (el.css("box-sizing") != "border-box" && el.css("-moz-box-sizing") != "border-box" && el.css("-webkit-box-sizing") != "border-box") {
$.each(h, function (n, val) {
headerColumnWidthDiff += parseFloat(el.css(val)) || 0;
});
$.each(v, function (n, val) {
headerColumnHeightDiff += parseFloat(el.css(val)) || 0;
});
}
el.remove();
var r = $("<div class='slick-row' />").appendTo($canvas);
el = $("<div class='slick-cell' id='' style='visibility:hidden'>-</div>").appendTo(r);
cellWidthDiff = cellHeightDiff = 0;
if (el.css("box-sizing") != "border-box" && el.css("-moz-box-sizing") != "border-box" && el.css("-webkit-box-sizing") != "border-box") {
$.each(h, function (n, val) {
cellWidthDiff += parseFloat(el.css(val)) || 0;
});
$.each(v, function (n, val) {
cellHeightDiff += parseFloat(el.css(val)) || 0;
});
}
r.remove();
absoluteColumnMinWidth = Math.max(headerColumnWidthDiff, cellWidthDiff);
}
function createCssRules() {
$style = $("<style type='text/css' rel='stylesheet' />").appendTo($("head"));
var rowHeight = (options.rowHeight - cellHeightDiff);
var rules = [
"." + uid + " .slick-header-column { left: 1000px; }",
"." + uid + " .slick-top-panel { height:" + options.topPanelHeight + "px; }",
"." + uid + " .slick-headerrow-columns { height:" + options.headerRowHeight + "px; }",
"." + uid + " .slick-cell { height:" + rowHeight + "px; }",
"." + uid + " .slick-row { height:" + options.rowHeight + "px; }"
];
for (var i = 0; i < columns.length; i++) {
rules.push("." + uid + " .l" + i + " { }");
rules.push("." + uid + " .r" + i + " { }");
}
if ($style[0].styleSheet) { // IE
$style[0].styleSheet.cssText = rules.join(" ");
} else {
$style[0].appendChild(document.createTextNode(rules.join(" ")));
}
}
function getColumnCssRules(idx) {
if (!stylesheet) {
var sheets = document.styleSheets;
for (var i = 0; i < sheets.length; i++) {
if ((sheets[i].ownerNode || sheets[i].owningElement) == $style[0]) {
stylesheet = sheets[i];
break;
}
}
if (!stylesheet) {
throw new Error("Cannot find stylesheet.");
}
// find and cache column CSS rules
columnCssRulesL = [];
columnCssRulesR = [];
var cssRules = (stylesheet.cssRules || stylesheet.rules);
var matches, columnIdx;
for (var i = 0; i < cssRules.length; i++) {
var selector = cssRules[i].selectorText;
if (matches = /\.l\d+/.exec(selector)) {
columnIdx = parseInt(matches[0].substr(2, matches[0].length - 2), 10);
columnCssRulesL[columnIdx] = cssRules[i];
} else if (matches = /\.r\d+/.exec(selector)) {
columnIdx = parseInt(matches[0].substr(2, matches[0].length - 2), 10);
columnCssRulesR[columnIdx] = cssRules[i];
}
}
}
return {
"left": columnCssRulesL[idx],
"right": columnCssRulesR[idx]
};
}
function removeCssRules() {
$style.remove();
stylesheet = null;
}
function destroy() {
getEditorLock().cancelCurrentEdit();
trigger(self.onBeforeDestroy, {});
var i = plugins.length;
while (i--) {
unregisterPlugin(plugins[i]);
}
if (options.enableColumnReorder) {
$headers.filter(":ui-sortable").sortable("destroy");
}
unbindAncestorScrollEvents();
$container.unbind(".slickgrid");
removeCssRules();
$canvas.unbind("draginit dragstart dragend drag");
$container.empty().removeClass(uid);
}
// ////////////////////////////////////////////////////////////////////////////////////////////
// General
function trigger(evt, args, e) {
e = e || new Slick.EventData();
args = args || {};
args.grid = self;
return evt.notify(args, e, self);
}
function getEditorLock() {
return options.editorLock;
}
function getEditController() {
return editController;
}
function getColumnIndex(id) {
return columnsById[id];
}
function autosizeColumns() {
var i, c, widths = [],
shrinkLeeway = 0,
total = 0,
prevTotal, availWidth = viewportHasVScroll ? viewportW - scrollbarDimensions.width : viewportW;
for (i = 0; i < columns.length; i++) {
c = columns[i];
widths.push(c.width);
total += c.width;
if (c.resizable) {
shrinkLeeway += c.width - Math.max(c.minWidth, absoluteColumnMinWidth);
}
}
// shrink
prevTotal = total;
while (total > availWidth && shrinkLeeway) {
var shrinkProportion = (total - availWidth) / shrinkLeeway;
for (i = 0; i < columns.length && total > availWidth; i++) {
c = columns[i];
var width = widths[i];
if (!c.resizable || width <= c.minWidth || width <= absoluteColumnMinWidth) {
continue;
}
var absMinWidth = Math.max(c.minWidth, absoluteColumnMinWidth);
var shrinkSize = Math.floor(shrinkProportion * (width - absMinWidth)) || 1;
shrinkSize = Math.min(shrinkSize, width - absMinWidth);
total -= shrinkSize;
shrinkLeeway -= shrinkSize;
widths[i] -= shrinkSize;
}
if (prevTotal == total) { // avoid infinite loop
break;
}
prevTotal = total;
}
// grow
prevTotal = total;
while (total < availWidth) {
var growProportion = availWidth / total;
for (i = 0; i < columns.length && total < availWidth; i++) {
c = columns[i];
if (!c.resizable || c.maxWidth <= c.width) {
continue;
}
var growSize = Math.min(Math.floor(growProportion * c.width) - c.width, (c.maxWidth - c.width) || 1000000) || 1;
total += growSize;
widths[i] += growSize;
}
if (prevTotal == total) { // avoid infinite loop
break;
}
prevTotal = total;
}
var reRender = false;
for (i = 0; i < columns.length; i++) {
if (columns[i].rerenderOnResize && columns[i].width != widths[i]) {
reRender = true;
}
columns[i].width = widths[i];
}
applyColumnHeaderWidths();
updateCanvasWidth(true);
if (reRender) {
invalidateAllRows();
render();
}
}
function applyColumnHeaderWidths() {
if (!initialized) {
return;
}
var h;
for (var i = 0, headers = $headers.children(), ii = headers.length; i < ii; i++) {
h = $(headers[i]);
if (h.width() !== columns[i].width - headerColumnWidthDiff) {
h.width(columns[i].width - headerColumnWidthDiff);
}
}
updateColumnCaches();
}
function applyColumnWidths() {
var x = 0,
w, rule;
for (var i = 0; i < columns.length; i++) {
w = columns[i].width;
rule = getColumnCssRules(i);
rule.left.style.left = x + "px";
rule.right.style.right = (((options.frozenColumn != -1 && i > options.frozenColumn) ? canvasWidthR : canvasWidthL) - x - w) + "px";
// If this column is frozen, reset the css left value since the
// column starts in a new viewport.
if (options.frozenColumn == i) {
x = 0;
} else {
x += columns[i].width;
}
}
}
function setSortColumn(columnId, ascending) {
setSortColumns([
{
columnId: columnId,
sortAsc: ascending
}
]);
}
function setSortColumns(cols) {
sortColumns = cols;
var headerColumnEls = $headers.children();
headerColumnEls.removeClass("slick-header-column-sorted").find(".slick-sort-indicator").removeClass("slick-sort-indicator-asc slick-sort-indicator-desc");
$.each(sortColumns, function (i, col) {
if (col.sortAsc == null) {
col.sortAsc = true;
}
var columnIndex = getColumnIndex(col.columnId);
if (columnIndex != null) {
headerColumnEls.eq(columnIndex).addClass("slick-header-column-sorted").find(".slick-sort-indicator").addClass(
col.sortAsc ? "slick-sort-indicator-asc" : "slick-sort-indicator-desc");
}
});
}
function getSortColumns() {
return sortColumns;
}
function handleSelectedRangesChanged(e, ranges) {
selectedRows = [];
var hash = {};
for (var i = 0; i < ranges.length; i++) {
for (var j = ranges[i].fromRow; j <= ranges[i].toRow; j++) {
if (!hash[j]) { // prevent duplicates
selectedRows.push(j);
hash[j] = {};
}
for (var k = ranges[i].fromCell; k <= ranges[i].toCell; k++) {
if (canCellBeSelected(j, k)) {
hash[j][columns[k].id] = options.selectedCellCssClass;
}
}
}
}
setCellCssStyles(options.selectedCellCssClass, hash);
trigger(self.onSelectedRowsChanged, {
rows: getSelectedRows()
}, e);
}
function getColumns() {
return columns;
}
function updateColumnCaches() {
// Pre-calculate cell boundaries.
columnPosLeft = [];
columnPosRight = [];
var x = 0;
for (var i = 0, ii = columns.length; i < ii; i++) {
columnPosLeft[i] = x;
columnPosRight[i] = x + columns[i].width;
if (options.frozenColumn == i) {
x = 0;
} else {
x += columns[i].width;
}
}
}
function setColumns(columnDefinitions) {
columns = columnDefinitions;
columnsById = {};
for (var i = 0; i < columns.length; i++) {
var m = columns[i] = $.extend({}, columnDefaults, columns[i]);
columnsById[m.id] = i;
if (m.minWidth && m.width < m.minWidth) {
m.width = m.minWidth;
}
if (m.maxWidth && m.width > m.maxWidth) {
m.width = m.maxWidth;
}
}
updateColumnCaches();
if (initialized) {
setPaneVisibility();
setOverflow();
invalidateAllRows();
createColumnHeaders();
removeCssRules();
createCssRules();
resizeCanvas();
updateCanvasWidth();
applyColumnWidths();
handleScroll();
}
}
function getOptions() {
return options;
}
function setOptions(args) {
if (!getEditorLock().commitCurrentEdit()) {
return;
}
makeActiveCellNormal();
if (options.enableAddRow !== args.enableAddRow) {
invalidateRow(getDataLength());
}
options = $.extend(options, args);
validateAndEnforceOptions();
setFrozenOptions();
setScroller();
setColumns(columns); // TODO: Is this necessary?
render();
}
function validateAndEnforceOptions() {
if (options.autoHeight) {
options.leaveSpaceForNewRows = false;
}
}
function setData(newData, scrollToTop) {
data = newData;
invalidateAllRows();
updateRowCount();
if (scrollToTop) {
scrollTo(0);
}
}
function getData() {
return data;
}
function getDataLength() {
if (data.getLength) {
return data.getLength();
} else {
return data.length;
}
}
function getDataLengthIncludingAddNew() {
return getDataLength() + (options.enableAddRow ? 1 : 0);
}
function getDataItem(i) {
if (data.getItem) {
return data.getItem(i);
} else {
return data[i];
}
}
function getTopPanel() {
return $topPanel[0];
}
function setTopPanelVisibility(visible) {
if (options.showTopPanel != visible) {
options.showTopPanel = visible;
if (visible) {
$topPanelScroller.slideDown("fast", resizeCanvas);
} else {
$topPanelScroller.slideUp("fast", resizeCanvas);
}
}
}
function setHeaderRowVisibility(visible) {
if (options.showHeaderRow != visible) {
options.showHeaderRow = visible;
if (visible) {
$headerRowScroller.slideDown("fast", resizeCanvas);
} else {
$headerRowScroller.slideUp("fast", resizeCanvas);
}
}
}
function getContainerNode() {
return $container.get(0);
}
// ////////////////////////////////////////////////////////////////////////////////////////////
// Rendering / Scrolling
function getRowTop(row) {
return options.rowHeight * row - offset;
}
function getRowFromPosition(y) {
return Math.floor((y + offset) / options.rowHeight);
}
function scrollTo(y) {
y = Math.max(y, 0);
y = Math.min(y, th - $viewportScrollContainerY.height() + ((viewportHasHScroll || options.frozenColumn > -1) ? scrollbarDimensions.height : 0));
var oldOffset = offset;
page = Math.min(n - 1, Math.floor(y / ph));
offset = Math.round(page * cj);
var newScrollTop = y - offset;
if (offset != oldOffset) {
var range = getVisibleRange(newScrollTop);
cleanupRows(range);
updateRowPositions();
}
if (prevScrollTop != newScrollTop) {
vScrollDir = (prevScrollTop + oldOffset < newScrollTop + offset) ? 1 : -1;
lastRenderedScrollTop = ( scrollTop = prevScrollTop = newScrollTop );
if (options.frozenColumn > -1) {
$viewportTopL[0].scrollTop = newScrollTop;
}
if (hasFrozenRows) {
$viewportBottomL[0].scrollTop = $viewportBottomR[0].scrollTop = newScrollTop;
}
$viewportScrollContainerY[0].scrollTop = newScrollTop;
trigger(self.onViewportChanged, {});
}
}
function defaultFormatter(row, cell, value, columnDef, dataContext) {
if (value == null) {
return "";
} else {
return (value + "").replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
}
}
function getFormatter(row, column) {
var rowMetadata = data.getItemMetadata && data.getItemMetadata(row);
// look up by id, then index
var columnOverrides = rowMetadata && rowMetadata.columns && (rowMetadata.columns[column.id] || rowMetadata.columns[getColumnIndex(column.id)]);
return (columnOverrides && columnOverrides.formatter) || (rowMetadata && rowMetadata.formatter) || column.formatter || (options.formatterFactory && options.formatterFactory.getFormatter(column)) || options.defaultFormatter;
}
function getEditor(row, cell) {
var column = columns[cell];
var rowMetadata = data.getItemMetadata && data.getItemMetadata(row);
var columnMetadata = rowMetadata && rowMetadata.columns;
if (columnMetadata && columnMetadata[column.id] && columnMetadata[column.id].editor !== undefined) {
return columnMetadata[column.id].editor;
}
if (columnMetadata && columnMetadata[cell] && columnMetadata[cell].editor !== undefined) {
return columnMetadata[cell].editor;
}
return column.editor || (options.editorFactory && options.editorFactory.getEditor(column));
}
function getDataItemValueForColumn(item, columnDef) {
if (options.dataItemColumnValueExtractor) {
return options.dataItemColumnValueExtractor(item, columnDef);
}
return item[columnDef.field];
}
function appendRowHtml(stringArrayL, stringArrayR, row, range, dataLength) {
var d = getDataItem(row);
var dataLoading = row < dataLength && !d;
var rowCss = "slick-row" +
(dataLoading ? " loading" : "") +
(row === activeRow ? " active" : "") +
(row % 2 == 1 ? " odd" : " even");
var metadata = data.getItemMetadata && data.getItemMetadata(row);
if (metadata && metadata.cssClasses) {
rowCss += " " + metadata.cssClasses;
}
var frozenRowOffset = getFrozenRowOffset(row);
var rowHtml = "<div class='ui-widget-content " + rowCss + "' style='top:"
+ (getRowTop(row) - frozenRowOffset )
+ "px'>";
stringArrayL.push(rowHtml);
if (options.frozenColumn > -1) {
stringArrayR.push(rowHtml);
}
var colspan, m;
for (var i = 0, ii = columns.length; i < ii; i++) {
m = columns[i];
colspan = 1;
if (metadata && metadata.columns) {
var columnData = metadata.columns[m.id] || metadata.columns[i];
colspan = (columnData && columnData.colspan) || 1;
if (colspan === "*") {
colspan = ii - i;
}
}
// Do not render cells outside of the viewport.
if (columnPosRight[Math.min(ii - 1, i + colspan - 1)] > range.leftPx) {
if (columnPosLeft[i] > range.rightPx) {
// All columns to the right are outside the range.
break;
}
if (( options.frozenColumn > -1 ) && ( i > options.frozenColumn )) {
appendCellHtml(stringArrayR, row, i, colspan, d);
} else {
appendCellHtml(stringArrayL, row, i, colspan, d);
}
} else if (( options.frozenColumn > -1 ) && ( i <= options.frozenColumn )) {
appendCellHtml(stringArrayL, row, i, colspan);
}
if (colspan > 1) {
i += (colspan - 1);
}
}
stringArrayL.push("</div>");
if (options.frozenColumn > -1) {
stringArrayR.push("</div>");
}
}
function appendCellHtml(stringArray, row, cell, colspan, item) {
var m = columns[cell];
var cellCss = "slick-cell l" + cell + " r" + Math.min(columns.length - 1, cell + colspan - 1)
+ (m.cssClass ? " " + m.cssClass : "");
if (row === activeRow && cell === activeCell) {
cellCss += (" active");
}
// TODO: merge them together in the setter
for (var key in cellCssClasses) {
if (cellCssClasses[key][row] && cellCssClasses[key][row][m.id]) {
cellCss += (" " + cellCssClasses[key][row][m.id]);
}
}
stringArray.push("<div class='" + cellCss + "'>");
// if there is a corresponding row (if not, this is the Add New row or this data hasn't been loaded yet)
if (item) {
var value = getDataItemValueForColumn(item, m);
stringArray.push(getFormatter(row, m)(row, cell, value, m, item));
}
stringArray.push("</div>");
rowsCache[row].cellRenderQueue.push(cell);
rowsCache[row].cellColSpans[cell] = colspan;
}
function cleanupRows(rangeToKeep) {
for (var i in rowsCache) {
var removeFrozenRow = true;
if (hasFrozenRows
&& ( ( options.frozenBottom && i >= actualFrozenRow ) // Frozen bottom rows
|| ( !options.frozenBottom && i <= actualFrozenRow ) // Frozen top rows
)
) {
removeFrozenRow = false;
}
if (( ( i = parseInt(i, 10)) !== activeRow )
&& ( i < rangeToKeep.top || i > rangeToKeep.bottom )
&& ( removeFrozenRow )
) {
removeRowFromCache(i);
}
}
}
function invalidate() {
updateRowCount();
invalidateAllRows();
render();
}
function invalidateAllRows() {
if (currentEditor) {
makeActiveCellNormal();
}
for (var row in rowsCache) {
removeRowFromCache(row);
}
}
function removeRowFromCache(row) {
var cacheEntry = rowsCache[row];
if (!cacheEntry) {
return;
}
cacheEntry.rowNode[0].parentElement.removeChild(cacheEntry.rowNode[0]);
// Remove the row from the right viewport
if (cacheEntry.rowNode[1]) {
cacheEntry.rowNode[1].parentElement.removeChild(cacheEntry.rowNode[1]);
}
delete rowsCache[row];
delete postProcessedRows[row];
renderedRows--;
counter_rows_removed++;
}
function invalidateRows(rows) {
var i, rl;
if (!rows || !rows.length) {
return;
}
vScrollDir = 0;
for (i = 0, rl = rows.length; i < rl; i++) {
if (currentEditor && activeRow === rows[i]) {
makeActiveCellNormal();
}
if (rowsCache[rows[i]]) {
removeRowFromCache(rows[i]);
}
}
}
function invalidateRow(row) {
invalidateRows([row]);
}
function updateCell(row, cell) {
var cellNode = getCellNode(row, cell);
if (!cellNode) {
return;
}
var m = columns[cell],
d = getDataItem(row);
if (currentEditor && activeRow === row && activeCell === cell) {
currentEditor.loadValue(d);
} else {
cellNode.innerHTML = d ? getFormatter(row, m)(row, cell, getDataItemValueForColumn(d, m), m, d) : "";
invalidatePostProcessingResults(row);
}
}
function updateRow(row) {
var cacheEntry = rowsCache[row];
if (!cacheEntry) {
return;
}
ensureCellNodesInRowsCache(row);
var d = getDataItem(row);
for (var columnIdx in cacheEntry.cellNodesByColumnIdx) {
if (!cacheEntry.cellNodesByColumnIdx.hasOwnProperty(columnIdx)) {
continue;
}
columnIdx = columnIdx | 0;
var m = columns[columnIdx],
node = cacheEntry.cellNodesByColumnIdx[columnIdx][0];
if (row === activeRow && columnIdx === activeCell && currentEditor) {
currentEditor.loadValue(d);
} else if (d) {
node.innerHTML = getFormatter(row, m)(row, columnIdx, getDataItemValueForColumn(d, m), m, d);
} else {
node.innerHTML = "";
}
}
invalidatePostProcessingResults(row);
}
function getViewportHeight() {
if (options.autoHeight) {
viewportH = options.rowHeight
* getDataLengthIncludingAddNew()
+ ( ( options.frozenColumn == -1 ) ? $headers.outerHeight() : 0 );
} else {
topPanelH = ( options.showTopPanel )
? options.topPanelHeight + getVBoxDelta($topPanelScroller)
: 0;
headerRowH = ( options.showHeaderRow )
? options.headerRowHeight + getVBoxDelta($headerRowScroller)
: 0;
viewportH = parseFloat($.css($container[0], "height", true))
- parseFloat($.css($container[0], "paddingTop", true))
- parseFloat($.css($container[0], "paddingBottom", true))
- parseFloat($.css($headerScroller[0], "height"))
- getVBoxDelta($headerScroller)
- topPanelH
- headerRowH;
}
numVisibleRows = Math.ceil(viewportH / options.rowHeight);
}
function getViewportWidth() {
viewportW = parseFloat($.css($container[0], "width", true));
}
function resizeCanvas() {
if (!initialized) {
return;
}
paneTopH = 0
paneBottomH = 0
viewportTopH = 0
viewportBottomH = 0;
getViewportWidth();
getViewportHeight();
// Account for Frozen Rows
if (hasFrozenRows) {
if (options.frozenBottom) {
paneTopH = viewportH - frozenRowsHeight - scrollbarDimensions.height;
paneBottomH = frozenRowsHeight + scrollbarDimensions.height;
} else {
paneTopH = frozenRowsHeight;
paneBottomH = viewportH - frozenRowsHeight;
}
} else {
paneTopH = viewportH;
}
// The top pane includes the top panel and the header row
paneTopH += topPanelH + headerRowH;
if (options.frozenColumn > -1 && options.autoHeight) {
paneTopH += scrollbarDimensions.height;
}
// The top viewport does not contain the top panel or header row
viewportTopH = paneTopH - topPanelH - headerRowH
if (options.autoHeight) {
if (options.frozenColumn > -1) {
$container.height(
paneTopH
+ parseFloat($.css($headerScrollerL[0], "height"))
);
}
$paneTopL.css('position', 'relative');
}
$paneTopL.css({
'top': $paneHeaderL.height(), 'height': paneTopH
});
var paneBottomTop = $paneTopL.position().top
+ paneTopH;
$viewportTopL.height(viewportTopH);
if (options.frozenColumn > -1) {
$paneTopR.css({
'top': $paneHeaderL.height(), 'height': paneTopH
});
$viewportTopR.height(viewportTopH);
if (hasFrozenRows) {
$paneBottomL.css({
'top': paneBottomTop, 'height': paneBottomH
});
$paneBottomR.css({
'top': paneBottomTop, 'height': paneBottomH
});
$viewportBottomR.height(paneBottomH);
}
} else {
if (hasFrozenRows) {
$paneBottomL.css({
'width': '100%', 'height': paneBottomH
});
$paneBottomL.css('top', paneBottomTop);
}
}
if (hasFrozenRows) {
$viewportBottomL.height(paneBottomH);
if (options.frozenBottom) {
$canvasBottomL.height(frozenRowsHeight);
if (options.frozenColumn > -1) {
$canvasBottomR.height(frozenRowsHeight);
}
} else {
$canvasTopL.height(frozenRowsHeight);
if (options.frozenColumn > -1) {
$canvasTopR.height(frozenRowsHeight);
}
}
} else {
$viewportTopR.height(viewportTopH);
}
if (options.forceFitColumns) {
autosizeColumns();
}
updateRowCount();
handleScroll();
// Since the width has changed, force the render() to reevaluate virtually rendered cells.
lastRenderedScrollLeft = -1;
render();
}
function updateRowCount() {
if (!initialized) {
return;
}
var dataLengthIncludingAddNew = getDataLengthIncludingAddNew();
var numberOfRows = 0;
var oldH = ( hasFrozenRows && !options.frozenBottom ) ? $canvasBottomL.height() : $canvasTopL.height();
if (hasFrozenRows && options.frozenBottom) {
var numberOfRows = getDataLength() - options.frozenRow;
} else {
var numberOfRows = dataLengthIncludingAddNew + (options.leaveSpaceForNewRows ? numVisibleRows - 1 : 0);
}
var tempViewportH = $viewportScrollContainerY.height();
var oldViewportHasVScroll = viewportHasVScroll;
// with autoHeight, we do not need to accommodate the vertical scroll bar
viewportHasVScroll = !options.autoHeight && (numberOfRows * options.rowHeight > tempViewportH);
// remove the rows that are now outside of the data range
// this helps avoid redundant calls to .removeRow() when the size of
// the data decreased by thousands of rows
var l = dataLengthIncludingAddNew - 1;
for (var i in rowsCache) {
if (i >= l) {
removeRowFromCache(i);
}
}
th = Math.max(options.rowHeight * numberOfRows, tempViewportH - scrollbarDimensions.height);
if (activeCellNode && activeRow > l) {
resetActiveCell();
}
if (th < maxSupportedCssHeight) {
// just one page
h = ph = th;
n = 1;
cj = 0;
} else {
// break into pages
h = maxSupportedCssHeight;
ph = h / 100;
n = Math.floor(th / ph);
cj = (th - h) / (n - 1);
}
if (h !== oldH) {
if (hasFrozenRows && !options.frozenBottom) {
$canvasBottomL.css("height", h);
if (options.frozenColumn > -1) {
$canvasBottomR.css("height", h);
}
} else {
$canvasTopL.css("height", h);
$canvasTopR.css("height", h);
}
scrollTop = $viewportScrollContainerY[0].scrollTop;
}
var oldScrollTopInRange = (scrollTop + offset <= th - tempViewportH);
if (th == 0 || scrollTop == 0) {
page = offset = 0;
} else if (oldScrollTopInRange) {
// maintain virtual position
scrollTo(scrollTop + offset);
} else {
// scroll to bottom
scrollTo(th - tempViewportH);
}
if (h != oldH && options.autoHeight) {
resizeCanvas();
}
if (options.forceFitColumns && oldViewportHasVScroll != viewportHasVScroll) {
autosizeColumns();
}
updateCanvasWidth(false);
}
function getVisibleRange(viewportTop, viewportLeft) {
if (viewportTop == null) {
viewportTop = scrollTop;
}
if (viewportLeft == null) {
viewportLeft = scrollLeft;
}
return {
top: getRowFromPosition(viewportTop),
bottom: getRowFromPosition(viewportTop + viewportH) + 1,
leftPx: viewportLeft,
rightPx: viewportLeft + viewportW
};
}
function getRenderedRange(viewportTop, viewportLeft) {
var range = getVisibleRange(viewportTop, viewportLeft);
var buffer = Math.round(viewportH / options.rowHeight);
var minBuffer = 3;
if (vScrollDir == -1) {
range.top -= buffer;
range.bottom += minBuffer;
} else if (vScrollDir == 1) {
range.top -= minBuffer;
range.bottom += buffer;
} else {
range.top -= minBuffer;
range.bottom += minBuffer;
}
range.top = Math.max(0, range.top);
range.bottom = Math.min(getDataLengthIncludingAddNew() - 1, range.bottom);
range.leftPx -= viewportW;
range.rightPx += viewportW;
range.leftPx = Math.max(0, range.leftPx);
range.rightPx = Math.min(canvasWidth, range.rightPx);
return range;
}
function ensureCellNodesInRowsCache(row) {
var cacheEntry = rowsCache[row];
if (cacheEntry) {
if (cacheEntry.cellRenderQueue.length) {
var $lastNode = cacheEntry.rowNode.children().last();
while (cacheEntry.cellRenderQueue.length) {
var columnIdx = cacheEntry.cellRenderQueue.pop();
cacheEntry.cellNodesByColumnIdx[columnIdx] = $lastNode;
$lastNode = $lastNode.prev();
// Hack to retrieve the frozen columns because
if ($lastNode.length == 0) {
$lastNode = $(cacheEntry.rowNode[0]).children().last();
}
}
}
}
}
function cleanUpCells(range, row) {
// Ignore frozen rows
if (hasFrozenRows
&& ( ( options.frozenBottom && row > actualFrozenRow ) // Frozen bottom rows
|| ( row <= actualFrozenRow ) // Frozen top rows
)
) {
return;
}
var totalCellsRemoved = 0;
var cacheEntry = rowsCache[row];
// Remove cells outside the range.
var cellsToRemove = [];
for (var i in cacheEntry.cellNodesByColumnIdx) {
// I really hate it when people mess with Array.prototype.
if (!cacheEntry.cellNodesByColumnIdx.hasOwnProperty(i)) {
continue;
}
// This is a string, so it needs to be cast back to a number.
i = i | 0;
// Ignore frozen columns
if (i <= options.frozenColumn) {
continue;
}
var colspan = cacheEntry.cellColSpans[i];
if (columnPosLeft[i] > range.rightPx || columnPosRight[Math.min(columns.length - 1, i + colspan - 1)] < range.leftPx) {
if (!(row == activeRow && i == activeCell)) {
cellsToRemove.push(i);
}
}
}
var cellToRemove;
while ((cellToRemove = cellsToRemove.pop()) != null) {
cacheEntry.cellNodesByColumnIdx[cellToRemove][0].parentElement.removeChild(cacheEntry.cellNodesByColumnIdx[cellToRemove][0]);
delete cacheEntry.cellColSpans[cellToRemove];
delete cacheEntry.cellNodesByColumnIdx[cellToRemove];
if (postProcessedRows[row]) {
delete postProcessedRows[row][cellToRemove];
}
totalCellsRemoved++;
}
}
function cleanUpAndRenderCells(range) {
var cacheEntry;
var stringArray = [];
var processedRows = [];
var cellsAdded;
var totalCellsAdded = 0;
var colspan;
for (var row = range.top, btm = range.bottom; row <= btm; row++) {
cacheEntry = rowsCache[row];
if (!cacheEntry) {
continue;
}
// cellRenderQueue populated in renderRows() needs to be cleared first
ensureCellNodesInRowsCache(row);
cleanUpCells(range, row);
// Render missing cells.
cellsAdded = 0;
var metadata = data.getItemMetadata && data.getItemMetadata(row);
metadata = metadata && metadata.columns;
var d = getDataItem(row);
// TODO: shorten this loop (index? heuristics? binary search?)
for (var i = 0, ii = columns.length; i < ii; i++) {
// Cells to the right are outside the range.
if (columnPosLeft[i] > range.rightPx) {
break;
}
// Already rendered.
if ((colspan = cacheEntry.cellColSpans[i]) != null) {
i += (colspan > 1 ? colspan - 1 : 0);
continue;
}
colspan = 1;
if (metadata) {
var columnData = metadata[columns[i].id] || metadata[i];
colspan = (columnData && columnData.colspan) || 1;
if (colspan === "*") {
colspan = ii - i;
}
}
if (columnPosRight[Math.min(ii - 1, i + colspan - 1)] > range.leftPx) {
appendCellHtml(stringArray, row, i, colspan, d);
cellsAdded++;
}
i += (colspan > 1 ? colspan - 1 : 0);
}
if (cellsAdded) {
totalCellsAdded += cellsAdded;
processedRows.push(row);
}
}
if (!stringArray.length) {
return;
}
var x = document.createElement("div");
x.innerHTML = stringArray.join("");
var processedRow;
var $node;
while ((processedRow = processedRows.pop()) != null) {
cacheEntry = rowsCache[processedRow];
var columnIdx;
while ((columnIdx = cacheEntry.cellRenderQueue.pop()) != null) {
$node = $(x).children().last();
if (( options.frozenColumn > -1 ) && ( columnIdx > options.frozenColumn )) {
$(cacheEntry.rowNode[1]).append($node);
} else {
$(cacheEntry.rowNode[0]).append($node);
}
cacheEntry.cellNodesByColumnIdx[columnIdx] = $node;
}
}
}
function renderRows(range) {
var stringArrayL = [],
stringArrayR = [],
rows = [],
needToReselectCell = false,
dataLength = getDataLength();
for (var i = range.top, ii = range.bottom; i <= ii; i++) {
if (rowsCache[i] || ( hasFrozenRows && options.frozenBottom && i == getDataLength() )) {
continue;
}
renderedRows++;
rows.push(i);
// Create an entry right away so that appendRowHtml() can
// start populatating it.
rowsCache[i] = {
"rowNode": null,
// ColSpans of rendered cells (by column idx).
// Can also be used for checking whether a cell has been rendered.
"cellColSpans": [],
// Cell nodes (by column idx). Lazy-populated by ensureCellNodesInRowsCache().
"cellNodesByColumnIdx": [],
// Column indices of cell nodes that have been rendered, but not yet indexed in
// cellNodesByColumnIdx. These are in the same order as cell nodes added at the
// end of the row.
"cellRenderQueue": []
};
appendRowHtml(stringArrayL, stringArrayR, i, range, dataLength);
if (activeCellNode && activeRow === i) {
needToReselectCell = true;
}
counter_rows_rendered++;
}
if (!rows.length) {
return;
}
var x = document.createElement("div"),
xRight = document.createElement("div");
x.innerHTML = stringArrayL.join("");
xRight.innerHTML = stringArrayR.join("");
for (var i = 0, ii = rows.length; i < ii; i++) {
if (( hasFrozenRows ) && ( rows[i] >= actualFrozenRow )) {
if (options.frozenColumn > -1) {
rowsCache[rows[i]].rowNode = $()
.add($(x.firstChild).appendTo($canvasBottomL))
.add($(xRight.firstChild).appendTo($canvasBottomR));
} else {
rowsCache[rows[i]].rowNode = $()
.add($(x.firstChild).appendTo($canvasBottomL));
}
} else if (options.frozenColumn > -1) {
rowsCache[rows[i]].rowNode = $()
.add($(x.firstChild).appendTo($canvasTopL))
.add($(xRight.firstChild).appendTo($canvasTopR));
} else {
rowsCache[rows[i]].rowNode = $()
.add($(x.firstChild).appendTo($canvasTopL));
}
}
if (needToReselectCell) {
activeCellNode = getCellNode(activeRow, activeCell);
}
}
function startPostProcessing() {
if (!options.enableAsyncPostRender) {
return;
}
clearTimeout(h_postrender);
h_postrender = setTimeout(asyncPostProcessRows, options.asyncPostRenderDelay);
}
function invalidatePostProcessingResults(row) {
delete postProcessedRows[row];
postProcessFromRow = Math.min(postProcessFromRow, row);
postProcessToRow = Math.max(postProcessToRow, row);
startPostProcessing();
}
function updateRowPositions() {
for (var row in rowsCache) {
rowsCache[row].rowNode.css('top', getRowTop(row) + "px");
}
}
function render() {
if (!initialized) {
return;
}
var visible = getVisibleRange();
var rendered = getRenderedRange();
// remove rows no longer in the viewport
cleanupRows(rendered);
// add new rows & missing cells in existing rows
if (lastRenderedScrollLeft != scrollLeft) {
cleanUpAndRenderCells(rendered);
}
// render missing rows
renderRows(rendered);
// Render frozen bottom rows
if (options.frozenBottom) {
renderRows({
top: actualFrozenRow, bottom: getDataLength() - 1, leftPx: rendered.leftPx, rightPx: rendered.rightPx
});
}
postProcessFromRow = visible.top;
postProcessToRow = Math.min(getDataLengthIncludingAddNew() - 1, visible.bottom);
startPostProcessing();
lastRenderedScrollTop = scrollTop;
lastRenderedScrollLeft = scrollLeft;
h_render = null;
}
function handleHeaderRowScroll() {
var scrollLeft = $headerRowScrollContainer[0].scrollLeft;
if (scrollLeft != $viewportScrollContainerX[0].scrollLeft) {
$viewportScrollContainerX[0].scrollLeft = scrollLeft;
}
}
function handleMouseWheel(event, delta, deltaX, deltaY) {
scrollTop = Math.max(0, $viewportScrollContainerY[0].scrollTop - (deltaY * options.rowHeight));
scrollLeft = $viewportScrollContainerX[0].scrollLeft + (deltaX * 10);
_handleScroll(true);
event.preventDefault();
}
function handleScroll() {
scrollTop = $viewportScrollContainerY[0].scrollTop;
scrollLeft = $viewportScrollContainerX[0].scrollLeft;
_handleScroll(false);
}
function _handleScroll(isMouseWheel) {
var maxScrollDistanceY = $viewportScrollContainerY[0].scrollHeight - $viewportScrollContainerY[0].clientHeight;
var maxScrollDistanceX = $viewportScrollContainerY[0].scrollWidth - $viewportScrollContainerY[0].clientWidth;
// Ceiling the max scroll values
if (scrollTop > maxScrollDistanceY) {
scrollTop = maxScrollDistanceY;
}
if (scrollLeft > maxScrollDistanceX) {
scrollLeft = maxScrollDistanceX;
}
var vScrollDist = Math.abs(scrollTop - prevScrollTop);
var hScrollDist = Math.abs(scrollLeft - prevScrollLeft);
if (hScrollDist) {
prevScrollLeft = scrollLeft;
$viewportScrollContainerX[0].scrollLeft = scrollLeft;
$headerScrollContainer[0].scrollLeft = scrollLeft;
$topPanelScroller[0].scrollLeft = scrollLeft;
$headerRowScrollContainer[0].scrollLeft = scrollLeft;
if (options.frozenColumn > -1) {
if (hasFrozenRows) {
$viewportTopR[0].scrollLeft = scrollLeft;
}
} else {
if (hasFrozenRows) {
$viewportTopL[0].scrollLeft = scrollLeft;
}
}
}
if (vScrollDist) {
vScrollDir = prevScrollTop < scrollTop ? 1 : -1;
prevScrollTop = scrollTop
if (isMouseWheel) {
$viewportScrollContainerY[0].scrollTop = scrollTop;
}
if (options.frozenColumn > -1) {
if (hasFrozenRows && !options.frozenBottom) {
$viewportBottomL[0].scrollTop = scrollTop;
} else {
$viewportTopL[0].scrollTop = scrollTop;
}
}
// switch virtual pages if needed
if (vScrollDist < viewportH) {
scrollTo(scrollTop + offset);
} else {
var oldOffset = offset;
if (h == viewportH) {
page = 0;
} else {
page = Math.min(n - 1, Math.floor(scrollTop * ((th - viewportH) / (h - viewportH)) * (1 / ph)));
}
offset = Math.round(page * cj);
if (oldOffset != offset) {
invalidateAllRows();
}
}
}
if (hScrollDist || vScrollDist) {
if (h_render) {
clearTimeout(h_render);
}
if (Math.abs(lastRenderedScrollTop - scrollTop) > 20 ||
Math.abs(lastRenderedScrollLeft - scrollLeft) > 20) {
if (options.forceSyncScrolling || (
Math.abs(lastRenderedScrollTop - scrollTop) < viewportH &&
Math.abs(lastRenderedScrollLeft - scrollLeft) < viewportW)) {
render();
} else {
h_render = setTimeout(render, 50);
}
trigger(self.onViewportChanged, {});
}
}
trigger(self.onScroll, {
scrollLeft: scrollLeft,
scrollTop: scrollTop
});
}
function asyncPostProcessRows() {
var dataLength = getDataLength();
while (postProcessFromRow <= postProcessToRow) {
var row = (vScrollDir >= 0) ? postProcessFromRow++ : postProcessToRow--;
var cacheEntry = rowsCache[row];
if (!cacheEntry || row >= dataLength) {
continue;
}
if (!postProcessedRows[row]) {
postProcessedRows[row] = {};
}
ensureCellNodesInRowsCache(row);
for (var columnIdx in cacheEntry.cellNodesByColumnIdx) {
if (!cacheEntry.cellNodesByColumnIdx.hasOwnProperty(columnIdx)) {
continue;
}
columnIdx = columnIdx | 0;
var m = columns[columnIdx];
if (m.asyncPostRender && !postProcessedRows[row][columnIdx]) {
var node = cacheEntry.cellNodesByColumnIdx[columnIdx];
if (node) {
m.asyncPostRender(node, row, getDataItem(row), m);
}
postProcessedRows[row][columnIdx] = true;
}
}
h_postrender = setTimeout(asyncPostProcessRows, options.asyncPostRenderDelay);
return;
}
}
function updateCellCssStylesOnRenderedRows(addedHash, removedHash) {
var node, columnId, addedRowHash, removedRowHash;
for (var row in rowsCache) {
removedRowHash = removedHash && removedHash[row];
addedRowHash = addedHash && addedHash[row];
if (removedRowHash) {
for (columnId in removedRowHash) {
if (!addedRowHash || removedRowHash[columnId] != addedRowHash[columnId]) {
node = getCellNode(row, getColumnIndex(columnId));
if (node) {
$(node).removeClass(removedRowHash[columnId]);
}
}
}
}
if (addedRowHash) {
for (columnId in addedRowHash) {
if (!removedRowHash || removedRowHash[columnId] != addedRowHash[columnId]) {
node = getCellNode(row, getColumnIndex(columnId));
if (node) {
$(node).addClass(addedRowHash[columnId]);
}
}
}
}
}
}
function addCellCssStyles(key, hash) {
if (cellCssClasses[key]) {
throw "addCellCssStyles: cell CSS hash with key '" + key + "' already exists.";
}
cellCssClasses[key] = hash;
updateCellCssStylesOnRenderedRows(hash, null);
trigger(self.onCellCssStylesChanged, {
"key": key,
"hash": hash
});
}
function removeCellCssStyles(key) {
if (!cellCssClasses[key]) {
return;
}
updateCellCssStylesOnRenderedRows(null, cellCssClasses[key]);
delete cellCssClasses[key];
trigger(self.onCellCssStylesChanged, {
"key": key,
"hash": null
});
}
function setCellCssStyles(key, hash) {
var prevHash = cellCssClasses[key];
cellCssClasses[key] = hash;
updateCellCssStylesOnRenderedRows(hash, prevHash);
trigger(self.onCellCssStylesChanged, {
"key": key,
"hash": hash
});
}
function getCellCssStyles(key) {
return cellCssClasses[key];
}
function flashCell(row, cell, speed) {
speed = speed || 100;
if (rowsCache[row]) {
var $cell = $(getCellNode(row, cell));
function toggleCellClass(times) {
if (!times) {
return;
}
setTimeout(function () {
$cell.queue(function () {
$cell.toggleClass(options.cellFlashingCssClass).dequeue();
toggleCellClass(times - 1);
});
}, speed);
}
toggleCellClass(4);
}
}
// ////////////////////////////////////////////////////////////////////////////////////////////
// Interactivity
function handleDragInit(e, dd) {
var cell = getCellFromEvent(e);
if (!cell || !cellExists(cell.row, cell.cell)) {
return false;
}
var retval = trigger(self.onDragInit, dd, e);
if (e.isImmediatePropagationStopped()) {
return retval;
}
// if nobody claims to be handling drag'n'drop by stopping immediate
// propagation, cancel out of it
return false;
}
function handleDragStart(e, dd) {
var cell = getCellFromEvent(e);
if (!cell || !cellExists(cell.row, cell.cell)) {
return false;
}
var retval = trigger(self.onDragStart, dd, e);
if (e.isImmediatePropagationStopped()) {
return retval;
}
return false;
}
function handleDrag(e, dd) {
return trigger(self.onDrag, dd, e);
}
function handleDragEnd(e, dd) {
trigger(self.onDragEnd, dd, e);
}
function handleKeyDown(e) {
trigger(self.onKeyDown, {
row: activeRow,
cell: activeCell
}, e);
var handled = e.isImmediatePropagationStopped();
if (!handled) {
if (!e.shiftKey && !e.altKey && !e.ctrlKey) {
if (e.which == 27) {
if (!getEditorLock().isActive()) {
return; // no editing mode to cancel, allow bubbling and default processing (exit without cancelling the event)
}
cancelEditAndSetFocus();
} else if (e.which == 34) {
navigatePageDown();
handled = true;
} else if (e.which == 33) {
navigatePageUp();
handled = true;
} else if (e.which == 37) {
handled = navigateLeft();
} else if (e.which == 39) {
handled = navigateRight();
} else if (e.which == 38) {
handled = navigateUp();
} else if (e.which == 40) {
handled = navigateDown();
} else if (e.which == 9) {
handled = navigateNext();
} else if (e.which == 13) {
if (options.editable) {
if (currentEditor) {
// adding new row
if (activeRow === getDataLength()) {
navigateDown();
} else {
commitEditAndSetFocus();
}
} else {
if (getEditorLock().commitCurrentEdit()) {
makeActiveCellEditable();
}
}
}
handled = true;
}
} else if (e.which == 9 && e.shiftKey && !e.ctrlKey && !e.altKey) {
handled = navigatePrev();
}
}
if (handled) {
// the event has been handled so don't let parent element (bubbling/propagation) or browser (default) handle it
e.stopPropagation();
e.preventDefault();
try {
e.originalEvent.keyCode = 0; // prevent default behaviour for special keys in IE browsers (F3, F5, etc.)
}
// ignore exceptions - setting the original event's keycode throws
// access denied exception for "Ctrl" (hitting control key only, nothing else), "Shift" (maybe others)
catch (error) {
}
}
}
function handleClick(e) {
if (!currentEditor) {
// if this click resulted in some cell child node getting focus,
// don't steal it back - keyboard events will still bubble up
// IE9+ seems to default DIVs to tabIndex=0 instead of -1, so check for cell clicks directly.
if (e.target != document.activeElement || $(e.target).hasClass("slick-cell")) {
setFocus();
}
}
var cell = getCellFromEvent(e);
if (!cell || (currentEditor !== null && activeRow == cell.row && activeCell == cell.cell)) {
return;
}
trigger(self.onClick, {
row: cell.row,
cell: cell.cell
}, e);
if (e.isImmediatePropagationStopped()) {
return;
}
if ((activeCell != cell.cell || activeRow != cell.row) && canCellBeActive(cell.row, cell.cell)) {
if (!getEditorLock().isActive() || getEditorLock().commitCurrentEdit()) {
if (hasFrozenRows) {
if (( !( options.frozenBottom ) && ( cell.row >= actualFrozenRow ) )
|| ( options.frozenBottom && ( cell.row < actualFrozenRow ) )
) {
scrollRowIntoView(cell.row, false);
}
setActiveCellInternal(getCellNode(cell.row, cell.cell));
}
}
}
}
function handleContextMenu(e) {
var $cell = $(e.target).closest(".slick-cell", $canvas);
if ($cell.length === 0) {
return;
}
// are we editing this cell?
if (activeCellNode === $cell[0] && currentEditor !== null) {
return;
}
trigger(self.onContextMenu, {}, e);
}
function handleDblClick(e) {
var cell = getCellFromEvent(e);
if (!cell || (currentEditor !== null && activeRow == cell.row && activeCell == cell.cell)) {
return;
}
trigger(self.onDblClick, {
row: cell.row,
cell: cell.cell
}, e);
if (e.isImmediatePropagationStopped()) {
return;
}
if (options.editable) {
gotoCell(cell.row, cell.cell, true);
}
}
function handleHeaderMouseEnter(e) {
trigger(self.onHeaderMouseEnter, {
"column": $(this).data("column")
}, e);
}
function handleHeaderMouseLeave(e) {
trigger(self.onHeaderMouseLeave, {
"column": $(this).data("column")
}, e);
}
function handleHeaderContextMenu(e) {
var $header = $(e.target).closest(".slick-header-column", ".slick-header-columns");
var column = $header && $header.data("column");
trigger(self.onHeaderContextMenu, {
column: column
}, e);
}
function handleHeaderClick(e) {
var $header = $(e.target).closest(".slick-header-column", ".slick-header-columns");
var column = $header && $header.data("column");
if (column) {
trigger(self.onHeaderClick, {
column: column
}, e);
}
}
function handleMouseEnter(e) {
trigger(self.onMouseEnter, {}, e);
}
function handleMouseLeave(e) {
trigger(self.onMouseLeave, {}, e);
}
function cellExists(row, cell) {
return !(row < 0 || row >= getDataLength() || cell < 0 || cell >= columns.length);
}
function getCellFromPoint(x, y) {
var row = getRowFromPosition(y);
var cell = 0;
var w = 0;
for (var i = 0; i < columns.length && w < x; i++) {
w += columns[i].width;
cell++;
}
if (cell < 0) {
cell = 0;
}
return {
row: row,
cell: cell - 1
};
}
function getCellFromNode(cellNode) {
// read column number from .l<columnNumber> CSS class
var cls = /l\d+/.exec(cellNode.className);
if (!cls) {
throw "getCellFromNode: cannot get cell - " + cellNode.className;
}
return parseInt(cls[0].substr(1, cls[0].length - 1), 10);
}
function getRowFromNode(rowNode) {
for (var row in rowsCache) {
if (rowsCache[row].rowNode[0] === rowNode[0]) {
return row | 0;
}
}
return null;
}
function getFrozenRowOffset(row) {
var offset =
( hasFrozenRows )
? ( options.frozenBottom )
? ( row >= actualFrozenRow )
? ( h < viewportTopH )
? ( actualFrozenRow * options.rowHeight )
: h
: 0
: ( row >= actualFrozenRow )
? frozenRowsHeight
: 0
: 0;
return offset;
}
function getCellFromEvent(e) {
var $cell = $(e.target).closest(".slick-cell", $canvas);
if (!$cell.length) {
return null;
}
// TODO: This change eliminates the need for getCellFromEvent since
// we're ultimately calling getCellFromPoint. Need to further analyze
// if getCellFromEvent can work with frozen columns
var c = $cell.parents('.grid-canvas').offset();
var rowOffset = 0;
var isBottom = $cell.parents('.grid-canvas-bottom').length;
if (hasFrozenRows && isBottom) {
rowOffset = ( options.frozenBottom ) ? $canvasTopL.height() : frozenRowsHeight;
}
var row = getCellFromPoint(e.clientX - c.left, e.clientY - c.top + rowOffset + $(document).scrollTop()).row;
var cell = getCellFromNode($cell[0]);
if (row == null || cell == null) {
return null;
} else {
return {
"row": row,
"cell": cell
};
}
}
function getCellNodeBox(row, cell) {
if (!cellExists(row, cell)) {
return null;
}
var frozenRowOffset = getFrozenRowOffset(row);
var y1 = getRowTop(row) - frozenRowOffset;
var y2 = y1 + options.rowHeight - 1;
var x1 = 0;
for (var i = 0; i < cell; i++) {
x1 += columns[i].width;
if (options.frozenColumn == i) {
x1 = 0;
}
}
var x2 = x1 + columns[cell].width;
return {
top: y1,
left: x1,
bottom: y2,
right: x2
};
}
// ////////////////////////////////////////////////////////////////////////////////////////////
// Cell switching
function resetActiveCell() {
setActiveCellInternal(null, false);
}
function setFocus() {
if (tabbingDirection == -1) {
$focusSink[0].focus();
} else {
$focusSink2[0].focus();
}
}
function scrollCellIntoView(row, cell, doPaging) {
// Don't scroll to frozen cells
if (cell <= options.frozenColumn) {
return;
}
if (row < actualFrozenRow) {
scrollRowIntoView(row, doPaging);
}
var colspan = getColspan(row, cell);
var left = columnPosLeft[cell],
right = columnPosRight[cell + (colspan > 1 ? colspan - 1 : 0)],
scrollRight = scrollLeft + $viewportScrollContainerX.width();
if (left < scrollLeft) {
$viewportScrollContainerX.scrollLeft(left);
handleScroll();
render();
} else if (right > scrollRight) {
$viewportScrollContainerX.scrollLeft(Math.min(left, right - $viewportScrollContainerX[0].clientWidth));
handleScroll();
render();
}
}
function setActiveCellInternal(newCell, opt_editMode) {
if (activeCellNode !== null) {
makeActiveCellNormal();
$(activeCellNode).removeClass("active");
if (rowsCache[activeRow]) {
$(rowsCache[activeRow].rowNode).removeClass("active");
}
}
var activeCellChanged = (activeCellNode !== newCell);
activeCellNode = newCell;
if (activeCellNode != null) {
var $activeCellNode = $(activeCellNode);
var $activeCellOffset = $activeCellNode.offset();
var rowOffset = Math.floor($activeCellNode.parents('.grid-canvas').offset().top);
var isBottom = $activeCellNode.parents('.grid-canvas-bottom').length;
if (hasFrozenRows && isBottom) {
rowOffset -= ( options.frozenBottom )
? $canvasTopL.height()
: frozenRowsHeight;
}
cell = getCellFromPoint($activeCellOffset.left, Math.ceil($activeCellOffset.top) - rowOffset);
activeRow = cell.row;
activeCell = activePosX = activeCell = activePosX = getCellFromNode(activeCellNode[0]);
$activeCellNode.addClass("active");
if (rowsCache[activeRow]) {
$(rowsCache[activeRow].rowNode).addClass('active');
}
if (opt_editMode == null) {
opt_editMode = (activeRow == getDataLength()) || options.autoEdit;
}
if (options.editable && opt_editMode && isCellPotentiallyEditable(activeRow, activeCell)) {
clearTimeout(h_editorLoader);
if (options.asyncEditorLoading) {
h_editorLoader = setTimeout(function () {
makeActiveCellEditable();
}, options.asyncEditorLoadDelay);
} else {
makeActiveCellEditable();
}
}
} else {
activeRow = activeCell = null;
}
if (activeCellChanged) {
setTimeout(scrollActiveCellIntoView, 50);
trigger(self.onActiveCellChanged, getActiveCell());
}
}
function clearTextSelection() {
if (document.selection && document.selection.empty) {
try {
//IE fails here if selected element is not in dom
document.selection.empty();
} catch (e) {
}
} else if (window.getSelection) {
var sel = window.getSelection();
if (sel && sel.removeAllRanges) {
sel.removeAllRanges();
}
}
}
function isCellPotentiallyEditable(row, cell) {
var dataLength = getDataLength();
// is the data for this row loaded?
if (row < dataLength && !getDataItem(row)) {
return false;
}
// are we in the Add New row? can we create new from this cell?
if (columns[cell].cannotTriggerInsert && row >= dataLength) {
return false;
}
// does this cell have an editor?
if (!getEditor(row, cell)) {
return false;
}
return true;
}
function makeActiveCellNormal() {
if (!currentEditor) {
return;
}
trigger(self.onBeforeCellEditorDestroy, {
editor: currentEditor
});
currentEditor.destroy();
currentEditor = null;
if (activeCellNode) {
var d = getDataItem(activeRow);
$(activeCellNode).removeClass("editable invalid");
if (d) {
var column = columns[activeCell];
var formatter = getFormatter(activeRow, column);
activeCellNode[0].innerHTML = formatter(activeRow, activeCell, getDataItemValueForColumn(d, column), column, d);
invalidatePostProcessingResults(activeRow);
}
}
// if there previously was text selected on a page (such as selected
// text in the edit cell just removed),
// IE can't set focus to anything else correctly
if (navigator.userAgent.toLowerCase().match(/msie/)) {
clearTextSelection();
}
getEditorLock().deactivate(editController);
}
function makeActiveCellEditable(editor) {
if (!activeCellNode) {
return;
}
if (!options.editable) {
throw "Grid : makeActiveCellEditable : should never get called when options.editable is false";
}
// cancel pending async call if there is one
clearTimeout(h_editorLoader);
if (!isCellPotentiallyEditable(activeRow, activeCell)) {
return;
}
var columnDef = columns[activeCell];
var item = getDataItem(activeRow);
if (trigger(self.onBeforeEditCell, {
row: activeRow,
cell: activeCell,
item: item,
column: columnDef
}) === false) {
setFocus();
return;
}
getEditorLock().activate(editController);
$(activeCellNode).addClass("editable");
// don't clear the cell if a custom editor is passed through
if (!editor) {
activeCellNode[0].innerHTML = "";
}
currentEditor = new (editor || getEditor(activeRow, activeCell))({
grid: self,
gridPosition: absBox($container[0]),
position: absBox(activeCellNode[0]),
container: activeCellNode,
column: columnDef,
item: item || {},
commitChanges: commitEditAndSetFocus,
cancelChanges: cancelEditAndSetFocus
});
if (item) {
currentEditor.loadValue(item);
}
serializedEditorValue = currentEditor.serializeValue();
if (currentEditor.position) {
handleActiveCellPositionChange();
}
}
function commitEditAndSetFocus() {
// if the commit fails, it would do so due to a validation error
// if so, do not steal the focus from the editor
if (getEditorLock().commitCurrentEdit()) {
setFocus();
if (options.autoEdit) {
navigateDown();
}
}
}
function cancelEditAndSetFocus() {
if (getEditorLock().cancelCurrentEdit()) {
setFocus();
}
}
function absBox(elem) {
var box = {
top: elem.offsetTop,
left: elem.offsetLeft,
bottom: 0,
right: 0,
width: $(elem).outerWidth(),
height: $(elem).outerHeight(),
visible: true
};
box.bottom = box.top + box.height;
box.right = box.left + box.width;
// walk up the tree
var offsetParent = elem.offsetParent;
while ((elem = elem.parentNode) != document.body) {
if (box.visible && elem.scrollHeight != elem.offsetHeight && $(elem).css("overflowY") != "visible") {
box.visible = box.bottom > elem.scrollTop && box.top < elem.scrollTop + elem.clientHeight;
}
if (box.visible && elem.scrollWidth != elem.offsetWidth && $(elem).css("overflowX") != "visible") {
box.visible = box.right > elem.scrollLeft && box.left < elem.scrollLeft + elem.clientWidth;
}
box.left -= elem.scrollLeft;
box.top -= elem.scrollTop;
if (elem === offsetParent) {
box.left += elem.offsetLeft;
box.top += elem.offsetTop;
offsetParent = elem.offsetParent;
}
box.bottom = box.top + box.height;
box.right = box.left + box.width;
}
return box;
}
function getActiveCellPosition() {
return absBox(activeCellNode[0]);
}
function getGridPosition() {
return absBox($container[0]);
}
function handleActiveCellPositionChange() {
if (!activeCellNode) {
return;
}
trigger(self.onActiveCellPositionChanged, {});
if (currentEditor) {
var cellBox = getActiveCellPosition();
if (currentEditor.show && currentEditor.hide) {
if (!cellBox.visible) {
currentEditor.hide();
} else {
currentEditor.show();
}
}
if (currentEditor.position) {
currentEditor.position(cellBox);
}
}
}
function getCellEditor() {
return currentEditor;
}
function getActiveCell() {
if (!activeCellNode) {
return null;
} else {
return {
row: activeRow,
cell: activeCell
};
}
}
function getActiveCellNode() {
return activeCellNode;
}
function scrollActiveCellIntoView() {
if (activeRow != null && activeCell != null) {
scrollCellIntoView(activeRow, activeCell);
}
}
function scrollRowIntoView(row, doPaging) {
if (hasFrozenRows && !options.frozenBottom) {
row -= actualFrozenRow;
}
var viewportScrollH = $viewportScrollContainerY.height();
var rowAtTop = row * options.rowHeight;
var rowAtBottom = (row + 1) * options.rowHeight
- viewportScrollH
+ (viewportHasHScroll ? scrollbarDimensions.height : 0);
// need to page down?
if ((row + 1) * options.rowHeight > scrollTop + viewportScrollH + offset) {
scrollTo(doPaging ? rowAtTop : rowAtBottom);
render();
}
// or page up?
else if (row * options.rowHeight < scrollTop + offset) {
scrollTo(doPaging ? rowAtBottom : rowAtTop);
render();
}
}
function scrollRowToTop(row) {
scrollTo(row * options.rowHeight);
render();
}
function scrollPage(dir) {
var deltaRows = dir * numVisibleRows;
scrollTo((getRowFromPosition(scrollTop) + deltaRows) * options.rowHeight);
render();
if (options.enableCellNavigation && activeRow != null) {
var row = activeRow + deltaRows;
var dataLengthIncludingAddNew = getDataLengthIncludingAddNew();
if (row >= dataLengthIncludingAddNew) {
row = dataLengthIncludingAddNew - 1;
}
if (row < 0) {
row = 0;
}
var cell = 0, prevCell = null;
var prevActivePosX = activePosX;
while (cell <= activePosX) {
if (canCellBeActive(row, cell)) {
prevCell = cell;
}
cell += getColspan(row, cell);
}
if (prevCell !== null) {
setActiveCellInternal(getCellNode(row, prevCell));
activePosX = prevActivePosX;
} else {
resetActiveCell();
}
}
}
function navigatePageDown() {
scrollPage(1);
}
function navigatePageUp() {
scrollPage(-1);
}
function getColspan(row, cell) {
var metadata = data.getItemMetadata && data.getItemMetadata(row);
if (!metadata || !metadata.columns) {
return 1;
}
var columnData = metadata.columns[columns[cell].id] || metadata.columns[cell];
var colspan = (columnData && columnData.colspan);
if (colspan === "*") {
colspan = columns.length - cell;
} else {
colspan = colspan || 1;
}
return (colspan || 1);
}
function findFirstFocusableCell(row) {
var cell = 0;
while (cell < columns.length) {
if (canCellBeActive(row, cell)) {
return cell;
}
cell += getColspan(row, cell);
}
return null;
}
function findLastFocusableCell(row) {
var cell = 0;
var lastFocusableCell = null;
while (cell < columns.length) {
if (canCellBeActive(row, cell)) {
lastFocusableCell = cell;
}
cell += getColspan(row, cell);
}
return lastFocusableCell;
}
function gotoRight(row, cell, posX) {
if (cell >= columns.length) {
return null;
}
do {
cell += getColspan(row, cell);
} while (cell < columns.length && !canCellBeActive(row, cell));
if (cell < columns.length) {
return {
"row": row,
"cell": cell,
"posX": cell
};
}
return null;
}
function gotoLeft(row, cell, posX) {
if (cell <= 0) {
return null;
}
var firstFocusableCell = findFirstFocusableCell(row);
if (firstFocusableCell === null || firstFocusableCell >= cell) {
return null;
}
var prev = {
"row": row,
"cell": firstFocusableCell,
"posX": firstFocusableCell
};
var pos;
while (true) {
pos = gotoRight(prev.row, prev.cell, prev.posX);
if (!pos) {
return null;
}
if (pos.cell >= cell) {
return prev;
}
prev = pos;
}
}
function gotoDown(row, cell, posX) {
var prevCell;
var dataLengthIncludingAddNew = getDataLengthIncludingAddNew();
while (true) {
if (++row >= dataLengthIncludingAddNew) {
return null;
}
prevCell = cell = 0;
while (cell <= posX) {
prevCell = cell;
cell += getColspan(row, cell);
}
if (canCellBeActive(row, prevCell)) {
return {
"row": row,
"cell": prevCell,
"posX": posX
};
}
}
}
function gotoUp(row, cell, posX) {
var prevCell;
while (true) {
if (--row < 0) {
return null;
}
prevCell = cell = 0;
while (cell <= posX) {
prevCell = cell;
cell += getColspan(row, cell);
}
if (canCellBeActive(row, prevCell)) {
return {
"row": row,
"cell": prevCell,
"posX": posX
};
}
}
}
function gotoNext(row, cell, posX) {
if (row == null && cell == null) {
row = cell = posX = 0;
if (canCellBeActive(row, cell)) {
return {
"row": row,
"cell": cell,
"posX": cell
};
}
}
var pos = gotoRight(row, cell, posX);
if (pos) {
return pos;
}
var firstFocusableCell = null;
var dataLengthIncludingAddNew = getDataLengthIncludingAddNew();
while (++row < dataLengthIncludingAddNew) {
firstFocusableCell = findFirstFocusableCell(row);
if (firstFocusableCell !== null) {
return {
"row": row,
"cell": firstFocusableCell,
"posX": firstFocusableCell
};
}
}
return null;
}
function gotoPrev(row, cell, posX) {
if (row == null && cell == null) {
row = getDataLengthIncludingAddNew() - 1;
cell = posX = columns.length - 1;
if (canCellBeActive(row, cell)) {
return {
"row": row,
"cell": cell,
"posX": cell
};
}
}
var pos;
var lastSelectableCell;
while (!pos) {
pos = gotoLeft(row, cell, posX);
if (pos) {
break;
}
if (--row < 0) {
return null;
}
cell = 0;
lastSelectableCell = findLastFocusableCell(row);
if (lastSelectableCell !== null) {
pos = {
"row": row,
"cell": lastSelectableCell,
"posX": lastSelectableCell
};
}
}
return pos;
}
function navigateRight() {
return navigate("right");
}
function navigateLeft() {
return navigate("left");
}
function navigateDown() {
return navigate("down");
}
function navigateUp() {
return navigate("up");
}
function navigateNext() {
return navigate("next");
}
function navigatePrev() {
return navigate("prev");
}
/**
* @param {string} dir Navigation direction.
* @return {boolean} Whether navigation resulted in a change of active cell.
*/
function navigate(dir) {
if (!options.enableCellNavigation) {
return false;
}
if (!activeCellNode && dir != "prev" && dir != "next") {
return false;
}
if (!getEditorLock().commitCurrentEdit()) {
return true;
}
setFocus();
var tabbingDirections = {
"up": -1,
"down": 1,
"left": -1,
"right": 1,
"prev": -1,
"next": 1
};
tabbingDirection = tabbingDirections[dir];
var stepFunctions = {
"up": gotoUp,
"down": gotoDown,
"left": gotoLeft,
"right": gotoRight,
"prev": gotoPrev,
"next": gotoNext
};
var stepFn = stepFunctions[dir];
var pos = stepFn(activeRow, activeCell, activePosX);
if (pos) {
if (hasFrozenRows && options.frozenBottom & pos.row == getDataLength()) {
return;
}
var isAddNewRow = (pos.row == getDataLength());
if (( !options.frozenBottom && pos.row >= actualFrozenRow )
|| ( options.frozenBottom && pos.row < actualFrozenRow )
) {
scrollCellIntoView(pos.row, pos.cell, !isAddNewRow);
}
setActiveCellInternal(getCellNode(pos.row, pos.cell))
activePosX = pos.posX;
return true;
} else {
setActiveCellInternal(getCellNode(activeRow, activeCell));
return false;
}
}
function getCellNode(row, cell) {
if (rowsCache[row]) {
ensureCellNodesInRowsCache(row);
return rowsCache[row].cellNodesByColumnIdx[cell];
}
return null;
}
function setActiveCell(row, cell) {
if (!initialized) {
return;
}
if (row > getDataLength() || row < 0 || cell >= columns.length || cell < 0) {
return;
}
if (!options.enableCellNavigation) {
return;
}
scrollCellIntoView(row, cell, false);
setActiveCellInternal(getCellNode(row, cell), false);
}
function canCellBeActive(row, cell) {
if (!options.enableCellNavigation || row >= getDataLengthIncludingAddNew() ||
row < 0 || cell >= columns.length || cell < 0) {
return false;
}
var rowMetadata = data.getItemMetadata && data.getItemMetadata(row);
if (rowMetadata && typeof rowMetadata.focusable === "boolean") {
return rowMetadata.focusable;
}
var columnMetadata = rowMetadata && rowMetadata.columns;
if (columnMetadata && columnMetadata[columns[cell].id] && typeof columnMetadata[columns[cell].id].focusable === "boolean") {
return columnMetadata[columns[cell].id].focusable;
}
if (columnMetadata && columnMetadata[cell] && typeof columnMetadata[cell].focusable === "boolean") {
return columnMetadata[cell].focusable;
}
return columns[cell].focusable;
}
function canCellBeSelected(row, cell) {
if (row >= getDataLength() || row < 0 || cell >= columns.length || cell < 0) {
return false;
}
var rowMetadata = data.getItemMetadata && data.getItemMetadata(row);
if (rowMetadata && typeof rowMetadata.selectable === "boolean") {
return rowMetadata.selectable;
}
var columnMetadata = rowMetadata && rowMetadata.columns && (rowMetadata.columns[columns[cell].id] || rowMetadata.columns[cell]);
if (columnMetadata && typeof columnMetadata.selectable === "boolean") {
return columnMetadata.selectable;
}
return columns[cell].selectable;
}
function gotoCell(row, cell, forceEdit) {
if (!initialized) {
return;
}
if (!canCellBeActive(row, cell)) {
return;
}
if (!getEditorLock().commitCurrentEdit()) {
return;
}
scrollCellIntoView(row, cell, false);
var newCell = getCellNode(row, cell);
// if selecting the 'add new' row, start editing right away
setActiveCellInternal(newCell, forceEdit || (row === getDataLength()) || options.autoEdit);
// if no editor was created, set the focus back on the grid
if (!currentEditor) {
setFocus();
}
}
// ////////////////////////////////////////////////////////////////////////////////////////////
// IEditor implementation for the editor lock
function commitCurrentEdit() {
var item = getDataItem(activeRow);
var column = columns[activeCell];
if (currentEditor) {
if (currentEditor.isValueChanged()) {
var validationResults = currentEditor.validate();
if (validationResults.valid) {
if (activeRow < getDataLength()) {
var editCommand = {
row: activeRow,
cell: activeCell,
editor: currentEditor,
serializedValue: currentEditor.serializeValue(),
prevSerializedValue: serializedEditorValue,
execute: function () {
this.editor.applyValue(item, this.serializedValue);
updateRow(this.row);
},
undo: function () {
this.editor.applyValue(item, this.prevSerializedValue);
updateRow(this.row);
}
};
if (options.editCommandHandler) {
makeActiveCellNormal();
options.editCommandHandler(item, column, editCommand);
} else {
editCommand.execute();
makeActiveCellNormal();
}
trigger(self.onCellChange, {
row: activeRow,
cell: activeCell,
item: item
});
} else {
var newItem = {};
currentEditor.applyValue(newItem, currentEditor.serializeValue());
makeActiveCellNormal();
trigger(self.onAddNewRow, {
item: newItem,
column: column
});
}
// check whether the lock has been re-acquired by event handlers
return !getEditorLock().isActive();
} else {
// Re-add the CSS class to trigger transitions, if any.
$(activeCellNode).removeClass("invalid");
$(activeCellNode).width(); // force layout
$(activeCellNode).addClass("invalid");
trigger(self.onValidationError, {
editor: currentEditor,
cellNode: activeCellNode,
validationResults: validationResults,
row: activeRow,
cell: activeCell,
column: column
});
currentEditor.focus();
return false;
}
}
makeActiveCellNormal();
}
return true;
}
function cancelCurrentEdit() {
makeActiveCellNormal();
return true;
}
function rowsToRanges(rows) {
var ranges = [];
var lastCell = columns.length - 1;
for (var i = 0; i < rows.length; i++) {
ranges.push(new Slick.Range(rows[i], 0, rows[i], lastCell));
}
return ranges;
}
function getSelectedRows() {
if (!selectionModel) {
throw "Selection model is not set";
}
return selectedRows;
}
function setSelectedRows(rows) {
if (!selectionModel) {
throw "Selection model is not set";
}
selectionModel.setSelectedRanges(rowsToRanges(rows));
}
// ////////////////////////////////////////////////////////////////////////////////////////////
// Debug
this.debug = function () {
var s = "";
s += ("\n" + "counter_rows_rendered: " + counter_rows_rendered);
s += ("\n" + "counter_rows_removed: " + counter_rows_removed);
s += ("\n" + "renderedRows: " + renderedRows);
s += ("\n" + "numVisibleRows: " + numVisibleRows);
s += ("\n" + "maxSupportedCssHeight: " + maxSupportedCssHeight);
s += ("\n" + "n(umber of pages): " + n);
s += ("\n" + "(current) page: " + page);
s += ("\n" + "page height (ph): " + ph);
s += ("\n" + "vScrollDir: " + vScrollDir);
alert(s);
};
// a debug helper to be able to access private members
this.eval = function (expr) {
return eval(expr);
};
// ////////////////////////////////////////////////////////////////////////////////////////////
// Public API
$.extend(this, {
"slickGridVersion": "2.1",
// Events
"onScroll": new Slick.Event(),
"onSort": new Slick.Event(),
"onHeaderMouseEnter": new Slick.Event(),
"onHeaderMouseLeave": new Slick.Event(),
"onHeaderContextMenu": new Slick.Event(),
"onHeaderClick": new Slick.Event(),
"onHeaderCellRendered": new Slick.Event(),
"onBeforeHeaderCellDestroy": new Slick.Event(),
"onHeaderRowCellRendered": new Slick.Event(),
"onBeforeHeaderRowCellDestroy": new Slick.Event(),
"onMouseEnter": new Slick.Event(),
"onMouseLeave": new Slick.Event(),
"onClick": new Slick.Event(),
"onDblClick": new Slick.Event(),
"onContextMenu": new Slick.Event(),
"onKeyDown": new Slick.Event(),
"onAddNewRow": new Slick.Event(),
"onValidationError": new Slick.Event(),
"onViewportChanged": new Slick.Event(),
"onColumnsReordered": new Slick.Event(),
"onColumnsResized": new Slick.Event(),
"onCellChange": new Slick.Event(),
"onBeforeEditCell": new Slick.Event(),
"onBeforeCellEditorDestroy": new Slick.Event(),
"onBeforeDestroy": new Slick.Event(),
"onActiveCellChanged": new Slick.Event(),
"onActiveCellPositionChanged": new Slick.Event(),
"onDragInit": new Slick.Event(),
"onDragStart": new Slick.Event(),
"onDrag": new Slick.Event(),
"onDragEnd": new Slick.Event(),
"onSelectedRowsChanged": new Slick.Event(),
"onCellCssStylesChanged": new Slick.Event(),
// Methods
"registerPlugin": registerPlugin,
"unregisterPlugin": unregisterPlugin,
"getColumns": getColumns,
"setColumns": setColumns,
"getColumnIndex": getColumnIndex,
"updateColumnHeader": updateColumnHeader,
"setSortColumn": setSortColumn,
"setSortColumns": setSortColumns,
"getSortColumns": getSortColumns,
"autosizeColumns": autosizeColumns,
"getOptions": getOptions,
"setOptions": setOptions,
"getData": getData,
"getDataLength": getDataLength,
"getDataItem": getDataItem,
"setData": setData,
"getSelectionModel": getSelectionModel,
"setSelectionModel": setSelectionModel,
"getSelectedRows": getSelectedRows,
"setSelectedRows": setSelectedRows,
"getContainerNode": getContainerNode,
"render": render,
"invalidate": invalidate,
"invalidateRow": invalidateRow,
"invalidateRows": invalidateRows,
"invalidateAllRows": invalidateAllRows,
"updateCell": updateCell,
"updateRow": updateRow,
"getViewport": getVisibleRange,
"getRenderedRange": getRenderedRange,
"resizeCanvas": resizeCanvas,
"updateRowCount": updateRowCount,
"scrollRowIntoView": scrollRowIntoView,
"scrollRowToTop": scrollRowToTop,
"scrollCellIntoView": scrollCellIntoView,
"getCanvasNode": getCanvasNode,
"getCanvases": getCanvases,
"getActiveCanvasNode": getActiveCanvasNode,
"setActiveCanvasNode": setActiveCanvasNode,
"getViewportNode": getViewportNode,
"getActiveViewportNode": getActiveViewportNode,
"setActiveViewportNode": setActiveViewportNode,
"focus": setFocus,
"getCellFromPoint": getCellFromPoint,
"getCellFromEvent": getCellFromEvent,
"getActiveCell": getActiveCell,
"setActiveCell": setActiveCell,
"getActiveCellNode": getActiveCellNode,
"getActiveCellPosition": getActiveCellPosition,
"resetActiveCell": resetActiveCell,
"editActiveCell": makeActiveCellEditable,
"getCellEditor": getCellEditor,
"getCellNode": getCellNode,
"getCellNodeBox": getCellNodeBox,
"canCellBeSelected": canCellBeSelected,
"canCellBeActive": canCellBeActive,
"navigatePrev": navigatePrev,
"navigateNext": navigateNext,
"navigateUp": navigateUp,
"navigateDown": navigateDown,
"navigateLeft": navigateLeft,
"navigateRight": navigateRight,
"navigatePageUp": navigatePageUp,
"navigatePageDown": navigatePageDown,
"gotoCell": gotoCell,
"getTopPanel": getTopPanel,
"setTopPanelVisibility": setTopPanelVisibility,
"setHeaderRowVisibility": setHeaderRowVisibility,
"getHeaderRow": getHeaderRow,
"getHeaderRowColumn": getHeaderRowColumn,
"getGridPosition": getGridPosition,
"flashCell": flashCell,
"addCellCssStyles": addCellCssStyles,
"setCellCssStyles": setCellCssStyles,
"removeCellCssStyles": removeCellCssStyles,
"getCellCssStyles": getCellCssStyles,
"getFrozenRowOffset": getFrozenRowOffset,
"init": finishInitialization,
"destroy": destroy,
// IEditor implementation
"getEditorLock": getEditorLock,
"getEditController": getEditController
});
init();
}
}(jQuery));
| when rendering a frozen column which is out of of viewport, we must give it data in order to render it correctly
| slick.grid.js | when rendering a frozen column which is out of of viewport, we must give it data in order to render it correctly | <ide><path>lick.grid.js
<ide> });
<ide> }
<ide> });
<del>
<add>
<ide> $headerRowL.empty();
<ide> $headerRowR.empty();
<del>
<add>
<ide> for (var i = 0; i < columns.length; i++) {
<ide> var m = columns[i];
<ide>
<ide> appendCellHtml(stringArrayL, row, i, colspan, d);
<ide> }
<ide> } else if (( options.frozenColumn > -1 ) && ( i <= options.frozenColumn )) {
<del> appendCellHtml(stringArrayL, row, i, colspan);
<add> appendCellHtml(stringArrayL, row, i, colspan, d);
<ide> }
<ide>
<ide> if (colspan > 1) { |
|
Java | apache-2.0 | 82b106713aad9610e1e3485e062333f1abee927f | 0 | amberarrow/incubator-apex-core,vrozov/apex-core,brightchen/incubator-apex-core,simplifi-it/otterx,klynchDS/incubator-apex-core,simplifi-it/otterx,mattqzhang/apex-core,mattqzhang/apex-core,deepak-narkhede/apex-core,ishark/incubator-apex-core,tweise/apex-core,PramodSSImmaneni/apex-core,brightchen/apex-core,mt0803/incubator-apex-core,sandeshh/incubator-apex-core,PramodSSImmaneni/apex-core,tushargosavi/incubator-apex-core,aniruddhas/incubator-apex-core,PramodSSImmaneni/incubator-apex-core,chinmaykolhatkar/incubator-apex-core,tweise/apex-core,sandeshh/incubator-apex-core,brightchen/apex-core,deepak-narkhede/apex-core,tweise/incubator-apex-core,simplifi-it/otterx,brightchen/incubator-apex-core,devtagare/incubator-apex-core,mattqzhang/apex-core,vrozov/incubator-apex-core,chinmaykolhatkar/incubator-apex-core,vrozov/apex-core,tushargosavi/apex-core,sandeshh/apex-core,deepak-narkhede/apex-core,tweise/incubator-apex-core,vrozov/apex-core,apache/incubator-apex-core,tushargosavi/incubator-apex-core,andyperlitch/incubator-apex-core,tushargosavi/incubator-apex-core,devtagare/incubator-apex-core,PramodSSImmaneni/apex-core,mt0803/incubator-apex-core,PramodSSImmaneni/incubator-apex-core,ishark/incubator-apex-core,brightchen/apex-core,vrozov/incubator-apex-core,andyperlitch/incubator-apex-core,MalharJenkins/incubator-apex-core,chinmaykolhatkar/incubator-apex-core,devtagare/incubator-apex-core,vrozov/incubator-apex-core,tushargosavi/apex-core,tweise/apex-core,MalharJenkins/incubator-apex-core,sandeshh/apex-core,tweise/incubator-apex-core,aniruddhas/incubator-apex-core,PramodSSImmaneni/incubator-apex-core,apache/incubator-apex-core,sandeshh/incubator-apex-core,klynchDS/incubator-apex-core,amberarrow/incubator-apex-core,ishark/incubator-apex-core,sandeshh/apex-core,apache/incubator-apex-core,tushargosavi/apex-core | /**
* Copyright (c) 2012-2012 Malhar, Inc.
* All rights reserved.
*/
package com.malhartech.stram;
import java.util.Collections;
import java.util.Map;
import java.util.Properties;
import org.apache.hadoop.conf.Configuration;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.malhartech.dag.ComponentContextPair;
import com.malhartech.dag.Context;
import com.malhartech.dag.Node;
import com.malhartech.dag.NodeContext;
import com.malhartech.stram.StramLocalCluster.LocalStramChild;
import com.malhartech.stram.StreamingNodeUmbilicalProtocol.ContainerHeartbeatResponse;
import com.malhartech.stram.StreamingNodeUmbilicalProtocol.StramToNodeRequest;
import com.malhartech.stram.StreamingNodeUmbilicalProtocol.StramToNodeRequest.RequestType;
import com.malhartech.stram.TopologyBuilderTest.EchoNode;
import com.malhartech.stram.TopologyDeployer.PTNode;
import com.malhartech.stram.conf.NewTopologyBuilder;
import com.malhartech.stram.conf.Topology;
import com.malhartech.stram.conf.Topology.NodeDecl;
import com.malhartech.stram.conf.TopologyBuilder;
import com.malhartech.stream.HDFSOutputStream;
public class StramLocalClusterTest
{
private static Logger LOG = LoggerFactory.getLogger(StramLocalClusterTest.class);
@Test
public void testLocalClusterInitShutdown() throws Exception
{
// create test topology
Properties props = new Properties();
// input adapter to ensure shutdown works on end of stream
props.put("stram.stream.input1.classname", NumberGeneratorInputAdapter.class.getName());
props.put("stram.stream.input1.outputNode", "node1");
props.put("stram.stream.input1.maxTuples", "1");
// fake output adapter - to be ignored when determine shutdown
props.put("stram.stream.output.classname", HDFSOutputStream.class.getName());
props.put("stram.stream.output.inputNode", "node2");
props.put("stram.stream.output.filepath", "target/" + StramLocalClusterTest.class.getName() + "-testSetupShutdown.out");
props.put("stram.stream.output.append", "false");
props.put("stram.stream.n1n2.inputNode", "node1");
props.put("stram.stream.n1n2.outputNode", "node2");
props.put("stram.stream.n1n2.template", "defaultstream");
props.put("stram.node.node1.classname", TopologyBuilderTest.EchoNode.class.getName());
props.put("stram.node.node1.myStringProperty", "myStringPropertyValue");
props.put("stram.node.node2.classname", TopologyBuilderTest.EchoNode.class.getName());
props.setProperty(Topology.STRAM_MAX_CONTAINERS, "2");
TopologyBuilder tb = new TopologyBuilder(new Configuration());
tb.addFromProperties(props);
StramLocalCluster localCluster = new StramLocalCluster(tb.getTopology());
localCluster.run();
}
@Ignore // we have a problem with windows randomly getting lost
@Test
public void testChildRecovery() throws Exception
{
NewTopologyBuilder tb = new NewTopologyBuilder();
NodeDecl node1 = tb.addNode("node1", new EchoNode());
NodeDecl node2 = tb.addNode("node2", new EchoNode());
tb.addStream("n1n2").
setSource(node1.getOutput(EchoNode.OUTPUT1)).
addSink(node2.getInput(EchoNode.INPUT1));
//tb.validate();
Topology tplg = tb.getTopology();
tplg.getConf().setInt(Topology.STRAM_WINDOW_SIZE_MILLIS, 0); // disable window generator
tplg.getConf().setInt(Topology.STRAM_CHECKPOINT_INTERVAL_MILLIS, 0); // disable auto backup
TestWindowGenerator wingen = new TestWindowGenerator();
StramLocalCluster localCluster = new StramLocalCluster(tplg);
localCluster.runAsync();
LocalStramChild c0 = waitForContainer(localCluster, node1);
Thread.sleep(1000);
Map<String, ComponentContextPair<Node, NodeContext>> nodeMap = c0.getNodes();
Assert.assertEquals("number nodes", 2, nodeMap.size());
PTNode ptNode1 = localCluster.findByLogicalNode(node1);
ComponentContextPair<Node, NodeContext> n1 = nodeMap.get(ptNode1.id);
Assert.assertNotNull(n1);
LocalStramChild c2 = waitForContainer(localCluster, node2);
Map<String, ComponentContextPair<Node, NodeContext>> c2NodeMap = c2.getNodes();
Assert.assertEquals("number nodes downstream", 1, c2NodeMap.size());
ComponentContextPair<Node, NodeContext> n2 = c2NodeMap.get(localCluster.findByLogicalNode(node2).id);
Assert.assertNotNull(n2);
Assert.assertEquals("initial window id", 0, n1.context.getLastProcessedWindowId());
wingen.tick(1);
waitForWindow(n1.context, 1);
backupNode(c0, n1.context);
wingen.tick(1);
waitForWindow(n2.context, 2);
backupNode(c2, n2.context);
wingen.tick(1);
// move window forward and wait for nodes to reach,
// to ensure backup in previous windows was processed
wingen.tick(1);
//waitForWindow(n1, 3);
waitForWindow(n2.context, 3);
// propagate checkpoints to master
c0.triggerHeartbeat();
// wait for heartbeat cycle to complete
c0.waitForHeartbeat(5000);
c2.triggerHeartbeat();
c2.waitForHeartbeat(5000);
// simulate node failure
localCluster.failContainer(c0);
// replacement container starts empty
// nodes will deploy after downstream node was removed
LocalStramChild c0Replaced = waitForContainer(localCluster, node1);
c0Replaced.triggerHeartbeat();
c0Replaced.waitForHeartbeat(5000); // next heartbeat after init
Assert.assertNotSame("old container", c0, c0Replaced);
Assert.assertNotSame("old container", c0.getContainerId(), c0Replaced.getContainerId());
// verify change in downstream container
LOG.debug("triggering c2 heartbeat processing");
StramChildAgent c2Agent = localCluster.getContainerAgent(c2);
// wait for downstream re-deploy to complete
while (c2Agent.hasPendingWork()) {
Thread.sleep(500);
c2.triggerHeartbeat();
LOG.debug("Waiting for {} to complete pending work.", c2.getContainerId());
}
Assert.assertEquals("downstream nodes after redeploy " + c2.getNodes(), 1, c2.getNodes().size());
// verify that the downstream node was replaced
ComponentContextPair<Node, NodeContext> n2Replaced = c2NodeMap.get(localCluster.findByLogicalNode(node2).id);
Assert.assertNotNull(n2Replaced);
Assert.assertNotSame("node2 redeployed", n2, n2Replaced);
ComponentContextPair<Node, NodeContext> n1Replaced = nodeMap.get(ptNode1.id);
Assert.assertNotNull(n1Replaced);
Assert.assertEquals("initial window id", 1, n1Replaced.context.getLastProcessedWindowId());
localCluster.shutdown();
}
/**
* Wait until instance of node comes online in a container
*
* @param localCluster
* @param nodeConf
* @return
* @throws InterruptedException
*/
private LocalStramChild waitForContainer(StramLocalCluster localCluster, NodeDecl nodeDecl) throws InterruptedException
{
PTNode node = localCluster.findByLogicalNode(nodeDecl);
Assert.assertNotNull("no node for " + nodeDecl, node);
LocalStramChild container;
while (true) {
if (node.container.containerId != null) {
if ((container = localCluster.getContainer(node.container.containerId)) != null) {
if (container.getNodes().get(node.id) != null) {
return container;
}
}
}
try {
LOG.debug("Waiting for {} in container {}", node, node.container.containerId);
Thread.sleep(500);
}
catch (InterruptedException e) {
}
}
}
private void waitForWindow(NodeContext nodeCtx, long windowId) throws InterruptedException
{
while (nodeCtx.getLastProcessedWindowId() < windowId) {
LOG.debug("Waiting for window {} at node {}", windowId, nodeCtx.getId());
Thread.sleep(100);
}
}
private void backupNode(StramChild c, NodeContext nodeCtx)
{
StramToNodeRequest backupRequest = new StramToNodeRequest();
backupRequest.setNodeId(nodeCtx.getId());
backupRequest.setRequestType(RequestType.CHECKPOINT);
ContainerHeartbeatResponse rsp = new ContainerHeartbeatResponse();
rsp.setNodeRequests(Collections.singletonList(backupRequest));
LOG.debug("Requesting backup {} {}", c.getContainerId(), nodeCtx);
c.processHeartbeatResponse(rsp);
}
public static class TestWindowGenerator {
private final ManualScheduledExecutorService mses = new ManualScheduledExecutorService(1);
public final WindowGenerator wingen = new WindowGenerator(mses);
public TestWindowGenerator() {
Configuration config = new Configuration();
config.setLong(WindowGenerator.FIRST_WINDOW_MILLIS, 0);
config.setInt(WindowGenerator.WINDOW_WIDTH_MILLIS, 1);
wingen.setup(config);
}
public void tick(long steps) {
mses.tick(steps);
}
}
}
| engine/src/test/java/com/malhartech/stram/StramLocalClusterTest.java | /**
* Copyright (c) 2012-2012 Malhar, Inc.
* All rights reserved.
*/
package com.malhartech.stram;
import java.util.Collections;
import java.util.Map;
import java.util.Properties;
import org.apache.hadoop.conf.Configuration;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.malhartech.dag.ComponentContextPair;
import com.malhartech.dag.Context;
import com.malhartech.dag.Node;
import com.malhartech.dag.NodeContext;
import com.malhartech.stram.StramLocalCluster.LocalStramChild;
import com.malhartech.stram.StreamingNodeUmbilicalProtocol.ContainerHeartbeatResponse;
import com.malhartech.stram.StreamingNodeUmbilicalProtocol.StramToNodeRequest;
import com.malhartech.stram.StreamingNodeUmbilicalProtocol.StramToNodeRequest.RequestType;
import com.malhartech.stram.TopologyBuilderTest.EchoNode;
import com.malhartech.stram.TopologyDeployer.PTNode;
import com.malhartech.stram.conf.NewTopologyBuilder;
import com.malhartech.stram.conf.Topology;
import com.malhartech.stram.conf.Topology.NodeDecl;
import com.malhartech.stram.conf.TopologyBuilder;
import com.malhartech.stream.HDFSOutputStream;
public class StramLocalClusterTest
{
private static Logger LOG = LoggerFactory.getLogger(StramLocalClusterTest.class);
@Test
public void testLocalClusterInitShutdown() throws Exception
{
// create test topology
Properties props = new Properties();
// input adapter to ensure shutdown works on end of stream
props.put("stram.stream.input1.classname", NumberGeneratorInputAdapter.class.getName());
props.put("stram.stream.input1.outputNode", "node1");
props.put("stram.stream.input1.maxTuples", "1");
// fake output adapter - to be ignored when determine shutdown
props.put("stram.stream.output.classname", HDFSOutputStream.class.getName());
props.put("stram.stream.output.inputNode", "node2");
props.put("stram.stream.output.filepath", "target/" + StramLocalClusterTest.class.getName() + "-testSetupShutdown.out");
props.put("stram.stream.output.append", "false");
props.put("stram.stream.n1n2.inputNode", "node1");
props.put("stram.stream.n1n2.outputNode", "node2");
props.put("stram.stream.n1n2.template", "defaultstream");
props.put("stram.node.node1.classname", TopologyBuilderTest.EchoNode.class.getName());
props.put("stram.node.node1.myStringProperty", "myStringPropertyValue");
props.put("stram.node.node2.classname", TopologyBuilderTest.EchoNode.class.getName());
props.setProperty(Topology.STRAM_MAX_CONTAINERS, "2");
TopologyBuilder tb = new TopologyBuilder(new Configuration());
tb.addFromProperties(props);
StramLocalCluster localCluster = new StramLocalCluster(tb.getTopology());
localCluster.run();
}
@Ignore // we have a problem with windows randomly getting lost
@Test
public void testChildRecovery() throws Exception
{
NewTopologyBuilder tb = new NewTopologyBuilder();
NodeDecl node1 = tb.addNode("node1", new EchoNode());
NodeDecl node2 = tb.addNode("node2", new EchoNode());
tb.addStream("n1n2").
setSource(node1.getOutput(EchoNode.OUTPUT1)).
addSink(node2.getInput(EchoNode.INPUT1));
//tb.validate();
Topology tplg = tb.getTopology();
tplg.getConf().setInt(Topology.STRAM_WINDOW_SIZE_MILLIS, 0); // disable window generator
tplg.getConf().setInt(Topology.STRAM_CHECKPOINT_INTERVAL_MILLIS, 0); // disable auto backup
TestWindowGenerator wingen = new TestWindowGenerator();
StramLocalCluster localCluster = new StramLocalCluster(tplg);
localCluster.runAsync();
LocalStramChild c0 = waitForContainer(localCluster, node1);
Thread.sleep(1000);
Map<String, ComponentContextPair<Node, NodeContext>> nodeMap = c0.getNodes();
Assert.assertEquals("number nodes", 2, nodeMap.size());
PTNode ptNode1 = localCluster.findByLogicalNode(node1);
ComponentContextPair<Node, NodeContext> n1 = nodeMap.get(ptNode1.id);
Assert.assertNotNull(n1);
LocalStramChild c2 = waitForContainer(localCluster, node2);
Map<String, ComponentContextPair<Node, NodeContext>> c2NodeMap = c2.getNodes();
Assert.assertEquals("number nodes downstream", 1, c2NodeMap.size());
ComponentContextPair<Node, NodeContext> n2 = c2NodeMap.get(localCluster.findByLogicalNode(node2).id);
Assert.assertNotNull(n2);
Assert.assertEquals("initial window id", 0, n1.context.getLastProcessedWindowId());
wingen.tick(1);
waitForWindow(n1.context, 1);
backupNode(c0, n1.context);
wingen.tick(1);
waitForWindow(n2.context, 2);
backupNode(c2, n2.context);
wingen.tick(1);
// move window forward and wait for nodes to reach,
// to ensure backup in previous windows was processed
wingen.tick(1);
//waitForWindow(n1, 3);
waitForWindow(n2.context, 3);
// propagate checkpoints to master
c0.triggerHeartbeat();
// wait for heartbeat cycle to complete
c0.waitForHeartbeat(5000);
c2.triggerHeartbeat();
c2.waitForHeartbeat(5000);
// simulate node failure
localCluster.failContainer(c0);
// replacement container starts empty
// nodes will deploy after downstream node was removed
LocalStramChild c0Replaced = waitForContainer(localCluster, node1);
c0Replaced.triggerHeartbeat();
c0Replaced.waitForHeartbeat(5000); // next heartbeat after init
Assert.assertNotSame("old container", c0, c0Replaced);
Assert.assertNotSame("old container", c0.getContainerId(), c0Replaced.getContainerId());
// verify change in downstream container
LOG.debug("triggering c2 heartbeat processing");
StramChildAgent c2Agent = localCluster.getContainerAgent(c2);
// wait for downstream re-deploy to complete
while (c2Agent.hasPendingWork()) {
Thread.sleep(500);
c2.triggerHeartbeat();
LOG.debug("Waiting for {} to complete pending work.", c2.getContainerId());
}
Assert.assertEquals("downstream nodes after redeploy " + c2.getNodes(), 1, c2.getNodes().size());
// verify that the downstream node was replaced
ComponentContextPair<Node, NodeContext> n2Replaced = c2NodeMap.get(localCluster.findByLogicalNode(node2).id);
Assert.assertNotNull(n2Replaced);
Assert.assertNotSame("node2 redeployed", n2, n2Replaced);
ComponentContextPair<Node, NodeContext> n1Replaced = nodeMap.get(ptNode1.id);
Assert.assertNotNull(n1Replaced);
Assert.assertEquals("initial window id", 1, n1Replaced.context.getLastProcessedWindowId());
localCluster.shutdown();
}
/**
* Wait until instance of node comes online in a container
*
* @param localCluster
* @param nodeConf
* @return
* @throws InterruptedException
*/
private LocalStramChild waitForContainer(StramLocalCluster localCluster, NodeDecl nodeDecl) throws InterruptedException
{
PTNode node = localCluster.findByLogicalNode(nodeDecl);
Assert.assertNotNull("no node for " + nodeDecl, node);
LocalStramChild container;
while (true) {
if (node.container.containerId != null) {
if ((container = localCluster.getContainer(node.container.containerId)) != null) {
if (container.getNodes().get(node.id) != null) {
return container;
}
}
}
try {
LOG.debug("Waiting for {} in container {}", node, node.container.containerId);
Thread.sleep(500);
}
catch (InterruptedException e) {
}
}
}
private void waitForWindow(NodeContext nodeCtx, long windowId) throws InterruptedException
{
while (nodeCtx.getLastProcessedWindowId() < windowId) {
LOG.debug("Waiting for window {} at node {}", windowId, nodeCtx.getId());
Thread.sleep(100);
}
}
private void backupNode(StramChild c, NodeContext nodeCtx)
{
StramToNodeRequest backupRequest = new StramToNodeRequest();
backupRequest.setNodeId(nodeCtx.getId());
backupRequest.setRequestType(RequestType.CHECKPOINT);
ContainerHeartbeatResponse rsp = new ContainerHeartbeatResponse();
rsp.setNodeRequests(Collections.singletonList(backupRequest));
LOG.debug("Requesting backup {} {}", c.getContainerId(), nodeCtx);
c.processHeartbeatResponse(rsp);
}
public static class TestWindowGenerator {
private final ManualScheduledExecutorService mses = new ManualScheduledExecutorService(1);
public final WindowGenerator wingen = new WindowGenerator(mses);
public TestWindowGenerator() {
Configuration config = new Configuration();
config.setLong(WindowGenerator.FIRST_WINDOW_MILLIS, 0);
config.setInt(WindowGenerator.WINDOW_WIDTH_MILLIS, 1);
wingen.setup(config);
}
public void tick(long steps) {
mses.tick(steps);
}
public void activate() {
wingen.activate(new Context() {});
}
}
}
| removed dead code. | engine/src/test/java/com/malhartech/stram/StramLocalClusterTest.java | removed dead code. | <ide><path>ngine/src/test/java/com/malhartech/stram/StramLocalClusterTest.java
<ide> public void tick(long steps) {
<ide> mses.tick(steps);
<ide> }
<del>
<del> public void activate() {
<del> wingen.activate(new Context() {});
<del> }
<del>
<del>
<del> }
<del>
<add> }
<ide> } |
|
JavaScript | mit | 5d799d0bfddbb6b6a287112e3a5a681e2a30ecb1 | 0 | nervetattoo/jquery-autosave | /**
* @fileOverview jQuery.autosave
*
* @author Kyle Florence
* @website https://github.com/kflorence/jquery-autosave
* @version 1.2-pre
*
* Inspired by the jQuery.autosave plugin written by Raymond Julin,
* Mads Erik Forberg and Simen Graaten.
*
* Dual licensed under the MIT and BSD Licenses.
*/
;(function($, window, document, undefined) {
// Figure out if html5 "input" event is available
var inputSupported = (function() {
var tmp = document.createElement("input");
if ('oninput' in tmp) return true;
// also try workaround for older versions of Firefox
tmp.setAttribute("oninput", "return;");
return typeof tmp["oninput"] === "function";
}());
/**
* Attempts to find a callback from a list of callbacks.
*
* @param {String|Object|function} callback
* The callback to get. Can be a string or object that represents one of
* the built in callback methods, or a custom function to use instead.
*
* @param {Object} callbacks
* An object containing the callbacks to search in.
*
* @returns {Object}
* The callback object. This will be an empty object if the callback
* could not be found. If it was found, this object will contain at the
* very least a "method" property and potentially an "options" property.
*/
var _findCallback = function(callback, callbacks) {
var cb = { options: {} }, callbackType = typeof callback;
if (callbackType === "function") {
// Custom function with no options
cb.method = callback;
} else if (callbackType === "string" && callbacks[callback]) {
// Built in method, use default options
cb.method = callbacks[callback].method;
} else if (callbackType === "object") {
callbackType = typeof callback.method;
if (callbackType === "function") {
// Custom function
cb.method = callback.method;
} else if (callbackType === "string" && callbacks[callback.method]) {
// Built in method
cb.method = callbacks[callback.method].method;
cb.options = $.extend(true, cb.options, callbacks[callback.method].options, callback.options);
}
}
return cb;
};
$.autosave = {
timer: 0,
$queues: $({}),
states: {
changed: "changed",
modified: "modified"
},
options: {
namespace: "autosave",
callbacks: {
trigger: "change",
scope: null,
data: "serialize",
condition: null,
save: "ajax"
},
events: {
save: "save",
saved: "saved",
changed: "changed",
modified: "modified"
},
classes: {
ignore: "ignore"
}
},
/**
* Initializes the plugin.
*
* @param {jQuery} $elements
* The elements passed to the plugin.
*
* @param {Object} [options]
* The user-defined options to merge with the defaults.
*
* @returns {jQuery} $elements
* The elements passed to the plugin to maintain chainability.
*/
initialize: function($elements, options) {
var self = this;
this.$elements = $elements;
this.options = $.extend(true, {}, this.options, options);
// If length == 0, we have no forms or inputs
if (this.elements().length) {
var validCallbacks, $forms = this.forms(), $inputs = this.inputs();
// Only attach to forms
$forms.data(this.options.namespace, this);
$.each(this.options.events, function(name, eventName) {
self.options.events[name] = [eventName, self.options.namespace].join(".");
});
$.each(this.options.classes, function(name, className) {
self.options.classes[name] = [self.options.namespace, className].join("-");
});
// Parse callback options into an array of callback objects
$.each(this.options.callbacks, function(key, value) {
validCallbacks = [];
if (value) {
$.each($.isArray(value) ? value : [value], function(i, callback) {
callback = _findCallback(callback, self.callbacks[key]);
// If callback has a valid method, we can use it
if ($.isFunction(callback.method)) {
validCallbacks.push(callback);
}
});
}
self.options.callbacks[key] = validCallbacks;
});
// Attempt to save when "save" is triggered on a form
$forms.bind([this.options.events.save, this.options.namespace].join("."), function(e, inputs) {
self.save(inputs, e.type);
});
// Listen for changes on all inputs
$inputs.bind(["change", this.options.namespace].join("."), function(e) {
$(this).data([self.options.namespace, self.states.changed].join("."), true);
$(this.form).triggerHandler(self.options.events.changed, [this]);
});
// Listen for modifications on all inputs
// Use html5 "input" event is available. Otherwise, use "keyup".
var modifyTriggerEvent = inputSupported ? "input" : "keyup";
$inputs.bind([modifyTriggerEvent, this.options.namespace].join("."), function(e) {
$(this).data([self.options.namespace, self.states.modified].join("."), true);
$(this.form).triggerHandler(self.options.events.modified, [this]);
});
// Set up triggers
$.each(this.options.callbacks.trigger, function(i, trigger) {
trigger.method.call(self, trigger.options);
});
}
return $elements;
},
/**
* Returns the forms and inputs within a specific context.
*
* @param {jQuery|Element|Element[]} [elements]
* The elements to search within. Uses the pass elements by default.
*
* @return {jQuery}
* A jQuery object containing any matched form and input elements.
*/
elements: function(elements) {
if (!elements) elements = this.$elements;
return $(elements).filter(function() {
return (this.elements || this.form);
});
},
/**
* Returns the forms found within elements.
*
* @param {jQuery|Element|Element[]} [elements]
* The elements to search within. Uses all of the currently found
* forms and form inputs by default.
*
* @returns {jQuery}
* A jQuery object containing any matched form elements.
*/
forms: function(elements) {
return $($.unique(this.elements(elements).map(function() {
return this.elements ? this : this.form;
}).get()));
},
/**
* Returns the inputs found within elements.
*
* @param {jQuery|Element|Element[]} elements
* The elements to search within. Uses all of the currently found
* forms and form inputs by default.
*
* @returns {jQuery}
* A jQuery object containing any matched input elements.
*/
inputs: function(elements) {
return this.elements(elements).map(function() {
return this.elements ? $.makeArray($(this).find(":input")) : this;
});
},
/**
* Returns the inputs from a set of inputs that are considered valid.
*
* @param {jQuery|Element|Element[]} [inputs]
* The set of inputs to search within. Uses all of the currently found
* inputs by default.
*
* @returns {jQuery}
* A jQuery object containing any matched input elements.
*/
validInputs: function(inputs) {
var self = this;
return this.inputs(inputs).filter(function() {
return !$(this).hasClass(self.options.classes.ignore);
});
},
/**
* Get all of the inputs whose value has changed since the last save.
*
* @param {jQuery|Element|Element[]} [inputs]
* The set of inputs to search within. Uses all of the currently found
* inputs by default.
*
* @returns {jQuery}
* A jQuery object containing any matched input elements.
*/
changedInputs: function(inputs) {
var self = this;
return this.inputs(inputs).filter(function() {
return $(this).data([self.options.namespace, self.states.changed].join("."));
});
},
/**
* Get all of the inputs whose value has been modified since the last save.
*
* @param {jQuery|Element|Element[]} [inputs]
* The set of inputs to search within. Uses all of the currently found
* inputs by default.
*
* @returns {jQuery}
* A jQuery object containing any matched input elements.
*/
modifiedInputs: function(inputs) {
var self = this;
return this.inputs(inputs).filter(function() {
return $(this).data([self.options.namespace, self.states.modified].join("."));
});
},
/**
* Starts an autosave interval loop, stopping the current one if needed.
*
* @param {number} interval
* An integer value representing the time between intervals in
* milliseconds.
*/
startInterval: function(interval) {
var self = this;
interval = interval || this.interval;
if (this.timer) {
this.stopInterval();
}
if (!isNaN(parseInt(interval))) {
this.timer = setTimeout(function() {
self.save(false, self.timer);
}, interval);
}
},
/**
* Stops an autosave interval loop.
*/
stopInterval: function() {
clearTimeout(this.timer);
this.timer = null;
},
/**
* Attemps to save form data.
*
* @param {jQuery|Element|Element[]} [inputs]
* The inputs to extract data from. Can be of type jQuery, a DOM
* element, or an array of DOM elements. If no inputs are passed, all
* of the currently available inputs will be used.
*
* @param {mixed} [caller]
* Used to denote who called this function. If passed, it is typically
* the ID of the current interval timer and may be used to check if the
* timer called this function.
*/
save: function(inputs, caller) {
var self = this, saved = false,
$inputs = this.validInputs(inputs);
// If there are no save methods defined, we can't save
if (this.options.callbacks.save.length) {
// Continue filtering the scope of inputs
$.each(this.options.callbacks.scope, function(i, scope) {
$inputs = scope.method.call(self, scope.options, $inputs);
});
if ($inputs.length) {
var formData, passes = true;
// Manipulate form data
$.each(this.options.callbacks.data, function(i, data) {
formData = data.method.call(self, data.options, $inputs, formData);
});
// Loop through pre-save conditions and proceed only if they pass
$.each(this.options.callbacks.condition, function(i, condition) {
return (passes = condition.method.call(
self, condition.options, $inputs, formData, caller
)) !== false;
});
if (passes) {
// Add all of our save methods to the queue
$.each(this.options.callbacks.save, function(i, save) {
self.$queues.queue("save", function() {
if (save.method.call(self, save.options, formData) === false) {
// Methods that return false should handle the call to next()
// we call resetFields manually here (immediately) before the async
// save fires, because the callback will call next without 'true'.
// and we want to reset the fields when the async save *starts*.
self.resetFields();
} else {
self.next("save", true);
}
});
});
// We were able to save
saved = true;
}
}
}
// Start the dequeue process
this.next("save", saved);
},
/**
* Maintains the queue; calls the next function in line, or performs
* necessary cleanup when the queue is empty.
*
* @param {String} name
* The name of the queue.
*
* @param {Boolean} [resetChanged]
* Whether or not to reset which elements were changed/modified before saving.
* Defaults to false.
*/
next: function(name, resetChanged) {
var queue = this.$queues.queue(name);
// Dequeue the next function if queue is not empty
if (queue && queue.length) {
this.$queues.dequeue(name);
}
// Queue is empty or does not exist
else {
this.finished(queue, name, resetChanged);
}
},
/**
* Reset which elements where changed/modified before saving.
*/
resetFields: function() {
this.inputs().data([this.options.namespace, this.states.changed].join("."), false);
this.inputs().data([this.options.namespace, this.states.modified].join("."), false);
},
/**
* Called whenever a queue finishes processing, usually to perform some
* type of cleanup.
*
* @param {Array} queue
* The queue that has finished processing.
*
* @param {Boolean} [resetChanged]
* Whether or not to reset which elements were changed/modified before saving.
* Defaults to false
*/
finished: function(queue, name, resetChanged) {
if (name === "save") {
if (queue) {
this.forms().triggerHandler(this.options.events.saved);
}
if (resetChanged) {
this.resetFields();
}
// If there is a timer running, start the next interval
if (this.timer) {
this.startInterval();
}
}
}
};
var callbacks = $.autosave.callbacks = {};
$.each($.autosave.options.callbacks, function(key) {
callbacks[key] = {};
});
$.extend(callbacks.trigger, {
/**
* Attempt to save any time an input value changes.
*/
change: {
method: function() {
var self = this;
this.forms().bind([this.options.events.changed, this.options.namespace].join("."), function(e, input) {
self.save(input, e.type);
});
}
},
/**
* Attempt to save any time an input value is modified.
*/
modify: {
method: function() {
var self = this;
this.forms().bind([this.options.events.modified, this.options.namespace].join("."), function(e, input) {
self.save(input, e.type);
});
}
},
/**
* Creates an interval loop that will attempt to save periodically.
*/
interval: {
method: function(options) {
if (!isNaN(parseInt(options.interval))) {
this.startInterval(this.interval = options.interval);
}
},
options: {
interval: 30000
}
}
});
$.extend(callbacks.scope, {
/**
* Use all inputs
*/
all: {
method: function() {
return this.validInputs();
}
},
/**
* Only use the inputs with values that have changed since the last save.
*/
changed: {
method: function() {
return this.changedInputs();
}
},
/**
* Only use the inputs with values that have been modified since the last save.
*/
modified: {
method: function() {
return this.modifiedInputs();
}
}
});
$.extend(callbacks.data, {
/**
* See: http://api.jquery.com/serialize/
*
* @returns {String}
* Standard URL-encoded string of form values.
*/
serialize: {
method: function(options, $inputs) {
return $inputs.serialize();
}
},
/**
* See: http://api.jquery.com/serializeArray/
*
* @returns {Array}
* An array of objects containing name/value pairs.
*/
serializeArray: {
method: function(options, $inputs) {
return $inputs.serializeArray();
}
},
/**
* Whereas .serializeArray() serializes a form into an array,
* .serializeObject() serializes a form into an object.
*
* jQuery serializeObject - v0.2 - 1/20/2010
* http://benalman.com/projects/jquery-misc-plugins/
*
* Copyright (c) 2010 "Cowboy" Ben Alman
* Dual licensed under the MIT and GPL licenses.
* http://benalman.com/about/license/
*
* @returns {Object}
* The resulting object of form values.
*/
serializeObject: {
method: function(options, $inputs) {
var obj = {};
$.each($inputs.serializeArray(), function(i, o) {
var n = o.name, v = o.value;
obj[n] = obj[n] === undefined ? v
: $.isArray(obj[n]) ? obj[n].concat(v)
: [obj[n], v];
});
return obj;
}
}
});
$.extend(callbacks.condition, {
/**
* Only save if the interval called the save method.
*/
interval: {
method: function(options, $inputs, data, caller) {
return (!this.timer || this.timer === caller);
}
},
/**
* Only save if at least one of the input values has changed.
*/
changed: {
method: function() {
return this.changedInputs().length > 0;
}
},
/**
* Only save if at least one of the input values has been modified.
*/
modified: {
method: function() {
return this.modifiedInputs().length > 0;
}
}
});
$.extend(callbacks.save, {
/**
* Saves form data using a jQuery.ajax call.
*/
ajax: {
method: function(options, formData) {
var self = this, o = $.extend({}, options);
// Wrap the complete method with our own
o.complete = function(xhr, status) {
if ($.isFunction(options.complete)) {
options.complete.apply(self, arguments);
}
self.next("save");
};
// Allow for dynamically generated data
if ($.isFunction(o.data)) {
o.data = o.data.call(self, formData);
}
var formDataType = $.type(formData),
optionsDataType = $.type(o.data);
// No options data given, use form data
if (optionsDataType == "undefined") {
o.data = formData;
// Data types must match in order to merge
} else if (formDataType == optionsDataType) {
switch(formDataType) {
case "array": {
o.data = $.merge(formData, o.data);
} break;
case "object": {
o.data = $.extend(formData, o.data);
} break;
case "string": {
o.data = formData + (formData.length ? "&" : "") + o.data;
} break;
}
} else {
throw "Cannot merge form data with options data, must be of same type.";
}
$.ajax(o);
return false;
},
options: {
url: window.location.href
}
}
});
/**
* Attaches an autosave class instance to the form elements associated with
* the elements passed into the plugin.
*
* @param {Object} [options]
* User supplied options to override the defaults within the plugin.
*
* @returns {jQuery}
* The elements that invoked this function.
*/
$.fn.autosave = function(options) {
return $.extend({}, $.autosave).initialize(this, options);
};
})(jQuery, window, document);
| src/jquery.autosave.js | /**
* @fileOverview jQuery.autosave
*
* @author Kyle Florence
* @website https://github.com/kflorence/jquery-autosave
* @version 1.2-pre
*
* Inspired by the jQuery.autosave plugin written by Raymond Julin,
* Mads Erik Forberg and Simen Graaten.
*
* Dual licensed under the MIT and BSD Licenses.
*/
;(function($, window, document, undefined) {
// Figure out if html5 "input" event is available
var inputSupported = (function() {
var tmp = document.createElement("input");
if ('oninput' in tmp) return true;
// also try workaround for older versions of Firefox
tmp.setAttribute("oninput", "return;");
return typeof tmp["oninput"] === "function";
}());
/**
* Attempts to find a callback from a list of callbacks.
*
* @param {String|Object|function} callback
* The callback to get. Can be a string or object that represents one of
* the built in callback methods, or a custom function to use instead.
*
* @param {Object} callbacks
* An object containing the callbacks to search in.
*
* @returns {Object}
* The callback object. This will be an empty object if the callback
* could not be found. If it was found, this object will contain at the
* very least a "method" property and potentially an "options" property.
*/
var _findCallback = function(callback, callbacks) {
var cb = { options: {} }, callbackType = typeof callback;
if (callbackType === "function") {
// Custom function with no options
cb.method = callback;
} else if (callbackType === "string" && callbacks[callback]) {
// Built in method, use default options
cb.method = callbacks[callback].method;
} else if (callbackType === "object") {
callbackType = typeof callback.method;
if (callbackType === "function") {
// Custom function
cb.method = callback.method;
} else if (callbackType === "string" && callbacks[callback.method]) {
// Built in method
cb.method = callbacks[callback.method].method;
cb.options = $.extend(true, cb.options, callbacks[callback.method].options, callback.options);
}
}
return cb;
};
$.autosave = {
timer: 0,
$queues: $({}),
states: {
changed: "changed",
modified: "modified"
},
options: {
namespace: "autosave",
callbacks: {
trigger: "change",
scope: null,
data: "serialize",
condition: null,
save: "ajax"
},
events: {
save: "save",
saved: "saved",
changed: "changed",
modified: "modified"
},
classes: {
ignore: "ignore"
}
},
/**
* Initializes the plugin.
*
* @param {jQuery} $elements
* The elements passed to the plugin.
*
* @param {Object} [options]
* The user-defined options to merge with the defaults.
*
* @returns {jQuery} $elements
* The elements passed to the plugin to maintain chainability.
*/
initialize: function($elements, options) {
var self = this;
$.extend(this, {
context: $elements.context || document,
selector: $elements.selector || $elements,
options: $.extend(true, {}, this.options, options)
});
// If length == 0, we have no forms or inputs
if (this.elements().length) {
var validCallbacks, $forms = this.forms(), $inputs = this.inputs();
// Only attach to forms
$forms.data(this.options.namespace, this);
$.each(this.options.events, function(name, eventName) {
self.options.events[name] = [eventName, self.options.namespace].join(".");
});
$.each(this.options.classes, function(name, className) {
self.options.classes[name] = [self.options.namespace, className].join("-");
});
// Parse callback options into an array of callback objects
$.each(this.options.callbacks, function(key, value) {
validCallbacks = [];
if (value) {
$.each($.isArray(value) ? value : [value], function(i, callback) {
callback = _findCallback(callback, self.callbacks[key]);
// If callback has a valid method, we can use it
if ($.isFunction(callback.method)) {
validCallbacks.push(callback);
}
});
}
self.options.callbacks[key] = validCallbacks;
});
// Attempt to save when "save" is triggered on a form
$forms.bind([this.options.events.save, this.options.namespace].join("."), function(e, inputs) {
self.save(inputs, e.type);
});
// Listen for changes on all inputs
$inputs.bind(["change", this.options.namespace].join("."), function(e) {
$(this).data([self.options.namespace, self.states.changed].join("."), true);
$(this.form).triggerHandler(self.options.events.changed, [this]);
});
// Listen for modifications on all inputs
// Use html5 "input" event is available. Otherwise, use "keyup".
var modifyTriggerEvent = inputSupported ? "input" : "keyup";
$inputs.bind([modifyTriggerEvent, this.options.namespace].join("."), function(e) {
$(this).data([self.options.namespace, self.states.modified].join("."), true);
$(this.form).triggerHandler(self.options.events.modified, [this]);
});
// Set up triggers
$.each(this.options.callbacks.trigger, function(i, trigger) {
trigger.method.call(self, trigger.options);
});
}
return $elements;
},
/**
* Returns the forms and inputs matched by the selector and context.
*
* @param {jQuery|Element|Element[]} [selector]
* The selector expression to use. Uses the selector passed into the
* plugin by default.
*
* @param {jQuery|Element|Document} [context]
* A context to limit our search. Uses document by default.
*
* @return {jQuery}
* A jQuery object containing any matched form and input elements.
*/
elements: function(selector, context) {
selector = selector || this.selector;
context = context || this.context;
return $(selector, context).filter(function() {
return (this.elements || this.form);
});
},
/**
* Returns the forms found within elements.
*
* @param {jQuery|Element|Element[]} [elements]
* The elements to search within. Uses all of the currently found
* forms and form inputs by default.
*
* @returns {jQuery}
* A jQuery object containing any matched form elements.
*/
forms: function(elements) {
return $($.unique(this.elements(elements).map(function() {
return this.elements ? this : this.form;
}).get()));
},
/**
* Returns the inputs found within elements.
*
* @param {jQuery|Element|Element[]} elements
* The elements to search within. Uses all of the currently found
* forms and form inputs by default.
*
* @returns {jQuery}
* A jQuery object containing any matched input elements.
*/
inputs: function(elements) {
return this.elements(elements).map(function() {
return this.elements ? $.makeArray($(this).find(":input")) : this;
});
},
/**
* Returns the inputs from a set of inputs that are considered valid.
*
* @param {jQuery|Element|Element[]} [inputs]
* The set of inputs to search within. Uses all of the currently found
* inputs by default.
*
* @returns {jQuery}
* A jQuery object containing any matched input elements.
*/
validInputs: function(inputs) {
var self = this;
return this.inputs(inputs).filter(function() {
return !$(this).hasClass(self.options.classes.ignore);
});
},
/**
* Get all of the inputs whose value has changed since the last save.
*
* @param {jQuery|Element|Element[]} [inputs]
* The set of inputs to search within. Uses all of the currently found
* inputs by default.
*
* @returns {jQuery}
* A jQuery object containing any matched input elements.
*/
changedInputs: function(inputs) {
var self = this;
return this.inputs(inputs).filter(function() {
return $(this).data([self.options.namespace, self.states.changed].join("."));
});
},
/**
* Get all of the inputs whose value has been modified since the last save.
*
* @param {jQuery|Element|Element[]} [inputs]
* The set of inputs to search within. Uses all of the currently found
* inputs by default.
*
* @returns {jQuery}
* A jQuery object containing any matched input elements.
*/
modifiedInputs: function(inputs) {
var self = this;
return this.inputs(inputs).filter(function() {
return $(this).data([self.options.namespace, self.states.modified].join("."));
});
},
/**
* Starts an autosave interval loop, stopping the current one if needed.
*
* @param {number} interval
* An integer value representing the time between intervals in
* milliseconds.
*/
startInterval: function(interval) {
var self = this;
interval = interval || this.interval;
if (this.timer) {
this.stopInterval();
}
if (!isNaN(parseInt(interval))) {
this.timer = setTimeout(function() {
self.save(false, self.timer);
}, interval);
}
},
/**
* Stops an autosave interval loop.
*/
stopInterval: function() {
clearTimeout(this.timer);
this.timer = null;
},
/**
* Attemps to save form data.
*
* @param {jQuery|Element|Element[]} [inputs]
* The inputs to extract data from. Can be of type jQuery, a DOM
* element, or an array of DOM elements. If no inputs are passed, all
* of the currently available inputs will be used.
*
* @param {mixed} [caller]
* Used to denote who called this function. If passed, it is typically
* the ID of the current interval timer and may be used to check if the
* timer called this function.
*/
save: function(inputs, caller) {
var self = this, saved = false,
$inputs = this.validInputs(inputs);
// If there are no save methods defined, we can't save
if (this.options.callbacks.save.length) {
// Continue filtering the scope of inputs
$.each(this.options.callbacks.scope, function(i, scope) {
$inputs = scope.method.call(self, scope.options, $inputs);
});
if ($inputs.length) {
var formData, passes = true;
// Manipulate form data
$.each(this.options.callbacks.data, function(i, data) {
formData = data.method.call(self, data.options, $inputs, formData);
});
// Loop through pre-save conditions and proceed only if they pass
$.each(this.options.callbacks.condition, function(i, condition) {
return (passes = condition.method.call(
self, condition.options, $inputs, formData, caller
)) !== false;
});
if (passes) {
// Add all of our save methods to the queue
$.each(this.options.callbacks.save, function(i, save) {
self.$queues.queue("save", function() {
if (save.method.call(self, save.options, formData) === false) {
// Methods that return false should handle the call to next()
// we call resetFields manually here (immediately) before the async
// save fires, because the callback will call next without 'true'.
// and we want to reset the fields when the async save *starts*.
self.resetFields();
} else {
self.next("save", true);
}
});
});
// We were able to save
saved = true;
}
}
}
// Start the dequeue process
this.next("save", saved);
},
/**
* Maintains the queue; calls the next function in line, or performs
* necessary cleanup when the queue is empty.
*
* @param {String} name
* The name of the queue.
*
* @param {Boolean} [resetChanged]
* Whether or not to reset which elements were changed/modified before saving.
* Defaults to false.
*/
next: function(name, resetChanged) {
var queue = this.$queues.queue(name);
// Dequeue the next function if queue is not empty
if (queue && queue.length) {
this.$queues.dequeue(name);
}
// Queue is empty or does not exist
else {
this.finished(queue, name, resetChanged);
}
},
/**
* Reset which elements where changed/modified before saving.
*/
resetFields: function() {
this.inputs().data([this.options.namespace, this.states.changed].join("."), false);
this.inputs().data([this.options.namespace, this.states.modified].join("."), false);
},
/**
* Called whenever a queue finishes processing, usually to perform some
* type of cleanup.
*
* @param {Array} queue
* The queue that has finished processing.
*
* @param {Boolean} [resetChanged]
* Whether or not to reset which elements were changed/modified before saving.
* Defaults to false
*/
finished: function(queue, name, resetChanged) {
if (name === "save") {
if (queue) {
this.forms().triggerHandler(this.options.events.saved);
}
if (resetChanged) {
this.resetFields();
}
// If there is a timer running, start the next interval
if (this.timer) {
this.startInterval();
}
}
}
};
var callbacks = $.autosave.callbacks = {};
$.each($.autosave.options.callbacks, function(key) {
callbacks[key] = {};
});
$.extend(callbacks.trigger, {
/**
* Attempt to save any time an input value changes.
*/
change: {
method: function() {
var self = this;
this.forms().bind([this.options.events.changed, this.options.namespace].join("."), function(e, input) {
self.save(input, e.type);
});
}
},
/**
* Attempt to save any time an input value is modified.
*/
modify: {
method: function() {
var self = this;
this.forms().bind([this.options.events.modified, this.options.namespace].join("."), function(e, input) {
self.save(input, e.type);
});
}
},
/**
* Creates an interval loop that will attempt to save periodically.
*/
interval: {
method: function(options) {
if (!isNaN(parseInt(options.interval))) {
this.startInterval(this.interval = options.interval);
}
},
options: {
interval: 30000
}
}
});
$.extend(callbacks.scope, {
/**
* Use all inputs
*/
all: {
method: function() {
return this.validInputs();
}
},
/**
* Only use the inputs with values that have changed since the last save.
*/
changed: {
method: function() {
return this.changedInputs();
}
},
/**
* Only use the inputs with values that have been modified since the last save.
*/
modified: {
method: function() {
return this.modifiedInputs();
}
}
});
$.extend(callbacks.data, {
/**
* See: http://api.jquery.com/serialize/
*
* @returns {String}
* Standard URL-encoded string of form values.
*/
serialize: {
method: function(options, $inputs) {
return $inputs.serialize();
}
},
/**
* See: http://api.jquery.com/serializeArray/
*
* @returns {Array}
* An array of objects containing name/value pairs.
*/
serializeArray: {
method: function(options, $inputs) {
return $inputs.serializeArray();
}
},
/**
* Whereas .serializeArray() serializes a form into an array,
* .serializeObject() serializes a form into an object.
*
* jQuery serializeObject - v0.2 - 1/20/2010
* http://benalman.com/projects/jquery-misc-plugins/
*
* Copyright (c) 2010 "Cowboy" Ben Alman
* Dual licensed under the MIT and GPL licenses.
* http://benalman.com/about/license/
*
* @returns {Object}
* The resulting object of form values.
*/
serializeObject: {
method: function(options, $inputs) {
var obj = {};
$.each($inputs.serializeArray(), function(i, o) {
var n = o.name, v = o.value;
obj[n] = obj[n] === undefined ? v
: $.isArray(obj[n]) ? obj[n].concat(v)
: [obj[n], v];
});
return obj;
}
}
});
$.extend(callbacks.condition, {
/**
* Only save if the interval called the save method.
*/
interval: {
method: function(options, $inputs, data, caller) {
return (!this.timer || this.timer === caller);
}
},
/**
* Only save if at least one of the input values has changed.
*/
changed: {
method: function() {
return this.changedInputs().length > 0;
}
},
/**
* Only save if at least one of the input values has been modified.
*/
modified: {
method: function() {
return this.modifiedInputs().length > 0;
}
}
});
$.extend(callbacks.save, {
/**
* Saves form data using a jQuery.ajax call.
*/
ajax: {
method: function(options, formData) {
var self = this, o = $.extend({}, options);
// Wrap the complete method with our own
o.complete = function(xhr, status) {
if ($.isFunction(options.complete)) {
options.complete.apply(self, arguments);
}
self.next("save");
};
// Allow for dynamically generated data
if ($.isFunction(o.data)) {
o.data = o.data.call(self, formData);
}
var formDataType = $.type(formData),
optionsDataType = $.type(o.data);
// No options data given, use form data
if (optionsDataType == "undefined") {
o.data = formData;
// Data types must match in order to merge
} else if (formDataType == optionsDataType) {
switch(formDataType) {
case "array": {
o.data = $.merge(formData, o.data);
} break;
case "object": {
o.data = $.extend(formData, o.data);
} break;
case "string": {
o.data = formData + (formData.length ? "&" : "") + o.data;
} break;
}
} else {
throw "Cannot merge form data with options data, must be of same type.";
}
$.ajax(o);
return false;
},
options: {
url: window.location.href
}
}
});
/**
* Attaches an autosave class instance to the form elements associated with
* the elements passed into the plugin.
*
* @param {Object} [options]
* User supplied options to override the defaults within the plugin.
*
* @returns {jQuery}
* The elements that invoked this function.
*/
$.fn.autosave = function(options) {
return $.extend({}, $.autosave).initialize(this, options);
};
})(jQuery, window, document);
| Constraint the scope of elements to those pass to initialize
| src/jquery.autosave.js | Constraint the scope of elements to those pass to initialize | <ide><path>rc/jquery.autosave.js
<ide> initialize: function($elements, options) {
<ide> var self = this;
<ide>
<del> $.extend(this, {
<del> context: $elements.context || document,
<del> selector: $elements.selector || $elements,
<del> options: $.extend(true, {}, this.options, options)
<del> });
<add> this.$elements = $elements;
<add> this.options = $.extend(true, {}, this.options, options);
<ide>
<ide> // If length == 0, we have no forms or inputs
<ide> if (this.elements().length) {
<ide> },
<ide>
<ide> /**
<del> * Returns the forms and inputs matched by the selector and context.
<del> *
<del> * @param {jQuery|Element|Element[]} [selector]
<del> * The selector expression to use. Uses the selector passed into the
<del> * plugin by default.
<del> *
<del> * @param {jQuery|Element|Document} [context]
<del> * A context to limit our search. Uses document by default.
<add> * Returns the forms and inputs within a specific context.
<add> *
<add> * @param {jQuery|Element|Element[]} [elements]
<add> * The elements to search within. Uses the pass elements by default.
<ide> *
<ide> * @return {jQuery}
<ide> * A jQuery object containing any matched form and input elements.
<ide> */
<del> elements: function(selector, context) {
<del> selector = selector || this.selector;
<del> context = context || this.context;
<del>
<del> return $(selector, context).filter(function() {
<add> elements: function(elements) {
<add> if (!elements) elements = this.$elements;
<add>
<add> return $(elements).filter(function() {
<ide> return (this.elements || this.form);
<ide> });
<ide> }, |
|
Java | mit | 779e2de0d38121ecca7ffd7d974b9bcda19fd9c0 | 0 | SerCeMan/jnr-fuse | package jnr.ffi.provider.jffi;
import jnr.ffi.Pointer;
import jnr.ffi.Runtime;
import jnr.ffi.mapper.CompositeTypeMapper;
import jnr.ffi.mapper.DefaultSignatureType;
import jnr.ffi.mapper.FromNativeContext;
import jnr.ffi.mapper.FromNativeConverter;
import jnr.ffi.provider.ClosureManager;
import ru.serce.jnrfuse.FuseException;
import java.lang.reflect.Field;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class ClosureHelper {
private final AsmClassLoader asmClassLoader;
private final CompositeTypeMapper ctm;
private final SimpleNativeContext ctx;
private final ConcurrentHashMap<Class<?>, FromNativeConverter<?, Pointer>> cache = new ConcurrentHashMap<>();
public static ClosureHelper getInstance() {
return SingletonHolder.INSTANCE;
}
@SuppressWarnings("unchecked")
public <T> FromNativeConverter<T, Pointer> getNativeConveter(Class<T> closureClass) {
FromNativeConverter<T, Pointer> result = (FromNativeConverter<T, Pointer>) cache.get(closureClass);
if (result != null) {
return result;
}
result = (FromNativeConverter<T, Pointer>) ClosureFromNativeConverter.
getInstance(Runtime.getSystemRuntime(), DefaultSignatureType.create(closureClass, (FromNativeContext) ctx), asmClassLoader, ctm);
cache.putIfAbsent(closureClass, result);
return result;
}
public FromNativeContext getFromNativeContext() {
return ctx;
}
private static class SingletonHolder {
private static final ClosureHelper INSTANCE = new ClosureHelper();
}
private ClosureHelper() {
try {
ClosureManager closureManager = jnr.ffi.Runtime.getSystemRuntime().getClosureManager();
Field asmClassLoadersField = NativeClosureManager.class.getDeclaredField("asmClassLoaders");
asmClassLoadersField.setAccessible(true);
Map<ClassLoader, AsmClassLoader> asmClassLoaders = (Map<ClassLoader, AsmClassLoader>) asmClassLoadersField.get(closureManager);
asmClassLoader = asmClassLoaders.get(ClosureHelper.class.getClassLoader());
Field typeMapperField = NativeClosureManager.class.getDeclaredField("typeMapper");
typeMapperField.setAccessible(true);
ctm = (CompositeTypeMapper) typeMapperField.get(closureManager);
ctx = new SimpleNativeContext(Runtime.getSystemRuntime(), Collections.emptyList());
} catch (Exception e) {
throw new FuseException("Unable to create helper", e);
}
}
}
| src/main/java/jnr/ffi/provider/jffi/ClosureHelper.java | package jnr.ffi.provider.jffi;
import jnr.ffi.Pointer;
import jnr.ffi.Runtime;
import jnr.ffi.mapper.CompositeTypeMapper;
import jnr.ffi.mapper.DefaultSignatureType;
import jnr.ffi.mapper.FromNativeContext;
import jnr.ffi.mapper.FromNativeConverter;
import jnr.ffi.provider.ClosureManager;
import ru.serce.jnrfuse.FuseException;
import java.lang.reflect.Field;
import java.util.Collections;
import java.util.concurrent.ConcurrentHashMap;
public class ClosureHelper {
private final AsmClassLoader classLoader;
private final CompositeTypeMapper ctm;
private final SimpleNativeContext ctx;
private final ConcurrentHashMap<Class<?>, FromNativeConverter<?, Pointer>> cache = new ConcurrentHashMap<>();
public static ClosureHelper getInstance() {
return SingletonHolder.INSTANCE;
}
@SuppressWarnings("unchecked")
public <T> FromNativeConverter<T, Pointer> getNativeConveter(Class<T> closureClass) {
FromNativeConverter<T, Pointer> result = (FromNativeConverter<T, Pointer>) cache.get(closureClass);
if (result != null) {
return result;
}
result = (FromNativeConverter<T, Pointer>) ClosureFromNativeConverter.
getInstance(Runtime.getSystemRuntime(), DefaultSignatureType.create(closureClass, (FromNativeContext) ctx), classLoader, ctm);
cache.putIfAbsent(closureClass, result);
return result;
}
public FromNativeContext getFromNativeContext() {
return ctx;
}
private static class SingletonHolder {
private static final ClosureHelper INSTANCE = new ClosureHelper();
}
private ClosureHelper() {
try {
ClosureManager closureManager = jnr.ffi.Runtime.getSystemRuntime().getClosureManager();
Field classLoaderField = NativeClosureManager.class.getDeclaredField("classLoader");
classLoaderField.setAccessible(true);
classLoader = (AsmClassLoader) classLoaderField.get(closureManager);
Field typeMapperField = NativeClosureManager.class.getDeclaredField("typeMapper");
typeMapperField.setAccessible(true);
ctm = (CompositeTypeMapper) typeMapperField.get(closureManager);
ctx = new SimpleNativeContext(Runtime.getSystemRuntime(), Collections.emptyList());
} catch (Exception e) {
throw new FuseException("Unable to create helper", e);
}
}
}
| Make jnr-fuse work with jnr-ffi 2.1.8 (#61)
| src/main/java/jnr/ffi/provider/jffi/ClosureHelper.java | Make jnr-fuse work with jnr-ffi 2.1.8 (#61) | <ide><path>rc/main/java/jnr/ffi/provider/jffi/ClosureHelper.java
<ide>
<ide> import java.lang.reflect.Field;
<ide> import java.util.Collections;
<add>import java.util.Map;
<ide> import java.util.concurrent.ConcurrentHashMap;
<ide>
<ide> public class ClosureHelper {
<ide>
<del> private final AsmClassLoader classLoader;
<add> private final AsmClassLoader asmClassLoader;
<ide> private final CompositeTypeMapper ctm;
<ide> private final SimpleNativeContext ctx;
<ide>
<ide> return result;
<ide> }
<ide> result = (FromNativeConverter<T, Pointer>) ClosureFromNativeConverter.
<del> getInstance(Runtime.getSystemRuntime(), DefaultSignatureType.create(closureClass, (FromNativeContext) ctx), classLoader, ctm);
<add> getInstance(Runtime.getSystemRuntime(), DefaultSignatureType.create(closureClass, (FromNativeContext) ctx), asmClassLoader, ctm);
<ide> cache.putIfAbsent(closureClass, result);
<ide> return result;
<ide> }
<ide> private ClosureHelper() {
<ide> try {
<ide> ClosureManager closureManager = jnr.ffi.Runtime.getSystemRuntime().getClosureManager();
<del> Field classLoaderField = NativeClosureManager.class.getDeclaredField("classLoader");
<del> classLoaderField.setAccessible(true);
<add> Field asmClassLoadersField = NativeClosureManager.class.getDeclaredField("asmClassLoaders");
<add> asmClassLoadersField.setAccessible(true);
<ide>
<del> classLoader = (AsmClassLoader) classLoaderField.get(closureManager);
<add> Map<ClassLoader, AsmClassLoader> asmClassLoaders = (Map<ClassLoader, AsmClassLoader>) asmClassLoadersField.get(closureManager);
<add> asmClassLoader = asmClassLoaders.get(ClosureHelper.class.getClassLoader());
<ide>
<ide> Field typeMapperField = NativeClosureManager.class.getDeclaredField("typeMapper");
<ide> typeMapperField.setAccessible(true); |
|
Java | apache-2.0 | c74276977104a7940d0c176bbb0a35839776b6a8 | 0 | openbaton/plugin-sdk | package org.openbaton.plugin;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import org.apache.commons.codec.binary.Base64;
import org.openbaton.catalogue.nfvo.PluginAnswer;
import org.openbaton.catalogue.nfvo.images.BaseNfvImage;
import org.openbaton.catalogue.nfvo.networks.BaseNetwork;
import org.openbaton.catalogue.nfvo.viminstances.BaseVimInstance;
import org.openbaton.exceptions.NotFoundException;
import org.openbaton.nfvo.common.configuration.NfvoGsonDeserializerImage;
import org.openbaton.nfvo.common.configuration.NfvoGsonDeserializerNetwork;
import org.openbaton.nfvo.common.configuration.NfvoGsonDeserializerVimInstance;
import org.openbaton.nfvo.common.configuration.NfvoGsonSerializerVimInstance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeoutException;
public class PluginListener implements Runnable {
private static final String exchange = "openbaton-exchange";
private String pluginId;
private Object pluginInstance;
private Logger log;
private Channel channel;
private Gson gson =
new GsonBuilder()
.registerTypeHierarchyAdapter(byte[].class, new ByteArrayToBase64TypeAdapter())
.registerTypeAdapter(BaseVimInstance.class, new NfvoGsonDeserializerVimInstance())
.registerTypeAdapter(BaseNetwork.class, new NfvoGsonDeserializerNetwork())
.registerTypeAdapter(BaseNfvImage.class, new NfvoGsonDeserializerImage())
.registerTypeAdapter(BaseVimInstance.class, new NfvoGsonSerializerVimInstance())
.setPrettyPrinting()
.create();
private String brokerIp;
private int brokerPort;
private String username;
private String password;
private String virtualHost;
private Connection connection;
private ThreadPoolExecutor executor;
public void setDurable(boolean durable) {
this.durable = durable;
}
private boolean durable = true;
public void setPluginId(String pluginId) {
this.pluginId = pluginId;
}
public void setPluginInstance(Object pluginInstance) {
this.pluginInstance = pluginInstance;
log = LoggerFactory.getLogger(pluginInstance.getClass().getName());
}
public void setExecutor(ThreadPoolExecutor executor) {
this.executor = executor;
}
public ThreadPoolExecutor getExecutor() {
return executor;
}
private static class ByteArrayToBase64TypeAdapter
implements JsonSerializer<byte[]>, JsonDeserializer<byte[]> {
public byte[] deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
return Base64.decodeBase64(json.getAsString());
}
public JsonElement serialize(byte[] src, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(Base64.encodeBase64String(src));
}
}
@Override
public void run() {
try {
initRabbitMQ();
} catch (IOException | TimeoutException e) {
e.printStackTrace();
return;
}
try {
Consumer consumer =
new DefaultConsumer(channel) {
@Override
public void handleDelivery(
String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
throws IOException {
AMQP.BasicProperties props =
new AMQP.BasicProperties.Builder()
.correlationId(properties.getCorrelationId())
.build();
executor.execute(
() -> {
String message;
try {
message = new String(body, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return;
}
log.trace("Received message");
log.trace("Message content received: " + message);
PluginAnswer answer = new PluginAnswer();
try {
answer.setAnswer(executeMethod(message));
} catch (InvocationTargetException e) {
e.getTargetException().printStackTrace();
answer.setException(e.getTargetException());
} catch (Exception e) {
e.printStackTrace();
answer.setException(e);
}
String response;
try {
response = gson.toJson(answer);
log.trace("Answer is: " + response);
log.trace("Reply queue is: " + properties.getReplyTo());
channel.basicPublish(
exchange, properties.getReplyTo(), props, response.getBytes());
} catch (Throwable e) {
e.printStackTrace();
answer.setException(e);
log.trace("Answer is: " + answer);
log.trace("Reply queue is: " + properties.getReplyTo());
try {
channel.basicPublish(
exchange,
properties.getReplyTo(),
props,
gson.toJson(answer).getBytes());
} catch (IOException ex) {
log.error(
String.format(
"Thread %s got an exception: %s",
Thread.currentThread().getName(),
e.getMessage()));
e.printStackTrace();
}
}
});
channel.basicAck(envelope.getDeliveryTag(), false);
log.trace(String.format("Ack %d", envelope.getDeliveryTag()));
synchronized (this) {
this.notify();
}
}
};
channel.basicConsume(pluginId, false, consumer);
// Wait and be prepared to consume the message from RPC client.
while (true) {
synchronized (consumer) {
try {
consumer.wait();
} catch (InterruptedException e) {
log.info("Ctrl-c received");
System.exit(0);
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null)
try {
connection.close();
} catch (IOException ignored) {
}
}
try {
if (channel == null || connection == null) System.exit(3);
channel.close();
connection.close();
} catch (IOException | TimeoutException e) {
e.printStackTrace();
}
}
private Serializable executeMethod(String pluginMessageString)
throws InvocationTargetException, IllegalAccessException, NotFoundException {
JsonObject pluginMessageObject = gson.fromJson(pluginMessageString, JsonObject.class);
List<Object> params = new ArrayList<>();
for (JsonElement param : pluginMessageObject.get("parameters").getAsJsonArray()) {
Object p = gson.fromJson(param, Object.class);
if (p != null) {
params.add(p);
}
}
Class pluginClass = pluginInstance.getClass();
log.trace("There are " + params.size() + " parameters");
String methodName = pluginMessageObject.get("methodName").getAsString();
log.trace("Looking for method: " + methodName);
for (Method m : pluginClass.getMethods()) {
log.trace(
"Method checking is: "
+ m.getName()
+ " with "
+ m.getParameterTypes().length
+ " parameters");
byte[] avoid = new byte[0];
if (m.getName().equals(methodName)
&& m.getParameterTypes().length == params.size()
&& !m.getParameterTypes()[m.getParameterTypes().length - 1]
.getCanonicalName()
.equals(avoid.getClass().getCanonicalName())) {
if (!m.getReturnType().equals(Void.class)) {
if (params.size() != 0) {
params =
getParameters(
pluginMessageObject.get("parameters").getAsJsonArray(), m.getParameterTypes());
for (Object p : params) {
log.trace("param class is: " + p.getClass());
}
return (Serializable) m.invoke(pluginInstance, params.toArray());
} else {
return (Serializable) m.invoke(pluginInstance);
}
} else {
if (params.size() != 0) {
params =
getParameters(
pluginMessageObject.get("parameters").getAsJsonArray(), m.getParameterTypes());
for (Object p : params) {
log.trace("param class is: " + p.getClass());
}
m.invoke(pluginInstance, params.toArray());
} else {
m.invoke(pluginInstance);
}
return null;
}
}
}
throw new NotFoundException("method not found");
}
private List<Object> getParameters(JsonArray parameters, Class<?>[] parameterTypes) {
List<Object> res = new LinkedList<>();
for (int i = 0; i < parameters.size(); i++) {
res.add(gson.fromJson(parameters.get(i), parameterTypes[i]));
}
return res;
}
private void initRabbitMQ() throws IOException, TimeoutException {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost(brokerIp);
factory.setPort(brokerPort);
factory.setPassword(password);
factory.setUsername(username);
factory.setVirtualHost(virtualHost);
connection = factory.newConnection();
channel = connection.createChannel();
channel.queueDeclare(pluginId, this.durable, false, true, null);
channel.queueBind(pluginId, exchange, pluginId);
channel.basicQos(1);
}
public void setBrokerIp(String brokerIp) {
this.brokerIp = brokerIp;
}
public void setBrokerPort(int brokerPort) {
this.brokerPort = brokerPort;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
public void setVirtualHost(String virtualHost) {
this.virtualHost = virtualHost;
}
}
| src/main/java/org/openbaton/plugin/PluginListener.java | package org.openbaton.plugin;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import org.apache.commons.codec.binary.Base64;
import org.openbaton.catalogue.nfvo.PluginAnswer;
import org.openbaton.catalogue.nfvo.images.BaseNfvImage;
import org.openbaton.catalogue.nfvo.networks.BaseNetwork;
import org.openbaton.catalogue.nfvo.viminstances.BaseVimInstance;
import org.openbaton.exceptions.NotFoundException;
import org.openbaton.nfvo.common.configuration.NfvoGsonDeserializerImage;
import org.openbaton.nfvo.common.configuration.NfvoGsonDeserializerNetwork;
import org.openbaton.nfvo.common.configuration.NfvoGsonDeserializerVimInstance;
import org.openbaton.nfvo.common.configuration.NfvoGsonSerializerVimInstance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeoutException;
public class PluginListener implements Runnable {
private static final String exchange = "openbaton-exchange";
private String pluginId;
private Object pluginInstance;
private Logger log;
private Channel channel;
private Gson gson =
new GsonBuilder()
.registerTypeHierarchyAdapter(byte[].class, new ByteArrayToBase64TypeAdapter())
.registerTypeAdapter(BaseVimInstance.class, new NfvoGsonDeserializerVimInstance())
.registerTypeAdapter(BaseNetwork.class, new NfvoGsonDeserializerNetwork())
.registerTypeAdapter(BaseNfvImage.class, new NfvoGsonDeserializerImage())
.registerTypeAdapter(BaseVimInstance.class, new NfvoGsonSerializerVimInstance())
.setPrettyPrinting()
.create();
private String brokerIp;
private int brokerPort;
private String username;
private String password;
private String virtualHost;
private Connection connection;
private ThreadPoolExecutor executor;
public void setDurable(boolean durable) {
this.durable = durable;
}
private boolean durable = true;
public void setPluginId(String pluginId) {
this.pluginId = pluginId;
}
public void setPluginInstance(Object pluginInstance) {
this.pluginInstance = pluginInstance;
log = LoggerFactory.getLogger(pluginInstance.getClass().getName());
}
public void setExecutor(ThreadPoolExecutor executor) {
this.executor = executor;
}
public ThreadPoolExecutor getExecutor() {
return executor;
}
private static class ByteArrayToBase64TypeAdapter
implements JsonSerializer<byte[]>, JsonDeserializer<byte[]> {
public byte[] deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
return Base64.decodeBase64(json.getAsString());
}
public JsonElement serialize(byte[] src, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(Base64.encodeBase64String(src));
}
}
@Override
public void run() {
try {
initRabbitMQ();
} catch (IOException | TimeoutException e) {
e.printStackTrace();
return;
}
try {
Consumer consumer =
new DefaultConsumer(channel) {
@Override
public void handleDelivery(
String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
throws IOException {
AMQP.BasicProperties props =
new AMQP.BasicProperties.Builder()
.correlationId(properties.getCorrelationId())
.build();
executor.execute(
() -> {
String message;
try {
message = new String(body, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return;
}
log.trace("Received message");
log.trace("Message content received: " + message);
PluginAnswer answer = new PluginAnswer();
try {
answer.setAnswer(executeMethod(message));
} catch (InvocationTargetException e) {
answer.setException(e.getTargetException());
} catch (Exception e) {
e.printStackTrace();
answer.setException(e);
}
String response;
try {
response = gson.toJson(answer);
log.trace("Answer is: " + response);
log.trace("Reply queue is: " + properties.getReplyTo());
channel.basicPublish(
exchange, properties.getReplyTo(), props, response.getBytes());
} catch (Throwable e) {
e.printStackTrace();
answer.setException(e);
log.trace("Answer is: " + answer);
log.trace("Reply queue is: " + properties.getReplyTo());
try {
channel.basicPublish(
exchange,
properties.getReplyTo(),
props,
gson.toJson(answer).getBytes());
} catch (IOException ex) {
log.error(
String.format(
"Thread %s got an exception: %s",
Thread.currentThread().getName(),
e.getMessage()));
e.printStackTrace();
}
}
});
channel.basicAck(envelope.getDeliveryTag(), false);
log.trace(String.format("Ack %d", envelope.getDeliveryTag()));
synchronized (this) {
this.notify();
}
}
};
channel.basicConsume(pluginId, false, consumer);
// Wait and be prepared to consume the message from RPC client.
while (true) {
synchronized (consumer) {
try {
consumer.wait();
} catch (InterruptedException e) {
log.info("Ctrl-c received");
System.exit(0);
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null)
try {
connection.close();
} catch (IOException ignored) {
}
}
try {
if (channel == null || connection == null) System.exit(3);
channel.close();
connection.close();
} catch (IOException | TimeoutException e) {
e.printStackTrace();
}
}
private Serializable executeMethod(String pluginMessageString)
throws InvocationTargetException, IllegalAccessException, NotFoundException {
JsonObject pluginMessageObject = gson.fromJson(pluginMessageString, JsonObject.class);
List<Object> params = new ArrayList<>();
for (JsonElement param : pluginMessageObject.get("parameters").getAsJsonArray()) {
Object p = gson.fromJson(param, Object.class);
if (p != null) {
params.add(p);
}
}
Class pluginClass = pluginInstance.getClass();
log.trace("There are " + params.size() + " parameters");
String methodName = pluginMessageObject.get("methodName").getAsString();
log.trace("Looking for method: " + methodName);
for (Method m : pluginClass.getMethods()) {
log.trace(
"Method checking is: "
+ m.getName()
+ " with "
+ m.getParameterTypes().length
+ " parameters");
byte[] avoid = new byte[0];
if (m.getName().equals(methodName)
&& m.getParameterTypes().length == params.size()
&& !m.getParameterTypes()[m.getParameterTypes().length - 1]
.getCanonicalName()
.equals(avoid.getClass().getCanonicalName())) {
if (!m.getReturnType().equals(Void.class)) {
if (params.size() != 0) {
params =
getParameters(
pluginMessageObject.get("parameters").getAsJsonArray(), m.getParameterTypes());
for (Object p : params) {
log.trace("param class is: " + p.getClass());
}
return (Serializable) m.invoke(pluginInstance, params.toArray());
} else {
return (Serializable) m.invoke(pluginInstance);
}
} else {
if (params.size() != 0) {
params =
getParameters(
pluginMessageObject.get("parameters").getAsJsonArray(), m.getParameterTypes());
for (Object p : params) {
log.trace("param class is: " + p.getClass());
}
m.invoke(pluginInstance, params.toArray());
} else {
m.invoke(pluginInstance);
}
return null;
}
}
}
throw new NotFoundException("method not found");
}
private List<Object> getParameters(JsonArray parameters, Class<?>[] parameterTypes) {
List<Object> res = new LinkedList<>();
for (int i = 0; i < parameters.size(); i++) {
res.add(gson.fromJson(parameters.get(i), parameterTypes[i]));
}
return res;
}
private void initRabbitMQ() throws IOException, TimeoutException {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost(brokerIp);
factory.setPort(brokerPort);
factory.setPassword(password);
factory.setUsername(username);
factory.setVirtualHost(virtualHost);
connection = factory.newConnection();
channel = connection.createChannel();
channel.queueDeclare(pluginId, this.durable, false, true, null);
channel.queueBind(pluginId, exchange, pluginId);
channel.basicQos(1);
}
public void setBrokerIp(String brokerIp) {
this.brokerIp = brokerIp;
}
public void setBrokerPort(int brokerPort) {
this.brokerPort = brokerPort;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
public void setVirtualHost(String virtualHost) {
this.virtualHost = virtualHost;
}
}
| add print stack trace
| src/main/java/org/openbaton/plugin/PluginListener.java | add print stack trace | <ide><path>rc/main/java/org/openbaton/plugin/PluginListener.java
<ide> try {
<ide> answer.setAnswer(executeMethod(message));
<ide> } catch (InvocationTargetException e) {
<add> e.getTargetException().printStackTrace();
<ide> answer.setException(e.getTargetException());
<ide> } catch (Exception e) {
<ide> e.printStackTrace(); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.